From a272f236bcbfe274e8db3da2ed89e763081ad7f5 Mon Sep 17 00:00:00 2001 From: Jay Moore Date: Thu, 28 Aug 2025 22:37:27 -0400 Subject: [PATCH] Might work. Probably does. Thicc. --- AUTHORS | 49 + COPYING | 339 ++ LICENSE | 339 ++ LICENSES/BSD-2-Clause.txt | 9 + LICENSES/GPL-2.0-or-later.txt | 117 + LICENSES/ISC.txt | 8 + LICENSES/LGPL-2.1-only.txt | 175 + NEWS | 2906 +++++++++++++++++ android/.gitignore | 24 + android/PrivacyPolicy.rst | 8 + android/README.md | 49 + android/app/.gitignore | 1 + android/app/build.gradle.kts | 128 + android/app/src/main/AndroidManifest.xml | 75 + .../app/src/main/aidl/org/musicpd/IMain.aidl | 13 + .../main/aidl/org/musicpd/IMainCallback.aidl | 8 + .../app/src/main/ic_launcher-playstore.png | Bin 0 -> 49970 bytes .../java/org/musicpd/AutomationReceiver.kt | 24 + .../app/src/main/java/org/musicpd/Bridge.java | 24 + .../app/src/main/java/org/musicpd/Loader.kt | 45 + .../main/java/org/musicpd/MPDApplication.kt | 9 + .../src/main/java/org/musicpd/MPDPlayer.java | 76 + android/app/src/main/java/org/musicpd/Main.kt | 326 ++ .../src/main/java/org/musicpd/MainActivity.kt | 57 + .../java/org/musicpd/MainServiceClient.java | 157 + .../main/java/org/musicpd/NetworkUtil.java | 34 + .../main/java/org/musicpd/Preferences.java | 34 + .../src/main/java/org/musicpd/Receiver.java | 34 + .../org/musicpd/data/LoggingRepository.kt | 34 + .../src/main/java/org/musicpd/ui/LogScreen.kt | 79 + .../main/java/org/musicpd/ui/MainScreen.kt | 109 + .../java/org/musicpd/ui/NetworkAddress.kt | 39 + .../java/org/musicpd/ui/SettingsScreen.kt | 77 + .../java/org/musicpd/ui/SettingsViewModel.kt | 73 + .../main/java/org/musicpd/ui/StatusScreen.kt | 188 ++ .../java/org/musicpd/utils/IntentUtils.kt | 32 + .../main/res/drawable/baseline_wifi_24.xml | 5 + .../res/drawable/ic_banner_foreground.xml | 239 ++ .../res/drawable/ic_launcher_foreground.xml | 235 ++ .../main/res/drawable/notification_icon.png | Bin 0 -> 1551 bytes .../res/layout/custom_notification_gb.xml | 22 + .../main/res/mipmap-anydpi-v26/ic_banner.xml | 5 + .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + .../src/main/res/mipmap-hdpi/ic_banner.png | Bin 0 -> 4779 bytes .../src/main/res/mipmap-hdpi/ic_launcher.webp | Bin 0 -> 1754 bytes .../res/mipmap-hdpi/ic_launcher_round.webp | Bin 0 -> 3570 bytes .../src/main/res/mipmap-mdpi/ic_banner.png | Bin 0 -> 2961 bytes .../src/main/res/mipmap-mdpi/ic_launcher.webp | Bin 0 -> 1208 bytes .../res/mipmap-mdpi/ic_launcher_round.webp | Bin 0 -> 2112 bytes .../src/main/res/mipmap-xhdpi/ic_banner.png | Bin 0 -> 6845 bytes .../main/res/mipmap-xhdpi/ic_launcher.webp | Bin 0 -> 2538 bytes .../res/mipmap-xhdpi/ic_launcher_round.webp | Bin 0 -> 4546 bytes .../src/main/res/mipmap-xxhdpi/ic_banner.png | Bin 0 -> 11442 bytes .../main/res/mipmap-xxhdpi/ic_launcher.webp | Bin 0 -> 3976 bytes .../res/mipmap-xxhdpi/ic_launcher_round.webp | Bin 0 -> 7696 bytes .../src/main/res/mipmap-xxxhdpi/ic_banner.png | Bin 0 -> 16542 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.webp | Bin 0 -> 5882 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.webp | Bin 0 -> 10772 bytes .../main/res/values/ic_banner_background.xml | 4 + .../res/values/ic_launcher_background.xml | 4 + android/app/src/main/res/values/strings.xml | 25 + android/app/src/main/res/values/themes.xml | 21 + android/build.gradle.kts | 7 + android/build.py | 82 + android/custom_rules.xml | 11 + android/gdb.sh | 54 + android/gradle.properties | 21 + android/gradle/libs.versions.toml | 41 + android/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 59203 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 + android/gradlew | 185 ++ android/gradlew.bat | 89 + android/include/meson.build | 21 + android/meson.build | 17 + android/settings.gradle.kts | 18 + doc/_static/css/custom.css | 3 + doc/client.rst | 66 + doc/conf.py | 239 ++ doc/developer.rst | 149 + doc/doxygen.conf.in | 2428 ++++++++++++++ doc/index.rst | 25 + doc/meson.build | 58 + doc/mpd.1.rst | 73 + doc/mpd.conf.5.rst | 204 ++ doc/mpdconf.example | 402 +++ doc/plugins.rst | 1445 ++++++++ doc/protocol.rst | 1951 +++++++++++ doc/requirements.txt | 1 + doc/user.rst | 1525 +++++++++ meson.build | 744 +++++ meson_options.txt | 212 ++ mpd.svg | 857 +++++ python/build/__init__.py | 0 python/build/autotools.py | 91 + python/build/cmake.py | 130 + python/build/dirs.py | 9 + python/build/download.py | 60 + python/build/ffmpeg.py | 51 + python/build/libs.py | 544 +++ python/build/makeproject.py | 35 + python/build/meson.py | 111 + python/build/project.py | 90 + python/build/quilt.py | 12 + python/build/tar.py | 20 + python/build/toolchain.py | 191 ++ python/build/verify.py | 45 + python/build/zlib.py | 34 + src/BulkEdit.hxx | 28 + src/Chrono.hxx | 209 ++ src/CommandLine.cxx | 430 +++ src/CommandLine.hxx | 32 + src/ConsumeMode.cxx | 42 + src/ConsumeMode.hxx | 28 + src/DbMain.cxx | 266 ++ src/GitVersion.cxx | 6 + src/GitVersion.hxx | 9 + src/Idle.cxx | 21 + src/Idle.hxx | 21 + src/Instance.cxx | 272 ++ src/Instance.hxx | 250 ++ src/Listen.cxx | 149 + src/Listen.hxx | 15 + src/LocateUri.cxx | 120 + src/LocateUri.hxx | 80 + src/Log.cxx | 34 + src/Log.hxx | 118 + src/LogBackend.cxx | 199 ++ src/LogBackend.hxx | 21 + src/LogInit.cxx | 240 ++ src/LogInit.hxx | 35 + src/LogLevel.hxx | 43 + src/Main.cxx | 708 ++++ src/Main.hxx | 64 + src/Mapper.cxx | 111 + src/Mapper.hxx | 62 + src/MusicBuffer.cxx | 38 + src/MusicBuffer.hxx | 72 + src/MusicChunk.cxx | 58 + src/MusicChunk.hxx | 136 + src/MusicChunkPtr.cxx | 11 + src/MusicChunkPtr.hxx | 24 + src/MusicPipe.cxx | 84 + src/MusicPipe.hxx | 98 + src/Partition.cxx | 248 ++ src/Partition.hxx | 284 ++ src/Permission.cxx | 167 + src/Permission.hxx | 45 + src/PlaylistDatabase.cxx | 54 + src/PlaylistDatabase.hxx | 23 + src/PlaylistError.cxx | 7 + src/PlaylistError.hxx | 58 + src/PlaylistFile.cxx | 448 +++ src/PlaylistFile.hxx | 97 + src/PlaylistPrint.cxx | 92 + src/PlaylistPrint.hxx | 71 + src/PlaylistSave.cxx | 105 + src/PlaylistSave.hxx | 33 + src/PluginUnavailable.hxx | 30 + src/RemoteTagCache.cxx | 122 + src/RemoteTagCache.hxx | 109 + src/RemoteTagCacheHandler.hxx | 14 + src/ReplayGainMode.cxx | 47 + src/ReplayGainMode.hxx | 30 + src/SingleMode.cxx | 42 + src/SingleMode.hxx | 28 + src/SongLoader.cxx | 91 + src/SongLoader.hxx | 66 + src/SongPrint.cxx | 120 + src/SongPrint.hxx | 25 + src/SongSave.cxx | 143 + src/SongSave.hxx | 33 + src/SongUpdate.cxx | 188 ++ src/StateFile.cxx | 142 + src/StateFile.hxx | 66 + src/StateFileConfig.cxx | 27 + src/StateFileConfig.hxx | 28 + src/Stats.cxx | 122 + src/Stats.hxx | 16 + src/TagAny.cxx | 151 + src/TagAny.hxx | 20 + src/TagArchive.cxx | 34 + src/TagArchive.hxx | 35 + src/TagFile.cxx | 92 + src/TagFile.hxx | 39 + src/TagPrint.cxx | 61 + src/TagPrint.hxx | 33 + src/TagSave.cxx | 25 + src/TagSave.hxx | 13 + src/TagStream.cxx | 94 + src/TagStream.hxx | 51 + src/TimePrint.cxx | 24 + src/TimePrint.hxx | 18 + src/android/AudioManager.cxx | 40 + src/android/AudioManager.hxx | 22 + src/android/Context.cxx | 64 + src/android/Context.hxx | 37 + src/android/Environment.cxx | 66 + src/android/Environment.hxx | 29 + src/android/LogListener.cxx | 24 + src/android/LogListener.hxx | 18 + src/apple/AudioObject.cxx | 14 + src/apple/AudioObject.hxx | 79 + src/apple/AudioUnit.hxx | 85 + src/apple/ErrorRef.hxx | 53 + src/apple/StringRef.hxx | 47 + src/apple/Throw.cxx | 42 + src/apple/Throw.hxx | 19 + src/apple/meson.build | 25 + src/archive/ArchiveFile.hxx | 32 + src/archive/ArchiveList.cxx | 97 + src/archive/ArchiveList.hxx | 47 + src/archive/ArchivePlugin.cxx | 18 + src/archive/ArchivePlugin.hxx | 46 + src/archive/ArchiveVisitor.hxx | 12 + src/archive/meson.build | 38 + src/archive/plugins/Bzip2ArchivePlugin.cxx | 179 + src/archive/plugins/Bzip2ArchivePlugin.hxx | 11 + src/archive/plugins/Iso9660ArchivePlugin.cxx | 323 ++ src/archive/plugins/Iso9660ArchivePlugin.hxx | 11 + src/archive/plugins/ZzipArchivePlugin.cxx | 186 ++ src/archive/plugins/ZzipArchivePlugin.hxx | 11 + src/archive/plugins/meson.build | 47 + src/client/BackgroundCommand.hxx | 31 + src/client/Client.cxx | 108 + src/client/Client.hxx | 307 ++ src/client/Config.cxx | 31 + src/client/Config.hxx | 18 + src/client/Domain.cxx | 7 + src/client/Domain.hxx | 9 + src/client/Event.cxx | 21 + src/client/Expire.cxx | 35 + src/client/File.cxx | 32 + src/client/IClient.hxx | 39 + src/client/Idle.cxx | 69 + src/client/List.cxx | 20 + src/client/List.hxx | 42 + src/client/Listener.cxx | 40 + src/client/Listener.hxx | 23 + src/client/Message.cxx | 23 + src/client/Message.hxx | 40 + src/client/New.cxx | 97 + src/client/Process.cxx | 145 + src/client/ProtocolFeature.cxx | 74 + src/client/ProtocolFeature.hxx | 110 + src/client/Read.cxx | 62 + src/client/Response.cxx | 66 + src/client/Response.hxx | 88 + src/client/Subscribe.cxx | 70 + src/client/ThreadBackgroundCommand.cxx | 59 + src/client/ThreadBackgroundCommand.hxx | 63 + src/client/Write.cxx | 13 + src/cmdline/OptionDef.hxx | 63 + src/cmdline/OptionParser.cxx | 80 + src/cmdline/OptionParser.hxx | 62 + src/cmdline/meson.build | 12 + src/command/AllCommands.cxx | 438 +++ src/command/AllCommands.hxx | 17 + src/command/ClientCommands.cxx | 182 ++ src/command/ClientCommands.hxx | 31 + src/command/CommandError.cxx | 104 + src/command/CommandError.hxx | 17 + src/command/CommandListBuilder.cxx | 26 + src/command/CommandListBuilder.hxx | 90 + src/command/CommandResult.hxx | 56 + src/command/DatabaseCommands.cxx | 399 +++ src/command/DatabaseCommands.hxx | 49 + src/command/FileCommands.cxx | 412 +++ src/command/FileCommands.hxx | 26 + src/command/FingerprintCommands.cxx | 357 ++ src/command/FingerprintCommands.hxx | 16 + src/command/MessageCommands.cxx | 118 + src/command/MessageCommands.hxx | 28 + src/command/NeighborCommands.cxx | 38 + src/command/NeighborCommands.hxx | 21 + src/command/OtherCommands.cxx | 415 +++ src/command/OtherCommands.hxx | 52 + src/command/OutputCommands.cxx | 115 + src/command/OutputCommands.hxx | 28 + src/command/PartitionCommands.cxx | 168 + src/command/PartitionCommands.hxx | 28 + src/command/PlayerCommands.cxx | 355 ++ src/command/PlayerCommands.hxx | 76 + src/command/PlaylistCommands.cxx | 347 ++ src/command/PlaylistCommands.hxx | 56 + src/command/PositionArg.cxx | 87 + src/command/PositionArg.hxx | 16 + src/command/QueueCommands.cxx | 435 +++ src/command/QueueCommands.hxx | 73 + src/command/Request.hxx | 133 + src/command/StickerCommands.cxx | 571 ++++ src/command/StickerCommands.hxx | 22 + src/command/StorageCommands.cxx | 269 ++ src/command/StorageCommands.hxx | 34 + src/command/TagCommands.cxx | 52 + src/command/TagCommands.hxx | 19 + src/config/Block.cxx | 162 + src/config/Block.hxx | 141 + src/config/Check.cxx | 32 + src/config/Check.hxx | 16 + src/config/Data.cxx | 151 + src/config/Data.hxx | 125 + src/config/Defaults.hxx | 9 + src/config/Domain.cxx | 7 + src/config/Domain.hxx | 9 + src/config/File.cxx | 247 ++ src/config/File.hxx | 13 + src/config/Migrate.cxx | 46 + src/config/Migrate.hxx | 15 + src/config/Net.cxx | 26 + src/config/Net.hxx | 28 + src/config/Option.hxx | 101 + src/config/Param.cxx | 27 + src/config/Param.hxx | 64 + src/config/Parser.cxx | 129 + src/config/Parser.hxx | 48 + src/config/PartitionConfig.cxx | 20 + src/config/PartitionConfig.hxx | 16 + src/config/Path.cxx | 127 + src/config/Path.hxx | 16 + src/config/PlayerConfig.cxx | 57 + src/config/PlayerConfig.hxx | 31 + src/config/QueueConfig.hxx | 11 + src/config/ReplayGainConfig.cxx | 42 + src/config/ReplayGainConfig.hxx | 20 + src/config/Templates.cxx | 116 + src/config/Templates.hxx | 23 + src/config/meson.build | 28 + src/db/Configured.cxx | 70 + src/db/Configured.hxx | 25 + src/db/Count.cxx | 113 + src/db/Count.hxx | 19 + src/db/DatabaseError.hxx | 33 + src/db/DatabaseGlue.cxx | 34 + src/db/DatabaseGlue.hxx | 26 + src/db/DatabaseListener.hxx | 30 + src/db/DatabaseLock.cxx | 10 + src/db/DatabaseLock.hxx | 106 + src/db/DatabasePlaylist.cxx | 66 + src/db/DatabasePlaylist.hxx | 32 + src/db/DatabasePlugin.hxx | 50 + src/db/DatabasePrint.cxx | 214 ++ src/db/DatabasePrint.hxx | 33 + src/db/DatabaseQueue.cxx | 30 + src/db/DatabaseQueue.hxx | 13 + src/db/DatabaseSong.cxx | 48 + src/db/DatabaseSong.hxx | 29 + src/db/Helpers.cxx | 70 + src/db/Helpers.hxx | 14 + src/db/Interface.hxx | 127 + src/db/LightDirectory.hxx | 43 + src/db/PlaylistInfo.hxx | 57 + src/db/PlaylistVector.cxx | 59 + src/db/PlaylistVector.hxx | 43 + src/db/Ptr.hxx | 13 + src/db/Registry.cxx | 32 + src/db/Registry.hxx | 19 + src/db/Selection.cxx | 36 + src/db/Selection.hxx | 59 + src/db/Stats.hxx | 37 + src/db/UniqueTags.cxx | 37 + src/db/UniqueTags.hxx | 23 + src/db/Uri.hxx | 15 + src/db/VHelper.cxx | 93 + src/db/VHelper.hxx | 54 + src/db/Visitor.hxx | 21 + src/db/meson.build | 73 + src/db/plugins/ProxyDatabasePlugin.cxx | 989 ++++++ src/db/plugins/ProxyDatabasePlugin.hxx | 11 + src/db/plugins/meson.build | 52 + src/db/plugins/simple/DatabaseSave.cxx | 125 + src/db/plugins/simple/DatabaseSave.hxx | 24 + src/db/plugins/simple/Directory.cxx | 279 ++ src/db/plugins/simple/Directory.hxx | 298 ++ src/db/plugins/simple/DirectorySave.cxx | 182 ++ src/db/plugins/simple/DirectorySave.hxx | 20 + src/db/plugins/simple/ExportedSong.hxx | 51 + src/db/plugins/simple/Mount.cxx | 87 + src/db/plugins/simple/Mount.hxx | 21 + src/db/plugins/simple/PrefixedLightSong.hxx | 27 + src/db/plugins/simple/Ptr.hxx | 13 + .../plugins/simple/SimpleDatabasePlugin.cxx | 472 +++ .../plugins/simple/SimpleDatabasePlugin.hxx | 141 + src/db/plugins/simple/Song.cxx | 134 + src/db/plugins/simple/Song.hxx | 148 + src/db/plugins/simple/SongSort.cxx | 92 + src/db/plugins/simple/SongSort.hxx | 14 + .../plugins/upnp/ContentDirectoryService.cxx | 124 + src/db/plugins/upnp/Directory.cxx | 223 ++ src/db/plugins/upnp/Directory.hxx | 47 + src/db/plugins/upnp/Object.cxx | 7 + src/db/plugins/upnp/Object.hxx | 90 + src/db/plugins/upnp/Tags.cxx | 16 + src/db/plugins/upnp/Tags.hxx | 12 + src/db/plugins/upnp/UpnpDatabasePlugin.cxx | 630 ++++ src/db/plugins/upnp/UpnpDatabasePlugin.hxx | 11 + src/db/update/Archive.cxx | 162 + src/db/update/Config.cxx | 21 + src/db/update/Config.hxx | 21 + src/db/update/Container.cxx | 87 + src/db/update/CueValidator.cxx | 162 + src/db/update/CueValidator.hxx | 22 + src/db/update/Editor.cxx | 97 + src/db/update/Editor.hxx | 52 + src/db/update/ExcludeList.cxx | 74 + src/db/update/ExcludeList.hxx | 64 + src/db/update/FilteredSongUpdate.cxx | 70 + src/db/update/FilteredSongUpdate.hxx | 24 + src/db/update/InotifyDomain.cxx | 7 + src/db/update/InotifyDomain.hxx | 9 + src/db/update/InotifyQueue.cxx | 90 + src/db/update/InotifyQueue.hxx | 32 + src/db/update/InotifyUpdate.cxx | 284 ++ src/db/update/InotifyUpdate.hxx | 39 + src/db/update/Playlist.cxx | 168 + src/db/update/Queue.cxx | 50 + src/db/update/Queue.hxx | 60 + src/db/update/Remove.cxx | 52 + src/db/update/Remove.hxx | 46 + src/db/update/Service.cxx | 243 ++ src/db/update/Service.hxx | 103 + src/db/update/SpecialDirectory.cxx | 71 + src/db/update/UpdateDomain.cxx | 7 + src/db/update/UpdateDomain.hxx | 9 + src/db/update/UpdateIO.cxx | 90 + src/db/update/UpdateIO.hxx | 45 + src/db/update/UpdateSong.cxx | 120 + src/db/update/VirtualDirectory.cxx | 49 + src/db/update/Walk.cxx | 538 +++ src/db/update/Walk.hxx | 167 + src/decoder/Bridge.cxx | 628 ++++ src/decoder/Bridge.hxx | 194 ++ src/decoder/Client.hxx | 173 + src/decoder/Command.hxx | 16 + src/decoder/Control.cxx | 157 + src/decoder/Control.hxx | 451 +++ src/decoder/DecoderAPI.cxx | 75 + src/decoder/DecoderAPI.hxx | 89 + src/decoder/DecoderBuffer.cxx | 51 + src/decoder/DecoderBuffer.hxx | 96 + src/decoder/DecoderList.cxx | 193 ++ src/decoder/DecoderList.hxx | 73 + src/decoder/DecoderPlugin.cxx | 50 + src/decoder/DecoderPlugin.hxx | 256 ++ src/decoder/DecoderPrint.cxx | 42 + src/decoder/DecoderPrint.hxx | 12 + src/decoder/Domain.cxx | 7 + src/decoder/Domain.hxx | 9 + src/decoder/Reader.cxx | 11 + src/decoder/Reader.hxx | 36 + src/decoder/Thread.cxx | 686 ++++ src/decoder/meson.build | 44 + src/decoder/plugins/AdPlugDecoderPlugin.cxx | 113 + src/decoder/plugins/AdPlugDecoderPlugin.h | 9 + .../plugins/AudiofileDecoderPlugin.cxx | 268 ++ .../plugins/AudiofileDecoderPlugin.hxx | 9 + src/decoder/plugins/DffDecoderPlugin.cxx | 355 ++ src/decoder/plugins/DffDecoderPlugin.hxx | 25 + src/decoder/plugins/DsdLib.cxx | 139 + src/decoder/plugins/DsdLib.hxx | 46 + src/decoder/plugins/DsdiffDecoderPlugin.cxx | 490 +++ src/decoder/plugins/DsdiffDecoderPlugin.hxx | 9 + src/decoder/plugins/DsfDecoderPlugin.cxx | 354 ++ src/decoder/plugins/DsfDecoderPlugin.hxx | 9 + src/decoder/plugins/DvdaIsoDecoderPlugin.cxx | 355 ++ src/decoder/plugins/DvdaIsoDecoderPlugin.hxx | 25 + src/decoder/plugins/FaadDecoderPlugin.cxx | 418 +++ src/decoder/plugins/FaadDecoderPlugin.hxx | 9 + src/decoder/plugins/FfmpegDecoderPlugin.cxx | 826 +++++ src/decoder/plugins/FfmpegDecoderPlugin.hxx | 9 + src/decoder/plugins/FfmpegIo.cxx | 105 + src/decoder/plugins/FfmpegIo.hxx | 36 + src/decoder/plugins/FfmpegMetaData.cxx | 81 + src/decoder/plugins/FfmpegMetaData.hxx | 13 + src/decoder/plugins/FlacCommon.cxx | 137 + src/decoder/plugins/FlacCommon.hxx | 90 + src/decoder/plugins/FlacDecoderPlugin.cxx | 409 +++ src/decoder/plugins/FlacDecoderPlugin.h | 10 + src/decoder/plugins/FlacDomain.cxx | 7 + src/decoder/plugins/FlacDomain.hxx | 9 + src/decoder/plugins/FlacInput.cxx | 144 + src/decoder/plugins/FlacInput.hxx | 69 + src/decoder/plugins/FlacPcm.cxx | 91 + src/decoder/plugins/FlacPcm.hxx | 39 + src/decoder/plugins/FlacStreamDecoder.hxx | 52 + .../plugins/FluidsynthDecoderPlugin.cxx | 219 ++ .../plugins/FluidsynthDecoderPlugin.hxx | 9 + src/decoder/plugins/GmeDecoderPlugin.cxx | 334 ++ src/decoder/plugins/GmeDecoderPlugin.hxx | 9 + src/decoder/plugins/MadDecoderPlugin.cxx | 998 ++++++ src/decoder/plugins/MadDecoderPlugin.hxx | 9 + src/decoder/plugins/MikmodDecoderPlugin.cxx | 218 ++ src/decoder/plugins/MikmodDecoderPlugin.hxx | 9 + src/decoder/plugins/ModCommon.cxx | 65 + src/decoder/plugins/ModCommon.hxx | 14 + src/decoder/plugins/ModplugDecoderPlugin.cxx | 145 + src/decoder/plugins/ModplugDecoderPlugin.hxx | 9 + src/decoder/plugins/MpcdecDecoderPlugin.cxx | 275 ++ src/decoder/plugins/MpcdecDecoderPlugin.hxx | 9 + src/decoder/plugins/Mpg123DecoderPlugin.cxx | 545 ++++ src/decoder/plugins/Mpg123DecoderPlugin.hxx | 9 + src/decoder/plugins/OggCodec.cxx | 34 + src/decoder/plugins/OggCodec.hxx | 24 + src/decoder/plugins/OggDecoder.cxx | 133 + src/decoder/plugins/OggDecoder.hxx | 51 + src/decoder/plugins/OpenmptDecoderPlugin.cxx | 158 + src/decoder/plugins/OpenmptDecoderPlugin.hxx | 9 + src/decoder/plugins/OpusDecoderPlugin.cxx | 519 +++ src/decoder/plugins/OpusDecoderPlugin.h | 9 + src/decoder/plugins/OpusDomain.cxx | 7 + src/decoder/plugins/OpusDomain.hxx | 9 + src/decoder/plugins/OpusHead.cxx | 31 + src/decoder/plugins/OpusHead.hxx | 13 + src/decoder/plugins/OpusReader.hxx | 82 + src/decoder/plugins/OpusTags.cxx | 102 + src/decoder/plugins/OpusTags.hxx | 17 + src/decoder/plugins/PcmDecoderPlugin.cxx | 243 ++ src/decoder/plugins/PcmDecoderPlugin.hxx | 17 + src/decoder/plugins/SacdIsoDecoderPlugin.cxx | 490 +++ src/decoder/plugins/SacdIsoDecoderPlugin.hxx | 25 + src/decoder/plugins/SidplayDecoderPlugin.cxx | 512 +++ src/decoder/plugins/SidplayDecoderPlugin.hxx | 9 + src/decoder/plugins/SndfileDecoderPlugin.cxx | 322 ++ src/decoder/plugins/SndfileDecoderPlugin.hxx | 9 + src/decoder/plugins/VorbisDecoderPlugin.cxx | 427 +++ src/decoder/plugins/VorbisDecoderPlugin.h | 9 + src/decoder/plugins/VorbisDomain.cxx | 7 + src/decoder/plugins/VorbisDomain.hxx | 11 + src/decoder/plugins/WavpackDecoderPlugin.cxx | 535 +++ src/decoder/plugins/WavpackDecoderPlugin.hxx | 9 + src/decoder/plugins/WildmidiDecoderPlugin.cxx | 161 + src/decoder/plugins/WildmidiDecoderPlugin.hxx | 9 + src/decoder/plugins/meson.build | 226 ++ src/encoder/Configured.cxx | 40 + src/encoder/Configured.hxx | 23 + src/encoder/EncoderAPI.hxx | 22 + src/encoder/EncoderInterface.hxx | 122 + src/encoder/EncoderList.cxx | 55 + src/encoder/EncoderList.hxx | 27 + src/encoder/EncoderPlugin.hxx | 32 + src/encoder/ToOutputStream.cxx | 23 + src/encoder/ToOutputStream.hxx | 16 + src/encoder/meson.build | 50 + src/encoder/plugins/FlacEncoderPlugin.cxx | 288 ++ src/encoder/plugins/FlacEncoderPlugin.hxx | 9 + src/encoder/plugins/LameEncoderPlugin.cxx | 187 ++ src/encoder/plugins/LameEncoderPlugin.hxx | 9 + src/encoder/plugins/NullEncoderPlugin.cxx | 42 + src/encoder/plugins/NullEncoderPlugin.hxx | 9 + src/encoder/plugins/OggEncoder.hxx | 55 + src/encoder/plugins/OpusEncoderPlugin.cxx | 402 +++ src/encoder/plugins/OpusEncoderPlugin.hxx | 9 + src/encoder/plugins/ShineEncoderPlugin.cxx | 193 ++ src/encoder/plugins/ShineEncoderPlugin.hxx | 9 + src/encoder/plugins/TwolameEncoderPlugin.cxx | 209 ++ src/encoder/plugins/TwolameEncoderPlugin.hxx | 9 + src/encoder/plugins/VorbisEncoderPlugin.cxx | 251 ++ src/encoder/plugins/VorbisEncoderPlugin.hxx | 9 + src/encoder/plugins/WaveEncoderPlugin.cxx | 217 ++ src/encoder/plugins/WaveEncoderPlugin.hxx | 9 + src/encoder/plugins/meson.build | 80 + src/event/Backend.hxx | 26 + src/event/BackendEvents.hxx | 22 + src/event/BufferedSocket.cxx | 102 + src/event/BufferedSocket.hxx | 122 + src/event/Call.cxx | 55 + src/event/Call.hxx | 17 + src/event/Chrono.hxx | 18 + src/event/CoarseTimerEvent.cxx | 31 + src/event/CoarseTimerEvent.hxx | 78 + src/event/DeferEvent.cxx | 32 + src/event/DeferEvent.hxx | 70 + src/event/EpollBackend.hxx | 70 + src/event/EpollEvents.hxx | 21 + src/event/FarTimerEvent.hxx | 20 + src/event/FineTimerEvent.cxx | 47 + src/event/FineTimerEvent.hxx | 104 + src/event/FullyBufferedSocket.cxx | 97 + src/event/FullyBufferedSocket.hxx | 65 + src/event/IdleEvent.hxx | 42 + src/event/InjectEvent.cxx | 17 + src/event/InjectEvent.hxx | 48 + src/event/InotifyEvent.cxx | 106 + src/event/InotifyEvent.hxx | 114 + src/event/InotifyManager.cxx | 104 + src/event/InotifyManager.hxx | 112 + src/event/Loop.cxx | 620 ++++ src/event/Loop.hxx | 373 +++ src/event/MaskMonitor.cxx | 19 + src/event/MaskMonitor.hxx | 46 + src/event/MultiSocketMonitor.cxx | 134 + src/event/MultiSocketMonitor.hxx | 248 ++ src/event/PipeEvent.hxx | 97 + src/event/PollBackend.cxx | 84 + src/event/PollBackend.hxx | 47 + src/event/PollEvents.hxx | 19 + src/event/PollResultGeneric.hxx | 49 + src/event/ServerSocket.cxx | 386 +++ src/event/ServerSocket.hxx | 137 + src/event/SignalMonitor.cxx | 207 ++ src/event/SignalMonitor.hxx | 50 + src/event/SocketEvent.cxx | 106 + src/event/SocketEvent.hxx | 204 ++ src/event/Thread.cxx | 92 + src/event/Thread.hxx | 37 + src/event/TimerList.cxx | 46 + src/event/TimerList.hxx | 43 + src/event/TimerWheel.cxx | 145 + src/event/TimerWheel.hxx | 117 + src/event/WakeFD.hxx | 41 + src/event/WinSelectBackend.cxx | 154 + src/event/WinSelectBackend.hxx | 116 + src/event/WinSelectEvents.hxx | 25 + src/event/meson.build | 60 + src/event/uring/Manager.hxx | 21 + src/filter/Factory.cxx | 23 + src/filter/Factory.hxx | 22 + src/filter/Filter.hxx | 84 + src/filter/FilterPlugin.hxx | 27 + src/filter/LoadChain.cxx | 40 + src/filter/LoadChain.hxx | 28 + src/filter/LoadOne.cxx | 24 + src/filter/LoadOne.hxx | 23 + src/filter/NullFilter.hxx | 18 + src/filter/Observer.cxx | 114 + src/filter/Observer.hxx | 31 + src/filter/Prepared.hxx | 28 + src/filter/Registry.cxx | 34 + src/filter/Registry.hxx | 19 + src/filter/meson.build | 30 + .../plugins/AutoConvertFilterPlugin.cxx | 56 + .../plugins/AutoConvertFilterPlugin.hxx | 20 + src/filter/plugins/ConvertFilterPlugin.cxx | 118 + src/filter/plugins/ConvertFilterPlugin.hxx | 31 + src/filter/plugins/FfmpegFilter.cxx | 104 + src/filter/plugins/FfmpegFilter.hxx | 62 + src/filter/plugins/FfmpegFilterPlugin.cxx | 114 + src/filter/plugins/FfmpegFilterPlugin.hxx | 11 + src/filter/plugins/HdcdFilterPlugin.cxx | 79 + src/filter/plugins/HdcdFilterPlugin.hxx | 11 + src/filter/plugins/NormalizeFilterPlugin.cxx | 73 + src/filter/plugins/NormalizeFilterPlugin.hxx | 17 + src/filter/plugins/NullFilterPlugin.cxx | 32 + src/filter/plugins/NullFilterPlugin.hxx | 11 + src/filter/plugins/ReplayGainFilterPlugin.cxx | 217 ++ src/filter/plugins/ReplayGainFilterPlugin.hxx | 49 + src/filter/plugins/RouteFilterPlugin.cxx | 260 ++ src/filter/plugins/RouteFilterPlugin.hxx | 11 + src/filter/plugins/TwoFilters.cxx | 100 + src/filter/plugins/TwoFilters.hxx | 66 + src/filter/plugins/VolumeFilterPlugin.cxx | 71 + src/filter/plugins/VolumeFilterPlugin.hxx | 21 + src/filter/plugins/meson.build | 38 + src/fs/AllocatedPath.cxx | 61 + src/fs/AllocatedPath.hxx | 344 ++ src/fs/Charset.cxx | 111 + src/fs/Charset.hxx | 41 + src/fs/Config.cxx | 28 + src/fs/Config.hxx | 20 + src/fs/DirectoryReader.cxx | 28 + src/fs/DirectoryReader.hxx | 137 + src/fs/Domain.cxx | 7 + src/fs/Domain.hxx | 9 + src/fs/Features.hxx | 17 + src/fs/FileInfo.cxx | 68 + src/fs/FileInfo.hxx | 116 + src/fs/FileSystem.cxx | 81 + src/fs/FileSystem.hxx | 155 + src/fs/Glob.cxx | 20 + src/fs/Glob.hxx | 49 + src/fs/Limits.hxx | 20 + src/fs/List.cxx | 49 + src/fs/List.hxx | 20 + src/fs/LookupFile.cxx | 78 + src/fs/LookupFile.hxx | 40 + src/fs/NarrowPath.cxx | 38 + src/fs/NarrowPath.hxx | 86 + src/fs/Path.cxx | 45 + src/fs/Path.hxx | 193 ++ src/fs/Path2.cxx | 31 + src/fs/Traits.cxx | 240 ++ src/fs/Traits.hxx | 358 ++ src/fs/XDG.hxx | 12 + src/fs/glue/CheckFile.cxx | 45 + src/fs/glue/CheckFile.hxx | 13 + src/fs/glue/StandardDirectory.cxx | 442 +++ src/fs/glue/StandardDirectory.hxx | 84 + src/fs/glue/meson.build | 17 + src/fs/meson.build | 39 + src/input/AsyncInputStream.cxx | 301 ++ src/input/AsyncInputStream.hxx | 161 + src/input/BufferedInputStream.cxx | 56 + src/input/BufferedInputStream.hxx | 53 + src/input/BufferingInputStream.cxx | 188 ++ src/input/BufferingInputStream.hxx | 124 + src/input/CondHandler.hxx | 26 + src/input/Error.cxx | 39 + src/input/Error.hxx | 18 + src/input/FailingInputStream.hxx | 46 + src/input/Handler.hxx | 35 + src/input/IcyInputStream.cxx | 91 + src/input/IcyInputStream.hxx | 59 + src/input/Init.cxx | 79 + src/input/Init.hxx | 34 + src/input/InputPlugin.cxx | 57 + src/input/InputPlugin.hxx | 93 + src/input/InputStream.cxx | 145 + src/input/InputStream.hxx | 418 +++ src/input/LastInputStream.cxx | 31 + src/input/LastInputStream.hxx | 70 + src/input/LocalOpen.cxx | 56 + src/input/LocalOpen.hxx | 21 + src/input/MaybeBufferedInputStream.cxx | 21 + src/input/MaybeBufferedInputStream.hxx | 22 + src/input/MemoryInputStream.cxx | 28 + src/input/MemoryInputStream.hxx | 29 + src/input/Offset.hxx | 11 + src/input/Open.cxx | 40 + src/input/ProxyInputStream.cxx | 115 + src/input/ProxyInputStream.hxx | 81 + src/input/Ptr.hxx | 13 + src/input/Reader.cxx | 14 + src/input/Reader.hxx | 26 + src/input/Registry.cxx | 82 + src/input/Registry.hxx | 35 + src/input/RemoteTagScanner.hxx | 46 + src/input/RewindInputStream.cxx | 137 + src/input/RewindInputStream.hxx | 19 + src/input/ScanTags.cxx | 22 + src/input/ScanTags.hxx | 22 + src/input/TextInputStream.cxx | 65 + src/input/TextInputStream.hxx | 41 + src/input/ThreadInputStream.cxx | 202 ++ src/input/ThreadInputStream.hxx | 161 + src/input/WaitReady.cxx | 27 + src/input/WaitReady.hxx | 14 + src/input/cache/Config.cxx | 19 + src/input/cache/Config.hxx | 17 + src/input/cache/Item.cxx | 47 + src/input/cache/Item.hxx | 58 + src/input/cache/Lease.hxx | 77 + src/input/cache/Manager.cxx | 145 + src/input/cache/Manager.hxx | 82 + src/input/cache/Stream.cxx | 80 + src/input/cache/Stream.hxx | 33 + src/input/meson.build | 86 + src/input/plugins/AlsaInputPlugin.cxx | 470 +++ src/input/plugins/AlsaInputPlugin.hxx | 12 + src/input/plugins/ArchiveInputPlugin.cxx | 48 + src/input/plugins/ArchiveInputPlugin.hxx | 15 + src/input/plugins/CdioParanoiaInputPlugin.cxx | 355 ++ src/input/plugins/CdioParanoiaInputPlugin.hxx | 12 + src/input/plugins/CurlInputPlugin.cxx | 659 ++++ src/input/plugins/CurlInputPlugin.hxx | 23 + src/input/plugins/FfmpegInputPlugin.cxx | 126 + src/input/plugins/FfmpegInputPlugin.hxx | 12 + src/input/plugins/FileInputPlugin.cxx | 90 + src/input/plugins/FileInputPlugin.hxx | 15 + src/input/plugins/MmsInputPlugin.cxx | 99 + src/input/plugins/MmsInputPlugin.hxx | 9 + src/input/plugins/NfsInputPlugin.cxx | 243 ++ src/input/plugins/NfsInputPlugin.hxx | 17 + src/input/plugins/QobuzClient.cxx | 199 ++ src/input/plugins/QobuzClient.hxx | 97 + src/input/plugins/QobuzErrorParser.cxx | 24 + src/input/plugins/QobuzErrorParser.hxx | 10 + src/input/plugins/QobuzInputPlugin.cxx | 206 ++ src/input/plugins/QobuzInputPlugin.hxx | 9 + src/input/plugins/QobuzLoginRequest.cxx | 96 + src/input/plugins/QobuzLoginRequest.hxx | 42 + src/input/plugins/QobuzSession.hxx | 16 + src/input/plugins/QobuzTagScanner.cxx | 84 + src/input/plugins/QobuzTagScanner.hxx | 36 + src/input/plugins/QobuzTrackRequest.cxx | 60 + src/input/plugins/QobuzTrackRequest.hxx | 43 + src/input/plugins/SmbclientInputPlugin.cxx | 137 + src/input/plugins/SmbclientInputPlugin.hxx | 9 + src/input/plugins/UringInputPlugin.cxx | 201 ++ src/input/plugins/UringInputPlugin.hxx | 18 + src/input/plugins/meson.build | 92 + src/io/BufferedOutputStream.cxx | 110 + src/io/BufferedOutputStream.hxx | 122 + src/io/BufferedReader.cxx | 104 + src/io/BufferedReader.hxx | 86 + src/io/FileAt.hxx | 16 + src/io/FileDescriptor.cxx | 336 ++ src/io/FileDescriptor.hxx | 292 ++ src/io/FileLineReader.hxx | 24 + src/io/FileOutputStream.cxx | 366 +++ src/io/FileOutputStream.hxx | 191 ++ src/io/FileReader.cxx | 113 + src/io/FileReader.hxx | 102 + src/io/LineReader.hxx | 17 + src/io/Open.cxx | 125 + src/io/Open.hxx | 60 + src/io/OutputStream.hxx | 18 + src/io/PeekReader.cxx | 44 + src/io/PeekReader.hxx | 33 + src/io/Reader.cxx | 14 + src/io/Reader.hxx | 42 + src/io/StdioOutputStream.hxx | 22 + src/io/StringOutputStream.hxx | 27 + src/io/UniqueFileDescriptor.hxx | 74 + src/io/linux/ProcPath.hxx | 31 + src/io/meson.build | 39 + src/io/uring/CancellableOperation.hxx | 70 + src/io/uring/Close.cxx | 26 + src/io/uring/Close.hxx | 21 + src/io/uring/Operation.cxx | 32 + src/io/uring/Operation.hxx | 70 + src/io/uring/Queue.cxx | 116 + src/io/uring/Queue.hxx | 116 + src/io/uring/ReadOperation.cxx | 43 + src/io/uring/ReadOperation.hxx | 62 + src/io/uring/Ring.cxx | 92 + src/io/uring/Ring.hxx | 160 + src/io/uring/meson.build | 43 + src/java/Class.hxx | 56 + src/java/Exception.cxx | 22 + src/java/Exception.hxx | 38 + src/java/File.cxx | 34 + src/java/File.hxx | 53 + src/java/Global.cxx | 15 + src/java/Global.hxx | 33 + src/java/Object.cxx | 19 + src/java/Object.hxx | 42 + src/java/Ref.hxx | 178 + src/java/String.cxx | 29 + src/java/String.hxx | 117 + src/java/meson.build | 19 + src/lib/alsa/AllowedFormat.cxx | 70 + src/lib/alsa/AllowedFormat.hxx | 42 + src/lib/alsa/ChannelMap.cxx | 263 ++ src/lib/alsa/ChannelMap.hxx | 22 + src/lib/alsa/Error.cxx | 19 + src/lib/alsa/Error.hxx | 27 + src/lib/alsa/Format.hxx | 104 + src/lib/alsa/HwSetup.cxx | 287 ++ src/lib/alsa/HwSetup.hxx | 36 + src/lib/alsa/NonBlock.cxx | 95 + src/lib/alsa/NonBlock.hxx | 70 + src/lib/alsa/PeriodBuffer.hxx | 187 ++ src/lib/alsa/Version.cxx | 38 + src/lib/alsa/Version.hxx | 24 + src/lib/alsa/meson.build | 35 + src/lib/avahi/Client.cxx | 123 + src/lib/avahi/Client.hxx | 71 + src/lib/avahi/ConnectionListener.hxx | 33 + src/lib/avahi/EntryGroup.hxx | 21 + src/lib/avahi/Error.cxx | 28 + src/lib/avahi/Error.hxx | 33 + src/lib/avahi/ErrorHandler.hxx | 22 + src/lib/avahi/Poll.cxx | 159 + src/lib/avahi/Poll.hxx | 38 + src/lib/avahi/Publisher.cxx | 259 ++ src/lib/avahi/Publisher.hxx | 112 + src/lib/avahi/Service.hxx | 38 + src/lib/cdio/Paranoia.hxx | 134 + src/lib/chromaprint/Context.hxx | 58 + src/lib/chromaprint/DecoderClient.cxx | 79 + src/lib/chromaprint/DecoderClient.hxx | 92 + src/lib/chromaprint/meson.build | 2 + src/lib/crypto/Base64.cxx | 40 + src/lib/crypto/Base64.hxx | 36 + src/lib/crypto/MD5.cxx | 45 + src/lib/crypto/MD5.hxx | 18 + src/lib/crypto/meson.build | 38 + src/lib/curl/Adapter.cxx | 167 + src/lib/curl/Adapter.hxx | 65 + src/lib/curl/Delegate.cxx | 28 + src/lib/curl/Delegate.hxx | 43 + src/lib/curl/Easy.hxx | 231 ++ src/lib/curl/Error.hxx | 31 + src/lib/curl/Escape.cxx | 45 + src/lib/curl/Escape.hxx | 24 + src/lib/curl/Form.cxx | 28 + src/lib/curl/Form.hxx | 20 + src/lib/curl/Global.cxx | 218 ++ src/lib/curl/Global.hxx | 56 + src/lib/curl/Handler.hxx | 55 + src/lib/curl/Headers.hxx | 14 + src/lib/curl/HttpStatusError.hxx | 23 + src/lib/curl/Init.cxx | 44 + src/lib/curl/Init.hxx | 45 + src/lib/curl/Multi.hxx | 109 + src/lib/curl/Parser.hxx | 13 + src/lib/curl/Request.cxx | 103 + src/lib/curl/Request.hxx | 99 + src/lib/curl/Setup.cxx | 23 + src/lib/curl/Setup.hxx | 13 + src/lib/curl/Slist.hxx | 48 + src/lib/curl/String.hxx | 48 + src/lib/curl/StringHandler.cxx | 30 + src/lib/curl/StringHandler.hxx | 43 + src/lib/curl/StringResponse.hxx | 15 + src/lib/curl/Version.cxx | 13 + src/lib/curl/Version.hxx | 11 + src/lib/curl/meson.build | 41 + src/lib/dbus/AppendIter.hxx | 188 ++ src/lib/dbus/AsyncRequest.hxx | 83 + src/lib/dbus/Connection.cxx | 33 + src/lib/dbus/Connection.hxx | 62 + src/lib/dbus/Error.cxx | 19 + src/lib/dbus/Error.hxx | 52 + src/lib/dbus/FilterHelper.cxx | 24 + src/lib/dbus/FilterHelper.hxx | 76 + src/lib/dbus/Glue.cxx | 43 + src/lib/dbus/Glue.hxx | 50 + src/lib/dbus/Init.hxx | 26 + src/lib/dbus/Iter.hxx | 22 + src/lib/dbus/Message.cxx | 53 + src/lib/dbus/Message.hxx | 124 + src/lib/dbus/ObjectManager.hxx | 57 + src/lib/dbus/PendingCall.hxx | 77 + src/lib/dbus/ReadIter.hxx | 116 + src/lib/dbus/ScopeMatch.cxx | 14 + src/lib/dbus/ScopeMatch.hxx | 30 + src/lib/dbus/Types.hxx | 90 + src/lib/dbus/UDisks2.cxx | 175 + src/lib/dbus/UDisks2.hxx | 86 + src/lib/dbus/Values.hxx | 97 + src/lib/dbus/Watch.cxx | 110 + src/lib/dbus/Watch.hxx | 129 + src/lib/dbus/meson.build | 39 + src/lib/dvdaiso/audio_stream.cpp | 173 + src/lib/dvdaiso/audio_stream.h | 104 + src/lib/dvdaiso/audio_stream_info.cpp | 130 + src/lib/dvdaiso/audio_stream_info.h | 89 + src/lib/dvdaiso/audio_track.cpp | 136 + src/lib/dvdaiso/audio_track.h | 63 + src/lib/dvdaiso/b2n.h | 22 + src/lib/dvdaiso/dvda_block.cpp | 82 + src/lib/dvdaiso/dvda_block.h | 66 + src/lib/dvdaiso/dvda_config.h | 23 + src/lib/dvdaiso/dvda_disc.cpp | 416 +++ src/lib/dvdaiso/dvda_disc.h | 83 + src/lib/dvdaiso/dvda_error.h | 61 + src/lib/dvdaiso/dvda_filesystem.cpp | 126 + src/lib/dvdaiso/dvda_filesystem.h | 60 + src/lib/dvdaiso/dvda_media.cpp | 172 + src/lib/dvdaiso/dvda_media.h | 75 + src/lib/dvdaiso/dvda_metabase.cpp | 297 ++ src/lib/dvdaiso/dvda_metabase.h | 47 + src/lib/dvdaiso/dvda_reader.h | 47 + src/lib/dvdaiso/dvda_zone.cpp | 385 +++ src/lib/dvdaiso/dvda_zone.h | 212 ++ src/lib/dvdaiso/dvdaerror.h | 61 + src/lib/dvdaiso/ifo.h | 948 ++++++ src/lib/dvdaiso/log_trunk.cpp | 64 + src/lib/dvdaiso/log_trunk.h | 30 + src/lib/dvdaiso/meson.build | 26 + src/lib/dvdaiso/mlp_audio_stream.cpp | 472 +++ src/lib/dvdaiso/mlp_audio_stream.h | 46 + src/lib/dvdaiso/pcm_audio_stream.cpp | 183 ++ src/lib/dvdaiso/pcm_audio_stream.h | 39 + src/lib/dvdaiso/stream_buffer.h | 148 + src/lib/dvdaiso/udf/dvd_input.cpp | 24 + src/lib/dvdaiso/udf/dvd_input.h | 32 + src/lib/dvdaiso/udf/dvd_reader.cpp | 185 ++ src/lib/dvdaiso/udf/dvd_reader.h | 133 + src/lib/dvdaiso/udf/dvd_udf.cpp | 973 ++++++ src/lib/dvdaiso/udf/dvd_udf.h | 67 + src/lib/expat/ExpatParser.cxx | 36 + src/lib/expat/ExpatParser.hxx | 137 + src/lib/expat/StreamExpatParser.cxx | 23 + src/lib/expat/meson.build | 24 + src/lib/ffmpeg/Buffer.hxx | 39 + src/lib/ffmpeg/ChannelLayout.hxx | 50 + src/lib/ffmpeg/Codec.hxx | 71 + src/lib/ffmpeg/DetectFilterFormat.cxx | 75 + src/lib/ffmpeg/DetectFilterFormat.hxx | 33 + src/lib/ffmpeg/Domain.cxx | 7 + src/lib/ffmpeg/Domain.hxx | 11 + src/lib/ffmpeg/Error.cxx | 25 + src/lib/ffmpeg/Error.hxx | 15 + src/lib/ffmpeg/Filter.cxx | 135 + src/lib/ffmpeg/Filter.hxx | 164 + src/lib/ffmpeg/Format.hxx | 65 + src/lib/ffmpeg/Frame.hxx | 68 + src/lib/ffmpeg/IOContext.hxx | 81 + src/lib/ffmpeg/Init.cxx | 18 + src/lib/ffmpeg/Init.hxx | 10 + src/lib/ffmpeg/Interleave.cxx | 57 + src/lib/ffmpeg/Interleave.hxx | 25 + src/lib/ffmpeg/LibFmt.hxx | 23 + src/lib/ffmpeg/LogCallback.cxx | 53 + src/lib/ffmpeg/LogCallback.hxx | 12 + src/lib/ffmpeg/SampleFormat.hxx | 64 + src/lib/ffmpeg/Time.hxx | 95 + src/lib/ffmpeg/meson.build | 79 + src/lib/fmt/AudioFormatFormatter.hxx | 32 + src/lib/fmt/ExceptionFormatter.cxx | 12 + src/lib/fmt/ExceptionFormatter.hxx | 14 + src/lib/fmt/PathFormatter.hxx | 19 + src/lib/fmt/RuntimeError.cxx | 19 + src/lib/fmt/RuntimeError.hxx | 34 + src/lib/fmt/SocketAddressFormatter.cxx | 20 + src/lib/fmt/SocketAddressFormatter.hxx | 21 + src/lib/fmt/SystemError.cxx | 43 + src/lib/fmt/SystemError.hxx | 95 + src/lib/fmt/ToBuffer.hxx | 46 + src/lib/fmt/Unsafe.hxx | 45 + src/lib/fmt/meson.build | 25 + src/lib/gcrypt/Hash.hxx | 24 + src/lib/gcrypt/Init.hxx | 19 + src/lib/gcrypt/MD5.cxx | 15 + src/lib/gcrypt/MD5.hxx | 15 + src/lib/gcrypt/meson.build | 40 + src/lib/icu/Canonicalize.cxx | 76 + src/lib/icu/Canonicalize.hxx | 34 + src/lib/icu/Collate.cxx | 111 + src/lib/icu/Collate.hxx | 22 + src/lib/icu/Compare.cxx | 127 + src/lib/icu/Compare.hxx | 64 + src/lib/icu/Converter.cxx | 146 + src/lib/icu/Converter.hxx | 79 + src/lib/icu/Error.hxx | 31 + src/lib/icu/FoldCase.cxx | 25 + src/lib/icu/FoldCase.hxx | 17 + src/lib/icu/Init.cxx | 30 + src/lib/icu/Init.hxx | 35 + src/lib/icu/Normalize.cxx | 45 + src/lib/icu/Normalize.hxx | 24 + src/lib/icu/Transliterator.cxx | 52 + src/lib/icu/Transliterator.hxx | 50 + src/lib/icu/Util.cxx | 54 + src/lib/icu/Util.hxx | 30 + src/lib/icu/Win32.cxx | 48 + src/lib/icu/Win32.hxx | 26 + src/lib/icu/meson.build | 52 + src/lib/modplug/patches/no_register | 22 + src/lib/modplug/patches/series | 1 + src/lib/nfs/Base.cxx | 43 + src/lib/nfs/Base.hxx | 24 + src/lib/nfs/Blocking.cxx | 67 + src/lib/nfs/Blocking.hxx | 74 + src/lib/nfs/Callback.hxx | 27 + src/lib/nfs/Cancellable.hxx | 145 + src/lib/nfs/Connection.cxx | 699 ++++ src/lib/nfs/Connection.hxx | 290 ++ src/lib/nfs/Error.cxx | 47 + src/lib/nfs/Error.hxx | 27 + src/lib/nfs/FileReader.cxx | 327 ++ src/lib/nfs/FileReader.hxx | 156 + src/lib/nfs/Glue.cxx | 57 + src/lib/nfs/Glue.hxx | 37 + src/lib/nfs/Lease.hxx | 29 + src/lib/nfs/Manager.cxx | 126 + src/lib/nfs/Manager.hxx | 75 + src/lib/nfs/meson.build | 37 + src/lib/nlohmann_json/meson.build | 14 + src/lib/oss/meson.build | 15 + src/lib/pcre/Error.cxx | 21 + src/lib/pcre/Error.hxx | 28 + src/lib/pcre/MatchData.hxx | 99 + src/lib/pcre/RegexPointer.hxx | 49 + src/lib/pcre/UniqueRegex.cxx | 29 + src/lib/pcre/UniqueRegex.hxx | 67 + src/lib/pcre/meson.build | 28 + src/lib/pipewire/Error.cxx | 18 + src/lib/pipewire/Error.hxx | 29 + src/lib/pipewire/ThreadLoop.hxx | 38 + src/lib/pipewire/meson.build | 30 + src/lib/pulse/Domain.cxx | 7 + src/lib/pulse/Domain.hxx | 11 + src/lib/pulse/Error.cxx | 25 + src/lib/pulse/Error.hxx | 34 + src/lib/pulse/LockGuard.hxx | 30 + src/lib/pulse/LogError.cxx | 16 + src/lib/pulse/LogError.hxx | 12 + src/lib/pulse/meson.build | 24 + src/lib/sacdiso/endianess.h | 49 + src/lib/sacdiso/libdstdec/ac.h | 152 + .../sacdiso/libdstdec/binding/dst_decoder.cpp | 56 + .../sacdiso/libdstdec/binding/dst_decoder.h | 33 + .../sacdiso/libdstdec/binding/dst_engine.h | 183 ++ .../sacdiso/libdstdec/binding/std_semaphore.h | 48 + src/lib/sacdiso/libdstdec/common.h | 25 + src/lib/sacdiso/libdstdec/consts.h | 47 + src/lib/sacdiso/libdstdec/ct.h | 83 + src/lib/sacdiso/libdstdec/ct_enc.h | 230 ++ src/lib/sacdiso/libdstdec/decoder/decoder.cpp | 322 ++ src/lib/sacdiso/libdstdec/decoder/decoder.h | 55 + src/lib/sacdiso/libdstdec/fh.h | 77 + src/lib/sacdiso/libdstdec/fr.h | 418 +++ src/lib/sacdiso/libdstdec/segment.h | 35 + src/lib/sacdiso/libdstdec/stream.h | 78 + src/lib/sacdiso/log_printf.cpp | 35 + src/lib/sacdiso/log_printf.h | 25 + src/lib/sacdiso/meson.build | 31 + src/lib/sacdiso/sacd_disc.cpp | 824 +++++ src/lib/sacdiso/sacd_disc.h | 101 + src/lib/sacdiso/sacd_dsd.h | 55 + src/lib/sacdiso/sacd_dsdiff.cpp | 499 +++ src/lib/sacdiso/sacd_dsdiff.h | 125 + src/lib/sacdiso/sacd_media.cpp | 164 + src/lib/sacdiso/sacd_media.h | 68 + src/lib/sacdiso/sacd_metabase.cpp | 255 ++ src/lib/sacdiso/sacd_metabase.h | 65 + src/lib/sacdiso/sacd_reader.h | 55 + src/lib/sacdiso/scarletbook.cpp | 72 + src/lib/sacdiso/scarletbook.h | 472 +++ src/lib/smbclient/Context.cxx | 51 + src/lib/smbclient/Context.hxx | 95 + src/lib/smbclient/Domain.cxx | 7 + src/lib/smbclient/Domain.hxx | 11 + src/lib/smbclient/Init.cxx | 11 + src/lib/smbclient/Init.hxx | 15 + src/lib/smbclient/meson.build | 23 + src/lib/sndio/meson.build | 12 + src/lib/sqlite/Database.cxx | 19 + src/lib/sqlite/Database.hxx | 42 + src/lib/sqlite/Error.cxx | 21 + src/lib/sqlite/Error.hxx | 24 + src/lib/sqlite/Util.hxx | 161 + src/lib/sqlite/meson.build | 30 + src/lib/systemd/Watchdog.cxx | 28 + src/lib/systemd/Watchdog.hxx | 30 + src/lib/systemd/meson.build | 23 + src/lib/upnp/Action.cxx | 81 + src/lib/upnp/Action.hxx | 69 + src/lib/upnp/Callback.hxx | 27 + src/lib/upnp/ClientInit.cxx | 72 + src/lib/upnp/ClientInit.hxx | 12 + src/lib/upnp/ContentDirectoryService.cxx | 47 + src/lib/upnp/ContentDirectoryService.hxx | 104 + src/lib/upnp/Device.cxx | 104 + src/lib/upnp/Device.hxx | 53 + src/lib/upnp/Discovery.cxx | 375 +++ src/lib/upnp/Discovery.hxx | 109 + src/lib/upnp/Error.hxx | 31 + src/lib/upnp/Init.cxx | 53 + src/lib/upnp/Init.hxx | 13 + src/lib/upnp/Util.cxx | 52 + src/lib/upnp/Util.hxx | 12 + src/lib/upnp/meson.build | 69 + src/lib/xiph/FlacAudioFormat.hxx | 30 + src/lib/xiph/FlacIOHandle.cxx | 129 + src/lib/xiph/FlacIOHandle.hxx | 28 + src/lib/xiph/FlacMetadataChain.cxx | 33 + src/lib/xiph/FlacMetadataChain.hxx | 65 + src/lib/xiph/FlacMetadataIterator.hxx | 38 + src/lib/xiph/FlacStreamMetadata.cxx | 132 + src/lib/xiph/FlacStreamMetadata.hxx | 29 + src/lib/xiph/OggFind.cxx | 58 + src/lib/xiph/OggFind.hxx | 43 + src/lib/xiph/OggPacket.cxx | 18 + src/lib/xiph/OggPacket.hxx | 19 + src/lib/xiph/OggPage.hxx | 34 + src/lib/xiph/OggStreamState.hxx | 77 + src/lib/xiph/OggSyncState.cxx | 91 + src/lib/xiph/OggSyncState.hxx | 69 + src/lib/xiph/OggVisitor.cxx | 105 + src/lib/xiph/OggVisitor.hxx | 94 + src/lib/xiph/ScanVorbisComment.cxx | 49 + src/lib/xiph/ScanVorbisComment.hxx | 14 + src/lib/xiph/VorbisComment.hxx | 40 + src/lib/xiph/VorbisComments.cxx | 78 + src/lib/xiph/VorbisComments.hxx | 24 + src/lib/xiph/VorbisPicture.cxx | 27 + src/lib/xiph/VorbisPicture.hxx | 14 + src/lib/xiph/XiphTags.cxx | 18 + src/lib/xiph/XiphTags.hxx | 11 + src/lib/xiph/meson.build | 149 + src/lib/zlib/AutoGunzipFileLineReader.cxx | 35 + src/lib/zlib/AutoGunzipFileLineReader.hxx | 43 + src/lib/zlib/AutoGunzipReader.cxx | 43 + src/lib/zlib/AutoGunzipReader.hxx | 33 + src/lib/zlib/Error.hxx | 27 + src/lib/zlib/GunzipReader.cxx | 70 + src/lib/zlib/GunzipReader.hxx | 40 + src/lib/zlib/GzipOutputStream.cxx | 98 + src/lib/zlib/GzipOutputStream.hxx | 48 + src/lib/zlib/meson.build | 25 + src/ls.cxx | 80 + src/ls.hxx | 31 + src/mixer/All.cxx | 181 + src/mixer/Control.cxx | 32 + src/mixer/Control.hxx | 31 + src/mixer/Listener.hxx | 20 + src/mixer/Memento.cxx | 80 + src/mixer/Memento.hxx | 59 + src/mixer/Mixer.cxx | 91 + src/mixer/Mixer.hxx | 125 + src/mixer/MixerPlugin.hxx | 42 + src/mixer/Type.cxx | 26 + src/mixer/Type.hxx | 32 + src/mixer/meson.build | 36 + src/mixer/plugins/AlsaMixerPlugin.cxx | 336 ++ src/mixer/plugins/AlsaMixerPlugin.hxx | 8 + src/mixer/plugins/AndroidMixerPlugin.cxx | 101 + src/mixer/plugins/AndroidMixerPlugin.hxx | 8 + src/mixer/plugins/NullMixerPlugin.cxx | 48 + src/mixer/plugins/NullMixerPlugin.hxx | 8 + src/mixer/plugins/OSXMixerPlugin.cxx | 53 + src/mixer/plugins/OSXMixerPlugin.hxx | 8 + src/mixer/plugins/OssMixerPlugin.cxx | 161 + src/mixer/plugins/OssMixerPlugin.hxx | 8 + src/mixer/plugins/PipeWireMixerPlugin.cxx | 84 + src/mixer/plugins/PipeWireMixerPlugin.hxx | 15 + src/mixer/plugins/PulseMixerPlugin.cxx | 230 ++ src/mixer/plugins/PulseMixerPlugin.hxx | 20 + src/mixer/plugins/SndioMixerPlugin.cxx | 45 + src/mixer/plugins/SndioMixerPlugin.hxx | 8 + src/mixer/plugins/SoftwareMixerPlugin.cxx | 98 + src/mixer/plugins/SoftwareMixerPlugin.hxx | 19 + src/mixer/plugins/VolumeMapping.cxx | 188 ++ src/mixer/plugins/VolumeMapping.hxx | 25 + src/mixer/plugins/WasapiMixerPlugin.cxx | 112 + src/mixer/plugins/WasapiMixerPlugin.hxx | 8 + src/mixer/plugins/WinmmMixerPlugin.cxx | 86 + src/mixer/plugins/WinmmMixerPlugin.hxx | 8 + src/mixer/plugins/meson.build | 62 + src/neighbor/Explorer.hxx | 56 + src/neighbor/Glue.cxx | 84 + src/neighbor/Glue.hxx | 67 + src/neighbor/Info.hxx | 19 + src/neighbor/Listener.hxx | 20 + src/neighbor/NeighborPlugin.hxx | 25 + src/neighbor/Registry.cxx | 34 + src/neighbor/Registry.hxx | 19 + src/neighbor/meson.build | 34 + .../plugins/SmbclientNeighborPlugin.cxx | 253 ++ .../plugins/SmbclientNeighborPlugin.hxx | 11 + src/neighbor/plugins/UdisksNeighborPlugin.cxx | 258 ++ src/neighbor/plugins/UdisksNeighborPlugin.hxx | 11 + src/neighbor/plugins/UpnpNeighborPlugin.cxx | 123 + src/neighbor/plugins/UpnpNeighborPlugin.hxx | 11 + src/neighbor/plugins/meson.build | 41 + src/net/AddressInfo.cxx | 56 + src/net/AddressInfo.hxx | 142 + src/net/AllocatedSocketAddress.cxx | 111 + src/net/AllocatedSocketAddress.hxx | 193 ++ src/net/DscpParser.cxx | 90 + src/net/DscpParser.hxx | 15 + src/net/FormatAddress.cxx | 141 + src/net/FormatAddress.hxx | 36 + src/net/HostParser.cxx | 123 + src/net/HostParser.hxx | 44 + src/net/IPv4Address.cxx | 13 + src/net/IPv4Address.hxx | 210 ++ src/net/IPv6Address.cxx | 67 + src/net/IPv6Address.hxx | 202 ++ src/net/Init.hxx | 28 + src/net/LocalSocketAddress.cxx | 18 + src/net/LocalSocketAddress.hxx | 124 + src/net/MsgHdr.hxx | 62 + src/net/PeerCredentials.hxx | 84 + src/net/Resolver.cxx | 127 + src/net/Resolver.hxx | 31 + src/net/SocketAddress.cxx | 151 + src/net/SocketAddress.hxx | 172 + src/net/SocketDescriptor.cxx | 645 ++++ src/net/SocketDescriptor.hxx | 415 +++ src/net/SocketError.cxx | 46 + src/net/SocketError.hxx | 206 ++ src/net/SocketUtil.cxx | 42 + src/net/SocketUtil.hxx | 38 + src/net/StaticSocketAddress.cxx | 44 + src/net/StaticSocketAddress.hxx | 144 + src/net/ToString.cxx | 116 + src/net/ToString.hxx | 24 + src/net/UniqueSocketDescriptor.hxx | 106 + src/net/meson.build | 71 + src/open.h | 25 + src/output/Client.hxx | 29 + src/output/Control.cxx | 461 +++ src/output/Control.hxx | 654 ++++ src/output/Defaults.cxx | 13 + src/output/Defaults.hxx | 30 + src/output/Domain.cxx | 7 + src/output/Domain.hxx | 9 + src/output/Error.hxx | 13 + src/output/Filtered.cxx | 202 ++ src/output/Filtered.hxx | 235 ++ src/output/Init.cxx | 303 ++ src/output/Interface.cxx | 13 + src/output/Interface.hxx | 210 ++ src/output/MultipleOutputs.cxx | 375 +++ src/output/MultipleOutputs.hxx | 199 ++ src/output/OutputAPI.hxx | 17 + src/output/OutputCommand.cxx | 102 + src/output/OutputCommand.hxx | 37 + src/output/OutputPlugin.cxx | 16 + src/output/OutputPlugin.hxx | 61 + src/output/Print.cxx | 33 + src/output/Print.hxx | 18 + src/output/Registry.cxx | 105 + src/output/Registry.hxx | 21 + src/output/SharedPipeConsumer.cxx | 41 + src/output/SharedPipeConsumer.hxx | 78 + src/output/Source.cxx | 261 ++ src/output/Source.hxx | 215 ++ src/output/State.cxx | 72 + src/output/State.hxx | 30 + src/output/Thread.cxx | 565 ++++ src/output/Timer.cxx | 47 + src/output/Timer.hxx | 40 + src/output/meson.build | 66 + src/output/plugins/AlsaOutputPlugin.cxx | 1367 ++++++++ src/output/plugins/AlsaOutputPlugin.hxx | 9 + src/output/plugins/AoOutputPlugin.cxx | 207 ++ src/output/plugins/AoOutputPlugin.hxx | 9 + src/output/plugins/FifoOutputPlugin.cxx | 223 ++ src/output/plugins/FifoOutputPlugin.hxx | 9 + src/output/plugins/JackOutputPlugin.cxx | 729 +++++ src/output/plugins/JackOutputPlugin.hxx | 9 + src/output/plugins/NullOutputPlugin.cxx | 61 + src/output/plugins/NullOutputPlugin.hxx | 9 + src/output/plugins/OSXOutputPlugin.cxx | 851 +++++ src/output/plugins/OSXOutputPlugin.hxx | 17 + src/output/plugins/OpenALOutputPlugin.cxx | 212 ++ src/output/plugins/OpenALOutputPlugin.hxx | 9 + src/output/plugins/OssOutputPlugin.cxx | 742 +++++ src/output/plugins/OssOutputPlugin.hxx | 9 + src/output/plugins/PipeOutputPlugin.cxx | 66 + src/output/plugins/PipeOutputPlugin.hxx | 9 + src/output/plugins/PipeWireOutputPlugin.cxx | 980 ++++++ src/output/plugins/PipeWireOutputPlugin.hxx | 21 + src/output/plugins/PulseOutputPlugin.cxx | 916 ++++++ src/output/plugins/PulseOutputPlugin.hxx | 25 + src/output/plugins/RecorderOutputPlugin.cxx | 332 ++ src/output/plugins/RecorderOutputPlugin.hxx | 9 + src/output/plugins/ShoutOutputPlugin.cxx | 468 +++ src/output/plugins/ShoutOutputPlugin.hxx | 9 + src/output/plugins/SndioOutputPlugin.cxx | 175 + src/output/plugins/SndioOutputPlugin.hxx | 39 + src/output/plugins/SolarisOutputPlugin.cxx | 150 + src/output/plugins/SolarisOutputPlugin.hxx | 9 + src/output/plugins/WinmmOutputPlugin.cxx | 307 ++ src/output/plugins/WinmmOutputPlugin.hxx | 24 + src/output/plugins/httpd/HttpdClient.cxx | 425 +++ src/output/plugins/httpd/HttpdClient.hxx | 187 ++ src/output/plugins/httpd/HttpdInternal.hxx | 257 ++ .../plugins/httpd/HttpdOutputPlugin.cxx | 423 +++ .../plugins/httpd/HttpdOutputPlugin.hxx | 9 + .../plugins/httpd/IcyMetaDataServer.cxx | 100 + .../plugins/httpd/IcyMetaDataServer.hxx | 21 + src/output/plugins/httpd/Page.hxx | 21 + src/output/plugins/meson.build | 187 ++ .../plugins/sles/AndroidSimpleBufferQueue.hxx | 41 + src/output/plugins/sles/Engine.hxx | 42 + src/output/plugins/sles/Object.hxx | 38 + src/output/plugins/sles/Play.hxx | 26 + src/output/plugins/sles/SlesOutputPlugin.cxx | 429 +++ src/output/plugins/sles/SlesOutputPlugin.hxx | 9 + src/output/plugins/snapcast/Chunk.hxx | 39 + src/output/plugins/snapcast/Client.cxx | 297 ++ src/output/plugins/snapcast/Client.hxx | 87 + src/output/plugins/snapcast/Internal.hxx | 190 ++ src/output/plugins/snapcast/Protocol.hxx | 56 + .../plugins/snapcast/SnapcastOutputPlugin.cxx | 363 ++ .../plugins/snapcast/SnapcastOutputPlugin.hxx | 9 + src/output/plugins/snapcast/Timestamp.hxx | 29 + src/output/plugins/wasapi/AudioClient.hxx | 87 + src/output/plugins/wasapi/Device.hxx | 101 + src/output/plugins/wasapi/ForMixer.hxx | 35 + src/output/plugins/wasapi/PropertyStore.hxx | 28 + .../plugins/wasapi/WasapiOutputPlugin.cxx | 1054 ++++++ .../plugins/wasapi/WasapiOutputPlugin.hxx | 9 + src/pcm/AudioFormat.cxx | 60 + src/pcm/AudioFormat.hxx | 216 ++ src/pcm/AudioParser.cxx | 128 + src/pcm/AudioParser.hxx | 25 + src/pcm/Buffer.cxx | 15 + src/pcm/Buffer.hxx | 43 + src/pcm/ChannelDefs.hxx | 18 + src/pcm/ChannelsConverter.cxx | 83 + src/pcm/ChannelsConverter.hxx | 64 + src/pcm/CheckAudioFormat.cxx | 41 + src/pcm/CheckAudioFormat.hxx | 28 + src/pcm/Clamp.hxx | 32 + src/pcm/ConfiguredResampler.cxx | 165 + src/pcm/ConfiguredResampler.hxx | 20 + src/pcm/Convert.cxx | 144 + src/pcm/Convert.hxx | 75 + src/pcm/Dither.cxx | 99 + src/pcm/Dither.hxx | 67 + src/pcm/Dop.cxx | 79 + src/pcm/Dop.hxx | 46 + src/pcm/Dsd16.cxx | 49 + src/pcm/Dsd16.hxx | 44 + src/pcm/Dsd2Pcm.cxx | 321 ++ src/pcm/Dsd2Pcm.hxx | 124 + src/pcm/Dsd32.cxx | 51 + src/pcm/Dsd32.hxx | 44 + src/pcm/Export.cxx | 332 ++ src/pcm/Export.hxx | 231 ++ src/pcm/FallbackResampler.cxx | 128 + src/pcm/FallbackResampler.hxx | 30 + src/pcm/FloatConvert.hxx | 49 + src/pcm/FormatConverter.cxx | 78 + src/pcm/FormatConverter.hxx | 63 + src/pcm/GlueResampler.cxx | 71 + src/pcm/GlueResampler.hxx | 54 + src/pcm/Interleave.cxx | 95 + src/pcm/Interleave.hxx | 40 + src/pcm/LibsamplerateResampler.cxx | 135 + src/pcm/LibsamplerateResampler.hxx | 40 + src/pcm/Mix.cxx | 216 ++ src/pcm/Mix.hxx | 35 + src/pcm/MixRampAnalyzer.cxx | 49 + src/pcm/MixRampAnalyzer.hxx | 72 + src/pcm/MixRampGlue.cxx | 91 + src/pcm/MixRampGlue.hxx | 18 + src/pcm/Neon.hxx | 78 + src/pcm/Normalizer.cxx | 102 + src/pcm/Normalizer.hxx | 46 + src/pcm/Order.cxx | 206 ++ src/pcm/Order.hxx | 21 + src/pcm/Pack.cxx | 89 + src/pcm/Pack.hxx | 46 + src/pcm/PcmChannels.cxx | 277 ++ src/pcm/PcmChannels.hxx | 86 + src/pcm/PcmDsd.cxx | 37 + src/pcm/PcmDsd.hxx | 30 + src/pcm/PcmFormat.cxx | 379 +++ src/pcm/PcmFormat.hxx | 65 + src/pcm/Prng.hxx | 17 + src/pcm/ReplayGainAnalyzer.cxx | 339 ++ src/pcm/ReplayGainAnalyzer.hxx | 141 + src/pcm/Resampler.hxx | 66 + src/pcm/RestBuffer.hxx | 129 + src/pcm/SampleFormat.cxx | 35 + src/pcm/SampleFormat.hxx | 106 + src/pcm/ShiftConvert.hxx | 53 + src/pcm/Silence.cxx | 18 + src/pcm/Silence.hxx | 19 + src/pcm/SoxrResampler.cxx | 286 ++ src/pcm/SoxrResampler.hxx | 35 + src/pcm/Traits.hxx | 185 ++ src/pcm/Volume.cxx | 247 ++ src/pcm/Volume.hxx | 112 + src/pcm/meson.build | 89 + src/player/Control.cxx | 307 ++ src/player/Control.hxx | 567 ++++ src/player/CrossFade.cxx | 142 + src/player/CrossFade.hxx | 80 + src/player/Listener.hxx | 43 + src/player/Outputs.hxx | 97 + src/player/Thread.cxx | 1355 ++++++++ src/playlist/Length.cxx | 76 + src/playlist/Length.hxx | 23 + src/playlist/MemorySongEnumerator.cxx | 15 + src/playlist/MemorySongEnumerator.hxx | 22 + src/playlist/PlaylistAny.cxx | 35 + src/playlist/PlaylistAny.hxx | 28 + src/playlist/PlaylistMapper.cxx | 90 + src/playlist/PlaylistMapper.hxx | 27 + src/playlist/PlaylistPlugin.cxx | 26 + src/playlist/PlaylistPlugin.hxx | 141 + src/playlist/PlaylistQueue.cxx | 85 + src/playlist/PlaylistQueue.hxx | 40 + src/playlist/PlaylistRegistry.cxx | 266 ++ src/playlist/PlaylistRegistry.hxx | 88 + src/playlist/PlaylistSong.cxx | 95 + src/playlist/PlaylistSong.hxx | 22 + src/playlist/PlaylistStream.cxx | 57 + src/playlist/PlaylistStream.hxx | 34 + src/playlist/Print.cxx | 139 + src/playlist/Print.hxx | 26 + src/playlist/SongEnumerator.hxx | 28 + src/playlist/cue/CueParser.cxx | 290 ++ src/playlist/cue/CueParser.hxx | 121 + src/playlist/meson.build | 32 + src/playlist/plugins/AsxPlaylistPlugin.cxx | 172 + src/playlist/plugins/AsxPlaylistPlugin.hxx | 9 + src/playlist/plugins/CuePlaylistPlugin.cxx | 61 + src/playlist/plugins/CuePlaylistPlugin.hxx | 9 + .../plugins/EmbeddedCuePlaylistPlugin.cxx | 149 + .../plugins/EmbeddedCuePlaylistPlugin.hxx | 9 + src/playlist/plugins/ExtM3uPlaylistPlugin.cxx | 137 + src/playlist/plugins/ExtM3uPlaylistPlugin.hxx | 9 + src/playlist/plugins/FlacPlaylistPlugin.cxx | 92 + src/playlist/plugins/FlacPlaylistPlugin.hxx | 9 + src/playlist/plugins/M3uPlaylistPlugin.cxx | 59 + src/playlist/plugins/M3uPlaylistPlugin.hxx | 9 + src/playlist/plugins/PlsPlaylistPlugin.cxx | 166 + src/playlist/plugins/PlsPlaylistPlugin.hxx | 9 + src/playlist/plugins/RssPlaylistPlugin.cxx | 154 + src/playlist/plugins/RssPlaylistPlugin.hxx | 9 + src/playlist/plugins/XspfPlaylistPlugin.cxx | 211 ++ src/playlist/plugins/XspfPlaylistPlugin.hxx | 9 + src/playlist/plugins/meson.build | 49 + src/protocol/Ack.hxx | 39 + src/protocol/ArgParser.cxx | 158 + src/protocol/ArgParser.hxx | 43 + src/protocol/IdleFlags.cxx | 51 + src/protocol/IdleFlags.hxx | 70 + src/protocol/RangeArg.hxx | 129 + src/queue/IdTable.hxx | 100 + src/queue/Listener.hxx | 27 + src/queue/Playlist.cxx | 344 ++ src/queue/Playlist.hxx | 389 +++ src/queue/PlaylistControl.cxx | 290 ++ src/queue/PlaylistEdit.cxx | 426 +++ src/queue/PlaylistState.cxx | 238 ++ src/queue/PlaylistState.hxx | 39 + src/queue/PlaylistTag.cxx | 61 + src/queue/PlaylistUpdate.cxx | 57 + src/queue/Print.cxx | 200 ++ src/queue/Print.hxx | 37 + src/queue/Queue.cxx | 509 +++ src/queue/Queue.hxx | 389 +++ src/queue/QueuePrint.cxx | 96 + src/queue/Save.cxx | 105 + src/queue/Save.hxx | 26 + src/queue/Selection.cxx | 21 + src/queue/Selection.hxx | 39 + src/song/AddedSinceSongFilter.cxx | 23 + src/song/AddedSinceSongFilter.hxx | 26 + src/song/AndSongFilter.cxx | 44 + src/song/AndSongFilter.hxx | 41 + src/song/AudioFormatSongFilter.cxx | 25 + src/song/AudioFormatSongFilter.hxx | 27 + src/song/BaseSongFilter.cxx | 19 + src/song/BaseSongFilter.hxx | 31 + src/song/DetachedSong.cxx | 65 + src/song/DetachedSong.hxx | 277 ++ src/song/Escape.cxx | 25 + src/song/Escape.hxx | 13 + src/song/Filter.cxx | 606 ++++ src/song/Filter.hxx | 103 + src/song/ISongFilter.hxx | 30 + src/song/LightSong.cxx | 19 + src/song/LightSong.hxx | 113 + src/song/ModifiedSinceSongFilter.cxx | 23 + src/song/ModifiedSinceSongFilter.hxx | 26 + src/song/NotSongFilter.hxx | 36 + src/song/OptimizeFilter.cxx | 56 + src/song/OptimizeFilter.hxx | 17 + src/song/PrioritySongFilter.cxx | 21 + src/song/PrioritySongFilter.hxx | 23 + src/song/StringFilter.cxx | 52 + src/song/StringFilter.hxx | 120 + src/song/TagSongFilter.cxx | 76 + src/song/TagSongFilter.hxx | 56 + src/song/UriSongFilter.cxx | 19 + src/song/UriSongFilter.hxx | 41 + src/song/meson.build | 33 + src/sticker/AllowedTags.cxx | 44 + src/sticker/AllowedTags.hxx | 11 + src/sticker/CleanupService.cxx | 112 + src/sticker/CleanupService.hxx | 53 + src/sticker/Database.cxx | 559 ++++ src/sticker/Database.hxx | 225 ++ src/sticker/Match.hxx | 63 + src/sticker/Print.cxx | 22 + src/sticker/Print.hxx | 22 + src/sticker/SongSticker.cxx | 138 + src/sticker/SongSticker.hxx | 111 + src/sticker/Sticker.hxx | 14 + src/sticker/TagSticker.cxx | 90 + src/sticker/TagSticker.hxx | 79 + src/storage/CompositeStorage.cxx | 336 ++ src/storage/CompositeStorage.hxx | 183 ++ src/storage/Configured.cxx | 61 + src/storage/Configured.hxx | 29 + src/storage/FileInfo.hxx | 54 + src/storage/MemoryDirectoryReader.cxx | 29 + src/storage/MemoryDirectoryReader.hxx | 50 + src/storage/Registry.cxx | 72 + src/storage/Registry.hxx | 31 + src/storage/StorageInterface.cxx | 20 + src/storage/StorageInterface.hxx | 83 + src/storage/StoragePlugin.cxx | 18 + src/storage/StoragePlugin.hxx | 31 + src/storage/StorageState.cxx | 141 + src/storage/StorageState.hxx | 33 + src/storage/meson.build | 32 + src/storage/plugins/CurlStorage.cxx | 578 ++++ src/storage/plugins/CurlStorage.hxx | 11 + src/storage/plugins/LocalStorage.cxx | 175 + src/storage/plugins/LocalStorage.hxx | 18 + src/storage/plugins/NfsStorage.cxx | 448 +++ src/storage/plugins/NfsStorage.hxx | 11 + src/storage/plugins/SmbclientStorage.cxx | 193 ++ src/storage/plugins/SmbclientStorage.hxx | 11 + src/storage/plugins/UdisksStorage.cxx | 382 +++ src/storage/plugins/UdisksStorage.hxx | 11 + src/storage/plugins/meson.build | 65 + src/system/Clock.cxx | 22 + src/system/Clock.hxx | 20 + src/system/EpollFD.cxx | 12 + src/system/EpollFD.hxx | 58 + src/system/Error.hxx | 128 + src/system/EventFD.cxx | 36 + src/system/EventFD.hxx | 38 + src/system/EventPipe.cxx | 87 + src/system/EventPipe.hxx | 59 + src/system/KernelVersion.cxx | 43 + src/system/KernelVersion.hxx | 28 + src/system/SignalFD.cxx | 35 + src/system/SignalFD.hxx | 41 + src/system/VmaName.hxx | 35 + src/system/linux/meson.build | 7 + src/system/linux/openat2.h | 17 + src/system/meson.build | 40 + src/tag/Aiff.cxx | 63 + src/tag/Aiff.hxx | 29 + src/tag/ApeLoader.cxx | 90 + src/tag/ApeLoader.hxx | 26 + src/tag/ApeReplayGain.cxx | 46 + src/tag/ApeReplayGain.hxx | 16 + src/tag/ApeTag.cxx | 66 + src/tag/ApeTag.hxx | 20 + src/tag/Builder.cxx | 258 ++ src/tag/Builder.hxx | 156 + src/tag/Config.cxx | 55 + src/tag/Config.hxx | 12 + src/tag/Fallback.hxx | 61 + src/tag/FixString.cxx | 128 + src/tag/FixString.hxx | 14 + src/tag/Format.cxx | 116 + src/tag/Format.hxx | 13 + src/tag/GenParseName.cxx | 65 + src/tag/Generic.cxx | 38 + src/tag/Generic.hxx | 28 + src/tag/Handler.cxx | 77 + src/tag/Handler.hxx | 169 + src/tag/IcyMetaDataParser.cxx | 239 ++ src/tag/IcyMetaDataParser.hxx | 87 + src/tag/Id3Load.cxx | 214 ++ src/tag/Id3Load.hxx | 19 + src/tag/Id3MixRamp.cxx | 36 + src/tag/Id3MixRamp.hxx | 11 + src/tag/Id3MusicBrainz.cxx | 21 + src/tag/Id3MusicBrainz.hxx | 9 + src/tag/Id3Parse.hxx | 21 + src/tag/Id3Picture.cxx | 60 + src/tag/Id3Picture.hxx | 17 + src/tag/Id3ReplayGain.cxx | 42 + src/tag/Id3ReplayGain.hxx | 13 + src/tag/Id3Scan.cxx | 368 +++ src/tag/Id3Scan.hxx | 28 + src/tag/Id3String.hxx | 39 + src/tag/Id3Unique.hxx | 19 + src/tag/Item.hxx | 43 + src/tag/Mask.hxx | 82 + src/tag/MixRampInfo.hxx | 58 + src/tag/MixRampParser.cxx | 65 + src/tag/MixRampParser.hxx | 15 + src/tag/Names.cxx | 71 + src/tag/Names.hxx | 14 + src/tag/ParseName.cxx | 52 + src/tag/ParseName.hxx | 39 + src/tag/Pool.cxx | 140 + src/tag/Pool.hxx | 29 + src/tag/ReplayGainInfo.cxx | 26 + src/tag/ReplayGainInfo.hxx | 58 + src/tag/ReplayGainParser.cxx | 70 + src/tag/ReplayGainParser.hxx | 18 + src/tag/RiffFormat.hxx | 37 + src/tag/RiffId3.cxx | 51 + src/tag/RiffId3.hxx | 29 + src/tag/Rva2.cxx | 135 + src/tag/Rva2.hxx | 20 + src/tag/Settings.cxx | 7 + src/tag/Settings.hxx | 25 + src/tag/Sort.cxx | 41 + src/tag/Sort.hxx | 14 + src/tag/Table.cxx | 69 + src/tag/Table.hxx | 52 + src/tag/Tag.cxx | 175 + src/tag/Tag.hxx | 164 + src/tag/Type.hxx | 50 + src/tag/VisitFallback.hxx | 44 + src/tag/VorbisComment.cxx | 20 + src/tag/VorbisComment.hxx | 17 + src/tag/meson.build | 73 + src/thread/AsyncWaiter.hxx | 53 + src/thread/Cond.hxx | 19 + src/thread/CriticalSection.hxx | 42 + src/thread/Future.hxx | 27 + src/thread/Id.hxx | 81 + src/thread/Mutex.hxx | 42 + src/thread/Name.hxx | 54 + src/thread/SafeSingleton.hxx | 69 + src/thread/Slack.hxx | 37 + src/thread/Thread.cxx | 87 + src/thread/Thread.hxx | 100 + src/thread/Util.cxx | 88 + src/thread/Util.hxx | 21 + src/thread/WindowsCond.hxx | 72 + src/thread/WindowsFuture.hxx | 379 +++ src/thread/meson.build | 27 + src/time/Calendar.hxx | 33 + src/time/ChronoUtil.hxx | 16 + src/time/ClockCache.hxx | 39 + src/time/Convert.cxx | 73 + src/time/Convert.hxx | 43 + src/time/FileTime.hxx | 128 + src/time/ISO8601.cxx | 211 ++ src/time/ISO8601.hxx | 35 + src/time/Math.cxx | 87 + src/time/Math.hxx | 43 + src/time/PeriodClock.hxx | 135 + src/time/SystemClock.hxx | 36 + src/time/Zone.cxx | 38 + src/time/Zone.hxx | 12 + src/time/meson.build | 12 + src/unix/Daemon.cxx | 236 ++ src/unix/Daemon.hxx | 98 + src/unix/PidFile.hxx | 92 + src/unix/SignalHandlers.cxx | 84 + src/unix/SignalHandlers.hxx | 26 + src/util/ASCII.hxx | 66 + src/util/AllocatedArray.hxx | 233 ++ src/util/AllocatedString.hxx | 162 + src/util/BindMethod.hxx | 171 + src/util/BitReverse.cxx | 15 + src/util/BitReverse.hxx | 33 + src/util/ByteOrder.hxx | 226 ++ src/util/ByteReverse.cxx | 116 + src/util/ByteReverse.hxx | 42 + src/util/CNumberParser.hxx | 48 + src/util/Cast.hxx | 56 + src/util/CharUtil.hxx | 147 + src/util/CircularBuffer.hxx | 191 ++ src/util/Clamp.hxx | 24 + src/util/Compiler.h | 72 + src/util/Concepts.hxx | 9 + src/util/CopyConst.hxx | 14 + src/util/DeleteDisposer.hxx | 16 + src/util/DereferenceIterator.hxx | 145 + src/util/DisposablePointer.hxx | 141 + src/util/Domain.hxx | 30 + src/util/DynamicFifoBuffer.hxx | 92 + src/util/Exception.cxx | 86 + src/util/Exception.hxx | 114 + src/util/FilteredContainer.hxx | 116 + src/util/ForeignFifoBuffer.hxx | 235 ++ src/util/GenerateArray.hxx | 38 + src/util/HexFormat.hxx | 92 + src/util/HugeAllocator.cxx | 99 + src/util/HugeAllocator.hxx | 244 ++ src/util/IntrusiveForwardList.hxx | 476 +++ src/util/IntrusiveHashSet.hxx | 465 +++ src/util/IntrusiveHookMode.hxx | 30 + src/util/IntrusiveList.hxx | 653 ++++ src/util/IntrusiveTreeSet.hxx | 511 +++ src/util/IterableSplitString.hxx | 99 + src/util/LazyRandomEngine.cxx | 12 + src/util/LazyRandomEngine.hxx | 42 + src/util/Manual.hxx | 94 + src/util/Math.hxx | 20 + src/util/MemberPointer.hxx | 28 + src/util/MimeType.cxx | 29 + src/util/MimeType.hxx | 27 + src/util/NumberParser.hxx | 51 + src/util/OffsetPointer.hxx | 24 + src/util/OptionalCounter.hxx | 60 + src/util/OptionalField.hxx | 33 + src/util/PackedBigEndian.hxx | 182 ++ src/util/PackedLittleEndian.hxx | 163 + src/util/PeakBuffer.cxx | 114 + src/util/PeakBuffer.hxx | 55 + src/util/PrintException.cxx | 36 + src/util/PrintException.hxx | 16 + src/util/RecursiveMap.hxx | 15 + src/util/RedBlackTree.hxx | 389 +++ src/util/ReusableArray.hxx | 72 + src/util/RingBuffer.hxx | 317 ++ src/util/RoundPowerOfTwo.hxx | 50 + src/util/ScopeExit.hxx | 65 + src/util/Serial.cxx | 29 + src/util/Serial.hxx | 13 + src/util/SliceBuffer.hxx | 133 + src/util/SortList.hxx | 95 + src/util/SpanCast.hxx | 112 + src/util/SparseBuffer.cxx | 87 + src/util/SparseBuffer.hxx | 113 + src/util/SplitString.cxx | 28 + src/util/SplitString.hxx | 20 + src/util/StaticFifoBuffer.hxx | 131 + src/util/StaticVector.hxx | 235 ++ src/util/StringAPI.hxx | 188 ++ src/util/StringBuffer.hxx | 90 + src/util/StringCompare.cxx | 43 + src/util/StringCompare.hxx | 156 + src/util/StringPointer.hxx | 49 + src/util/StringSplit.hxx | 120 + src/util/StringStrip.cxx | 92 + src/util/StringStrip.hxx | 85 + src/util/StringUtil.cxx | 41 + src/util/StringUtil.hxx | 31 + src/util/StringVerify.hxx | 39 + src/util/TagStructs.hxx | 24 + src/util/TemplateString.hxx | 118 + src/util/TerminatedArray.hxx | 132 + src/util/TextFile.hxx | 27 + src/util/Tokenizer.cxx | 150 + src/util/Tokenizer.hxx | 71 + src/util/TransformN.hxx | 38 + src/util/TruncateString.cxx | 22 + src/util/TruncateString.hxx | 21 + src/util/UTF8.cxx | 321 ++ src/util/UTF8.hxx | 61 + src/util/UriExtract.cxx | 149 + src/util/UriExtract.hxx | 55 + src/util/UriQueryParser.cxx | 23 + src/util/UriQueryParser.hxx | 17 + src/util/UriRelative.cxx | 174 + src/util/UriRelative.hxx | 33 + src/util/UriUtil.cxx | 122 + src/util/UriUtil.hxx | 39 + src/util/VarSize.hxx | 52 + src/util/WCharUtil.hxx | 123 + src/util/WStringAPI.hxx | 187 ++ src/util/WStringCompare.cxx | 43 + src/util/WStringCompare.hxx | 97 + src/util/djb_hash.hxx | 48 + src/util/format.c | 244 ++ src/util/format.h | 34 + src/util/meson.build | 31 + src/win32/Com.hxx | 32 + src/win32/ComHeapPtr.hxx | 81 + src/win32/ComPtr.hxx | 104 + src/win32/ComWorker.cxx | 29 + src/win32/ComWorker.hxx | 75 + src/win32/HResult.cxx | 74 + src/win32/HResult.hxx | 37 + src/win32/PropVariant.cxx | 24 + src/win32/PropVariant.hxx | 16 + src/win32/Win32Main.cxx | 140 + src/win32/WinEvent.cxx | 12 + src/win32/WinEvent.hxx | 40 + src/win32/meson.build | 23 + src/zeroconf/Bonjour.cxx | 76 + src/zeroconf/Bonjour.hxx | 55 + src/zeroconf/Glue.cxx | 75 + src/zeroconf/Glue.hxx | 26 + src/zeroconf/Helper.cxx | 20 + src/zeroconf/Helper.hxx | 31 + src/zeroconf/avahi/Helper.cxx | 60 + src/zeroconf/avahi/Helper.hxx | 30 + src/zeroconf/avahi/meson.build | 26 + src/zeroconf/meson.build | 79 + subprojects/.gitignore | 20 + subprojects/curl.wrap | 13 + subprojects/expat.wrap | 13 + subprojects/flac.wrap | 13 + subprojects/fmt.wrap | 13 + subprojects/gtest.wrap | 16 + subprojects/id3tag.wrap | 9 + subprojects/lame.wrap | 14 + subprojects/libmpdclient.wrap | 6 + subprojects/libnpupnp.wrap | 10 + subprojects/libsndfile.wrap | 13 + subprojects/liburing.wrap | 13 + subprojects/nlohmann_json.wrap | 11 + subprojects/ogg.wrap | 13 + subprojects/openssl.wrap | 15 + subprojects/opus.wrap | 10 + subprojects/packagefiles/id3tag/meson.build | 39 + subprojects/sqlite3.wrap | 13 + subprojects/vorbis.wrap | 14 + systemd/meson.build | 22 + systemd/system/meson.build | 27 + systemd/system/mpd.service.in | 35 + systemd/system/mpd.socket.in | 8 + systemd/user/meson.build | 27 + systemd/user/mpd.service.in | 40 + test/ConfigGlue.hxx | 25 + test/ContainerScan.cxx | 78 + test/DumpDatabase.cxx | 124 + test/DumpDecoderClient.cxx | 131 + test/DumpDecoderClient.hxx | 46 + test/DumpOgg.cxx | 52 + test/LoadDatabase.cxx | 30 + test/MakeTag.hxx | 28 + test/NullMixerListener.hxx | 15 + test/ParseSongFilter.cxx | 33 + test/ReadApeTags.cxx | 61 + test/ReadFrames.cxx | 36 + test/ReadFrames.hxx | 10 + test/RunChromaprint.cxx | 136 + test/RunCurl.cxx | 80 + test/RunMixRampAnalyzer.cxx | 68 + test/RunReplayGainAnalyzer.cxx | 46 + test/RunZeroconf.cxx | 21 + test/ShutdownHandler.cxx | 32 + test/ShutdownHandler.hxx | 20 + test/TestAudioFormat.cxx | 48 + test/TestIcu.cxx | 48 + test/TestRewindInputStream.cxx | 126 + test/TestStringFilter.cxx | 162 + test/TestTagSongFilter.cxx | 193 ++ test/WriteFile.cxx | 56 + test/dump_playlist.cxx | 108 + test/dump_rva2.cxx | 78 + test/dump_text_file.cxx | 83 + test/fs/TestGlob.cxx | 79 + test/fs/TestLookupFile.cxx | 29 + test/fs/TestParsePath.cxx | 142 + test/fs/TestPath.cxx | 128 + test/fs/meson.build | 31 + test/fuzzer/FuzzCueParser.cxx | 23 + test/fuzzer/meson.build | 9 + test/meson.build | 645 ++++ test/net/TestIPv4Address.cxx | 149 + test/net/TestIPv6Address.cxx | 139 + test/net/TestLocalSocketAddress.cxx | 110 + test/net/meson.build | 28 + test/playlist/PlaylistUtil.cxx | 39 + test/playlist/PlaylistUtil.hxx | 15 + test/playlist/TestPlsPlaylistPlugin.cxx | 88 + test/playlist/meson.build | 19 + test/read_conf.cxx | 41 + test/read_mixer.cxx | 60 + test/read_tags.cxx | 134 + test/run_convert.cxx | 148 + test/run_decoder.cxx | 216 ++ test/run_encoder.cxx | 79 + test/run_filter.cxx | 143 + test/run_gunzip.cxx | 57 + test/run_gzip.cxx | 58 + test/run_inotify.cxx | 63 + test/run_input.cxx | 260 ++ test/run_neighbor_explorer.cxx | 71 + test/run_normalize.cxx | 49 + test/run_output.cxx | 178 + test/run_resolver.cxx | 32 + test/run_storage.cxx | 319 ++ test/software_volume.cxx | 51 + test/tag/TestMixRampInterpolate.cxx | 66 + test/tag/TestMixRampParser.cxx | 73 + test/tag/meson.build | 16 + test/test_archive_bzip2.sh | 10 + test/test_archive_iso9660.sh | 13 + test/test_archive_zzip.sh | 10 + test/test_icy_parser.cxx | 63 + test/test_pcm_channels.cxx | 92 + test/test_pcm_dither.cxx | 37 + test/test_pcm_export.cxx | 417 +++ test/test_pcm_format.cxx | 145 + test/test_pcm_interleave.cxx | 108 + test/test_pcm_mix.cxx | 67 + test/test_pcm_pack.cxx | 73 + test/test_pcm_util.hxx | 90 + test/test_pcm_volume.cxx | 144 + test/test_protocol.cxx | 23 + test/test_queue_priority.cxx | 172 + test/test_translate_song.cxx | 297 ++ test/test_vorbis_encoder.cxx | 83 + test/time/TestConvert.cxx | 36 + test/time/TestFileTime.cxx | 27 + test/time/TestISO8601.cxx | 74 + test/time/meson.build | 22 + test/util/TestCircularBuffer.cxx | 150 + test/util/TestException.cxx | 223 ++ test/util/TestIntrusiveForwardList.cxx | 226 ++ test/util/TestIntrusiveHashSet.cxx | 224 ++ test/util/TestIntrusiveList.cxx | 374 +++ test/util/TestIntrusiveTreeSet.cxx | 358 ++ test/util/TestMimeType.cxx | 38 + test/util/TestRingBuffer.cxx | 116 + test/util/TestSplitString.cxx | 56 + test/util/TestStringStrip.cxx | 39 + test/util/TestTemplateString.cxx | 35 + test/util/TestTerminatedArray.cxx | 34 + test/util/TestUriExtract.cxx | 22 + test/util/TestUriQueryParser.cxx | 24 + test/util/TestUriRelative.cxx | 97 + test/util/TestUriUtil.cxx | 21 + test/util/meson.build | 29 + test/util/test_byte_reverse.cxx | 53 + test/visit_archive.cxx | 83 + valgrind.suppressions | 629 ++++ win32/build.py | 64 + win32/meson.build | 1 + win32/res/meson.build | 18 + win32/res/mpd.ico | Bin 0 -> 353118 bytes win32/res/mpd.rc.in | 34 + 1974 files changed, 195111 insertions(+) create mode 100644 AUTHORS create mode 100644 COPYING create mode 100644 LICENSE create mode 100644 LICENSES/BSD-2-Clause.txt create mode 100644 LICENSES/GPL-2.0-or-later.txt create mode 100644 LICENSES/ISC.txt create mode 100644 LICENSES/LGPL-2.1-only.txt create mode 100644 NEWS create mode 100644 android/.gitignore create mode 100644 android/PrivacyPolicy.rst create mode 100644 android/README.md create mode 100644 android/app/.gitignore create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/aidl/org/musicpd/IMain.aidl create mode 100644 android/app/src/main/aidl/org/musicpd/IMainCallback.aidl create mode 100644 android/app/src/main/ic_launcher-playstore.png create mode 100644 android/app/src/main/java/org/musicpd/AutomationReceiver.kt create mode 100644 android/app/src/main/java/org/musicpd/Bridge.java create mode 100644 android/app/src/main/java/org/musicpd/Loader.kt create mode 100644 android/app/src/main/java/org/musicpd/MPDApplication.kt create mode 100644 android/app/src/main/java/org/musicpd/MPDPlayer.java create mode 100644 android/app/src/main/java/org/musicpd/Main.kt create mode 100644 android/app/src/main/java/org/musicpd/MainActivity.kt create mode 100644 android/app/src/main/java/org/musicpd/MainServiceClient.java create mode 100644 android/app/src/main/java/org/musicpd/NetworkUtil.java create mode 100644 android/app/src/main/java/org/musicpd/Preferences.java create mode 100644 android/app/src/main/java/org/musicpd/Receiver.java create mode 100644 android/app/src/main/java/org/musicpd/data/LoggingRepository.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/LogScreen.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/MainScreen.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/NetworkAddress.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/SettingsScreen.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/SettingsViewModel.kt create mode 100644 android/app/src/main/java/org/musicpd/ui/StatusScreen.kt create mode 100644 android/app/src/main/java/org/musicpd/utils/IntentUtils.kt create mode 100644 android/app/src/main/res/drawable/baseline_wifi_24.xml create mode 100644 android/app/src/main/res/drawable/ic_banner_foreground.xml create mode 100644 android/app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 android/app/src/main/res/drawable/notification_icon.png create mode 100644 android/app/src/main/res/layout/custom_notification_gb.xml create mode 100644 android/app/src/main/res/mipmap-anydpi-v26/ic_banner.xml create mode 100644 android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 android/app/src/main/res/mipmap-hdpi/ic_banner.png create mode 100644 android/app/src/main/res/mipmap-hdpi/ic_launcher.webp create mode 100644 android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp create mode 100644 android/app/src/main/res/mipmap-mdpi/ic_banner.png create mode 100644 android/app/src/main/res/mipmap-mdpi/ic_launcher.webp create mode 100644 android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp create mode 100644 android/app/src/main/res/mipmap-xhdpi/ic_banner.png create mode 100644 android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp create mode 100644 android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp create mode 100644 android/app/src/main/res/mipmap-xxhdpi/ic_banner.png create mode 100644 android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp create mode 100644 android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp create mode 100644 android/app/src/main/res/mipmap-xxxhdpi/ic_banner.png create mode 100644 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp create mode 100644 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp create mode 100644 android/app/src/main/res/values/ic_banner_background.xml create mode 100644 android/app/src/main/res/values/ic_launcher_background.xml create mode 100644 android/app/src/main/res/values/strings.xml create mode 100644 android/app/src/main/res/values/themes.xml create mode 100644 android/build.gradle.kts create mode 100755 android/build.py create mode 100644 android/custom_rules.xml create mode 100755 android/gdb.sh create mode 100644 android/gradle.properties create mode 100644 android/gradle/libs.versions.toml create mode 100644 android/gradle/wrapper/gradle-wrapper.jar create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100755 android/gradlew create mode 100644 android/gradlew.bat create mode 100644 android/include/meson.build create mode 100644 android/meson.build create mode 100644 android/settings.gradle.kts create mode 100644 doc/_static/css/custom.css create mode 100644 doc/client.rst create mode 100644 doc/conf.py create mode 100644 doc/developer.rst create mode 100644 doc/doxygen.conf.in create mode 100644 doc/index.rst create mode 100644 doc/meson.build create mode 100644 doc/mpd.1.rst create mode 100644 doc/mpd.conf.5.rst create mode 100644 doc/mpdconf.example create mode 100644 doc/plugins.rst create mode 100644 doc/protocol.rst create mode 100644 doc/requirements.txt create mode 100644 doc/user.rst create mode 100644 meson.build create mode 100644 meson_options.txt create mode 100644 mpd.svg create mode 100644 python/build/__init__.py create mode 100644 python/build/autotools.py create mode 100644 python/build/cmake.py create mode 100644 python/build/dirs.py create mode 100644 python/build/download.py create mode 100644 python/build/ffmpeg.py create mode 100644 python/build/libs.py create mode 100644 python/build/makeproject.py create mode 100644 python/build/meson.py create mode 100644 python/build/project.py create mode 100644 python/build/quilt.py create mode 100644 python/build/tar.py create mode 100644 python/build/toolchain.py create mode 100644 python/build/verify.py create mode 100644 python/build/zlib.py create mode 100644 src/BulkEdit.hxx create mode 100644 src/Chrono.hxx create mode 100644 src/CommandLine.cxx create mode 100644 src/CommandLine.hxx create mode 100644 src/ConsumeMode.cxx create mode 100644 src/ConsumeMode.hxx create mode 100644 src/DbMain.cxx create mode 100644 src/GitVersion.cxx create mode 100644 src/GitVersion.hxx create mode 100644 src/Idle.cxx create mode 100644 src/Idle.hxx create mode 100644 src/Instance.cxx create mode 100644 src/Instance.hxx create mode 100644 src/Listen.cxx create mode 100644 src/Listen.hxx create mode 100644 src/LocateUri.cxx create mode 100644 src/LocateUri.hxx create mode 100644 src/Log.cxx create mode 100644 src/Log.hxx create mode 100644 src/LogBackend.cxx create mode 100644 src/LogBackend.hxx create mode 100644 src/LogInit.cxx create mode 100644 src/LogInit.hxx create mode 100644 src/LogLevel.hxx create mode 100644 src/Main.cxx create mode 100644 src/Main.hxx create mode 100644 src/Mapper.cxx create mode 100644 src/Mapper.hxx create mode 100644 src/MusicBuffer.cxx create mode 100644 src/MusicBuffer.hxx create mode 100644 src/MusicChunk.cxx create mode 100644 src/MusicChunk.hxx create mode 100644 src/MusicChunkPtr.cxx create mode 100644 src/MusicChunkPtr.hxx create mode 100644 src/MusicPipe.cxx create mode 100644 src/MusicPipe.hxx create mode 100644 src/Partition.cxx create mode 100644 src/Partition.hxx create mode 100644 src/Permission.cxx create mode 100644 src/Permission.hxx create mode 100644 src/PlaylistDatabase.cxx create mode 100644 src/PlaylistDatabase.hxx create mode 100644 src/PlaylistError.cxx create mode 100644 src/PlaylistError.hxx create mode 100644 src/PlaylistFile.cxx create mode 100644 src/PlaylistFile.hxx create mode 100644 src/PlaylistPrint.cxx create mode 100644 src/PlaylistPrint.hxx create mode 100644 src/PlaylistSave.cxx create mode 100644 src/PlaylistSave.hxx create mode 100644 src/PluginUnavailable.hxx create mode 100644 src/RemoteTagCache.cxx create mode 100644 src/RemoteTagCache.hxx create mode 100644 src/RemoteTagCacheHandler.hxx create mode 100644 src/ReplayGainMode.cxx create mode 100644 src/ReplayGainMode.hxx create mode 100644 src/SingleMode.cxx create mode 100644 src/SingleMode.hxx create mode 100644 src/SongLoader.cxx create mode 100644 src/SongLoader.hxx create mode 100644 src/SongPrint.cxx create mode 100644 src/SongPrint.hxx create mode 100644 src/SongSave.cxx create mode 100644 src/SongSave.hxx create mode 100644 src/SongUpdate.cxx create mode 100644 src/StateFile.cxx create mode 100644 src/StateFile.hxx create mode 100644 src/StateFileConfig.cxx create mode 100644 src/StateFileConfig.hxx create mode 100644 src/Stats.cxx create mode 100644 src/Stats.hxx create mode 100644 src/TagAny.cxx create mode 100644 src/TagAny.hxx create mode 100644 src/TagArchive.cxx create mode 100644 src/TagArchive.hxx create mode 100644 src/TagFile.cxx create mode 100644 src/TagFile.hxx create mode 100644 src/TagPrint.cxx create mode 100644 src/TagPrint.hxx create mode 100644 src/TagSave.cxx create mode 100644 src/TagSave.hxx create mode 100644 src/TagStream.cxx create mode 100644 src/TagStream.hxx create mode 100644 src/TimePrint.cxx create mode 100644 src/TimePrint.hxx create mode 100644 src/android/AudioManager.cxx create mode 100644 src/android/AudioManager.hxx create mode 100644 src/android/Context.cxx create mode 100644 src/android/Context.hxx create mode 100644 src/android/Environment.cxx create mode 100644 src/android/Environment.hxx create mode 100644 src/android/LogListener.cxx create mode 100644 src/android/LogListener.hxx create mode 100644 src/apple/AudioObject.cxx create mode 100644 src/apple/AudioObject.hxx create mode 100644 src/apple/AudioUnit.hxx create mode 100644 src/apple/ErrorRef.hxx create mode 100644 src/apple/StringRef.hxx create mode 100644 src/apple/Throw.cxx create mode 100644 src/apple/Throw.hxx create mode 100644 src/apple/meson.build create mode 100644 src/archive/ArchiveFile.hxx create mode 100644 src/archive/ArchiveList.cxx create mode 100644 src/archive/ArchiveList.hxx create mode 100644 src/archive/ArchivePlugin.cxx create mode 100644 src/archive/ArchivePlugin.hxx create mode 100644 src/archive/ArchiveVisitor.hxx create mode 100644 src/archive/meson.build create mode 100644 src/archive/plugins/Bzip2ArchivePlugin.cxx create mode 100644 src/archive/plugins/Bzip2ArchivePlugin.hxx create mode 100644 src/archive/plugins/Iso9660ArchivePlugin.cxx create mode 100644 src/archive/plugins/Iso9660ArchivePlugin.hxx create mode 100644 src/archive/plugins/ZzipArchivePlugin.cxx create mode 100644 src/archive/plugins/ZzipArchivePlugin.hxx create mode 100644 src/archive/plugins/meson.build create mode 100644 src/client/BackgroundCommand.hxx create mode 100644 src/client/Client.cxx create mode 100644 src/client/Client.hxx create mode 100644 src/client/Config.cxx create mode 100644 src/client/Config.hxx create mode 100644 src/client/Domain.cxx create mode 100644 src/client/Domain.hxx create mode 100644 src/client/Event.cxx create mode 100644 src/client/Expire.cxx create mode 100644 src/client/File.cxx create mode 100644 src/client/IClient.hxx create mode 100644 src/client/Idle.cxx create mode 100644 src/client/List.cxx create mode 100644 src/client/List.hxx create mode 100644 src/client/Listener.cxx create mode 100644 src/client/Listener.hxx create mode 100644 src/client/Message.cxx create mode 100644 src/client/Message.hxx create mode 100644 src/client/New.cxx create mode 100644 src/client/Process.cxx create mode 100644 src/client/ProtocolFeature.cxx create mode 100644 src/client/ProtocolFeature.hxx create mode 100644 src/client/Read.cxx create mode 100644 src/client/Response.cxx create mode 100644 src/client/Response.hxx create mode 100644 src/client/Subscribe.cxx create mode 100644 src/client/ThreadBackgroundCommand.cxx create mode 100644 src/client/ThreadBackgroundCommand.hxx create mode 100644 src/client/Write.cxx create mode 100644 src/cmdline/OptionDef.hxx create mode 100644 src/cmdline/OptionParser.cxx create mode 100644 src/cmdline/OptionParser.hxx create mode 100644 src/cmdline/meson.build create mode 100644 src/command/AllCommands.cxx create mode 100644 src/command/AllCommands.hxx create mode 100644 src/command/ClientCommands.cxx create mode 100644 src/command/ClientCommands.hxx create mode 100644 src/command/CommandError.cxx create mode 100644 src/command/CommandError.hxx create mode 100644 src/command/CommandListBuilder.cxx create mode 100644 src/command/CommandListBuilder.hxx create mode 100644 src/command/CommandResult.hxx create mode 100644 src/command/DatabaseCommands.cxx create mode 100644 src/command/DatabaseCommands.hxx create mode 100644 src/command/FileCommands.cxx create mode 100644 src/command/FileCommands.hxx create mode 100644 src/command/FingerprintCommands.cxx create mode 100644 src/command/FingerprintCommands.hxx create mode 100644 src/command/MessageCommands.cxx create mode 100644 src/command/MessageCommands.hxx create mode 100644 src/command/NeighborCommands.cxx create mode 100644 src/command/NeighborCommands.hxx create mode 100644 src/command/OtherCommands.cxx create mode 100644 src/command/OtherCommands.hxx create mode 100644 src/command/OutputCommands.cxx create mode 100644 src/command/OutputCommands.hxx create mode 100644 src/command/PartitionCommands.cxx create mode 100644 src/command/PartitionCommands.hxx create mode 100644 src/command/PlayerCommands.cxx create mode 100644 src/command/PlayerCommands.hxx create mode 100644 src/command/PlaylistCommands.cxx create mode 100644 src/command/PlaylistCommands.hxx create mode 100644 src/command/PositionArg.cxx create mode 100644 src/command/PositionArg.hxx create mode 100644 src/command/QueueCommands.cxx create mode 100644 src/command/QueueCommands.hxx create mode 100644 src/command/Request.hxx create mode 100644 src/command/StickerCommands.cxx create mode 100644 src/command/StickerCommands.hxx create mode 100644 src/command/StorageCommands.cxx create mode 100644 src/command/StorageCommands.hxx create mode 100644 src/command/TagCommands.cxx create mode 100644 src/command/TagCommands.hxx create mode 100644 src/config/Block.cxx create mode 100644 src/config/Block.hxx create mode 100644 src/config/Check.cxx create mode 100644 src/config/Check.hxx create mode 100644 src/config/Data.cxx create mode 100644 src/config/Data.hxx create mode 100644 src/config/Defaults.hxx create mode 100644 src/config/Domain.cxx create mode 100644 src/config/Domain.hxx create mode 100644 src/config/File.cxx create mode 100644 src/config/File.hxx create mode 100644 src/config/Migrate.cxx create mode 100644 src/config/Migrate.hxx create mode 100644 src/config/Net.cxx create mode 100644 src/config/Net.hxx create mode 100644 src/config/Option.hxx create mode 100644 src/config/Param.cxx create mode 100644 src/config/Param.hxx create mode 100644 src/config/Parser.cxx create mode 100644 src/config/Parser.hxx create mode 100644 src/config/PartitionConfig.cxx create mode 100644 src/config/PartitionConfig.hxx create mode 100644 src/config/Path.cxx create mode 100644 src/config/Path.hxx create mode 100644 src/config/PlayerConfig.cxx create mode 100644 src/config/PlayerConfig.hxx create mode 100644 src/config/QueueConfig.hxx create mode 100644 src/config/ReplayGainConfig.cxx create mode 100644 src/config/ReplayGainConfig.hxx create mode 100644 src/config/Templates.cxx create mode 100644 src/config/Templates.hxx create mode 100644 src/config/meson.build create mode 100644 src/db/Configured.cxx create mode 100644 src/db/Configured.hxx create mode 100644 src/db/Count.cxx create mode 100644 src/db/Count.hxx create mode 100644 src/db/DatabaseError.hxx create mode 100644 src/db/DatabaseGlue.cxx create mode 100644 src/db/DatabaseGlue.hxx create mode 100644 src/db/DatabaseListener.hxx create mode 100644 src/db/DatabaseLock.cxx create mode 100644 src/db/DatabaseLock.hxx create mode 100644 src/db/DatabasePlaylist.cxx create mode 100644 src/db/DatabasePlaylist.hxx create mode 100644 src/db/DatabasePlugin.hxx create mode 100644 src/db/DatabasePrint.cxx create mode 100644 src/db/DatabasePrint.hxx create mode 100644 src/db/DatabaseQueue.cxx create mode 100644 src/db/DatabaseQueue.hxx create mode 100644 src/db/DatabaseSong.cxx create mode 100644 src/db/DatabaseSong.hxx create mode 100644 src/db/Helpers.cxx create mode 100644 src/db/Helpers.hxx create mode 100644 src/db/Interface.hxx create mode 100644 src/db/LightDirectory.hxx create mode 100644 src/db/PlaylistInfo.hxx create mode 100644 src/db/PlaylistVector.cxx create mode 100644 src/db/PlaylistVector.hxx create mode 100644 src/db/Ptr.hxx create mode 100644 src/db/Registry.cxx create mode 100644 src/db/Registry.hxx create mode 100644 src/db/Selection.cxx create mode 100644 src/db/Selection.hxx create mode 100644 src/db/Stats.hxx create mode 100644 src/db/UniqueTags.cxx create mode 100644 src/db/UniqueTags.hxx create mode 100644 src/db/Uri.hxx create mode 100644 src/db/VHelper.cxx create mode 100644 src/db/VHelper.hxx create mode 100644 src/db/Visitor.hxx create mode 100644 src/db/meson.build create mode 100644 src/db/plugins/ProxyDatabasePlugin.cxx create mode 100644 src/db/plugins/ProxyDatabasePlugin.hxx create mode 100644 src/db/plugins/meson.build create mode 100644 src/db/plugins/simple/DatabaseSave.cxx create mode 100644 src/db/plugins/simple/DatabaseSave.hxx create mode 100644 src/db/plugins/simple/Directory.cxx create mode 100644 src/db/plugins/simple/Directory.hxx create mode 100644 src/db/plugins/simple/DirectorySave.cxx create mode 100644 src/db/plugins/simple/DirectorySave.hxx create mode 100644 src/db/plugins/simple/ExportedSong.hxx create mode 100644 src/db/plugins/simple/Mount.cxx create mode 100644 src/db/plugins/simple/Mount.hxx create mode 100644 src/db/plugins/simple/PrefixedLightSong.hxx create mode 100644 src/db/plugins/simple/Ptr.hxx create mode 100644 src/db/plugins/simple/SimpleDatabasePlugin.cxx create mode 100644 src/db/plugins/simple/SimpleDatabasePlugin.hxx create mode 100644 src/db/plugins/simple/Song.cxx create mode 100644 src/db/plugins/simple/Song.hxx create mode 100644 src/db/plugins/simple/SongSort.cxx create mode 100644 src/db/plugins/simple/SongSort.hxx create mode 100644 src/db/plugins/upnp/ContentDirectoryService.cxx create mode 100644 src/db/plugins/upnp/Directory.cxx create mode 100644 src/db/plugins/upnp/Directory.hxx create mode 100644 src/db/plugins/upnp/Object.cxx create mode 100644 src/db/plugins/upnp/Object.hxx create mode 100644 src/db/plugins/upnp/Tags.cxx create mode 100644 src/db/plugins/upnp/Tags.hxx create mode 100644 src/db/plugins/upnp/UpnpDatabasePlugin.cxx create mode 100644 src/db/plugins/upnp/UpnpDatabasePlugin.hxx create mode 100644 src/db/update/Archive.cxx create mode 100644 src/db/update/Config.cxx create mode 100644 src/db/update/Config.hxx create mode 100644 src/db/update/Container.cxx create mode 100644 src/db/update/CueValidator.cxx create mode 100644 src/db/update/CueValidator.hxx create mode 100644 src/db/update/Editor.cxx create mode 100644 src/db/update/Editor.hxx create mode 100644 src/db/update/ExcludeList.cxx create mode 100644 src/db/update/ExcludeList.hxx create mode 100644 src/db/update/FilteredSongUpdate.cxx create mode 100644 src/db/update/FilteredSongUpdate.hxx create mode 100644 src/db/update/InotifyDomain.cxx create mode 100644 src/db/update/InotifyDomain.hxx create mode 100644 src/db/update/InotifyQueue.cxx create mode 100644 src/db/update/InotifyQueue.hxx create mode 100644 src/db/update/InotifyUpdate.cxx create mode 100644 src/db/update/InotifyUpdate.hxx create mode 100644 src/db/update/Playlist.cxx create mode 100644 src/db/update/Queue.cxx create mode 100644 src/db/update/Queue.hxx create mode 100644 src/db/update/Remove.cxx create mode 100644 src/db/update/Remove.hxx create mode 100644 src/db/update/Service.cxx create mode 100644 src/db/update/Service.hxx create mode 100644 src/db/update/SpecialDirectory.cxx create mode 100644 src/db/update/UpdateDomain.cxx create mode 100644 src/db/update/UpdateDomain.hxx create mode 100644 src/db/update/UpdateIO.cxx create mode 100644 src/db/update/UpdateIO.hxx create mode 100644 src/db/update/UpdateSong.cxx create mode 100644 src/db/update/VirtualDirectory.cxx create mode 100644 src/db/update/Walk.cxx create mode 100644 src/db/update/Walk.hxx create mode 100644 src/decoder/Bridge.cxx create mode 100644 src/decoder/Bridge.hxx create mode 100644 src/decoder/Client.hxx create mode 100644 src/decoder/Command.hxx create mode 100644 src/decoder/Control.cxx create mode 100644 src/decoder/Control.hxx create mode 100644 src/decoder/DecoderAPI.cxx create mode 100644 src/decoder/DecoderAPI.hxx create mode 100644 src/decoder/DecoderBuffer.cxx create mode 100644 src/decoder/DecoderBuffer.hxx create mode 100644 src/decoder/DecoderList.cxx create mode 100644 src/decoder/DecoderList.hxx create mode 100644 src/decoder/DecoderPlugin.cxx create mode 100644 src/decoder/DecoderPlugin.hxx create mode 100644 src/decoder/DecoderPrint.cxx create mode 100644 src/decoder/DecoderPrint.hxx create mode 100644 src/decoder/Domain.cxx create mode 100644 src/decoder/Domain.hxx create mode 100644 src/decoder/Reader.cxx create mode 100644 src/decoder/Reader.hxx create mode 100644 src/decoder/Thread.cxx create mode 100644 src/decoder/meson.build create mode 100644 src/decoder/plugins/AdPlugDecoderPlugin.cxx create mode 100644 src/decoder/plugins/AdPlugDecoderPlugin.h create mode 100644 src/decoder/plugins/AudiofileDecoderPlugin.cxx create mode 100644 src/decoder/plugins/AudiofileDecoderPlugin.hxx create mode 100644 src/decoder/plugins/DffDecoderPlugin.cxx create mode 100644 src/decoder/plugins/DffDecoderPlugin.hxx create mode 100644 src/decoder/plugins/DsdLib.cxx create mode 100644 src/decoder/plugins/DsdLib.hxx create mode 100644 src/decoder/plugins/DsdiffDecoderPlugin.cxx create mode 100644 src/decoder/plugins/DsdiffDecoderPlugin.hxx create mode 100644 src/decoder/plugins/DsfDecoderPlugin.cxx create mode 100644 src/decoder/plugins/DsfDecoderPlugin.hxx create mode 100644 src/decoder/plugins/DvdaIsoDecoderPlugin.cxx create mode 100644 src/decoder/plugins/DvdaIsoDecoderPlugin.hxx create mode 100644 src/decoder/plugins/FaadDecoderPlugin.cxx create mode 100644 src/decoder/plugins/FaadDecoderPlugin.hxx create mode 100644 src/decoder/plugins/FfmpegDecoderPlugin.cxx create mode 100644 src/decoder/plugins/FfmpegDecoderPlugin.hxx create mode 100644 src/decoder/plugins/FfmpegIo.cxx create mode 100644 src/decoder/plugins/FfmpegIo.hxx create mode 100644 src/decoder/plugins/FfmpegMetaData.cxx create mode 100644 src/decoder/plugins/FfmpegMetaData.hxx create mode 100644 src/decoder/plugins/FlacCommon.cxx create mode 100644 src/decoder/plugins/FlacCommon.hxx create mode 100644 src/decoder/plugins/FlacDecoderPlugin.cxx create mode 100644 src/decoder/plugins/FlacDecoderPlugin.h create mode 100644 src/decoder/plugins/FlacDomain.cxx create mode 100644 src/decoder/plugins/FlacDomain.hxx create mode 100644 src/decoder/plugins/FlacInput.cxx create mode 100644 src/decoder/plugins/FlacInput.hxx create mode 100644 src/decoder/plugins/FlacPcm.cxx create mode 100644 src/decoder/plugins/FlacPcm.hxx create mode 100644 src/decoder/plugins/FlacStreamDecoder.hxx create mode 100644 src/decoder/plugins/FluidsynthDecoderPlugin.cxx create mode 100644 src/decoder/plugins/FluidsynthDecoderPlugin.hxx create mode 100644 src/decoder/plugins/GmeDecoderPlugin.cxx create mode 100644 src/decoder/plugins/GmeDecoderPlugin.hxx create mode 100644 src/decoder/plugins/MadDecoderPlugin.cxx create mode 100644 src/decoder/plugins/MadDecoderPlugin.hxx create mode 100644 src/decoder/plugins/MikmodDecoderPlugin.cxx create mode 100644 src/decoder/plugins/MikmodDecoderPlugin.hxx create mode 100644 src/decoder/plugins/ModCommon.cxx create mode 100644 src/decoder/plugins/ModCommon.hxx create mode 100644 src/decoder/plugins/ModplugDecoderPlugin.cxx create mode 100644 src/decoder/plugins/ModplugDecoderPlugin.hxx create mode 100644 src/decoder/plugins/MpcdecDecoderPlugin.cxx create mode 100644 src/decoder/plugins/MpcdecDecoderPlugin.hxx create mode 100644 src/decoder/plugins/Mpg123DecoderPlugin.cxx create mode 100644 src/decoder/plugins/Mpg123DecoderPlugin.hxx create mode 100644 src/decoder/plugins/OggCodec.cxx create mode 100644 src/decoder/plugins/OggCodec.hxx create mode 100644 src/decoder/plugins/OggDecoder.cxx create mode 100644 src/decoder/plugins/OggDecoder.hxx create mode 100644 src/decoder/plugins/OpenmptDecoderPlugin.cxx create mode 100644 src/decoder/plugins/OpenmptDecoderPlugin.hxx create mode 100644 src/decoder/plugins/OpusDecoderPlugin.cxx create mode 100644 src/decoder/plugins/OpusDecoderPlugin.h create mode 100644 src/decoder/plugins/OpusDomain.cxx create mode 100644 src/decoder/plugins/OpusDomain.hxx create mode 100644 src/decoder/plugins/OpusHead.cxx create mode 100644 src/decoder/plugins/OpusHead.hxx create mode 100644 src/decoder/plugins/OpusReader.hxx create mode 100644 src/decoder/plugins/OpusTags.cxx create mode 100644 src/decoder/plugins/OpusTags.hxx create mode 100644 src/decoder/plugins/PcmDecoderPlugin.cxx create mode 100644 src/decoder/plugins/PcmDecoderPlugin.hxx create mode 100644 src/decoder/plugins/SacdIsoDecoderPlugin.cxx create mode 100644 src/decoder/plugins/SacdIsoDecoderPlugin.hxx create mode 100644 src/decoder/plugins/SidplayDecoderPlugin.cxx create mode 100644 src/decoder/plugins/SidplayDecoderPlugin.hxx create mode 100644 src/decoder/plugins/SndfileDecoderPlugin.cxx create mode 100644 src/decoder/plugins/SndfileDecoderPlugin.hxx create mode 100644 src/decoder/plugins/VorbisDecoderPlugin.cxx create mode 100644 src/decoder/plugins/VorbisDecoderPlugin.h create mode 100644 src/decoder/plugins/VorbisDomain.cxx create mode 100644 src/decoder/plugins/VorbisDomain.hxx create mode 100644 src/decoder/plugins/WavpackDecoderPlugin.cxx create mode 100644 src/decoder/plugins/WavpackDecoderPlugin.hxx create mode 100644 src/decoder/plugins/WildmidiDecoderPlugin.cxx create mode 100644 src/decoder/plugins/WildmidiDecoderPlugin.hxx create mode 100644 src/decoder/plugins/meson.build create mode 100644 src/encoder/Configured.cxx create mode 100644 src/encoder/Configured.hxx create mode 100644 src/encoder/EncoderAPI.hxx create mode 100644 src/encoder/EncoderInterface.hxx create mode 100644 src/encoder/EncoderList.cxx create mode 100644 src/encoder/EncoderList.hxx create mode 100644 src/encoder/EncoderPlugin.hxx create mode 100644 src/encoder/ToOutputStream.cxx create mode 100644 src/encoder/ToOutputStream.hxx create mode 100644 src/encoder/meson.build create mode 100644 src/encoder/plugins/FlacEncoderPlugin.cxx create mode 100644 src/encoder/plugins/FlacEncoderPlugin.hxx create mode 100644 src/encoder/plugins/LameEncoderPlugin.cxx create mode 100644 src/encoder/plugins/LameEncoderPlugin.hxx create mode 100644 src/encoder/plugins/NullEncoderPlugin.cxx create mode 100644 src/encoder/plugins/NullEncoderPlugin.hxx create mode 100644 src/encoder/plugins/OggEncoder.hxx create mode 100644 src/encoder/plugins/OpusEncoderPlugin.cxx create mode 100644 src/encoder/plugins/OpusEncoderPlugin.hxx create mode 100644 src/encoder/plugins/ShineEncoderPlugin.cxx create mode 100644 src/encoder/plugins/ShineEncoderPlugin.hxx create mode 100644 src/encoder/plugins/TwolameEncoderPlugin.cxx create mode 100644 src/encoder/plugins/TwolameEncoderPlugin.hxx create mode 100644 src/encoder/plugins/VorbisEncoderPlugin.cxx create mode 100644 src/encoder/plugins/VorbisEncoderPlugin.hxx create mode 100644 src/encoder/plugins/WaveEncoderPlugin.cxx create mode 100644 src/encoder/plugins/WaveEncoderPlugin.hxx create mode 100644 src/encoder/plugins/meson.build create mode 100644 src/event/Backend.hxx create mode 100644 src/event/BackendEvents.hxx create mode 100644 src/event/BufferedSocket.cxx create mode 100644 src/event/BufferedSocket.hxx create mode 100644 src/event/Call.cxx create mode 100644 src/event/Call.hxx create mode 100644 src/event/Chrono.hxx create mode 100644 src/event/CoarseTimerEvent.cxx create mode 100644 src/event/CoarseTimerEvent.hxx create mode 100644 src/event/DeferEvent.cxx create mode 100644 src/event/DeferEvent.hxx create mode 100644 src/event/EpollBackend.hxx create mode 100644 src/event/EpollEvents.hxx create mode 100644 src/event/FarTimerEvent.hxx create mode 100644 src/event/FineTimerEvent.cxx create mode 100644 src/event/FineTimerEvent.hxx create mode 100644 src/event/FullyBufferedSocket.cxx create mode 100644 src/event/FullyBufferedSocket.hxx create mode 100644 src/event/IdleEvent.hxx create mode 100644 src/event/InjectEvent.cxx create mode 100644 src/event/InjectEvent.hxx create mode 100644 src/event/InotifyEvent.cxx create mode 100644 src/event/InotifyEvent.hxx create mode 100644 src/event/InotifyManager.cxx create mode 100644 src/event/InotifyManager.hxx create mode 100644 src/event/Loop.cxx create mode 100644 src/event/Loop.hxx create mode 100644 src/event/MaskMonitor.cxx create mode 100644 src/event/MaskMonitor.hxx create mode 100644 src/event/MultiSocketMonitor.cxx create mode 100644 src/event/MultiSocketMonitor.hxx create mode 100644 src/event/PipeEvent.hxx create mode 100644 src/event/PollBackend.cxx create mode 100644 src/event/PollBackend.hxx create mode 100644 src/event/PollEvents.hxx create mode 100644 src/event/PollResultGeneric.hxx create mode 100644 src/event/ServerSocket.cxx create mode 100644 src/event/ServerSocket.hxx create mode 100644 src/event/SignalMonitor.cxx create mode 100644 src/event/SignalMonitor.hxx create mode 100644 src/event/SocketEvent.cxx create mode 100644 src/event/SocketEvent.hxx create mode 100644 src/event/Thread.cxx create mode 100644 src/event/Thread.hxx create mode 100644 src/event/TimerList.cxx create mode 100644 src/event/TimerList.hxx create mode 100644 src/event/TimerWheel.cxx create mode 100644 src/event/TimerWheel.hxx create mode 100644 src/event/WakeFD.hxx create mode 100644 src/event/WinSelectBackend.cxx create mode 100644 src/event/WinSelectBackend.hxx create mode 100644 src/event/WinSelectEvents.hxx create mode 100644 src/event/meson.build create mode 100644 src/event/uring/Manager.hxx create mode 100644 src/filter/Factory.cxx create mode 100644 src/filter/Factory.hxx create mode 100644 src/filter/Filter.hxx create mode 100644 src/filter/FilterPlugin.hxx create mode 100644 src/filter/LoadChain.cxx create mode 100644 src/filter/LoadChain.hxx create mode 100644 src/filter/LoadOne.cxx create mode 100644 src/filter/LoadOne.hxx create mode 100644 src/filter/NullFilter.hxx create mode 100644 src/filter/Observer.cxx create mode 100644 src/filter/Observer.hxx create mode 100644 src/filter/Prepared.hxx create mode 100644 src/filter/Registry.cxx create mode 100644 src/filter/Registry.hxx create mode 100644 src/filter/meson.build create mode 100644 src/filter/plugins/AutoConvertFilterPlugin.cxx create mode 100644 src/filter/plugins/AutoConvertFilterPlugin.hxx create mode 100644 src/filter/plugins/ConvertFilterPlugin.cxx create mode 100644 src/filter/plugins/ConvertFilterPlugin.hxx create mode 100644 src/filter/plugins/FfmpegFilter.cxx create mode 100644 src/filter/plugins/FfmpegFilter.hxx create mode 100644 src/filter/plugins/FfmpegFilterPlugin.cxx create mode 100644 src/filter/plugins/FfmpegFilterPlugin.hxx create mode 100644 src/filter/plugins/HdcdFilterPlugin.cxx create mode 100644 src/filter/plugins/HdcdFilterPlugin.hxx create mode 100644 src/filter/plugins/NormalizeFilterPlugin.cxx create mode 100644 src/filter/plugins/NormalizeFilterPlugin.hxx create mode 100644 src/filter/plugins/NullFilterPlugin.cxx create mode 100644 src/filter/plugins/NullFilterPlugin.hxx create mode 100644 src/filter/plugins/ReplayGainFilterPlugin.cxx create mode 100644 src/filter/plugins/ReplayGainFilterPlugin.hxx create mode 100644 src/filter/plugins/RouteFilterPlugin.cxx create mode 100644 src/filter/plugins/RouteFilterPlugin.hxx create mode 100644 src/filter/plugins/TwoFilters.cxx create mode 100644 src/filter/plugins/TwoFilters.hxx create mode 100644 src/filter/plugins/VolumeFilterPlugin.cxx create mode 100644 src/filter/plugins/VolumeFilterPlugin.hxx create mode 100644 src/filter/plugins/meson.build create mode 100644 src/fs/AllocatedPath.cxx create mode 100644 src/fs/AllocatedPath.hxx create mode 100644 src/fs/Charset.cxx create mode 100644 src/fs/Charset.hxx create mode 100644 src/fs/Config.cxx create mode 100644 src/fs/Config.hxx create mode 100644 src/fs/DirectoryReader.cxx create mode 100644 src/fs/DirectoryReader.hxx create mode 100644 src/fs/Domain.cxx create mode 100644 src/fs/Domain.hxx create mode 100644 src/fs/Features.hxx create mode 100644 src/fs/FileInfo.cxx create mode 100644 src/fs/FileInfo.hxx create mode 100644 src/fs/FileSystem.cxx create mode 100644 src/fs/FileSystem.hxx create mode 100644 src/fs/Glob.cxx create mode 100644 src/fs/Glob.hxx create mode 100644 src/fs/Limits.hxx create mode 100644 src/fs/List.cxx create mode 100644 src/fs/List.hxx create mode 100644 src/fs/LookupFile.cxx create mode 100644 src/fs/LookupFile.hxx create mode 100644 src/fs/NarrowPath.cxx create mode 100644 src/fs/NarrowPath.hxx create mode 100644 src/fs/Path.cxx create mode 100644 src/fs/Path.hxx create mode 100644 src/fs/Path2.cxx create mode 100644 src/fs/Traits.cxx create mode 100644 src/fs/Traits.hxx create mode 100644 src/fs/XDG.hxx create mode 100644 src/fs/glue/CheckFile.cxx create mode 100644 src/fs/glue/CheckFile.hxx create mode 100644 src/fs/glue/StandardDirectory.cxx create mode 100644 src/fs/glue/StandardDirectory.hxx create mode 100644 src/fs/glue/meson.build create mode 100644 src/fs/meson.build create mode 100644 src/input/AsyncInputStream.cxx create mode 100644 src/input/AsyncInputStream.hxx create mode 100644 src/input/BufferedInputStream.cxx create mode 100644 src/input/BufferedInputStream.hxx create mode 100644 src/input/BufferingInputStream.cxx create mode 100644 src/input/BufferingInputStream.hxx create mode 100644 src/input/CondHandler.hxx create mode 100644 src/input/Error.cxx create mode 100644 src/input/Error.hxx create mode 100644 src/input/FailingInputStream.hxx create mode 100644 src/input/Handler.hxx create mode 100644 src/input/IcyInputStream.cxx create mode 100644 src/input/IcyInputStream.hxx create mode 100644 src/input/Init.cxx create mode 100644 src/input/Init.hxx create mode 100644 src/input/InputPlugin.cxx create mode 100644 src/input/InputPlugin.hxx create mode 100644 src/input/InputStream.cxx create mode 100644 src/input/InputStream.hxx create mode 100644 src/input/LastInputStream.cxx create mode 100644 src/input/LastInputStream.hxx create mode 100644 src/input/LocalOpen.cxx create mode 100644 src/input/LocalOpen.hxx create mode 100644 src/input/MaybeBufferedInputStream.cxx create mode 100644 src/input/MaybeBufferedInputStream.hxx create mode 100644 src/input/MemoryInputStream.cxx create mode 100644 src/input/MemoryInputStream.hxx create mode 100644 src/input/Offset.hxx create mode 100644 src/input/Open.cxx create mode 100644 src/input/ProxyInputStream.cxx create mode 100644 src/input/ProxyInputStream.hxx create mode 100644 src/input/Ptr.hxx create mode 100644 src/input/Reader.cxx create mode 100644 src/input/Reader.hxx create mode 100644 src/input/Registry.cxx create mode 100644 src/input/Registry.hxx create mode 100644 src/input/RemoteTagScanner.hxx create mode 100644 src/input/RewindInputStream.cxx create mode 100644 src/input/RewindInputStream.hxx create mode 100644 src/input/ScanTags.cxx create mode 100644 src/input/ScanTags.hxx create mode 100644 src/input/TextInputStream.cxx create mode 100644 src/input/TextInputStream.hxx create mode 100644 src/input/ThreadInputStream.cxx create mode 100644 src/input/ThreadInputStream.hxx create mode 100644 src/input/WaitReady.cxx create mode 100644 src/input/WaitReady.hxx create mode 100644 src/input/cache/Config.cxx create mode 100644 src/input/cache/Config.hxx create mode 100644 src/input/cache/Item.cxx create mode 100644 src/input/cache/Item.hxx create mode 100644 src/input/cache/Lease.hxx create mode 100644 src/input/cache/Manager.cxx create mode 100644 src/input/cache/Manager.hxx create mode 100644 src/input/cache/Stream.cxx create mode 100644 src/input/cache/Stream.hxx create mode 100644 src/input/meson.build create mode 100644 src/input/plugins/AlsaInputPlugin.cxx create mode 100644 src/input/plugins/AlsaInputPlugin.hxx create mode 100644 src/input/plugins/ArchiveInputPlugin.cxx create mode 100644 src/input/plugins/ArchiveInputPlugin.hxx create mode 100644 src/input/plugins/CdioParanoiaInputPlugin.cxx create mode 100644 src/input/plugins/CdioParanoiaInputPlugin.hxx create mode 100644 src/input/plugins/CurlInputPlugin.cxx create mode 100644 src/input/plugins/CurlInputPlugin.hxx create mode 100644 src/input/plugins/FfmpegInputPlugin.cxx create mode 100644 src/input/plugins/FfmpegInputPlugin.hxx create mode 100644 src/input/plugins/FileInputPlugin.cxx create mode 100644 src/input/plugins/FileInputPlugin.hxx create mode 100644 src/input/plugins/MmsInputPlugin.cxx create mode 100644 src/input/plugins/MmsInputPlugin.hxx create mode 100644 src/input/plugins/NfsInputPlugin.cxx create mode 100644 src/input/plugins/NfsInputPlugin.hxx create mode 100644 src/input/plugins/QobuzClient.cxx create mode 100644 src/input/plugins/QobuzClient.hxx create mode 100644 src/input/plugins/QobuzErrorParser.cxx create mode 100644 src/input/plugins/QobuzErrorParser.hxx create mode 100644 src/input/plugins/QobuzInputPlugin.cxx create mode 100644 src/input/plugins/QobuzInputPlugin.hxx create mode 100644 src/input/plugins/QobuzLoginRequest.cxx create mode 100644 src/input/plugins/QobuzLoginRequest.hxx create mode 100644 src/input/plugins/QobuzSession.hxx create mode 100644 src/input/plugins/QobuzTagScanner.cxx create mode 100644 src/input/plugins/QobuzTagScanner.hxx create mode 100644 src/input/plugins/QobuzTrackRequest.cxx create mode 100644 src/input/plugins/QobuzTrackRequest.hxx create mode 100644 src/input/plugins/SmbclientInputPlugin.cxx create mode 100644 src/input/plugins/SmbclientInputPlugin.hxx create mode 100644 src/input/plugins/UringInputPlugin.cxx create mode 100644 src/input/plugins/UringInputPlugin.hxx create mode 100644 src/input/plugins/meson.build create mode 100644 src/io/BufferedOutputStream.cxx create mode 100644 src/io/BufferedOutputStream.hxx create mode 100644 src/io/BufferedReader.cxx create mode 100644 src/io/BufferedReader.hxx create mode 100644 src/io/FileAt.hxx create mode 100644 src/io/FileDescriptor.cxx create mode 100644 src/io/FileDescriptor.hxx create mode 100644 src/io/FileLineReader.hxx create mode 100644 src/io/FileOutputStream.cxx create mode 100644 src/io/FileOutputStream.hxx create mode 100644 src/io/FileReader.cxx create mode 100644 src/io/FileReader.hxx create mode 100644 src/io/LineReader.hxx create mode 100644 src/io/Open.cxx create mode 100644 src/io/Open.hxx create mode 100644 src/io/OutputStream.hxx create mode 100644 src/io/PeekReader.cxx create mode 100644 src/io/PeekReader.hxx create mode 100644 src/io/Reader.cxx create mode 100644 src/io/Reader.hxx create mode 100644 src/io/StdioOutputStream.hxx create mode 100644 src/io/StringOutputStream.hxx create mode 100644 src/io/UniqueFileDescriptor.hxx create mode 100644 src/io/linux/ProcPath.hxx create mode 100644 src/io/meson.build create mode 100644 src/io/uring/CancellableOperation.hxx create mode 100644 src/io/uring/Close.cxx create mode 100644 src/io/uring/Close.hxx create mode 100644 src/io/uring/Operation.cxx create mode 100644 src/io/uring/Operation.hxx create mode 100644 src/io/uring/Queue.cxx create mode 100644 src/io/uring/Queue.hxx create mode 100644 src/io/uring/ReadOperation.cxx create mode 100644 src/io/uring/ReadOperation.hxx create mode 100644 src/io/uring/Ring.cxx create mode 100644 src/io/uring/Ring.hxx create mode 100644 src/io/uring/meson.build create mode 100644 src/java/Class.hxx create mode 100644 src/java/Exception.cxx create mode 100644 src/java/Exception.hxx create mode 100644 src/java/File.cxx create mode 100644 src/java/File.hxx create mode 100644 src/java/Global.cxx create mode 100644 src/java/Global.hxx create mode 100644 src/java/Object.cxx create mode 100644 src/java/Object.hxx create mode 100644 src/java/Ref.hxx create mode 100644 src/java/String.cxx create mode 100644 src/java/String.hxx create mode 100644 src/java/meson.build create mode 100644 src/lib/alsa/AllowedFormat.cxx create mode 100644 src/lib/alsa/AllowedFormat.hxx create mode 100644 src/lib/alsa/ChannelMap.cxx create mode 100644 src/lib/alsa/ChannelMap.hxx create mode 100644 src/lib/alsa/Error.cxx create mode 100644 src/lib/alsa/Error.hxx create mode 100644 src/lib/alsa/Format.hxx create mode 100644 src/lib/alsa/HwSetup.cxx create mode 100644 src/lib/alsa/HwSetup.hxx create mode 100644 src/lib/alsa/NonBlock.cxx create mode 100644 src/lib/alsa/NonBlock.hxx create mode 100644 src/lib/alsa/PeriodBuffer.hxx create mode 100644 src/lib/alsa/Version.cxx create mode 100644 src/lib/alsa/Version.hxx create mode 100644 src/lib/alsa/meson.build create mode 100644 src/lib/avahi/Client.cxx create mode 100644 src/lib/avahi/Client.hxx create mode 100644 src/lib/avahi/ConnectionListener.hxx create mode 100644 src/lib/avahi/EntryGroup.hxx create mode 100644 src/lib/avahi/Error.cxx create mode 100644 src/lib/avahi/Error.hxx create mode 100644 src/lib/avahi/ErrorHandler.hxx create mode 100644 src/lib/avahi/Poll.cxx create mode 100644 src/lib/avahi/Poll.hxx create mode 100644 src/lib/avahi/Publisher.cxx create mode 100644 src/lib/avahi/Publisher.hxx create mode 100644 src/lib/avahi/Service.hxx create mode 100644 src/lib/cdio/Paranoia.hxx create mode 100644 src/lib/chromaprint/Context.hxx create mode 100644 src/lib/chromaprint/DecoderClient.cxx create mode 100644 src/lib/chromaprint/DecoderClient.hxx create mode 100644 src/lib/chromaprint/meson.build create mode 100644 src/lib/crypto/Base64.cxx create mode 100644 src/lib/crypto/Base64.hxx create mode 100644 src/lib/crypto/MD5.cxx create mode 100644 src/lib/crypto/MD5.hxx create mode 100644 src/lib/crypto/meson.build create mode 100644 src/lib/curl/Adapter.cxx create mode 100644 src/lib/curl/Adapter.hxx create mode 100644 src/lib/curl/Delegate.cxx create mode 100644 src/lib/curl/Delegate.hxx create mode 100644 src/lib/curl/Easy.hxx create mode 100644 src/lib/curl/Error.hxx create mode 100644 src/lib/curl/Escape.cxx create mode 100644 src/lib/curl/Escape.hxx create mode 100644 src/lib/curl/Form.cxx create mode 100644 src/lib/curl/Form.hxx create mode 100644 src/lib/curl/Global.cxx create mode 100644 src/lib/curl/Global.hxx create mode 100644 src/lib/curl/Handler.hxx create mode 100644 src/lib/curl/Headers.hxx create mode 100644 src/lib/curl/HttpStatusError.hxx create mode 100644 src/lib/curl/Init.cxx create mode 100644 src/lib/curl/Init.hxx create mode 100644 src/lib/curl/Multi.hxx create mode 100644 src/lib/curl/Parser.hxx create mode 100644 src/lib/curl/Request.cxx create mode 100644 src/lib/curl/Request.hxx create mode 100644 src/lib/curl/Setup.cxx create mode 100644 src/lib/curl/Setup.hxx create mode 100644 src/lib/curl/Slist.hxx create mode 100644 src/lib/curl/String.hxx create mode 100644 src/lib/curl/StringHandler.cxx create mode 100644 src/lib/curl/StringHandler.hxx create mode 100644 src/lib/curl/StringResponse.hxx create mode 100644 src/lib/curl/Version.cxx create mode 100644 src/lib/curl/Version.hxx create mode 100644 src/lib/curl/meson.build create mode 100644 src/lib/dbus/AppendIter.hxx create mode 100644 src/lib/dbus/AsyncRequest.hxx create mode 100644 src/lib/dbus/Connection.cxx create mode 100644 src/lib/dbus/Connection.hxx create mode 100644 src/lib/dbus/Error.cxx create mode 100644 src/lib/dbus/Error.hxx create mode 100644 src/lib/dbus/FilterHelper.cxx create mode 100644 src/lib/dbus/FilterHelper.hxx create mode 100644 src/lib/dbus/Glue.cxx create mode 100644 src/lib/dbus/Glue.hxx create mode 100644 src/lib/dbus/Init.hxx create mode 100644 src/lib/dbus/Iter.hxx create mode 100644 src/lib/dbus/Message.cxx create mode 100644 src/lib/dbus/Message.hxx create mode 100644 src/lib/dbus/ObjectManager.hxx create mode 100644 src/lib/dbus/PendingCall.hxx create mode 100644 src/lib/dbus/ReadIter.hxx create mode 100644 src/lib/dbus/ScopeMatch.cxx create mode 100644 src/lib/dbus/ScopeMatch.hxx create mode 100644 src/lib/dbus/Types.hxx create mode 100644 src/lib/dbus/UDisks2.cxx create mode 100644 src/lib/dbus/UDisks2.hxx create mode 100644 src/lib/dbus/Values.hxx create mode 100644 src/lib/dbus/Watch.cxx create mode 100644 src/lib/dbus/Watch.hxx create mode 100644 src/lib/dbus/meson.build create mode 100644 src/lib/dvdaiso/audio_stream.cpp create mode 100644 src/lib/dvdaiso/audio_stream.h create mode 100644 src/lib/dvdaiso/audio_stream_info.cpp create mode 100644 src/lib/dvdaiso/audio_stream_info.h create mode 100644 src/lib/dvdaiso/audio_track.cpp create mode 100644 src/lib/dvdaiso/audio_track.h create mode 100644 src/lib/dvdaiso/b2n.h create mode 100644 src/lib/dvdaiso/dvda_block.cpp create mode 100644 src/lib/dvdaiso/dvda_block.h create mode 100644 src/lib/dvdaiso/dvda_config.h create mode 100644 src/lib/dvdaiso/dvda_disc.cpp create mode 100644 src/lib/dvdaiso/dvda_disc.h create mode 100644 src/lib/dvdaiso/dvda_error.h create mode 100644 src/lib/dvdaiso/dvda_filesystem.cpp create mode 100644 src/lib/dvdaiso/dvda_filesystem.h create mode 100644 src/lib/dvdaiso/dvda_media.cpp create mode 100644 src/lib/dvdaiso/dvda_media.h create mode 100644 src/lib/dvdaiso/dvda_metabase.cpp create mode 100644 src/lib/dvdaiso/dvda_metabase.h create mode 100644 src/lib/dvdaiso/dvda_reader.h create mode 100644 src/lib/dvdaiso/dvda_zone.cpp create mode 100644 src/lib/dvdaiso/dvda_zone.h create mode 100644 src/lib/dvdaiso/dvdaerror.h create mode 100644 src/lib/dvdaiso/ifo.h create mode 100644 src/lib/dvdaiso/log_trunk.cpp create mode 100644 src/lib/dvdaiso/log_trunk.h create mode 100644 src/lib/dvdaiso/meson.build create mode 100644 src/lib/dvdaiso/mlp_audio_stream.cpp create mode 100644 src/lib/dvdaiso/mlp_audio_stream.h create mode 100644 src/lib/dvdaiso/pcm_audio_stream.cpp create mode 100644 src/lib/dvdaiso/pcm_audio_stream.h create mode 100644 src/lib/dvdaiso/stream_buffer.h create mode 100644 src/lib/dvdaiso/udf/dvd_input.cpp create mode 100644 src/lib/dvdaiso/udf/dvd_input.h create mode 100644 src/lib/dvdaiso/udf/dvd_reader.cpp create mode 100644 src/lib/dvdaiso/udf/dvd_reader.h create mode 100644 src/lib/dvdaiso/udf/dvd_udf.cpp create mode 100644 src/lib/dvdaiso/udf/dvd_udf.h create mode 100644 src/lib/expat/ExpatParser.cxx create mode 100644 src/lib/expat/ExpatParser.hxx create mode 100644 src/lib/expat/StreamExpatParser.cxx create mode 100644 src/lib/expat/meson.build create mode 100644 src/lib/ffmpeg/Buffer.hxx create mode 100644 src/lib/ffmpeg/ChannelLayout.hxx create mode 100644 src/lib/ffmpeg/Codec.hxx create mode 100644 src/lib/ffmpeg/DetectFilterFormat.cxx create mode 100644 src/lib/ffmpeg/DetectFilterFormat.hxx create mode 100644 src/lib/ffmpeg/Domain.cxx create mode 100644 src/lib/ffmpeg/Domain.hxx create mode 100644 src/lib/ffmpeg/Error.cxx create mode 100644 src/lib/ffmpeg/Error.hxx create mode 100644 src/lib/ffmpeg/Filter.cxx create mode 100644 src/lib/ffmpeg/Filter.hxx create mode 100644 src/lib/ffmpeg/Format.hxx create mode 100644 src/lib/ffmpeg/Frame.hxx create mode 100644 src/lib/ffmpeg/IOContext.hxx create mode 100644 src/lib/ffmpeg/Init.cxx create mode 100644 src/lib/ffmpeg/Init.hxx create mode 100644 src/lib/ffmpeg/Interleave.cxx create mode 100644 src/lib/ffmpeg/Interleave.hxx create mode 100644 src/lib/ffmpeg/LibFmt.hxx create mode 100644 src/lib/ffmpeg/LogCallback.cxx create mode 100644 src/lib/ffmpeg/LogCallback.hxx create mode 100644 src/lib/ffmpeg/SampleFormat.hxx create mode 100644 src/lib/ffmpeg/Time.hxx create mode 100644 src/lib/ffmpeg/meson.build create mode 100644 src/lib/fmt/AudioFormatFormatter.hxx create mode 100644 src/lib/fmt/ExceptionFormatter.cxx create mode 100644 src/lib/fmt/ExceptionFormatter.hxx create mode 100644 src/lib/fmt/PathFormatter.hxx create mode 100644 src/lib/fmt/RuntimeError.cxx create mode 100644 src/lib/fmt/RuntimeError.hxx create mode 100644 src/lib/fmt/SocketAddressFormatter.cxx create mode 100644 src/lib/fmt/SocketAddressFormatter.hxx create mode 100644 src/lib/fmt/SystemError.cxx create mode 100644 src/lib/fmt/SystemError.hxx create mode 100644 src/lib/fmt/ToBuffer.hxx create mode 100644 src/lib/fmt/Unsafe.hxx create mode 100644 src/lib/fmt/meson.build create mode 100644 src/lib/gcrypt/Hash.hxx create mode 100644 src/lib/gcrypt/Init.hxx create mode 100644 src/lib/gcrypt/MD5.cxx create mode 100644 src/lib/gcrypt/MD5.hxx create mode 100644 src/lib/gcrypt/meson.build create mode 100644 src/lib/icu/Canonicalize.cxx create mode 100644 src/lib/icu/Canonicalize.hxx create mode 100644 src/lib/icu/Collate.cxx create mode 100644 src/lib/icu/Collate.hxx create mode 100644 src/lib/icu/Compare.cxx create mode 100644 src/lib/icu/Compare.hxx create mode 100644 src/lib/icu/Converter.cxx create mode 100644 src/lib/icu/Converter.hxx create mode 100644 src/lib/icu/Error.hxx create mode 100644 src/lib/icu/FoldCase.cxx create mode 100644 src/lib/icu/FoldCase.hxx create mode 100644 src/lib/icu/Init.cxx create mode 100644 src/lib/icu/Init.hxx create mode 100644 src/lib/icu/Normalize.cxx create mode 100644 src/lib/icu/Normalize.hxx create mode 100644 src/lib/icu/Transliterator.cxx create mode 100644 src/lib/icu/Transliterator.hxx create mode 100644 src/lib/icu/Util.cxx create mode 100644 src/lib/icu/Util.hxx create mode 100644 src/lib/icu/Win32.cxx create mode 100644 src/lib/icu/Win32.hxx create mode 100644 src/lib/icu/meson.build create mode 100644 src/lib/modplug/patches/no_register create mode 100644 src/lib/modplug/patches/series create mode 100644 src/lib/nfs/Base.cxx create mode 100644 src/lib/nfs/Base.hxx create mode 100644 src/lib/nfs/Blocking.cxx create mode 100644 src/lib/nfs/Blocking.hxx create mode 100644 src/lib/nfs/Callback.hxx create mode 100644 src/lib/nfs/Cancellable.hxx create mode 100644 src/lib/nfs/Connection.cxx create mode 100644 src/lib/nfs/Connection.hxx create mode 100644 src/lib/nfs/Error.cxx create mode 100644 src/lib/nfs/Error.hxx create mode 100644 src/lib/nfs/FileReader.cxx create mode 100644 src/lib/nfs/FileReader.hxx create mode 100644 src/lib/nfs/Glue.cxx create mode 100644 src/lib/nfs/Glue.hxx create mode 100644 src/lib/nfs/Lease.hxx create mode 100644 src/lib/nfs/Manager.cxx create mode 100644 src/lib/nfs/Manager.hxx create mode 100644 src/lib/nfs/meson.build create mode 100644 src/lib/nlohmann_json/meson.build create mode 100644 src/lib/oss/meson.build create mode 100644 src/lib/pcre/Error.cxx create mode 100644 src/lib/pcre/Error.hxx create mode 100644 src/lib/pcre/MatchData.hxx create mode 100644 src/lib/pcre/RegexPointer.hxx create mode 100644 src/lib/pcre/UniqueRegex.cxx create mode 100644 src/lib/pcre/UniqueRegex.hxx create mode 100644 src/lib/pcre/meson.build create mode 100644 src/lib/pipewire/Error.cxx create mode 100644 src/lib/pipewire/Error.hxx create mode 100644 src/lib/pipewire/ThreadLoop.hxx create mode 100644 src/lib/pipewire/meson.build create mode 100644 src/lib/pulse/Domain.cxx create mode 100644 src/lib/pulse/Domain.hxx create mode 100644 src/lib/pulse/Error.cxx create mode 100644 src/lib/pulse/Error.hxx create mode 100644 src/lib/pulse/LockGuard.hxx create mode 100644 src/lib/pulse/LogError.cxx create mode 100644 src/lib/pulse/LogError.hxx create mode 100644 src/lib/pulse/meson.build create mode 100644 src/lib/sacdiso/endianess.h create mode 100644 src/lib/sacdiso/libdstdec/ac.h create mode 100644 src/lib/sacdiso/libdstdec/binding/dst_decoder.cpp create mode 100644 src/lib/sacdiso/libdstdec/binding/dst_decoder.h create mode 100644 src/lib/sacdiso/libdstdec/binding/dst_engine.h create mode 100644 src/lib/sacdiso/libdstdec/binding/std_semaphore.h create mode 100644 src/lib/sacdiso/libdstdec/common.h create mode 100644 src/lib/sacdiso/libdstdec/consts.h create mode 100644 src/lib/sacdiso/libdstdec/ct.h create mode 100644 src/lib/sacdiso/libdstdec/ct_enc.h create mode 100644 src/lib/sacdiso/libdstdec/decoder/decoder.cpp create mode 100644 src/lib/sacdiso/libdstdec/decoder/decoder.h create mode 100644 src/lib/sacdiso/libdstdec/fh.h create mode 100644 src/lib/sacdiso/libdstdec/fr.h create mode 100644 src/lib/sacdiso/libdstdec/segment.h create mode 100644 src/lib/sacdiso/libdstdec/stream.h create mode 100644 src/lib/sacdiso/log_printf.cpp create mode 100644 src/lib/sacdiso/log_printf.h create mode 100644 src/lib/sacdiso/meson.build create mode 100644 src/lib/sacdiso/sacd_disc.cpp create mode 100644 src/lib/sacdiso/sacd_disc.h create mode 100644 src/lib/sacdiso/sacd_dsd.h create mode 100644 src/lib/sacdiso/sacd_dsdiff.cpp create mode 100644 src/lib/sacdiso/sacd_dsdiff.h create mode 100644 src/lib/sacdiso/sacd_media.cpp create mode 100644 src/lib/sacdiso/sacd_media.h create mode 100644 src/lib/sacdiso/sacd_metabase.cpp create mode 100644 src/lib/sacdiso/sacd_metabase.h create mode 100644 src/lib/sacdiso/sacd_reader.h create mode 100644 src/lib/sacdiso/scarletbook.cpp create mode 100644 src/lib/sacdiso/scarletbook.h create mode 100644 src/lib/smbclient/Context.cxx create mode 100644 src/lib/smbclient/Context.hxx create mode 100644 src/lib/smbclient/Domain.cxx create mode 100644 src/lib/smbclient/Domain.hxx create mode 100644 src/lib/smbclient/Init.cxx create mode 100644 src/lib/smbclient/Init.hxx create mode 100644 src/lib/smbclient/meson.build create mode 100644 src/lib/sndio/meson.build create mode 100644 src/lib/sqlite/Database.cxx create mode 100644 src/lib/sqlite/Database.hxx create mode 100644 src/lib/sqlite/Error.cxx create mode 100644 src/lib/sqlite/Error.hxx create mode 100644 src/lib/sqlite/Util.hxx create mode 100644 src/lib/sqlite/meson.build create mode 100644 src/lib/systemd/Watchdog.cxx create mode 100644 src/lib/systemd/Watchdog.hxx create mode 100644 src/lib/systemd/meson.build create mode 100644 src/lib/upnp/Action.cxx create mode 100644 src/lib/upnp/Action.hxx create mode 100644 src/lib/upnp/Callback.hxx create mode 100644 src/lib/upnp/ClientInit.cxx create mode 100644 src/lib/upnp/ClientInit.hxx create mode 100644 src/lib/upnp/ContentDirectoryService.cxx create mode 100644 src/lib/upnp/ContentDirectoryService.hxx create mode 100644 src/lib/upnp/Device.cxx create mode 100644 src/lib/upnp/Device.hxx create mode 100644 src/lib/upnp/Discovery.cxx create mode 100644 src/lib/upnp/Discovery.hxx create mode 100644 src/lib/upnp/Error.hxx create mode 100644 src/lib/upnp/Init.cxx create mode 100644 src/lib/upnp/Init.hxx create mode 100644 src/lib/upnp/Util.cxx create mode 100644 src/lib/upnp/Util.hxx create mode 100644 src/lib/upnp/meson.build create mode 100644 src/lib/xiph/FlacAudioFormat.hxx create mode 100644 src/lib/xiph/FlacIOHandle.cxx create mode 100644 src/lib/xiph/FlacIOHandle.hxx create mode 100644 src/lib/xiph/FlacMetadataChain.cxx create mode 100644 src/lib/xiph/FlacMetadataChain.hxx create mode 100644 src/lib/xiph/FlacMetadataIterator.hxx create mode 100644 src/lib/xiph/FlacStreamMetadata.cxx create mode 100644 src/lib/xiph/FlacStreamMetadata.hxx create mode 100644 src/lib/xiph/OggFind.cxx create mode 100644 src/lib/xiph/OggFind.hxx create mode 100644 src/lib/xiph/OggPacket.cxx create mode 100644 src/lib/xiph/OggPacket.hxx create mode 100644 src/lib/xiph/OggPage.hxx create mode 100644 src/lib/xiph/OggStreamState.hxx create mode 100644 src/lib/xiph/OggSyncState.cxx create mode 100644 src/lib/xiph/OggSyncState.hxx create mode 100644 src/lib/xiph/OggVisitor.cxx create mode 100644 src/lib/xiph/OggVisitor.hxx create mode 100644 src/lib/xiph/ScanVorbisComment.cxx create mode 100644 src/lib/xiph/ScanVorbisComment.hxx create mode 100644 src/lib/xiph/VorbisComment.hxx create mode 100644 src/lib/xiph/VorbisComments.cxx create mode 100644 src/lib/xiph/VorbisComments.hxx create mode 100644 src/lib/xiph/VorbisPicture.cxx create mode 100644 src/lib/xiph/VorbisPicture.hxx create mode 100644 src/lib/xiph/XiphTags.cxx create mode 100644 src/lib/xiph/XiphTags.hxx create mode 100644 src/lib/xiph/meson.build create mode 100644 src/lib/zlib/AutoGunzipFileLineReader.cxx create mode 100644 src/lib/zlib/AutoGunzipFileLineReader.hxx create mode 100644 src/lib/zlib/AutoGunzipReader.cxx create mode 100644 src/lib/zlib/AutoGunzipReader.hxx create mode 100644 src/lib/zlib/Error.hxx create mode 100644 src/lib/zlib/GunzipReader.cxx create mode 100644 src/lib/zlib/GunzipReader.hxx create mode 100644 src/lib/zlib/GzipOutputStream.cxx create mode 100644 src/lib/zlib/GzipOutputStream.hxx create mode 100644 src/lib/zlib/meson.build create mode 100644 src/ls.cxx create mode 100644 src/ls.hxx create mode 100644 src/mixer/All.cxx create mode 100644 src/mixer/Control.cxx create mode 100644 src/mixer/Control.hxx create mode 100644 src/mixer/Listener.hxx create mode 100644 src/mixer/Memento.cxx create mode 100644 src/mixer/Memento.hxx create mode 100644 src/mixer/Mixer.cxx create mode 100644 src/mixer/Mixer.hxx create mode 100644 src/mixer/MixerPlugin.hxx create mode 100644 src/mixer/Type.cxx create mode 100644 src/mixer/Type.hxx create mode 100644 src/mixer/meson.build create mode 100644 src/mixer/plugins/AlsaMixerPlugin.cxx create mode 100644 src/mixer/plugins/AlsaMixerPlugin.hxx create mode 100644 src/mixer/plugins/AndroidMixerPlugin.cxx create mode 100644 src/mixer/plugins/AndroidMixerPlugin.hxx create mode 100644 src/mixer/plugins/NullMixerPlugin.cxx create mode 100644 src/mixer/plugins/NullMixerPlugin.hxx create mode 100644 src/mixer/plugins/OSXMixerPlugin.cxx create mode 100644 src/mixer/plugins/OSXMixerPlugin.hxx create mode 100644 src/mixer/plugins/OssMixerPlugin.cxx create mode 100644 src/mixer/plugins/OssMixerPlugin.hxx create mode 100644 src/mixer/plugins/PipeWireMixerPlugin.cxx create mode 100644 src/mixer/plugins/PipeWireMixerPlugin.hxx create mode 100644 src/mixer/plugins/PulseMixerPlugin.cxx create mode 100644 src/mixer/plugins/PulseMixerPlugin.hxx create mode 100644 src/mixer/plugins/SndioMixerPlugin.cxx create mode 100644 src/mixer/plugins/SndioMixerPlugin.hxx create mode 100644 src/mixer/plugins/SoftwareMixerPlugin.cxx create mode 100644 src/mixer/plugins/SoftwareMixerPlugin.hxx create mode 100644 src/mixer/plugins/VolumeMapping.cxx create mode 100644 src/mixer/plugins/VolumeMapping.hxx create mode 100644 src/mixer/plugins/WasapiMixerPlugin.cxx create mode 100644 src/mixer/plugins/WasapiMixerPlugin.hxx create mode 100644 src/mixer/plugins/WinmmMixerPlugin.cxx create mode 100644 src/mixer/plugins/WinmmMixerPlugin.hxx create mode 100644 src/mixer/plugins/meson.build create mode 100644 src/neighbor/Explorer.hxx create mode 100644 src/neighbor/Glue.cxx create mode 100644 src/neighbor/Glue.hxx create mode 100644 src/neighbor/Info.hxx create mode 100644 src/neighbor/Listener.hxx create mode 100644 src/neighbor/NeighborPlugin.hxx create mode 100644 src/neighbor/Registry.cxx create mode 100644 src/neighbor/Registry.hxx create mode 100644 src/neighbor/meson.build create mode 100644 src/neighbor/plugins/SmbclientNeighborPlugin.cxx create mode 100644 src/neighbor/plugins/SmbclientNeighborPlugin.hxx create mode 100644 src/neighbor/plugins/UdisksNeighborPlugin.cxx create mode 100644 src/neighbor/plugins/UdisksNeighborPlugin.hxx create mode 100644 src/neighbor/plugins/UpnpNeighborPlugin.cxx create mode 100644 src/neighbor/plugins/UpnpNeighborPlugin.hxx create mode 100644 src/neighbor/plugins/meson.build create mode 100644 src/net/AddressInfo.cxx create mode 100644 src/net/AddressInfo.hxx create mode 100644 src/net/AllocatedSocketAddress.cxx create mode 100644 src/net/AllocatedSocketAddress.hxx create mode 100644 src/net/DscpParser.cxx create mode 100644 src/net/DscpParser.hxx create mode 100644 src/net/FormatAddress.cxx create mode 100644 src/net/FormatAddress.hxx create mode 100644 src/net/HostParser.cxx create mode 100644 src/net/HostParser.hxx create mode 100644 src/net/IPv4Address.cxx create mode 100644 src/net/IPv4Address.hxx create mode 100644 src/net/IPv6Address.cxx create mode 100644 src/net/IPv6Address.hxx create mode 100644 src/net/Init.hxx create mode 100644 src/net/LocalSocketAddress.cxx create mode 100644 src/net/LocalSocketAddress.hxx create mode 100644 src/net/MsgHdr.hxx create mode 100644 src/net/PeerCredentials.hxx create mode 100644 src/net/Resolver.cxx create mode 100644 src/net/Resolver.hxx create mode 100644 src/net/SocketAddress.cxx create mode 100644 src/net/SocketAddress.hxx create mode 100644 src/net/SocketDescriptor.cxx create mode 100644 src/net/SocketDescriptor.hxx create mode 100644 src/net/SocketError.cxx create mode 100644 src/net/SocketError.hxx create mode 100644 src/net/SocketUtil.cxx create mode 100644 src/net/SocketUtil.hxx create mode 100644 src/net/StaticSocketAddress.cxx create mode 100644 src/net/StaticSocketAddress.hxx create mode 100644 src/net/ToString.cxx create mode 100644 src/net/ToString.hxx create mode 100644 src/net/UniqueSocketDescriptor.hxx create mode 100644 src/net/meson.build create mode 100644 src/open.h create mode 100644 src/output/Client.hxx create mode 100644 src/output/Control.cxx create mode 100644 src/output/Control.hxx create mode 100644 src/output/Defaults.cxx create mode 100644 src/output/Defaults.hxx create mode 100644 src/output/Domain.cxx create mode 100644 src/output/Domain.hxx create mode 100644 src/output/Error.hxx create mode 100644 src/output/Filtered.cxx create mode 100644 src/output/Filtered.hxx create mode 100644 src/output/Init.cxx create mode 100644 src/output/Interface.cxx create mode 100644 src/output/Interface.hxx create mode 100644 src/output/MultipleOutputs.cxx create mode 100644 src/output/MultipleOutputs.hxx create mode 100644 src/output/OutputAPI.hxx create mode 100644 src/output/OutputCommand.cxx create mode 100644 src/output/OutputCommand.hxx create mode 100644 src/output/OutputPlugin.cxx create mode 100644 src/output/OutputPlugin.hxx create mode 100644 src/output/Print.cxx create mode 100644 src/output/Print.hxx create mode 100644 src/output/Registry.cxx create mode 100644 src/output/Registry.hxx create mode 100644 src/output/SharedPipeConsumer.cxx create mode 100644 src/output/SharedPipeConsumer.hxx create mode 100644 src/output/Source.cxx create mode 100644 src/output/Source.hxx create mode 100644 src/output/State.cxx create mode 100644 src/output/State.hxx create mode 100644 src/output/Thread.cxx create mode 100644 src/output/Timer.cxx create mode 100644 src/output/Timer.hxx create mode 100644 src/output/meson.build create mode 100644 src/output/plugins/AlsaOutputPlugin.cxx create mode 100644 src/output/plugins/AlsaOutputPlugin.hxx create mode 100644 src/output/plugins/AoOutputPlugin.cxx create mode 100644 src/output/plugins/AoOutputPlugin.hxx create mode 100644 src/output/plugins/FifoOutputPlugin.cxx create mode 100644 src/output/plugins/FifoOutputPlugin.hxx create mode 100644 src/output/plugins/JackOutputPlugin.cxx create mode 100644 src/output/plugins/JackOutputPlugin.hxx create mode 100644 src/output/plugins/NullOutputPlugin.cxx create mode 100644 src/output/plugins/NullOutputPlugin.hxx create mode 100644 src/output/plugins/OSXOutputPlugin.cxx create mode 100644 src/output/plugins/OSXOutputPlugin.hxx create mode 100644 src/output/plugins/OpenALOutputPlugin.cxx create mode 100644 src/output/plugins/OpenALOutputPlugin.hxx create mode 100644 src/output/plugins/OssOutputPlugin.cxx create mode 100644 src/output/plugins/OssOutputPlugin.hxx create mode 100644 src/output/plugins/PipeOutputPlugin.cxx create mode 100644 src/output/plugins/PipeOutputPlugin.hxx create mode 100644 src/output/plugins/PipeWireOutputPlugin.cxx create mode 100644 src/output/plugins/PipeWireOutputPlugin.hxx create mode 100644 src/output/plugins/PulseOutputPlugin.cxx create mode 100644 src/output/plugins/PulseOutputPlugin.hxx create mode 100644 src/output/plugins/RecorderOutputPlugin.cxx create mode 100644 src/output/plugins/RecorderOutputPlugin.hxx create mode 100644 src/output/plugins/ShoutOutputPlugin.cxx create mode 100644 src/output/plugins/ShoutOutputPlugin.hxx create mode 100644 src/output/plugins/SndioOutputPlugin.cxx create mode 100644 src/output/plugins/SndioOutputPlugin.hxx create mode 100644 src/output/plugins/SolarisOutputPlugin.cxx create mode 100644 src/output/plugins/SolarisOutputPlugin.hxx create mode 100644 src/output/plugins/WinmmOutputPlugin.cxx create mode 100644 src/output/plugins/WinmmOutputPlugin.hxx create mode 100644 src/output/plugins/httpd/HttpdClient.cxx create mode 100644 src/output/plugins/httpd/HttpdClient.hxx create mode 100644 src/output/plugins/httpd/HttpdInternal.hxx create mode 100644 src/output/plugins/httpd/HttpdOutputPlugin.cxx create mode 100644 src/output/plugins/httpd/HttpdOutputPlugin.hxx create mode 100644 src/output/plugins/httpd/IcyMetaDataServer.cxx create mode 100644 src/output/plugins/httpd/IcyMetaDataServer.hxx create mode 100644 src/output/plugins/httpd/Page.hxx create mode 100644 src/output/plugins/meson.build create mode 100644 src/output/plugins/sles/AndroidSimpleBufferQueue.hxx create mode 100644 src/output/plugins/sles/Engine.hxx create mode 100644 src/output/plugins/sles/Object.hxx create mode 100644 src/output/plugins/sles/Play.hxx create mode 100644 src/output/plugins/sles/SlesOutputPlugin.cxx create mode 100644 src/output/plugins/sles/SlesOutputPlugin.hxx create mode 100644 src/output/plugins/snapcast/Chunk.hxx create mode 100644 src/output/plugins/snapcast/Client.cxx create mode 100644 src/output/plugins/snapcast/Client.hxx create mode 100644 src/output/plugins/snapcast/Internal.hxx create mode 100644 src/output/plugins/snapcast/Protocol.hxx create mode 100644 src/output/plugins/snapcast/SnapcastOutputPlugin.cxx create mode 100644 src/output/plugins/snapcast/SnapcastOutputPlugin.hxx create mode 100644 src/output/plugins/snapcast/Timestamp.hxx create mode 100644 src/output/plugins/wasapi/AudioClient.hxx create mode 100644 src/output/plugins/wasapi/Device.hxx create mode 100644 src/output/plugins/wasapi/ForMixer.hxx create mode 100644 src/output/plugins/wasapi/PropertyStore.hxx create mode 100644 src/output/plugins/wasapi/WasapiOutputPlugin.cxx create mode 100644 src/output/plugins/wasapi/WasapiOutputPlugin.hxx create mode 100644 src/pcm/AudioFormat.cxx create mode 100644 src/pcm/AudioFormat.hxx create mode 100644 src/pcm/AudioParser.cxx create mode 100644 src/pcm/AudioParser.hxx create mode 100644 src/pcm/Buffer.cxx create mode 100644 src/pcm/Buffer.hxx create mode 100644 src/pcm/ChannelDefs.hxx create mode 100644 src/pcm/ChannelsConverter.cxx create mode 100644 src/pcm/ChannelsConverter.hxx create mode 100644 src/pcm/CheckAudioFormat.cxx create mode 100644 src/pcm/CheckAudioFormat.hxx create mode 100644 src/pcm/Clamp.hxx create mode 100644 src/pcm/ConfiguredResampler.cxx create mode 100644 src/pcm/ConfiguredResampler.hxx create mode 100644 src/pcm/Convert.cxx create mode 100644 src/pcm/Convert.hxx create mode 100644 src/pcm/Dither.cxx create mode 100644 src/pcm/Dither.hxx create mode 100644 src/pcm/Dop.cxx create mode 100644 src/pcm/Dop.hxx create mode 100644 src/pcm/Dsd16.cxx create mode 100644 src/pcm/Dsd16.hxx create mode 100644 src/pcm/Dsd2Pcm.cxx create mode 100644 src/pcm/Dsd2Pcm.hxx create mode 100644 src/pcm/Dsd32.cxx create mode 100644 src/pcm/Dsd32.hxx create mode 100644 src/pcm/Export.cxx create mode 100644 src/pcm/Export.hxx create mode 100644 src/pcm/FallbackResampler.cxx create mode 100644 src/pcm/FallbackResampler.hxx create mode 100644 src/pcm/FloatConvert.hxx create mode 100644 src/pcm/FormatConverter.cxx create mode 100644 src/pcm/FormatConverter.hxx create mode 100644 src/pcm/GlueResampler.cxx create mode 100644 src/pcm/GlueResampler.hxx create mode 100644 src/pcm/Interleave.cxx create mode 100644 src/pcm/Interleave.hxx create mode 100644 src/pcm/LibsamplerateResampler.cxx create mode 100644 src/pcm/LibsamplerateResampler.hxx create mode 100644 src/pcm/Mix.cxx create mode 100644 src/pcm/Mix.hxx create mode 100644 src/pcm/MixRampAnalyzer.cxx create mode 100644 src/pcm/MixRampAnalyzer.hxx create mode 100644 src/pcm/MixRampGlue.cxx create mode 100644 src/pcm/MixRampGlue.hxx create mode 100644 src/pcm/Neon.hxx create mode 100644 src/pcm/Normalizer.cxx create mode 100644 src/pcm/Normalizer.hxx create mode 100644 src/pcm/Order.cxx create mode 100644 src/pcm/Order.hxx create mode 100644 src/pcm/Pack.cxx create mode 100644 src/pcm/Pack.hxx create mode 100644 src/pcm/PcmChannels.cxx create mode 100644 src/pcm/PcmChannels.hxx create mode 100644 src/pcm/PcmDsd.cxx create mode 100644 src/pcm/PcmDsd.hxx create mode 100644 src/pcm/PcmFormat.cxx create mode 100644 src/pcm/PcmFormat.hxx create mode 100644 src/pcm/Prng.hxx create mode 100644 src/pcm/ReplayGainAnalyzer.cxx create mode 100644 src/pcm/ReplayGainAnalyzer.hxx create mode 100644 src/pcm/Resampler.hxx create mode 100644 src/pcm/RestBuffer.hxx create mode 100644 src/pcm/SampleFormat.cxx create mode 100644 src/pcm/SampleFormat.hxx create mode 100644 src/pcm/ShiftConvert.hxx create mode 100644 src/pcm/Silence.cxx create mode 100644 src/pcm/Silence.hxx create mode 100644 src/pcm/SoxrResampler.cxx create mode 100644 src/pcm/SoxrResampler.hxx create mode 100644 src/pcm/Traits.hxx create mode 100644 src/pcm/Volume.cxx create mode 100644 src/pcm/Volume.hxx create mode 100644 src/pcm/meson.build create mode 100644 src/player/Control.cxx create mode 100644 src/player/Control.hxx create mode 100644 src/player/CrossFade.cxx create mode 100644 src/player/CrossFade.hxx create mode 100644 src/player/Listener.hxx create mode 100644 src/player/Outputs.hxx create mode 100644 src/player/Thread.cxx create mode 100644 src/playlist/Length.cxx create mode 100644 src/playlist/Length.hxx create mode 100644 src/playlist/MemorySongEnumerator.cxx create mode 100644 src/playlist/MemorySongEnumerator.hxx create mode 100644 src/playlist/PlaylistAny.cxx create mode 100644 src/playlist/PlaylistAny.hxx create mode 100644 src/playlist/PlaylistMapper.cxx create mode 100644 src/playlist/PlaylistMapper.hxx create mode 100644 src/playlist/PlaylistPlugin.cxx create mode 100644 src/playlist/PlaylistPlugin.hxx create mode 100644 src/playlist/PlaylistQueue.cxx create mode 100644 src/playlist/PlaylistQueue.hxx create mode 100644 src/playlist/PlaylistRegistry.cxx create mode 100644 src/playlist/PlaylistRegistry.hxx create mode 100644 src/playlist/PlaylistSong.cxx create mode 100644 src/playlist/PlaylistSong.hxx create mode 100644 src/playlist/PlaylistStream.cxx create mode 100644 src/playlist/PlaylistStream.hxx create mode 100644 src/playlist/Print.cxx create mode 100644 src/playlist/Print.hxx create mode 100644 src/playlist/SongEnumerator.hxx create mode 100644 src/playlist/cue/CueParser.cxx create mode 100644 src/playlist/cue/CueParser.hxx create mode 100644 src/playlist/meson.build create mode 100644 src/playlist/plugins/AsxPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/AsxPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/CuePlaylistPlugin.cxx create mode 100644 src/playlist/plugins/CuePlaylistPlugin.hxx create mode 100644 src/playlist/plugins/EmbeddedCuePlaylistPlugin.cxx create mode 100644 src/playlist/plugins/EmbeddedCuePlaylistPlugin.hxx create mode 100644 src/playlist/plugins/ExtM3uPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/ExtM3uPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/FlacPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/FlacPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/M3uPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/M3uPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/PlsPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/PlsPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/RssPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/RssPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/XspfPlaylistPlugin.cxx create mode 100644 src/playlist/plugins/XspfPlaylistPlugin.hxx create mode 100644 src/playlist/plugins/meson.build create mode 100644 src/protocol/Ack.hxx create mode 100644 src/protocol/ArgParser.cxx create mode 100644 src/protocol/ArgParser.hxx create mode 100644 src/protocol/IdleFlags.cxx create mode 100644 src/protocol/IdleFlags.hxx create mode 100644 src/protocol/RangeArg.hxx create mode 100644 src/queue/IdTable.hxx create mode 100644 src/queue/Listener.hxx create mode 100644 src/queue/Playlist.cxx create mode 100644 src/queue/Playlist.hxx create mode 100644 src/queue/PlaylistControl.cxx create mode 100644 src/queue/PlaylistEdit.cxx create mode 100644 src/queue/PlaylistState.cxx create mode 100644 src/queue/PlaylistState.hxx create mode 100644 src/queue/PlaylistTag.cxx create mode 100644 src/queue/PlaylistUpdate.cxx create mode 100644 src/queue/Print.cxx create mode 100644 src/queue/Print.hxx create mode 100644 src/queue/Queue.cxx create mode 100644 src/queue/Queue.hxx create mode 100644 src/queue/QueuePrint.cxx create mode 100644 src/queue/Save.cxx create mode 100644 src/queue/Save.hxx create mode 100644 src/queue/Selection.cxx create mode 100644 src/queue/Selection.hxx create mode 100644 src/song/AddedSinceSongFilter.cxx create mode 100644 src/song/AddedSinceSongFilter.hxx create mode 100644 src/song/AndSongFilter.cxx create mode 100644 src/song/AndSongFilter.hxx create mode 100644 src/song/AudioFormatSongFilter.cxx create mode 100644 src/song/AudioFormatSongFilter.hxx create mode 100644 src/song/BaseSongFilter.cxx create mode 100644 src/song/BaseSongFilter.hxx create mode 100644 src/song/DetachedSong.cxx create mode 100644 src/song/DetachedSong.hxx create mode 100644 src/song/Escape.cxx create mode 100644 src/song/Escape.hxx create mode 100644 src/song/Filter.cxx create mode 100644 src/song/Filter.hxx create mode 100644 src/song/ISongFilter.hxx create mode 100644 src/song/LightSong.cxx create mode 100644 src/song/LightSong.hxx create mode 100644 src/song/ModifiedSinceSongFilter.cxx create mode 100644 src/song/ModifiedSinceSongFilter.hxx create mode 100644 src/song/NotSongFilter.hxx create mode 100644 src/song/OptimizeFilter.cxx create mode 100644 src/song/OptimizeFilter.hxx create mode 100644 src/song/PrioritySongFilter.cxx create mode 100644 src/song/PrioritySongFilter.hxx create mode 100644 src/song/StringFilter.cxx create mode 100644 src/song/StringFilter.hxx create mode 100644 src/song/TagSongFilter.cxx create mode 100644 src/song/TagSongFilter.hxx create mode 100644 src/song/UriSongFilter.cxx create mode 100644 src/song/UriSongFilter.hxx create mode 100644 src/song/meson.build create mode 100644 src/sticker/AllowedTags.cxx create mode 100644 src/sticker/AllowedTags.hxx create mode 100644 src/sticker/CleanupService.cxx create mode 100644 src/sticker/CleanupService.hxx create mode 100644 src/sticker/Database.cxx create mode 100644 src/sticker/Database.hxx create mode 100644 src/sticker/Match.hxx create mode 100644 src/sticker/Print.cxx create mode 100644 src/sticker/Print.hxx create mode 100644 src/sticker/SongSticker.cxx create mode 100644 src/sticker/SongSticker.hxx create mode 100644 src/sticker/Sticker.hxx create mode 100644 src/sticker/TagSticker.cxx create mode 100644 src/sticker/TagSticker.hxx create mode 100644 src/storage/CompositeStorage.cxx create mode 100644 src/storage/CompositeStorage.hxx create mode 100644 src/storage/Configured.cxx create mode 100644 src/storage/Configured.hxx create mode 100644 src/storage/FileInfo.hxx create mode 100644 src/storage/MemoryDirectoryReader.cxx create mode 100644 src/storage/MemoryDirectoryReader.hxx create mode 100644 src/storage/Registry.cxx create mode 100644 src/storage/Registry.hxx create mode 100644 src/storage/StorageInterface.cxx create mode 100644 src/storage/StorageInterface.hxx create mode 100644 src/storage/StoragePlugin.cxx create mode 100644 src/storage/StoragePlugin.hxx create mode 100644 src/storage/StorageState.cxx create mode 100644 src/storage/StorageState.hxx create mode 100644 src/storage/meson.build create mode 100644 src/storage/plugins/CurlStorage.cxx create mode 100644 src/storage/plugins/CurlStorage.hxx create mode 100644 src/storage/plugins/LocalStorage.cxx create mode 100644 src/storage/plugins/LocalStorage.hxx create mode 100644 src/storage/plugins/NfsStorage.cxx create mode 100644 src/storage/plugins/NfsStorage.hxx create mode 100644 src/storage/plugins/SmbclientStorage.cxx create mode 100644 src/storage/plugins/SmbclientStorage.hxx create mode 100644 src/storage/plugins/UdisksStorage.cxx create mode 100644 src/storage/plugins/UdisksStorage.hxx create mode 100644 src/storage/plugins/meson.build create mode 100644 src/system/Clock.cxx create mode 100644 src/system/Clock.hxx create mode 100644 src/system/EpollFD.cxx create mode 100644 src/system/EpollFD.hxx create mode 100644 src/system/Error.hxx create mode 100644 src/system/EventFD.cxx create mode 100644 src/system/EventFD.hxx create mode 100644 src/system/EventPipe.cxx create mode 100644 src/system/EventPipe.hxx create mode 100644 src/system/KernelVersion.cxx create mode 100644 src/system/KernelVersion.hxx create mode 100644 src/system/SignalFD.cxx create mode 100644 src/system/SignalFD.hxx create mode 100644 src/system/VmaName.hxx create mode 100644 src/system/linux/meson.build create mode 100644 src/system/linux/openat2.h create mode 100644 src/system/meson.build create mode 100644 src/tag/Aiff.cxx create mode 100644 src/tag/Aiff.hxx create mode 100644 src/tag/ApeLoader.cxx create mode 100644 src/tag/ApeLoader.hxx create mode 100644 src/tag/ApeReplayGain.cxx create mode 100644 src/tag/ApeReplayGain.hxx create mode 100644 src/tag/ApeTag.cxx create mode 100644 src/tag/ApeTag.hxx create mode 100644 src/tag/Builder.cxx create mode 100644 src/tag/Builder.hxx create mode 100644 src/tag/Config.cxx create mode 100644 src/tag/Config.hxx create mode 100644 src/tag/Fallback.hxx create mode 100644 src/tag/FixString.cxx create mode 100644 src/tag/FixString.hxx create mode 100644 src/tag/Format.cxx create mode 100644 src/tag/Format.hxx create mode 100644 src/tag/GenParseName.cxx create mode 100644 src/tag/Generic.cxx create mode 100644 src/tag/Generic.hxx create mode 100644 src/tag/Handler.cxx create mode 100644 src/tag/Handler.hxx create mode 100644 src/tag/IcyMetaDataParser.cxx create mode 100644 src/tag/IcyMetaDataParser.hxx create mode 100644 src/tag/Id3Load.cxx create mode 100644 src/tag/Id3Load.hxx create mode 100644 src/tag/Id3MixRamp.cxx create mode 100644 src/tag/Id3MixRamp.hxx create mode 100644 src/tag/Id3MusicBrainz.cxx create mode 100644 src/tag/Id3MusicBrainz.hxx create mode 100644 src/tag/Id3Parse.hxx create mode 100644 src/tag/Id3Picture.cxx create mode 100644 src/tag/Id3Picture.hxx create mode 100644 src/tag/Id3ReplayGain.cxx create mode 100644 src/tag/Id3ReplayGain.hxx create mode 100644 src/tag/Id3Scan.cxx create mode 100644 src/tag/Id3Scan.hxx create mode 100644 src/tag/Id3String.hxx create mode 100644 src/tag/Id3Unique.hxx create mode 100644 src/tag/Item.hxx create mode 100644 src/tag/Mask.hxx create mode 100644 src/tag/MixRampInfo.hxx create mode 100644 src/tag/MixRampParser.cxx create mode 100644 src/tag/MixRampParser.hxx create mode 100644 src/tag/Names.cxx create mode 100644 src/tag/Names.hxx create mode 100644 src/tag/ParseName.cxx create mode 100644 src/tag/ParseName.hxx create mode 100644 src/tag/Pool.cxx create mode 100644 src/tag/Pool.hxx create mode 100644 src/tag/ReplayGainInfo.cxx create mode 100644 src/tag/ReplayGainInfo.hxx create mode 100644 src/tag/ReplayGainParser.cxx create mode 100644 src/tag/ReplayGainParser.hxx create mode 100644 src/tag/RiffFormat.hxx create mode 100644 src/tag/RiffId3.cxx create mode 100644 src/tag/RiffId3.hxx create mode 100644 src/tag/Rva2.cxx create mode 100644 src/tag/Rva2.hxx create mode 100644 src/tag/Settings.cxx create mode 100644 src/tag/Settings.hxx create mode 100644 src/tag/Sort.cxx create mode 100644 src/tag/Sort.hxx create mode 100644 src/tag/Table.cxx create mode 100644 src/tag/Table.hxx create mode 100644 src/tag/Tag.cxx create mode 100644 src/tag/Tag.hxx create mode 100644 src/tag/Type.hxx create mode 100644 src/tag/VisitFallback.hxx create mode 100644 src/tag/VorbisComment.cxx create mode 100644 src/tag/VorbisComment.hxx create mode 100644 src/tag/meson.build create mode 100644 src/thread/AsyncWaiter.hxx create mode 100644 src/thread/Cond.hxx create mode 100644 src/thread/CriticalSection.hxx create mode 100644 src/thread/Future.hxx create mode 100644 src/thread/Id.hxx create mode 100644 src/thread/Mutex.hxx create mode 100644 src/thread/Name.hxx create mode 100644 src/thread/SafeSingleton.hxx create mode 100644 src/thread/Slack.hxx create mode 100644 src/thread/Thread.cxx create mode 100644 src/thread/Thread.hxx create mode 100644 src/thread/Util.cxx create mode 100644 src/thread/Util.hxx create mode 100644 src/thread/WindowsCond.hxx create mode 100644 src/thread/WindowsFuture.hxx create mode 100644 src/thread/meson.build create mode 100644 src/time/Calendar.hxx create mode 100644 src/time/ChronoUtil.hxx create mode 100644 src/time/ClockCache.hxx create mode 100644 src/time/Convert.cxx create mode 100644 src/time/Convert.hxx create mode 100644 src/time/FileTime.hxx create mode 100644 src/time/ISO8601.cxx create mode 100644 src/time/ISO8601.hxx create mode 100644 src/time/Math.cxx create mode 100644 src/time/Math.hxx create mode 100644 src/time/PeriodClock.hxx create mode 100644 src/time/SystemClock.hxx create mode 100644 src/time/Zone.cxx create mode 100644 src/time/Zone.hxx create mode 100644 src/time/meson.build create mode 100644 src/unix/Daemon.cxx create mode 100644 src/unix/Daemon.hxx create mode 100644 src/unix/PidFile.hxx create mode 100644 src/unix/SignalHandlers.cxx create mode 100644 src/unix/SignalHandlers.hxx create mode 100644 src/util/ASCII.hxx create mode 100644 src/util/AllocatedArray.hxx create mode 100644 src/util/AllocatedString.hxx create mode 100644 src/util/BindMethod.hxx create mode 100644 src/util/BitReverse.cxx create mode 100644 src/util/BitReverse.hxx create mode 100644 src/util/ByteOrder.hxx create mode 100644 src/util/ByteReverse.cxx create mode 100644 src/util/ByteReverse.hxx create mode 100644 src/util/CNumberParser.hxx create mode 100644 src/util/Cast.hxx create mode 100644 src/util/CharUtil.hxx create mode 100644 src/util/CircularBuffer.hxx create mode 100644 src/util/Clamp.hxx create mode 100644 src/util/Compiler.h create mode 100644 src/util/Concepts.hxx create mode 100644 src/util/CopyConst.hxx create mode 100644 src/util/DeleteDisposer.hxx create mode 100644 src/util/DereferenceIterator.hxx create mode 100644 src/util/DisposablePointer.hxx create mode 100644 src/util/Domain.hxx create mode 100644 src/util/DynamicFifoBuffer.hxx create mode 100644 src/util/Exception.cxx create mode 100644 src/util/Exception.hxx create mode 100644 src/util/FilteredContainer.hxx create mode 100644 src/util/ForeignFifoBuffer.hxx create mode 100644 src/util/GenerateArray.hxx create mode 100644 src/util/HexFormat.hxx create mode 100644 src/util/HugeAllocator.cxx create mode 100644 src/util/HugeAllocator.hxx create mode 100644 src/util/IntrusiveForwardList.hxx create mode 100644 src/util/IntrusiveHashSet.hxx create mode 100644 src/util/IntrusiveHookMode.hxx create mode 100644 src/util/IntrusiveList.hxx create mode 100644 src/util/IntrusiveTreeSet.hxx create mode 100644 src/util/IterableSplitString.hxx create mode 100644 src/util/LazyRandomEngine.cxx create mode 100644 src/util/LazyRandomEngine.hxx create mode 100644 src/util/Manual.hxx create mode 100644 src/util/Math.hxx create mode 100644 src/util/MemberPointer.hxx create mode 100644 src/util/MimeType.cxx create mode 100644 src/util/MimeType.hxx create mode 100644 src/util/NumberParser.hxx create mode 100644 src/util/OffsetPointer.hxx create mode 100644 src/util/OptionalCounter.hxx create mode 100644 src/util/OptionalField.hxx create mode 100644 src/util/PackedBigEndian.hxx create mode 100644 src/util/PackedLittleEndian.hxx create mode 100644 src/util/PeakBuffer.cxx create mode 100644 src/util/PeakBuffer.hxx create mode 100644 src/util/PrintException.cxx create mode 100644 src/util/PrintException.hxx create mode 100644 src/util/RecursiveMap.hxx create mode 100644 src/util/RedBlackTree.hxx create mode 100644 src/util/ReusableArray.hxx create mode 100644 src/util/RingBuffer.hxx create mode 100644 src/util/RoundPowerOfTwo.hxx create mode 100644 src/util/ScopeExit.hxx create mode 100644 src/util/Serial.cxx create mode 100644 src/util/Serial.hxx create mode 100644 src/util/SliceBuffer.hxx create mode 100644 src/util/SortList.hxx create mode 100644 src/util/SpanCast.hxx create mode 100644 src/util/SparseBuffer.cxx create mode 100644 src/util/SparseBuffer.hxx create mode 100644 src/util/SplitString.cxx create mode 100644 src/util/SplitString.hxx create mode 100644 src/util/StaticFifoBuffer.hxx create mode 100644 src/util/StaticVector.hxx create mode 100644 src/util/StringAPI.hxx create mode 100644 src/util/StringBuffer.hxx create mode 100644 src/util/StringCompare.cxx create mode 100644 src/util/StringCompare.hxx create mode 100644 src/util/StringPointer.hxx create mode 100644 src/util/StringSplit.hxx create mode 100644 src/util/StringStrip.cxx create mode 100644 src/util/StringStrip.hxx create mode 100644 src/util/StringUtil.cxx create mode 100644 src/util/StringUtil.hxx create mode 100644 src/util/StringVerify.hxx create mode 100644 src/util/TagStructs.hxx create mode 100644 src/util/TemplateString.hxx create mode 100644 src/util/TerminatedArray.hxx create mode 100644 src/util/TextFile.hxx create mode 100644 src/util/Tokenizer.cxx create mode 100644 src/util/Tokenizer.hxx create mode 100644 src/util/TransformN.hxx create mode 100644 src/util/TruncateString.cxx create mode 100644 src/util/TruncateString.hxx create mode 100644 src/util/UTF8.cxx create mode 100644 src/util/UTF8.hxx create mode 100644 src/util/UriExtract.cxx create mode 100644 src/util/UriExtract.hxx create mode 100644 src/util/UriQueryParser.cxx create mode 100644 src/util/UriQueryParser.hxx create mode 100644 src/util/UriRelative.cxx create mode 100644 src/util/UriRelative.hxx create mode 100644 src/util/UriUtil.cxx create mode 100644 src/util/UriUtil.hxx create mode 100644 src/util/VarSize.hxx create mode 100644 src/util/WCharUtil.hxx create mode 100644 src/util/WStringAPI.hxx create mode 100644 src/util/WStringCompare.cxx create mode 100644 src/util/WStringCompare.hxx create mode 100644 src/util/djb_hash.hxx create mode 100644 src/util/format.c create mode 100644 src/util/format.h create mode 100644 src/util/meson.build create mode 100644 src/win32/Com.hxx create mode 100644 src/win32/ComHeapPtr.hxx create mode 100644 src/win32/ComPtr.hxx create mode 100644 src/win32/ComWorker.cxx create mode 100644 src/win32/ComWorker.hxx create mode 100644 src/win32/HResult.cxx create mode 100644 src/win32/HResult.hxx create mode 100644 src/win32/PropVariant.cxx create mode 100644 src/win32/PropVariant.hxx create mode 100644 src/win32/Win32Main.cxx create mode 100644 src/win32/WinEvent.cxx create mode 100644 src/win32/WinEvent.hxx create mode 100644 src/win32/meson.build create mode 100644 src/zeroconf/Bonjour.cxx create mode 100644 src/zeroconf/Bonjour.hxx create mode 100644 src/zeroconf/Glue.cxx create mode 100644 src/zeroconf/Glue.hxx create mode 100644 src/zeroconf/Helper.cxx create mode 100644 src/zeroconf/Helper.hxx create mode 100644 src/zeroconf/avahi/Helper.cxx create mode 100644 src/zeroconf/avahi/Helper.hxx create mode 100644 src/zeroconf/avahi/meson.build create mode 100644 src/zeroconf/meson.build create mode 100644 subprojects/.gitignore create mode 100644 subprojects/curl.wrap create mode 100644 subprojects/expat.wrap create mode 100644 subprojects/flac.wrap create mode 100644 subprojects/fmt.wrap create mode 100644 subprojects/gtest.wrap create mode 100644 subprojects/id3tag.wrap create mode 100644 subprojects/lame.wrap create mode 100644 subprojects/libmpdclient.wrap create mode 100644 subprojects/libnpupnp.wrap create mode 100644 subprojects/libsndfile.wrap create mode 100644 subprojects/liburing.wrap create mode 100644 subprojects/nlohmann_json.wrap create mode 100644 subprojects/ogg.wrap create mode 100644 subprojects/openssl.wrap create mode 100644 subprojects/opus.wrap create mode 100644 subprojects/packagefiles/id3tag/meson.build create mode 100644 subprojects/sqlite3.wrap create mode 100644 subprojects/vorbis.wrap create mode 100644 systemd/meson.build create mode 100644 systemd/system/meson.build create mode 100644 systemd/system/mpd.service.in create mode 100644 systemd/system/mpd.socket.in create mode 100644 systemd/user/meson.build create mode 100644 systemd/user/mpd.service.in create mode 100644 test/ConfigGlue.hxx create mode 100644 test/ContainerScan.cxx create mode 100644 test/DumpDatabase.cxx create mode 100644 test/DumpDecoderClient.cxx create mode 100644 test/DumpDecoderClient.hxx create mode 100644 test/DumpOgg.cxx create mode 100644 test/LoadDatabase.cxx create mode 100644 test/MakeTag.hxx create mode 100644 test/NullMixerListener.hxx create mode 100644 test/ParseSongFilter.cxx create mode 100644 test/ReadApeTags.cxx create mode 100644 test/ReadFrames.cxx create mode 100644 test/ReadFrames.hxx create mode 100644 test/RunChromaprint.cxx create mode 100644 test/RunCurl.cxx create mode 100644 test/RunMixRampAnalyzer.cxx create mode 100644 test/RunReplayGainAnalyzer.cxx create mode 100644 test/RunZeroconf.cxx create mode 100644 test/ShutdownHandler.cxx create mode 100644 test/ShutdownHandler.hxx create mode 100644 test/TestAudioFormat.cxx create mode 100644 test/TestIcu.cxx create mode 100644 test/TestRewindInputStream.cxx create mode 100644 test/TestStringFilter.cxx create mode 100644 test/TestTagSongFilter.cxx create mode 100644 test/WriteFile.cxx create mode 100644 test/dump_playlist.cxx create mode 100644 test/dump_rva2.cxx create mode 100644 test/dump_text_file.cxx create mode 100644 test/fs/TestGlob.cxx create mode 100644 test/fs/TestLookupFile.cxx create mode 100644 test/fs/TestParsePath.cxx create mode 100644 test/fs/TestPath.cxx create mode 100644 test/fs/meson.build create mode 100644 test/fuzzer/FuzzCueParser.cxx create mode 100644 test/fuzzer/meson.build create mode 100644 test/meson.build create mode 100644 test/net/TestIPv4Address.cxx create mode 100644 test/net/TestIPv6Address.cxx create mode 100644 test/net/TestLocalSocketAddress.cxx create mode 100644 test/net/meson.build create mode 100644 test/playlist/PlaylistUtil.cxx create mode 100644 test/playlist/PlaylistUtil.hxx create mode 100644 test/playlist/TestPlsPlaylistPlugin.cxx create mode 100644 test/playlist/meson.build create mode 100644 test/read_conf.cxx create mode 100644 test/read_mixer.cxx create mode 100644 test/read_tags.cxx create mode 100644 test/run_convert.cxx create mode 100644 test/run_decoder.cxx create mode 100644 test/run_encoder.cxx create mode 100644 test/run_filter.cxx create mode 100644 test/run_gunzip.cxx create mode 100644 test/run_gzip.cxx create mode 100644 test/run_inotify.cxx create mode 100644 test/run_input.cxx create mode 100644 test/run_neighbor_explorer.cxx create mode 100644 test/run_normalize.cxx create mode 100644 test/run_output.cxx create mode 100644 test/run_resolver.cxx create mode 100644 test/run_storage.cxx create mode 100644 test/software_volume.cxx create mode 100644 test/tag/TestMixRampInterpolate.cxx create mode 100644 test/tag/TestMixRampParser.cxx create mode 100644 test/tag/meson.build create mode 100755 test/test_archive_bzip2.sh create mode 100755 test/test_archive_iso9660.sh create mode 100755 test/test_archive_zzip.sh create mode 100644 test/test_icy_parser.cxx create mode 100644 test/test_pcm_channels.cxx create mode 100644 test/test_pcm_dither.cxx create mode 100644 test/test_pcm_export.cxx create mode 100644 test/test_pcm_format.cxx create mode 100644 test/test_pcm_interleave.cxx create mode 100644 test/test_pcm_mix.cxx create mode 100644 test/test_pcm_pack.cxx create mode 100644 test/test_pcm_util.hxx create mode 100644 test/test_pcm_volume.cxx create mode 100644 test/test_protocol.cxx create mode 100644 test/test_queue_priority.cxx create mode 100644 test/test_translate_song.cxx create mode 100644 test/test_vorbis_encoder.cxx create mode 100644 test/time/TestConvert.cxx create mode 100644 test/time/TestFileTime.cxx create mode 100644 test/time/TestISO8601.cxx create mode 100644 test/time/meson.build create mode 100644 test/util/TestCircularBuffer.cxx create mode 100644 test/util/TestException.cxx create mode 100644 test/util/TestIntrusiveForwardList.cxx create mode 100644 test/util/TestIntrusiveHashSet.cxx create mode 100644 test/util/TestIntrusiveList.cxx create mode 100644 test/util/TestIntrusiveTreeSet.cxx create mode 100644 test/util/TestMimeType.cxx create mode 100644 test/util/TestRingBuffer.cxx create mode 100644 test/util/TestSplitString.cxx create mode 100644 test/util/TestStringStrip.cxx create mode 100644 test/util/TestTemplateString.cxx create mode 100644 test/util/TestTerminatedArray.cxx create mode 100644 test/util/TestUriExtract.cxx create mode 100644 test/util/TestUriQueryParser.cxx create mode 100644 test/util/TestUriRelative.cxx create mode 100644 test/util/TestUriUtil.cxx create mode 100644 test/util/meson.build create mode 100644 test/util/test_byte_reverse.cxx create mode 100644 test/visit_archive.cxx create mode 100644 valgrind.suppressions create mode 100755 win32/build.py create mode 100644 win32/meson.build create mode 100644 win32/res/meson.build create mode 100644 win32/res/mpd.ico create mode 100644 win32/res/mpd.rc.in diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..26f6a86 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,49 @@ +Music Player Daemon - http://www.musicpd.org +Copyright 2003-2025 The Music Player Daemon Project + +The following people have contributed code to MPD: + + Warren Dukes + Avuton Olrich + Max Kellermann + Laszlo Ashin + Viliam Mateicka + Eric Wollesen + Thomas Jansen + Romain Bignon + David Guibert + Jochen Keil + Jeffrey Middleton + Sean McNamara + Niklas Hofer + Jim Ramsay + Guus Sliepen + J. Alexander Treuman + Eric Wong + José Anarch + Patrik Weiskircher + Nick Welch + Jonathan Neuschäfer + Anton Khirnov + Simon Kagstrom + Denis Krjuchkov + Jurgen Kramer + Jean-Francois Dockes + Yue Wang + Matthew Leon Grinshpun + Dimitris Papastamos + Florian Schlichting + François Revol + Jacob Vosmaer + Thomas Guillem + Andrew Basterfield + Bart Nagel + Christian Kröner + Christopher Zimmermann + John Regan + Joshua Wise + Ryan Walklin + Stefan Roellin + Stefano Miccoli + Steven O'Brien + Thomas Zander diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/LICENSES/BSD-2-Clause.txt b/LICENSES/BSD-2-Clause.txt new file mode 100644 index 0000000..5f662b3 --- /dev/null +++ b/LICENSES/BSD-2-Clause.txt @@ -0,0 +1,9 @@ +Copyright (c) + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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 COPYRIGHT HOLDER 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. diff --git a/LICENSES/GPL-2.0-or-later.txt b/LICENSES/GPL-2.0-or-later.txt new file mode 100644 index 0000000..17cb286 --- /dev/null +++ b/LICENSES/GPL-2.0-or-later.txt @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/LICENSES/ISC.txt b/LICENSES/ISC.txt new file mode 100644 index 0000000..b9c199c --- /dev/null +++ b/LICENSES/ISC.txt @@ -0,0 +1,8 @@ +ISC License: + +Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1995-2003 by Internet Software Consortium + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/LGPL-2.1-only.txt b/LICENSES/LGPL-2.1-only.txt new file mode 100644 index 0000000..c9aa530 --- /dev/null +++ b/LICENSES/LGPL-2.1-only.txt @@ -0,0 +1,175 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..e08e9fc --- /dev/null +++ b/NEWS @@ -0,0 +1,2906 @@ +ver 0.25 (not yet released) +* protocol + - implement "window" parameter for command "list" +* output + - pipewire: add option "reconnect_stream" +* switch to C++23 +* require Meson 1.2 + +ver 0.24.5 (not yet released) + +ver 0.24.4 (2025/05/20) +* protocol + - fix stuck "getfingerprint" with io_uring +* decoder + - mpg123: support Icy stream tags + - mpg123: use libid3tag to parse stream tags +* tags + - id3: fix assertion failure with broken AIFF/RIFF ID3 chunks +* output + - fix resuming playback after it was paused by "single" mode + - alsa: fix compiler warning with alsa-lib 1.2.14 + +ver 0.24.3 (2025/04/09) +* input + - qobuz: use nlohmann_json instead of yajl +* playlist + - soundcloud: remove defunct plugin +* decoder + - ffmpeg: support WMA + - mpg123: fix trailing space in tag values +* tags + - libid3tag: fix Meson subproject configure error + - libid3tag: add missing zlib dependency to Meson subproject +* output + - oss: fix error "Resource temporarily unavailable" + - shout: fix hang on activating shout output + - snapcast: use nlohmann_json instead of yajl to generate JSON tags +* Linux + - allow using io_uring on Linux kernels older than 6.0 +* Windows + - fix cross build on Linux when WINE is not installed +* DSD: support channel conversion + +ver 0.24.2 (2025/03/26) +* input + - io_uring: fix stuck seek after I/O error +* decoder + - flac: enable chained Ogg decoding +* player + - fix stalled playback after queue modification + - fix deadlock with "single" mode +* Linux: fix build failure with ancient kernel headers + +ver 0.24.1 (2025/03/21) +* input + - curl: fix malformed "Range" header +* output + - sndio: fix rounding error in volume calculation +* log: include year in time stamp +* Linux + - add configure-time check for openat2() + - fix use-after-free bug on io_uring shutdown +* macOS + - implement standard directories + - fix command-line parser errors +* fix build failure in the "id3tag" Meson subproject +* doc: use "sphinx_rtd_theme" only if it is installed + +ver 0.24 (2025/03/11) +* protocol + - new command "searchcount" (case-insensitive "count") + - "playlistfind"/"playlistsearch" have "sort" and "window" parameters + - allow range in "playlistmove" + - "save" can append to or replace an existing playlist + - filter "prio" (for "playlistfind"/"playlistsearch") + - limit "player" idle events to the current partition + - operator "starts_with" + - show PCRE support in "config" response + - apply Unicode normalization to case-insensitive filter expressions + - stickers on playlists and some tag types + - new commands "stickernames", "stickertypes", "stickernamestypes", "playlistlength", "searchplaylist", "protocol" + - new "search"/"find" filter "added-since" + - allow range in listplaylist and listplaylistinfo + - "sticker find" supports sort and window parameter and new sticker compare operators "eq", "lt", "gt", "contains" and "starts_with" + - consume only idle flags that were subscribed to + - volume command is no longer deprecated + - new "available" and "reset" subcommands for tagtypes + - searching stored playlists respond now with song position + - new sticker subcommand "inc" and "dec" +* database + - attribute "added" shows when each song was added to the database + - proxy: require MPD 0.21 or later + - proxy: require libmpdclient 2.15 or later +* archive + - add option to disable archive plugins in mpd.conf +* storage + - curl: optimize database update + - nfs: require libnfs 4.0 or later + - nfs: support libnfs 6 (API version 2) + - nfs: support libnfs URL arguments +* input + - alsa: limit ALSA buffer time to 2 seconds + - alsa: set up a channel map + - alsa: support the alsa-lib 1.2.11 API + - alsa: add option "close_on_pause" + - curl: add "connect_timeout" configuration +* decoder + - ffmpeg: require FFmpeg 4.0 or later + - ffmpeg: query supported demuxers at runtime + - hybrid_dsd: remove + - mpg123: prefer over "mad" + - mpg123: support streaming + - opus: implement bitrate calculation + - sidplay: require libsidplayfp (drop support for the original sidplay) + - wavpack: require libwavpack version 5 + - fix MixRamp bug +* resampler + - soxr: require libsoxr 0.1.2 or later +* player + - add option "mixramp_analyzer" to scan MixRamp tags on-the-fly + - "one-shot" consume mode +* tags + - new tags "TitleSort", "Mood", "ShowMovement" +* output + - add option "always_off" + - alsa: require alsa-lib 1.1 or later + - pipewire: map tags "Date" and "Comment" +* switch to C++20 + - GCC 12 or clang 14 (or newer) recommended +* static partition configuration +* Windows + - build with libsamplerate + - remove JACK DLL support +* remove Haiku support +* remove Boost dependency +* require libfmt 9 or later +* documentation: switch to sphinx-rtd-theme +* require Meson 1.0 + +ver 0.23.17 (2025/01/29) +* protocol + - "albumart" tries to send larger chunks if available + - explicitly disallow "idle" and "noidle" in command lists +* storage + - nfs: require libnfs 4.0 or later +* database + - inotify: trigger update after symlink was created +* decoder + - ffmpeg: prefer over sndfile and audiofile for its DTS-WAV support +* support libfmt 11.1 + +ver 0.23.16 (2024/12/03) +* database + - fix integer overflows with 64-bit inode numbers +* filter + - ffmpeg: fix for filters producing no output +* support libfmt 11 +* support ICU 76 + +ver 0.23.15 (2023/12/20) +* decoder + - ffmpeg: fix build failure with FFmpeg 6.1 +* output + - alsa: limit buffer time to 2 seconds + +ver 0.23.14 (2023/10/08) +* decoder + - flac: fix scanning files with non-ASCII names on Windows + - mad: fix calculation of LAME peak values +* mixer + - wasapi: fix problem setting volume +* more libfmt 10 fixes +* fix auto-detected systemd unit directory +* Android + - require Android 7 or newer + +ver 0.23.13 (2023/05/22) +* input + - curl: fix busy loop after connection failed + - curl: hide "404" log messages for non-existent ".mpdignore" files +* archive + - zzip: fix crash bug +* database + - simple: reveal hidden songs after deleting containing CUE +* decoder + - ffmpeg: reorder to a lower priority than "gme" + - gme: require GME 0.6 or later +* output + - pipewire: fix corruption bug due to missing lock +* Linux + - shut down if parent process dies in --no-daemon mode + - determine systemd unit directories via pkg-config +* support libfmt 10 + +ver 0.23.12 (2023/01/17) +* input + - curl: require CURL 7.55.0 or later +* decoder + - mad: fix integer underflow with very small files +* tags + - fix crash bug due to race condition +* output + - pipewire: adjust to PipeWire 0.3.64 API change +* fix build failures with GCC 13 + +ver 0.23.11 (2022/11/28) +* database + - simple: move default database to ~/.cache/mpd/db from ~/.cache/mpd.db + - simple: default "cache_directory" to ~/.cache/mpd/mounts +* macOS: fix build failure "no archive members specified" +* Windows + - fix crash bug (stack buffer overflow) after I/O errors + - fix path traversal bug because backslash was allowed in playlist names +* Android/Windows + - update OpenSSL to 3.0.7 + - re-enable CURL's verbose error strings + +ver 0.23.10 (2022/10/14) +* storage + - curl: fix file time stamps +* decoder + - ffmpeg: fix libfmt 9 compiler warning +* encoder + - flac: fix failure when libFLAC is built without Ogg support +* output + - alsa: fix crash bug +* Windows + - log to stdout by default, don't require "log_file" setting + +ver 0.23.9 (2022/08/18) +* input + - cdio_paranoia: add options "mode" and "skip" +* decoder + - ffmpeg: support FFmpeg 5.1 +* filter + - replay gain: fix delayed volume display with handler=mixer +* output + - pipewire: set app icon +* fix bogus volume levels with multiple partitions +* improve iconv detection +* macOS: fix macOS 10 build problem (0.23.8 regression) +* Android + - load mpd.conf from app data directory + +ver 0.23.8 (2022/07/09) +* storage + - curl: fix crash if web server does not understand WebDAV +* input + - cdio_paranoia: fix crash if no drive was found + - cdio_paranoia: faster cancellation + - cdio_paranoia: don't scan for replay gain tags + - pipewire: fix playback of very short tracks + - pipewire: drop all buffers before manual song change + - pipewire: fix stuttering after manual song change + - snapcast: fix busy loop while paused + - snapcast: fix stuttering after resuming playback +* mixer + - better error messages + - alsa: fix setting volume before playback starts + - pipewire: fix crash bug + - pipewire: fix volume change events with PipeWire 0.3.53 + - pipewire: don't force initial volume=100% +* support libfmt 9 + +ver 0.23.7 (2022/05/09) +* database + - upnp: support pupnp 1.14 +* decoder + - ffmpeg: fix HLS seeking + - opus: fix missing song length on high-latency files +* output + - shout: require at least libshout 2.4.0 +* mixer + - pipewire: fix volume restore + - software: update volume of disabled outputs +* support libiconv + +ver 0.23.6 (2022/03/14) +* protocol + - support filename "cover.webp" for "albumart" command + - support "readcomments" and "readpicture" on CUE tracks +* decoder + - ffmpeg: fix end-of-file check (update stuck at empty files) + - opus: fix "readpicture" on Opus files +* output + - pipewire: fix crash bug if setting volume before playback starts + - wasapi: fix resume after pause + +ver 0.23.5 (2021/12/01) +* protocol + - support relative offsets for "searchadd" + - fix "searchaddpl" bug (bogus error "Bad position") +* database + - upnp: fix crash bug +* tags + - fix MixRamp support +* migrate to PCRE2 +* GCC 12 build fixes + +ver 0.23.4 (2021/11/11) +* protocol + - add optional position parameter to "searchaddpl" +* decoder + - ffmpeg: support libavcodec 59 +* output + - alsa: add option "thesycon_dsd_workaround" to work around device bug +* fix crash on debug builds if startup fails +* systemd + - remove "RuntimeDirectory" directive because it caused problems + - ignore the "pid_file" setting if started as systemd service +* Windows + - enable the "openmpt" decoder plugin + +ver 0.23.3 (2021/10/31) +* protocol + - add optional position parameter to "add" and "playlistadd" + - allow range in "playlistdelete" +* database + - fix scanning files with question mark in the name + - inotify: fix use-after-free bug +* output + - alsa: add option "stop_dsd_silence" to work around DSD DAC noise +* macOS: fix libfmt related build failure +* systemd: add "RuntimeDirectory" directive + +ver 0.23.2 (2021/10/22) +* protocol + - fix "albumart" timeout bug +* input + - nfs: fix playback bug +* output + - pipewire: send artist and title to PipeWire + - pipewire: DSD support +* neighbor + - mention failed plugin name in error message +* player + - fix cross-fade regression +* fix crash with libfmt versions older than 7 + +ver 0.23.1 (2021/10/19) +* protocol + - use decimal notation instead of scientific notation + - "load" supports relative positions +* output + - emit "mixer" idle event when replay gain changes volume + - pipewire: emit "mixer" idle events on external volume change + - pipewire: attempt to change the graph sample rate + - snapcast: fix time stamp bug which caused "Failed to get chunk" +* fix libfmt linker problems +* fix broken password authentication + +ver 0.23 (2021/10/14) +* protocol + - new command "getvol" + - show the audio format in "playlistinfo" + - support "listfiles" with arbitrary storage plugins + - support relative positions in "addid" + - fix relative positions in "move" and "moveid" + - add "position" parameter to "findadd" and "searchadd" + - add position parameter to "load" +* database + - proxy: require MPD 0.20 or later + - proxy: require libmpdclient 2.11 or later + - proxy: split search into chunks to avoid exceeding the output buffer + - simple: add option to hide CUE target songs + - upnp: support libnpupnp instead of libupnp +* archive + - zzip, iso9660: ignore file names which are invalid UTF-8 +* decoder + - openmpt: new plugin + - wavpack: fix WVC file support +* player + - do not cross-fade songs shorter than 20 seconds +* output + - oss: support DSD over PCM + - pipewire: new plugin + - snapcast: new plugin +* tags + - new tags "ComposerSort", "Ensemble", "Movement", "MovementNumber", and "Location" +* split permission "player" from "control" +* add option "host_permissions" +* new build-time dependency: libfmt + +ver 0.22.11 (2021/08/24) +* protocol + - fix "albumart" crash +* filter + - ffmpeg: pass "channel_layout" instead of "channels" to buffersrc + - ffmpeg: fix "av_buffersink_get_frame() failed: Resource temporarily unavailable" + - ffmpeg: support double-precision samples (by converting to single precision) +* Android + - build with NDK r23 + - playlist_directory defaults to "/sdcard/Android/data/org.musicpd/files/playlists" + +ver 0.22.10 (2021/08/06) +* protocol + - support "albumart" for virtual tracks in CUE sheets +* database + - simple: fix crash bug + - simple: fix absolute paths in CUE "as_directory" entries + - simple: prune CUE entries from database for non-existent songs +* input + - curl: fix crash bug after stream with Icy metadata was closed by peer + - tidal: remove defunct unmaintained plugin +* tags + - fix crash caused by bug in TagBuilder and a few potential reference leaks +* output + - httpd: fix missing tag after seeking into a new song + - oss: fix channel order of multi-channel files +* mixer + - alsa: fix yet more rounding errors + +ver 0.22.9 (2021/06/23) +* database + - simple: load all .mpdignore files of all parent directories +* tags + - fix "readcomments" and "readpicture" on remote files with ID3 tags +* decoder + - ffmpeg: support the tags "sort_album", "album-sort", "artist-sort" + - ffmpeg: fix build failure with FFmpeg 3.4 +* Android + - fix auto-start on boot in Android 8 or later +* Windows + - fix build failure with SQLite + +ver 0.22.8 (2021/05/22) +* fix crash bug in "albumart" command (0.22.7 regression) + +ver 0.22.7 (2021/05/19) +* protocol + - don't use glibc extension to parse time stamps + - optimize the "albumart" command +* input + - curl: send user/password in the first request, save one roundtrip +* decoder + - ffmpeg: fix build problem with FFmpeg 3.4 + - gme: support RSN files +* storage + - curl: don't use glibc extension +* database + - simple: fix database corruption bug +* output + - fix crash when pausing with multiple partitions + - jack: enable on Windows + - httpd: send header "Access-Control-Allow-Origin: *" + - wasapi: add algorithm for finding usable audio format + - wasapi: use default device only if none was configured + - wasapi: add DoP support + +ver 0.22.6 (2021/02/16) +* fix missing tags on songs in queue + +ver 0.22.5 (2021/02/15) +* protocol + - error for malformed ranges instead of ignoring silently + - better error message for open-ended range with "move" +* database + - simple: fix missing CUE sheet metadata in "addid" command +* tags + - id: translate TPE3 to Conductor, not Performer +* archive + - iso9660: another fix for unaligned reads +* output + - httpd: error handling on Windows improved + - pulse: fix deadlock with "always_on" +* Windows: + - enable https:// support (via Schannel) +* Android + - work around "Permission denied" on mpd.conf + +ver 0.22.4 (2021/01/21) +* protocol + - add command "binarylimit" to allow larger chunk sizes + - fix "readpicture" on 32 bit machines + - show duration and tags of songs in virtual playlist (CUE) folders +* storage + - curl: fix several WebDAV protocol bugs +* decoder + - dsdiff: apply padding to odd-sized chunks +* filter + - ffmpeg: detect the output sample format +* output + - moveoutput: fix always_on and tag lost on move +* Android + - enable https:// support (via OpenSSL) + +ver 0.22.3 (2020/11/06) +* playlist + - add option "as_directory", making CUE file expansion optional +* storage + - curl: fix crash bug +* filter + - fix garbage after "Audio format not supported by filter" message + - ffmpeg: support planar output + - ffmpeg: support sample formats other than 16 bit + +ver 0.22.2 (2020/10/28) +* database + - simple: purge songs and virtual directories for unavailable plugins + on update +* input + - qobuz/tidal: fix protocol errors due to newlines in error messages + - smbclient: disable by default due to libsmbclient crash bug +* playlist + - soundcloud: fix protocol errors due to newlines in error messages +* state_file: save on shutdown + +ver 0.22.1 (2020/10/17) +* decoder + - opus: apply the OpusHead output gain even if there is no EBU R128 tag + - opus: fix track/album ReplayGain fallback +* output + - alsa: don't deadlock when the ALSA driver is buggy + - jack, pulse: reduce the delay when stopping or pausing playback +* playlist + - cue: fix two crash bugs +* state_file: fix the state_file_interval setting + +ver 0.22 (2020/09/23) +* protocol + - "findadd"/"searchadd"/"searchaddpl" support the "sort" and + "window" parameters + - add command "readpicture" to download embedded pictures + - command "moveoutput" moves an output between partitions + - command "delpartition" deletes a partition + - show partition name in "status" response +* tags + - new tags "Grouping" (for ID3 "TIT1"), "Work" and "Conductor" +* input + - curl: support "charset" parameter in URI fragment + - ffmpeg: allow partial reads + - io_uring: new plugin for local files on Linux (using liburing) + - smbclient: close unused SMB/CIFS connections +* database + - upnp: drop support for libupnp versions older than 1.8 +* playlist + - cue: integrate contents in database +* decoder + - ffmpeg: support RTSP + - mad: remove option "gapless", always do gapless + - sidplay: add option "default_genre" + - sidplay: map SID name field to "Album" tag + - sidplay: add support for new song length format with libsidplayfp 2.0 + - vorbis, opus: improve seeking accuracy +* playlist + - flac: support reading CUE sheets from remote FLAC files +* filter + - ffmpeg: new plugin based on FFmpeg's libavfilter library + - hdcd: new plugin based on FFmpeg's "af_hdcd" for HDCD playback + - volume: convert S16 to S24 to preserve quality and reduce dithering noise + - dsd: add integer-only DSD to PCM converter +* output + - jack: add option "auto_destination_ports" + - jack: report error details + - pulse: add option "media_role" + - solaris: support S8 and S32 +* lower the real-time priority from 50 to 40 +* switch to C++17 + - GCC 8 or clang 5 (or newer) recommended + +ver 0.21.26 (2020/09/21) +* database + - inotify: obey ".mpdignore" files +* output + - osx: fix crash bug + - sles: support floating point samples +* archive + - bzip2: fix crash on corrupt bzip2 file + - bzip2: flush output at end of input file + - iso9660: fix unaligned reads + - iso9660: support seeking + - zzip: fix crash on corrupt ZIP file +* decoder + - ffmpeg: remove "rtsp://" from the list of supported protocols + - ffmpeg: add "hls+http://" to the list of supported protocols + - opus: support the gain value from the Opus header + - sndfile: fix lost samples at end of file +* fix "single" mode bug after resuming playback +* the default log_level is "default", not "info" + +ver 0.21.25 (2020/07/06) +* protocol: + - fix crash when using "rangeid" while playing +* database + - simple: automatically scan new mounts + - upnp: fix compatibility with Plex DLNA +* storage + - fix disappearing mounts after mounting twice + - udisks: fix reading ".mpdignore" +* input + - file: detect premature end of file + - smbclient: don't send credentials to MPD clients +* decoder + - opus: apply pre-skip and end trimming + - opus: fix memory leak + - opus: fix crash bug + - vorbis: fix crash bug +* output + - osx: improve sample rate selection + - osx: fix noise while stopping +* neighbor + - upnp: fix crash during shutdown +* Windows/Android: + - fix Boost detection after breaking change in Meson 0.54 + +ver 0.21.24 (2020/06/10) +* protocol + - "tagtypes" requires no permissions +* database + - simple: fix crash when mounting twice +* decoder + - modplug: fix Windows build failure + - wildmidi: attempt to detect WildMidi using pkg-config + - wildmidi: fix Windows build failure +* player + - don't restart current song if seeking beyond end +* Android + - enable the decoder plugins GME, ModPlug and WildMidi + - fix build failure with Android NDK r21 +* Windows + - fix stream playback + - enable the decoder plugins GME, ModPlug and WildMidi + - work around Meson bug breaking the Windows build with GCC 10 +* fix unit test failure + +ver 0.21.23 (2020/04/23) +* protocol + - add tag fallback for AlbumSort +* storage + - curl: fix corrupt "href" values in the presence of XML entities + - curl: unescape "href" values +* input + - nfs: fix crash bug + - nfs: fix freeze bug on reconnect +* decoder + - gme: adapt to API change in the upcoming version 0.7.0 +* output + - alsa: implement channel mapping for 5.0 and 7.0 +* player + - drain outputs at end of song in "single" mode +* Windows + - fix case insensitive search + +ver 0.21.22 (2020/04/02) +* database + - simple: optimize startup +* input + - curl: fix streaming errors on Android +* playlist + - rss: support MIME type application/xml +* mixer + - android: new mixer plugin for "sles" output +* Android + - TV support +* Windows + - fix time zone offset check +* fix build failures with uClibc-ng + +ver 0.21.21 (2020/03/19) +* configuration + - fix bug in "metadata_to_use" setting +* playlist + - asx, xspf: fix corrupt tags in the presence of XML entities +* archive + - iso9660: skip empty file names to work around libcdio bug +* decoder + - gme: ignore empty tags +* output + - solaris: port to NetBSD +* raise default "max_connections" value to 100 + +ver 0.21.20 (2020/02/16) +* decoder + - audiofile, ffmpeg, sndfile: handle MIME type "audio/wav" + - ffmpeg: fix playback of AIFF and TTA + - vorbis, opus: fix seeking in small files +* fix backwards seeking on ARM (and other non-x86 CPUs) + +ver 0.21.19 (2020/01/17) +* configuration + - allow overriding top-level settings in includes +* output + - pulse: obey Pulse's maximum sample rate (fixes DSD128 playback) +* fix build failure with clang 10 +* fix build failure with Android NDK r20 + +ver 0.21.18 (2019/12/24) +* protocol + - work around Mac OS X bug in the ISO 8601 parser +* output + - alsa: fix hang bug with ALSA "null" outputs +* storage + - curl: fix crash bug +* drop support for CURL versions older than 7.32.0 +* reduce unnecessary CPU wakeups + +ver 0.21.17 (2019/12/16) +* protocol + - relax the ISO 8601 parser: allow omitting field separators, the + time of day and the "Z" suffix +* archive + - zzip: improve error reporting +* outputs + - jack: mark ports as terminal + - shout: declare metadata as UTF-8 +* fix build failure with -Ddatabase=false + +ver 0.21.16 (2019/10/16) +* queue + - fix relative destination offset when moving a range +* storage + - curl: request the "resourcetype" property to fix database update + - curl: URL-encode more paths + - curl: follow redirects for collections without trailing slash +* update + - fix crash when music_directory is not a directory +* fix build with iconv() instead of ICU + +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 +* require Meson 0.49.0 for native libgcrypt-config support +* fix build failure with -Dlocal_socket=false +* Haiku + - fix build + - add version info + +ver 0.21.6 (2019/03/17) +* protocol + - allow loading playlists specified as absolute filesystem paths + - fix negated filter expressions with multiple tag values + - fix "list" with filter expression + - omit empty playlist names in "listplaylists" +* input + - cdio_paranoia: fix build failure due to missing #include +* decoder + - opus: fix replay gain when there are no other tags + - opus: fix seeking to beginning of song + - vorbis: fix Tremor conflict resulting in crash +* output + - pulse: work around error with unusual channel count + - osx: fix build failure +* playlist + - flac: fix use-after-free bug +* support abstract sockets on Linux +* Windows + - remove the unused libwinpthread-1.dll dependency +* Android + - enable SLES power saving mode + +ver 0.21.5 (2019/02/22) +* protocol + - fix deadlock in "albumart" command + - fix "tagtypes disable" command +* database + - simple: fix assertion failure + - fix assertion failures with mount points +* storage + - udisks: fix "AlreadyMounted" error + - udisks: use relative path from mount URI + - fix memory leak +* input + - buffer: fix crash bug when playing remote WAV file +* tags + - ape: map "Album Artist" +* output + - shout: add support for TLS +* mixer + - pulse: add "scale_volume" setting + +ver 0.21.4 (2019/01/04) +* database + - inotify: fix crash bug "terminate called after throwing ..." + - upnp: implement "list ... group" +* output + - httpd: declare protocol "HTTP/1.1" instead of "ICY" +* remove libwrap support +* Windows + - fix "Failed to accept connection: unknown error" +* fix Haiku build + +ver 0.21.3 (2018/11/16) +* output + - alsa: fix crash bug + - alsa: fix stuttering at start of playback + - alsa: fix discarded samples at end of song + - alsa: clear error after reopening device +* log: default to journal if MPD was started as systemd service + +ver 0.21.2 (2018/11/12) +* protocol + - operator "=~" matches a regular expression + - operator "contains" matches substrings +* decoder + - ffmpeg: require FFmpeg 3.1 or later + - ffmpeg: fix broken sound with certain codecs +* output + - alsa: fix high CPU usage with dmix + - httpd: fix three crash bugs +* mixer + - alsa: fix more rounding errors +* fix zlib support + +ver 0.21.1 (2018/11/04) +* protocol + - allow escaping quotes in filter expressions + - operator "==" never searches substrings in filter expressions +* decoder + - ffmpeg: fix build failure with non-standard FFmpeg installation path + - flac: fix linker failure when building without FLAC support +* encoder + - vorbis: fix linker failure when building without Vorbis decoder +* fix build failure on Linux-PowerPC +* fix build failure on FreeBSD +* eliminate DLL dependencies on Windows +* add warning about buggy Boost version 1.67 +* require Meson 0.47.2 because a Meson 0.47.1 bug breaks our build + +ver 0.21 (2018/10/31) +* configuration + - add "include" directive, allows including config files + - incremental "metadata_to_use" setting +* protocol + - "tagtypes" can be used to hide tags + - "find" and "search" can sort + - "outputs" prints the plugin name + - "outputset" sets runtime attributes + - close connection when client sends HTTP request + - new filter syntax for "find"/"search" etc. with negation +* database + - simple: scan audio formats + - proxy: require libmpdclient 2.9 + - proxy: forward `sort` and `window` to server +* player + - hard-code "buffer_before_play" to 1 second, independent of audio format + - "one-shot" single mode +* input + - curl: download to buffer instead of throttling transfer + - qobuz: new plugin to play Qobuz streams + - tidal: new plugin to play Tidal streams +* tags + - new tags "OriginalDate", "MUSICBRAINZ_WORKID" +* decoder + - ffmpeg: require at least version 11.12 + - gme: try loading m3u sidecar files + - hybrid_dsd: new decoder plugin + - mad: move "gapless_mp3_playback" setting to "decoder" block + - mikmod: require at least version 3.2 + - pcm: support audio/L24 (RFC 3190) + - sidplay: support basic and kernal rom (libsidplayfp) +* resampler + - soxr: flush resampler at end of song +* output + - alsa: non-blocking mode + - alsa: change "dop" and "allowed_formats" settings at runtime + - ao: fix crash bug due to partial frames + - shout: support the Shine encoder plugin + - sndio: remove support for the broken RoarAudio sndio emulation + - osx: initial support for DSD over PCM + - roar: removed + - httpd_output: support for unix sockets +* mixer + - sndio: new mixer plugin +* encoder + - opus: support for sending metadata using ogg stream chaining +* listen on $XDG_RUNTIME_DIR/mpd/socket by default +* append hostname to Zeroconf service name +* systemd watchdog support +* require GCC 6 +* build with Meson instead of autotools +* use GTest instead of cppunit + +ver 0.20.23 (2018/10/29) +* protocol + - emit "player" idle event when restarting the current song +* fix broken float to s32 conversion +* new clang crash bug workaround + +ver 0.20.22 (2018/10/23) +* protocol + - add tag fallbacks for AlbumArtistSort, ArtistSort + - fix empty string filter on fallback tags + - "count group ..." can print an empty group + - fix broken command "list ... group" +* storage + - curl: URL-encode paths +* decoder + - fluidsynth: adapt to API change in version 2.0 +* Android + - now runs as a service + - add button to start/stop MPD + - add option to auto-start on boot +* work around clang bug leading to crash +* install the SVG icon + +ver 0.20.21 (2018/08/17) +* database + - proxy: add "password" setting + - proxy: support tags "ArtistSort", "AlbumArtistSort", "AlbumSort" + - simple: allow .mpdignore comments only at start of line +* output + - httpd: remove broken DLNA support code +* playlist + - cue: support file type declaration "FLAC" (non-standard) +* URI schemes are case insensitive +* Android, Windows + - enable the "curl" storage plugin + +ver 0.20.20 (2018/05/22) +* protocol + - fix "modified-since" filter regression +* output + - pulse: cork stream when paused due to "single" mode +* decoder + - dsdiff, dsf: support more MIME types + - dsdiff, dsf: allow 4 MB ID3 tags + - opus: support R128_ALBUM_GAIN tag +* Android, Windows + - enable the "proxy" database plugin + +ver 0.20.19 (2018/04/26) +* protocol + - validate absolute seek time, reject negative values +* database + - proxy: fix "search already in progress" errors + - proxy: implement "list ... group" +* input + - mms: fix lockup bug and a crash bug +* decoder + - ffmpeg: fix av_register_all() deprecation warning (FFmpeg 4.0) +* player + - fix spurious "Not seekable" error when switching radio streams +* macOS: fix crash bug + +ver 0.20.18 (2018/02/24) +* input + - curl: allow authentication methods other than "Basic" +* decoder + - flac: improve seeking precision +* fix gapless CUE song transitions +* Android, Windows + - enable the NFS storage plugin + +ver 0.20.17 (2018/02/11) +* output + - alsa: fix crash bug with 8 channels +* mixer + - alsa: fix rounding error at volume 0 +* fix real-time and idle scheduling with Musl +* Android + - fix compatibility with Android 4.0 + +ver 0.20.16 (2018/02/03) +* output + - pulse: fix crash during auto-detection +* database + - simple: fix search within mount points + - upnp: enable IPv6 +* archive + - iso9660: libcdio 2.0 compatibility +* fix crash in debug build on Haiku and other operating systems + +ver 0.20.15 (2018/01/05) +* queue: fix crash after seek failure +* resampler + - soxr: clear internal state after manual song change +* state file + - make mount point restore errors non-fatal + - fix crash when restoring mounts with incompatible database plugin +* Android + - build without Ant + - fix for SIGSYS crash + +ver 0.20.14 (2018/01/01) +* database + - simple: fix file corruption in the presence of mount points +* archive + - bz2: fix deadlock + - reduce lock contention, fixing lots of xrun problems +* fix Solaris build failure + +ver 0.20.13 (2017/12/18) +* output + - osx: set up ring buffer to hold at least 100ms +* mixer + - alsa: fix rounding errors +* database + - simple: don't purge mount points on update/rescan + - simple: fix "mount" bug caused by bad compiler optimization + - simple: fix "lsinfo" into mount points + - upnp: work around libupnp 1.6.24 API breakage +* queue: fix spuriously misplaced prioritized songs +* save and restore mountpoints within the state file +* include Windows cross-build script in source tarball +* fix Windows build failures + +ver 0.20.12 (2017/11/25) +* database + - upnp: adapt to libupnp 1.8 API changes +* input + - cdio_paranoia, ffmpeg, file, smbclient: reduce lock contention, + fixing lots of xrun problems + - curl: fix seeking +* decoder + - ffmpeg: fix GCC 8 warning + - vorbis: fix Tremor support +* player + - log message when decoder is too slow +* encoder + - vorbis: default to quality 3 +* output + - fix hanging playback with soxr resampler + - httpd: flush encoder after tag; fixes corrupt Vorbis stream + +ver 0.20.11 (2017/10/18) +* storage + - curl: support Content-Type application/xml +* decoder + - ffmpeg: more reliable song duration + - gme: fix track numbering +* improve random song order when switching songs manually +* fix case insensitive search without libicu +* fix Unicode file names in playlists on Windows +* fix endless loop when accessing malformed file names in ZIP files + +ver 0.20.10 (2017/08/24) +* decoder + - ffmpeg: support MusicBrainz ID3v2 tags +* tags + - aiff: fix FORM chunk size endianness (is big-endian) +* mixer + - osx: add a mixer for OSX. +* fix crash when resuming playback before decoder is ready +* fix crash on Windows + +ver 0.20.9 (2017/06/04) +* decoder + - ffmpeg: support *.adx +* fix byte order detection on FreeBSD/aarch64 +* fix more random crashes when compiled with clang + +ver 0.20.8 (2017/05/19) +* output + - osx: fix build failure due to missing "noexcept" +* playlist + - m3u: support MIME type `audio/mpegurl` +* fix build failure with GCC 4.x + +ver 0.20.7 (2017/05/15) +* database + - simple: fix false positive directory loop detection with NFS +* enforce a reasonable minimum audio_buffer_size setting +* cap buffer_before_play at 80% to prevent deadlock +* fix random crashes when compiled with clang + +ver 0.20.6 (2017/03/10) +* input + - curl: fix headers after HTTP redirect to Shoutcast server +* decoder + - ffmpeg: re-enable as fallback + - mpcdec: fix crash (division by zero) after seeking + - sidplay: make compatible with libsidplayfp < 1.8 +* fix stream tags after automatic song change +* workaround for GCC 4.9.4 / libstdc++ bug (build failure) + +ver 0.20.5 (2017/02/20) +* tags + - id3: fix memory leak on corrupt ID3 tags +* decoder + - sidplay: don't require libsidutils when building with libsidplayfp +* output + - httpd: fix two buffer overflows in IcyMetaData length calculation +* mixer + - alsa: fix crash bug + +ver 0.20.4 (2017/02/01) +* input + - nfs: fix freeze after reconnect +* output + - sndio: work around a libroar C++ incompatibility +* workaround for GCC 4.9 "constexpr" bug +* fix FreeBSD build failure + +ver 0.20.3 (2017/01/25) +* protocol + - "playlistadd" creates new playlist if it does not exist, as documented +* database + - proxy: fix error "terminate called after throwing ..." + - proxy: make connect errors during startup non-fatal +* neighbor + - upnp: fix premature expiry +* replay gain: don't reset ReplayGain levels when unpausing playback +* silence surround channels when converting from stereo +* use shortcuts such as "dsd64" in log messages + +ver 0.20.2 (2017/01/15) +* input + - alsa: fix crash bug + - alsa: fix buffer overruns +* decoder + - flac: add options "probesize" and "analyzeduration" +* resampler + - libsamplerate: reset state after seeking +* output + - fix static noise after changing to a different audio format + - alsa: fix the DSD_U32 sample rate + - alsa: fix the DSD_U32 byte order + - alsa: support DSD_U16 + - recorder: fix error "Failed to create : No such file or directory" +* playlist + - cue: fix skipping songs + +ver 0.20.1 (2017/01/09) +* input + - curl: fix crash bug + - curl: fix freeze bug +* decoder + - wavpack: fix crash bug +* storage + - curl: new storage plugin for WebDAV (work in progress) +* mixer + - alsa: normalize displayed volume according to human perception +* fix crash with volume_normalization enabled + +ver 0.20 (2017/01/04) +* protocol + - "commands" returns playlist commands only if playlist_directory configured + - "search"/"find" have a "window" parameter + - report song duration with milliseconds precision + - "sticker find" can match sticker values + - drop the "file:///" prefix for absolute file paths + - add range parameter to command "plchanges" and "plchangesposid" + - send verbose error message to client +* input + - curl: fix memory leak +* tags + - ape, ogg: drop support for non-standard tag "album artist" + affected filetypes: vorbis, flac, opus & all files with ape2 tags + (most importantly some mp3s) + - id3: remove the "id3v1_encoding" setting; by definition, all ID3v1 tags + are ISO-Latin-1 + - ape: support APE replay gain on remote files + - read ID3 tags from NFS/SMB +* decoder + - improved error logging + - report I/O errors to clients + - ffmpeg: support ReplayGain and MixRamp + - ffmpeg: support stream tags + - gme: add option "accuracy" + - gme: provide the TRACK tag + - gme: faster scanning + - mad: reduce memory usage while scanning tags + - mpcdec: read the bit rate + - pcm: support audio/L16 (RFC 2586) and audio/x-mpd-float + - sidplay: faster scanning + - wavpack: large file support + - wavpack: support DSD (WavPack 5) + - wavpack: archive support +* playlist + - cue: don't skip pregap + - embcue: fix last track + - flac: new plugin which reads the "CUESHEET" metadata block +* output + - alsa: fix multi-channel order + - alsa: remove option "use_mmap" + - alsa: support DSD_U32 + - alsa: disable DoP if it fails + - jack: reduce CPU usage + - pulse: set channel map to WAVE-EX + - recorder: record tags + - recorder: allow dynamic file names + - sndio: new output plugin +* mixer + - null: new plugin +* resampler + - new block "resampler" in configuration file + replacing the old "samplerate_converter" setting + - soxr: allow multi-threaded resampling +* player + - reset song priority on playback + - reduce xruns +* write database and state file atomically +* always write UTF-8 to the log file. +* remove dependency on GLib +* support libsystemd (instead of the older libsystemd-daemon) +* database + - proxy: add TCP keepalive option +* update + - apply .mpdignore matches to subdirectories +* switch the code base to C++14 + - GCC 4.9 or clang 3.4 (or newer) recommended + +ver 0.19.21 (2016/12/13) +* decoder + - ffmpeg: fix crash bug +* fix unit test failure after recent "setprio" change +* systemd: add user unit + +ver 0.19.20 (2016/12/09) +* protocol + - "setprio" re-enqueues old song if priority has been raised +* decoder + - ffmpeg: ignore empty packets + - pcm: fix corruption bug with partial frames (after short read) + - sidplay: fix playback speed with libsidplayfp +* output + - winmm: fix 8 bit playback +* fix gcc 7.0 -Wimplicit-fallthrough +* systemd: paranoid security settings + +ver 0.19.19 (2016/08/23) +* decoder + - ffmpeg: bug fix for FFmpeg 3.1 support + - wildmidi: support libWildMidi 0.4 +* output + - pulse: support 32 bit, 24 bit and floating point playback +* support non-x86 NetBSD +* fix clang 3.9 warnings + +ver 0.19.18 (2016/08/05) +* decoder + - ffmpeg: fix crash with older FFmpeg versions (< 3.0) + - ffmpeg: log detailed error message + - ffmpeg: support FFmpeg 3.1 + - sidplay: detect libsidplay2 with pkg-config + - sidplay: log detailed error message + - sidplay: read the "date" tag + - sidplay: allow building with libsidplayfp instead of libsidplay2 +* output + - shout: recognize setting "encoder" instead of "encoding" +* fix memory leak after stream failure +* fix build failure with Boost 1.61 +* require gcc 4.7 or newer + +ver 0.19.17 (2016/07/09) +* decoder + - flac: fix assertion failure while seeking + - flac: fix stream duration indicator + - fix seek problems in several plugins +* fix spurious seek error "Failed to allocate silence buffer" +* replay gain: fix "replay_gain_handler mixer" setting +* DSD: use 0x69 as silence pattern +* fix use-after-free bug on "close" and "kill" + +ver 0.19.16 (2016/06/13) +* faster seeking +* fix system include path order +* add missing DocBook file to tarball + +ver 0.19.15 (2016/04/30) +* decoder + - ffmpeg: support FFmpeg 3.0 + - ffmpeg: use as fallback instead of "mad" if no plugin matches + - opus: support bigger OpusTags packets +* fix more build failures on non-glibc builds due to constexpr Mutex +* fix build failure due to missing include +* fix unit test on Alpha + +ver 0.19.14 (2016/03/18) +* decoder + - dsdiff: fix off-by-one buffer overflow + - opus: limit tag size to 64 kB +* archive + - iso9660: fix buffer overflow +* fix quadratic runtime bug in the tag pool +* fix build failures on non-glibc builds due to constexpr Mutex + +ver 0.19.13 (2016/02/23) +* tags + - aiff, riff: fix ID3 chunk padding +* decoder + - ffmpeg: support the TAK codec +* fix disappearing duration of remote songs during playback +* initialize supplementary groups with glibc 2.19+ + +ver 0.19.12 (2015/12/15) +* fix assertion failure on malformed UTF-8 tag +* fix build failure on non-Linux systems +* fix LimitRTTIME in systemd unit file + +ver 0.19.11 (2015/10/27) +* tags + - ape: fix buffer overflow +* decoder + - ffmpeg: fix crash due to wrong avio_alloc_context() call + - gme: don't loop forever, fall back to GME's default play length +* encoder + - flac: fix crash with 32 bit playback +* mixer + - fix mixer lag after enabling/disabling output + +ver 0.19.10 (2015/06/21) +* input + - curl: fix deadlock on small responses + - smbclient: fix DFF playback +* decoder + - ffmpeg: improve seeking accuracy + - fix stuck stream tags +* encoder + - opus: fix bogus granulepos +* output + - fix failure to open device right after booting +* neighbor + - nfs: fix deadlock when connecting +* fix "single" mode breakage due to queue edits + +ver 0.19.9 (2015/02/06) +* decoder + - dsdiff, dsf: raise ID3 tag limit to 1 MB +* playlist: fix loading duplicate tag types from state file +* despotify: remove defunct plugin +* fix clock integer overflow on OS X +* fix gcc 5.0 warnings +* fix build failure with uClibc +* fix build failure on non-POSIX operating systems +* fix dependency issue on parallel Android build +* fix database/state file saving on Windows + +ver 0.19.8 (2015/01/14) +* input + - curl: fix bug after rewinding from end-of-file + - mms: reduce delay at the beginning of playback +* decoder + - dsdiff, dsf: allow ID3 tags larger than 4 kB + - ffmpeg: support interleaved floating point +* fix clang 3.6 warnings +* fix build failure on NetBSD + +ver 0.19.7 (2014/12/17) +* input + - nfs: fix crash while canceling a failing file open operation + - nfs: fix memory leak on connection failure + - nfs: fix reconnect after mount failure + - nfs: implement mount timeout (60 seconds) +* storage + - nfs: implement I/O timeout (60 seconds) +* playlist + - embcue: fix filename suffix detection + - don't skip non-existent songs in "listplaylist" +* decoder + - ffmpeg: fix time stamp underflow +* fix memory allocator bug on Windows + +ver 0.19.6 (2014/12/08) +* decoder + - ffmpeg: support FFmpeg 2.5 +* fix build failure with musl +* android + - update libFLAC to 1.3.1 + - update FFmpeg to 2.5 + +ver 0.19.5 (2014/11/26) +* input + - nfs: fix crash on connection failure +* archive + - zzip: fix crash after seeking +* decoder + - dsdiff, dsf, opus: fix deadlock while seeking + - mp4v2: remove because of incompatible license + +ver 0.19.4 (2014/11/18) +* protocol + - workaround for buggy clients that send "add /" +* decoder + - ffmpeg: support opus + - opus: add MIME types audio/ogg and application/ogg +* fix crash on failed filename charset conversion +* fix local socket detection from uid=0 (root) + +ver 0.19.3 (2014/11/11) +* protocol + - fix "(null)" result string to "list" when AlbumArtist is disabled +* database + - upnp: fix breakage due to malformed URIs +* input + - curl: another fix for redirected streams +* decoder + - audiofile: fix crash while playing streams + - audiofile: fix bit rate calculation + - ffmpeg: support opus + - opus: fix bogus duration on streams + - opus: support chained streams + - opus: improved error logging +* fix distorted audio with soxr resampler +* fix build failure on Mac OS X with non-Apple compilers + +ver 0.19.2 (2014/11/02) +* input + - curl: fix redirected streams +* playlist + - don't allow empty playlist name + - m3u: don't ignore unterminated last line + - m3u: recognize the file suffix ".m3u8" +* decoder + - ignore URI query string for plugin detection + - faad: remove workaround for ancient libfaad2 ABI bug + - ffmpeg: recognize MIME type audio/aacp + - mad: fix negative replay gain values +* output + - fix memory leak after filter initialization error + - fall back to PCM if given DSD sample rate is not supported +* fix assertion failure on unsupported PCM conversion +* auto-disable plugins that require GLib when --disable-glib is used + +ver 0.19.1 (2014/10/19) +* input + - mms: fix deadlock bug +* playlist + - extm3u: fix Extended M3U detection + - m3u, extm3u, cue: fix truncated lines +* fix build failure on Mac OS X +* add missing file systemd/mpd.socket to tarball + +ver 0.19 (2014/10/10) +* protocol + - new commands "addtagid", "cleartagid", "listfiles", "listmounts", + "listneighbors", "mount", "rangeid", "unmount" + - "lsinfo" and "readcomments" allowed for remote files + - "listneighbors" lists file servers on the local network + - "playlistadd" supports file:/// + - "idle" with unrecognized event name fails + - "list" on album artist falls back to the artist tag + - "list" and "count" allow grouping + - new "search"/"find" filter "modified-since" + - "seek*" allows fractional position + - close connection after syntax error +* database + - proxy: forward "idle" events + - proxy: forward the "update" command + - proxy: copy "Last-Modified" from remote directories + - simple: compress the database file using gzip + - upnp: new plugin + - cancel the update on shutdown +* storage + - music_directory can point to a remote file server + - nfs: new plugin + - smbclient: new plugin +* playlist + - cue: fix bogus duration of the last track + - cue: restore CUE tracks from state file + - soundcloud: use https instead of http + - soundcloud: add default API key +* archive + - read tags from songs in an archive +* input + - alsa: new input plugin + - curl: options "verify_peer" and "verify_host" + - ffmpeg: update offset after seeking + - ffmpeg: improved error messages + - mms: non-blocking I/O + - nfs: new input plugin + - smbclient: new input plugin +* filter + - volume: improved software volume dithering +* decoder: + - vorbis, flac, opus: honor DESCRIPTION= tag in Xiph-based files as a comment to the song + - audiofile: support scanning remote files + - audiofile: log libaudiofile errors + - dsdiff, dsf: report bit rate + - dsdiff, dsf: implement seeking + - dsf: support DSD512 + - dsf: support multi-channel files + - dsf: fix big-endian bugs + - dsf: fix noise at end of malformed file + - mpg123: support ID3v2, ReplayGain and MixRamp + - sndfile: support scanning remote files + - sndfile: support tags "comment", "album", "track", "genre" + - sndfile: native floating point playback + - sndfile: optimized 16 bit playback + - mp4v2: support playback of MP4 files. +* encoder: + - shine: new encoder plugin +* output + - alsa: support native DSD playback + - alsa: rename "DSD over USB" to "DoP" + - osx: fix hang after (un)plugging headphones +* threads: + - the update thread runs at "idle" priority + - the output thread runs at "real-time" priority + - increase kernel timer slack on Linux + - name each thread (for debugging) +* configuration + - allow playlist directory without music directory + - use XDG to auto-detect "music_directory" and "db_file" +* add tags "AlbumSort", "MUSICBRAINZ_RELEASETRACKID" +* disable global Latin-1 fallback for tag values +* new resampler option using libsoxr +* ARM NEON optimizations +* install systemd unit for socket activation +* Android port + +ver 0.18.23 (2015/02/06) +* despotify: remove defunct plugin +* fix clock integer overflow on OS X +* fix gcc 5.0 warnings + +ver 0.18.22 (2015/01/14) +* fix clang 3.6 warnings + +ver 0.18.21 (2014/12/17) +* playlist + - embcue: fix filename suffix detection +* decoder + - ffmpeg: fix time stamp underflow + +ver 0.18.20 (2014/12/08) +* decoder + - ffmpeg: support FFmpeg 2.5 +* fix build failure with musl + +ver 0.18.19 (2014/11/26) +* archive + - zzip: fix crash after seeking + +ver 0.18.18 (2014/11/18) +* decoder + - ffmpeg: support opus +* fix crash on failed filename charset conversion +* fix local socket detection from uid=0 (root) + +ver 0.18.17 (2014/11/02) +* playlist + - don't allow empty playlist name + - m3u: recognize the file suffix ".m3u8" +* decoder + - ignore URI query string for plugin detection + - faad: remove workaround for ancient libfaad2 ABI bug + - ffmpeg: recognize MIME type audio/aacp + +ver 0.18.16 (2014/09/26) +* fix DSD breakage due to typo in configure.ac + +ver 0.18.15 (2014/09/26) +* command + - list: reset used size after the list has been processed +* fix MixRamp +* work around build failure on NetBSD + +ver 0.18.14 (2014/09/11) +* protocol + - fix range parser bug on certain 32 bit architectures +* decoder + - audiofile: fix crash after seeking + - ffmpeg: fix crash with ffmpeg/libav version 11 + - fix assertion failure after seeking + +ver 0.18.13 (2014/08/31) +* protocol + - don't change song on "seekcur" in random mode + +* decoder + - dsdiff, dsf: fix endless loop on malformed file + - ffmpeg: support ffmpeg/libav version 11 + - gme: fix song duration +* output + - alsa: fix endless loop at end of file in dsd_usb mode +* fix state file saver +* fix build failure on Darwin + +ver 0.18.12 (2014/07/30) +* database + - proxy: fix build failure with libmpdclient 2.2 + - proxy: fix add/search and other commands with libmpdclient < 2.9 +* decoder + - audiofile: improve responsiveness + - audiofile: fix WAV stream playback + - dsdiff, dsf: fix stream playback + - dsdiff: fix metadata parser bug (uninitialized variables) + - faad: estimate song duration for remote files + - sndfile: improve responsiveness +* randomize next song when enabling "random" mode while not playing +* randomize next song when adding to single-song queue + +ver 0.18.11 (2014/05/12) +* decoder + - opus: fix missing song length on high-latency files +* fix race condition when using GLib event loop (non-Linux) + +ver 0.18.10 (2014/04/10) +* decoder + - ffmpeg: fix seeking bug + - ffmpeg: handle unknown stream start time + - gme: fix memory leak + - sndfile: work around libsndfile bug on partial read +* don't interrupt playback when current song gets deleted + +ver 0.18.9 (2014/03/02) +* protocol + - "findadd" requires the "add" permission +* output + - alsa: improved workaround for noise after manual song change +* decoder + - vorbis: fix linker failure when libvorbis/libogg are static +* encoder + - vorbis: fix another linker failure +* output + - pipe: fix hanging child process due to blocked signals +* fix build failure due to missing signal.h include + +ver 0.18.8 (2014/02/07) +* decoder + - ffmpeg: support libav v10_alpha1 +* encoder + - vorbis: fix linker failure +* output + - roar: documentation +* more robust Icy-Metadata parser +* fix Solaris build failure + +ver 0.18.7 (2014/01/13) +* playlist + - pls: fix crash after parser error + - soundcloud: fix build failure with libyajl 2.0.1 +* decoder + - faad: fix memory leak + - mpcdec: reject libmpcdec SV7 in configure script +* daemon: don't initialize supplementary groups when already running + as the configured user + +ver 0.18.6 (2013/12/24) +* input + - cdio_paranoia: support libcdio-paranoia 0.90 +* tags + - riff: recognize upper-case "ID3" chunk name +* decoder + - ffmpeg: use relative timestamps +* output + - openal: fix build failure on Mac OS X + - osx: fix build failure +* mixer + - alsa: fix build failure with uClibc +* fix replay gain during cross-fade +* accept files without metadata + +ver 0.18.5 (2013/11/23) +* configuration + - fix crash when db_file is configured without music_directory + - fix crash on "stats" without db_file/music_directory +* database + - proxy: auto-reload statistics + - proxy: provide "db_update" in "stats" response +* input + - curl: work around stream resume bug (fixed in libcurl 7.32.0) +* decoder + - fluidsynth: auto-detect by default +* clip 24 bit data from libsamplerate +* fix ia64, mipsel and other little-endian architectures +* fix build failures due to missing includes +* fix build failure with static libmpdclient + +ver 0.18.4 (2013/11/13) +* decoder + - dsdiff: fix byte order bug +* fix build failures due to missing includes +* libc++ compatibility + +ver 0.18.3 (2013/11/08) +* fix stuck MPD after song change (0.18.2 regression) + +ver 0.18.2 (2013/11/07) +* protocol: + - "close" flushes the output buffer +* input: + - cdio_paranoia: add setting "default_byte_order" + - curl: fix bug with redirected streams +* playlist: + - pls: fix reversed song order +* decoder: + - audiofile: require libaudiofile 0.3 due to API breakage + - dsf: enable DSD128 +* enable buffering when starting playback (regression fix) +* fix build failures due to missing includes +* fix big-endian support + +ver 0.18.1 (2013/11/04) +* protocol: + - always ignore whitespace at the end of the line +* networking: + - log UNIX domain path names instead of "localhost" + - open listener sockets in the order they were configured + - don't abort if IPv6 is not available +* output: + - alsa: avoid endless loop in Raspberry Pi workaround +* filter: + - autoconvert: fix "volume_normalization" with mp3 files +* add missing files to source tarball + +ver 0.18 (2013/10/31) +* configuration: + - allow tilde paths for socket + - default filesystem charset is UTF-8 instead of ISO-8859-1 + - increase default buffer size to 4 MB +* protocol: + - new command "readcomments" lists arbitrary file tags + - new command "toggleoutput" + - "find"/"search" with "any" does not match file name + - "search" and "find" with base URI (keyword "base") + - search for album artist falls back to the artist tag + - re-add the "volume" command +* input: + - curl: enable https + - soup: plugin removed +* playlist: + - lastfm: remove defunct Last.fm support +* decoder: + - adplug: new decoder plugin using libadplug + - dsf: don't play junk at the end of the "data" chunk + - ffmpeg: drop support for pre-0.8 ffmpeg + - flac: require libFLAC 1.2 or newer + - flac: support FLAC files inside archives + - opus: new decoder plugin for the Opus codec + - vorbis: skip 16 bit quantisation, provide float samples + - mikmod: add "loop" configuration parameter + - modplug: add "loop_count" configuration parameter + - mp4ff: obsolete plugin removed +* encoder: + - opus: new encoder plugin for the Opus codec + - vorbis: accept floating point input samples +* output: + - new option "tags" may be used to disable sending tags to output + - alsa: workaround for noise after manual song change + - ffado: remove broken plugin + - httpd: support HEAD requests + - mvp: remove obsolete plugin + - osx: disabled by default because it's unmaintained and unsupported +* improved decoder/output error reporting +* eliminate timer wakeup on idle MPD +* fix unresponsive MPD while waiting for stream +* port of the source code to C++11 + +ver 0.17.6 (2013/10/14) +* mixer: + - alsa: fix busy loop when USB sound device gets unplugged +* decoder: + - modplug: fix build with Debian package 1:0.8.8.4-4 +* stored playlists: + - fix loading playlists with references to local files + - obey filesystem_charset for URLs + +ver 0.17.5 (2013/08/04) +* protocol: + - fix "playlistadd" with URI + - fix "move" relative to current when there is no current song +* decoder: + - ffmpeg: support "application/flv" + - mikmod: adapt to libmikmod 3.2 +* configure.ac: + - detect system "ar" + +ver 0.17.4 (2013/04/08) +* protocol: + - allow to omit END in ranges (START:END) + - don't emit IDLE_PLAYER before audio format is known +* decoder: + - ffmpeg: support float planar audio (ffmpeg 1.1) + - ffmpeg: fix AVFrame allocation +* player: + - implement missing "idle" events on output errors +* clock: fix build failure + +ver 0.17.3 (2013/01/06) +* output: + - osx: fix pops during playback + - recorder: fix I/O error check + - shout: fix memory leak in error handler + - recorder, shout: support Ogg packets that span more than one page +* decoder: + - ffmpeg: ignore negative time stamps + - ffmpeg: support planar audio +* playlist: + - cue: fix memory leak + - cue: fix CUE files with only one track + +ver 0.17.2 (2012/09/30) +* protocol: + - fix crash in local file check +* decoder: + - fluidsynth: remove throttle (requires libfluidsynth 1.1) + - fluidsynth: stop playback at end of file + - fluidsynth: check MIDI file format while scanning + - fluidsynth: add sample rate setting + - wavpack: support all APEv2 tags +* output: + - httpd: use monotonic clock, avoid hiccups after system clock adjustment + - httpd: fix throttling bug after resuming playback +* playlist: + - cue: map "PERFORMER" to "artist" or "album artist" +* mapper: fix non-UTF8 music directory name +* mapper: fix potential crash in file permission check +* playlist: fix use-after-free bug +* playlist: fix memory leak +* state_file: save song priorities +* player: disable cross-fading in "single" mode +* update: fix unsafe readlink() usage +* configure.ac: + - don't auto-detect the vorbis encoder when Tremor is enabled + +ver 0.17.1 (2012/07/31) +* protocol: + - require appropriate permissions for searchadd{,pl} +* tags: + - aiff: support the AIFC format + - ape: check for ID3 if no usable APE tag was found +* playlist: + - cue: support file types "MP3", "AIFF" +* output: + - fix noisy playback with conversion and software volume + +ver 0.17 (2012/06/27) +* protocol: + - support client-to-client communication + - "update" and "rescan" need only "CONTROL" permission + - new command "seekcur" for simpler seeking within current song + - new command "config" dumps location of music directory + - add range parameter to command "load" + - print extra "playlist" object for embedded CUE sheets + - new commands "searchadd", "searchaddpl" +* input: + - cdio_paranoia: new input plugin to play audio CDs + - curl: enable CURLOPT_NETRC + - curl: non-blocking I/O + - soup: new input plugin based on libsoup +* tags: + - RVA2: support separate album/track replay gain +* decoder: + - mpg123: implement seeking + - ffmpeg: drop support for pre-0.5 ffmpeg + - ffmpeg: support WebM + - oggflac: delete this obsolete plugin + - dsdiff: new decoder plugin +* output: + - alsa: support DSD-over-USB (dCS suggested standard) + - httpd: support for streaming to a DLNA client + - openal: improve buffer cancellation + - osx: allow user to specify other audio devices + - osx: implement 32 bit playback + - shout: add possibility to set url + - roar: new output plugin for RoarAudio + - winmm: fail if wrong device specified instead of using default device +* mixer: + - alsa: listen for external volume changes +* playlist: + - allow references to songs outside the music directory + - new CUE parser, without libcue + - soundcloud: new plugin for accessing soundcloud.com +* state_file: add option "restore_paused" +* cue: show CUE track numbers +* allow port specification in "bind_to_address" settings +* support floating point samples +* systemd socket activation +* improve --version output +* WIN32: fix renaming of stored playlists with non-ASCII names + + +ver 0.16.8 (2012/04/04) +* fix for libsamplerate assertion failure +* decoder: + - vorbis (and others): fix seeking at startup + - ffmpeg: read the "year" tag +* encoder: + - vorbis: generate end-of-stream packet before tag + - vorbis: generate end-of-stream packet when playback ends +* output: + - jack: check for connection failure before starting playback + - jack: workaround for libjack1 crash bug + - osx: fix stuttering due to buffering bug +* fix endless loop in text file reader +* update: skip symlinks in path that is to be updated + + +ver 0.16.7 (2012/02/04) +* input: + - ffmpeg: support libavformat 0.7 +* decoder: + - ffmpeg: support libavformat 0.8, libavcodec 0.9 + - ffmpeg: support all MPD tags +* output: + - httpd: fix excessive buffering + - openal: force 16 bit playback, as 8 bit doesn't work + - osx: remove sleep call from render callback + - osx: clear render buffer when there's not enough data +* fix moving after current song + + +ver 0.16.6 (2011/12/01) +* decoder: + - fix assertion failure when resuming streams + - ffmpeg: work around bogus channel count +* encoder: + - flac, null, wave: fix buffer corruption bug + - wave: support packed 24 bit samples +* mapper: fix the bogus "not a directory" error message +* mapper: check "x" and "r" permissions on music directory +* log: print reason for failure +* event_pipe: fix WIN32 regression +* define WINVER in ./configure +* WIN32: autodetect filesystem encoding + + +ver 0.16.5 (2011/10/09) +* configure.ac + - disable assertions in the non-debugging build + - show solaris plugin result correctly + - add option --enable-solaris-output +* pcm_format: fix 32-to-24 bit conversion (the "silence" bug) +* input: + - rewind: reduce heap usage +* decoder: + - ffmpeg: higher precision timestamps + - ffmpeg: don't require key frame for seeking + - fix CUE track seeking +* output: + - openal: auto-fallback to mono if channel count is unsupported +* player: + - make seeking to CUE track more reliable + - the "seek" command works when MPD is stopped + - restore song position from state file (bug fix) + - fix crash that sometimes occurred when audio device fails on startup + - fix absolute path support in playlists +* WIN32: close sockets properly +* install systemd service file if systemd is available + + +ver 0.16.4 (2011/09/01) +* don't abort configure when avahi is not found +* auto-detect libmad without pkg-config +* fix memory leaks +* don't resume playback when seeking to another song while paused +* apply follow_inside_symlinks to absolute symlinks +* fix playback discontinuation after seeking +* input: + - curl: limit the receive buffer size + - curl: implement a hard-coded timeout of 10 seconds +* decoder: + - ffmpeg: workaround for semantic API change in recent ffmpeg versions + - flac: validate the sample rate when scanning the tag + - wavpack: obey all decoder commands, stop at CUE track border +* encoder: + - vorbis: don't send end-of-stream on flush +* output: + - alsa: fix SIGFPE when alsa announces a period size of 0 + - httpd: don't warn on client disconnect + - osx: don't drain the buffer when closing + - pulse: fix deadlock when resuming the stream + - pulse: fix deadlock when the stream was suspended + + +ver 0.16.3 (2011/06/04) +* fix assertion failure in audio format mask parser +* fix NULL pointer dereference in playlist parser +* fix playlist files in base music directory +* database: allow directories with just playlists +* decoder: + - ffmpeg: support libavcodec 0.7 + + +ver 0.16.2 (2011/03/18) +* configure.ac: + - fix bashism in tremor test +* decoder: + - tremor: fix configure test + - gme: detect end of song +* encoder: + - vorbis: reset the Ogg stream after flush +* output: + - httpd: fix uninitialized variable + - httpd: include sys/socket.h + - oss: AFMT_S24_PACKED is little-endian + - oss: disable 24 bit playback on FreeBSD + + +ver 0.16.1 (2011/01/09) +* audio_check: fix parameter in prototype +* add void casts to suppress "result unused" warnings (clang) +* input: + - ffado: disable by default +* decoder: + - mad: work around build failure on Solaris + - resolve modplug vs. libsndfile cflags/headers conflict +* output: + - solaris: add missing parameter to open_cloexec() cal + - osx: fix up audio format first, then apply it to device +* player_thread: discard empty chunks while cross-fading +* player_thread: fix assertion failure due to early seek +* output_thread: fix double lock + + +ver 0.16 (2010/12/11) +* protocol: + - send song modification time to client + - added "update" idle event + - removed the deprecated "volume" command + - added the "findadd" command + - range support for "delete" + - "previous" really plays the previous song + - "addid" with negative position is deprecated + - "load" supports remote playlists (extm3u, pls, asx, xspf, lastfm://) + - allow changing replay gain mode on-the-fly + - omitting the range end is possible + - "update" checks if the path is malformed +* archive: + - iso: renamed plugin to "iso9660" + - zip: renamed plugin to "zzip" +* input: + - lastfm: obsolete plugin removed + - ffmpeg: new input plugin using libavformat's "avio" library +* tags: + - added tags "ArtistSort", "AlbumArtistSort" + - id3: revised "performer" tag support + - id3: support multiple values + - ape: MusicBrainz tags + - ape: support multiple values +* decoders: + - don't try a plugin twice (MIME type & suffix) + - don't fall back to "mad" unless no plugin matches + - ffmpeg: support multiple tags + - ffmpeg: convert metadata to generic format + - ffmpeg: implement the libavutil log callback + - sndfile: new decoder plugin based on libsndfile + - flac: moved CUE sheet support to a playlist plugin + - flac: support streams without STREAMINFO block + - mikmod: sample rate is configurable + - mpg123: new decoder plugin based on libmpg123 + - sidplay: support sub-tunes + - sidplay: implemented songlength database + - sidplay: support seeking + - sidplay: play monaural SID tunes in mono + - sidplay: play mus, str, prg, x00 files + - wavpack: activate 32 bit support + - wavpack: allow more than 2 channels + - mp4ff: rename plugin "mp4" to "mp4ff" +* encoders: + - twolame: new encoder plugin based on libtwolame + - flac: new encoder plugin based on libFLAC + - wave: new encoder plugin for PCM WAV format +* output: + - recorder: new output plugin for recording radio streams + - alsa: don't recover on CANCEL + - alsa: fill period buffer with silence before draining + - openal: new output plugin + - pulse: announce "media.role=music" + - pulse: renamed context to "Music Player Daemon" + - pulse: connect to server on MPD startup, implement pause + - jack: require libjack 0.100 + - jack: don't disconnect during pause + - jack: connect to server on MPD startup + - jack: added options "client_name", "server_name" + - jack: clear ring buffers before activating + - jack: renamed option "ports" to "destination_ports" + - jack: support more than two audio channels + - httpd: bind port when output is enabled + - httpd: added name/genre/website configuration + - httpd: implement "pause" + - httpd: bind_to_address support (including IPv6) + - oss: 24 bit support via OSS4 + - win32: new output plugin for Windows Wave + - shout, httpd: more responsive to control commands + - wildcards allowed in audio_format configuration + - consistently lock audio output objects +* player: + - drain audio outputs at the end of the playlist +* mixers: + - removed support for legacy mixer configuration + - reimplemented software volume as mixer+filter plugin + - per-device software/hardware mixer setting +* commands: + - added new "status" line with more precise "elapsed time" +* update: + - automatically update the database with Linux inotify + - support .mpdignore files in the music directory + - sort songs by album name first, then disc/track number + - rescan after metadata_to_use change +* normalize: upgraded to AudioCompress 2.0 + - automatically convert to 16 bit samples +* replay gain: + - reimplemented as a filter plugin + - fall back to track gain if album gain is unavailable + - optionally use hardware mixer to apply replay gain + - added mode "auto" + - parse replay gain from APE tags +* log unused/unknown block parameters +* removed the deprecated "error_file" option +* save state when stopped +* renamed option "--stdout" to "--stderr" +* removed options --create-db and --no-create-db +* state_file: save only if something has changed +* database: eliminated maximum line length +* log: redirect stdout/stderr to /dev/null if syslog is used +* set the close-on-exec flag on all file descriptors +* pcm_volume, pcm_mix: implemented 32 bit support +* support packed 24 bit samples +* CUE sheet support +* support for MixRamp tags +* obey $(sysconfdir) for default mpd.conf location +* build with large file support by default +* added test suite ("make check") +* require GLib 2.12 +* added libwrap support +* make single mode 'sticky' + + +ver 0.15.17 (2011/??/??) +* encoder: + - vorbis: reset the Ogg stream after flush +* decoders: + - vorbis: fix tremor support + + +ver 0.15.16 (2011/03/13) +* output: + - ao: initialize the ao_sample_format struct + - jack: fix crash with mono playback +* encoders: + - lame: explicitly configure the output sample rate +* update: log all file permission problems + + +ver 0.15.15 (2010/11/08) +* input: + - rewind: fix assertion failure +* output: + - shout: artist comes first in stream title + + +ver 0.15.14 (2010/11/06) +* player_thread: fix assertion failure due to wrong music pipe on seek +* output_thread: fix assertion failure due to race condition in OPEN +* input: + - rewind: fix double free bug +* decoders: + - mp4ff, ffmpeg: add extension ".m4b" (audio book) + + +ver 0.15.13 (2010/10/10) +* output_thread: fix race condition after CANCEL command +* output: + - httpd: fix random data in stream title + - httpd: MIME type audio/ogg for Ogg Vorbis +* input: + - rewind: update MIME not only once + - rewind: enable for MMS + + +ver 0.15.12 (2010/07/20) +* input: + - curl: remove assertion after curl_multi_fdset() +* tags: + - rva2: set "gain", not "peak" +* decoders: + - wildmidi: support version 0.2.3 + + +ver 0.15.11 (2010/06/14) +* tags: + - ape: support album artist +* decoders: + - mp4ff: support tags "album artist", "albumartist", "band" + - mikmod: fix memory leak + - vorbis: handle uri==NULL + - ffmpeg: fix memory leak + - ffmpeg: free AVFormatContext on error + - ffmpeg: read more metadata + - ffmpeg: fix libavformat 0.6 by using av_open_input_stream() +* playlist: emit IDLE_OPTIONS when resetting single mode +* listen: make get_remote_uid() work on BSD + + +ver 0.15.10 (2010/05/30) +* input: + - mms: fix memory leak in error handler + - mms: initialize the "eof" attribute +* decoders: + - mad: properly calculate ID3 size without libid3tag + + +ver 0.15.9 (2010/03/21) +* decoders: + - mad: fix crash when seeking at end of song + - mpcdec: fix negative shift on fixed-point samples + - mpcdec: fix replay gain formula with v8 +* playlist: fix single+repeat in random mode +* player: postpone song tags during cross-fade + + +ver 0.15.8 (2010/01/17) +* input: + - curl: allow rewinding with Icy-Metadata +* decoders: + - ffmpeg, flac, vorbis: added more flac/vorbis MIME types + - ffmpeg: enabled libavformat's file name extension detection +* dbUtils: return empty tag value only if no value was found +* decoder_thread: fix CUE track playback +* queue: don't repeat current song in consume mode + + +ver 0.15.7 (2009/12/27) +* archive: + - close archive when stream is closed + - iso, zip: fixed memory leak in destructor +* input: + - file: don't fall back to parent directory + - archive: fixed memory leak in error handler +* tags: + - id3: fix ID3v1 charset conversion +* decoders: + - eliminate jitter after seek failure + - ffmpeg: don't try to force stereo + - wavpack: allow fine-grained seeking +* mixer: explicitly close all mixers on shutdown +* mapper: fix memory leak when playlist_directory is not set +* mapper: apply filesystem_charset to playlists +* command: verify playlist name in the "rm" command +* database: return multiple tag values per song + + +ver 0.15.6 (2009/11/18) +* input: + - lastfm: fixed variable name in GLib<2.16 code path + - input/mms: require libmms 0.4 +* archive: + - zzip: require libzzip 0.13 +* tags: + - id3: allow 4 MB RIFF/AIFF tags +* decoders: + - ffmpeg: convert metadata + - ffmpeg: align the output buffer + - oggflac: rewind stream after FLAC detection + - flac: fixed CUE seeking range check + - flac: fixed NULL pointer dereference in CUE code +* output_thread: check again if output is open on PAUSE +* update: delete ignored symlinks from database +* database: increased maximum line length to 32 kB +* sticker: added fallback for sqlite3_prepare_v2() + + +ver 0.15.5 (2009/10/18) +* input: + - curl: don't abort if a packet has only metadata + - curl: fixed endless loop during buffering +* tags: + - riff, aiff: fixed "limited range" gcc warning +* decoders: + - flac: fixed two memory leaks in the CUE tag loader +* decoder_thread: change the fallback decoder name to "mad" +* output_thread: check again if output is open on CANCEL +* update: fixed memory leak during container scan + + +ver 0.15.4 (2009/10/03) +* decoders: + - vorbis: revert "faster tag scanning with ov_test_callback()" + - faad: skip assertion failure on large ID3 tags + - ffmpeg: use the "artist" tag if "author" is not present +* output: + - osx: fix the OS X 10.6 build + + +ver 0.15.3 (2009/08/29) +* decoders: + - vorbis: faster tag scanning with ov_test_callback() +* output: + - fix stuttering due to uninitialized variable +* update: don't re-read unchanged container files + + +ver 0.15.2 (2009/08/15) +* tags: + - ape: check the tag size (fixes integer underflow) + - ape: added protection against large memory allocations +* decoders: + - mad: skip ID3 frames when libid3tag is disabled + - flac: parse all replaygain tags + - flac: don't allocate cuesheet twice (memleak) +* output: + - shout: fixed stuck pause bug + - shout: minimize the unpause latency +* update: free empty path string (memleak) +* update: free temporary string in container scan (memleak) +* directory: free empty directories after removing them (memleak) + + +ver 0.15.1 (2009/07/15) +* decoders: + - flac: fix assertion failure in tag_free() call +* output: + - httpd: include sys/types.h (fixes Mac OS X) +* commands: + - don't resume playback when stopping during pause +* database: fixed NULL pointer dereference after charset change +* log: fix double free() bug during shutdown + + +ver 0.15 (2009/06/23) +* input: + - parse Icy-Metadata + - added support for the MMS protocol + - hide HTTP password in playlist + - lastfm: new input plugin for last.fm radio (experimental and incomplete!) + - curl: moved proxy settings to "input" block +* tags: + - support the "album artist" tag + - support MusicBrainz tags + - parse RVA2 tags in mp3 files + - parse ID3 tags in AIFF/RIFF/WAV files + - ffmpeg: support new metadata API + - ffmpeg: added support for the tags comment, genre, year +* decoders: + - audiofile: streaming support added + - audiofile: added 24 bit support + - modplug: another MOD plugin, based on libmodplug + - mikmod disabled by default, due to severe security issues in libmikmod + - sidplay: new decoder plugin for C64 SID (using libsidplay2) + - fluidsynth: new decoder plugin for MIDI files (using libfluidsynth, + experimental due to shortcomings in libfluidsynth) + - wildmidi: another decoder plugin for MIDI files (using libwildmidi) + - flac: parse stream tags + - mpcdec: support the new libmpcdec SV8 API + - added configuration option to disable decoder plugins + - flac: support embedded cuesheets + - ffmpeg: updated list of supported formats +* audio outputs: + - added option to disable audio outputs by default + - wait 10 seconds before reopening after play failure + - shout: enlarged buffer size to 32 kB + - null: allow disabling synchronization + - mvp: fall back to stereo + - mvp: fall back to 16 bit audio samples + - mvp: check for reopen errors + - mvp: fixed default device detection + - pipe: new audio output plugin which runs a command + - alsa: better period_time default value for high sample rates + - solaris: new audio output plugin for Solaris /dev/audio + - httpd: new audio output plugin for web based streaming, similar to icecast + but built in. +* commands: + - "playlistinfo" and "move" supports a range now + - added "sticker database", command "sticker", which allows clients + to implement features like "song rating" + - added "consume" command which removes a song after play + - added "single" command, if activated, stops playback after current song or + repeats the song if "repeat" is active. +* mixers: + - rewritten mixer code to support multiple mixers + - new pulseaudio mixer + - alsa: new mixer_index option supports choosing between multiple + identically-named controls on a device. +* Add audio archive extraction support: + - bzip2 + - iso9660 + - zip +* the option "error_file" was removed, all messages are logged into + "log_file" +* support logging to syslog +* fall back to XDG music directory if no music_directory is configured +* failure to read the state file is non-fatal +* --create-db starts the MPD daemon instead of exiting +* playlist_directory and music_directory are optional +* playlist: recalculate the queued song after random is toggled +* playlist: don't unpause on delete +* pause when all audio outputs fail to play +* daemon: ignore "user" setting if already running as that user +* listen: fix broken client IP addresses in log +* listen: bind failure on secondary address is non-fatal +* 24/32 bit audio support +* print available protocols in --version +* fill buffer after seeking +* choose the fallback resampler at runtime +* steps taken towards win32 compatibility +* require glib 2.6 or greater +* built-in documentation using doxygen and docbook + + +ver 0.14.2 (2009/02/13) +* configure.ac: + - define HAVE_FFMPEG after all checks +* decoders: + - ffmpeg: added support for the tags comment, genre, year + - ffmpeg: don't warn of empty packet output + - ffmpeg: check if the time stamp is valid + - ffmpeg: fixed seek integer overflow + - ffmpeg: enable WAV streaming + - ffmpeg: added TTA support + - wavpack: pass NULL if the .wvc file fails to open + - mikmod: call MikMod_Exit() only in the finish() method + - aac: fix stream metadata +* audio outputs: + - jack: allocate ring buffers before connecting + - jack: clear "shutdown" flag on reconnect + - jack: reduced sleep time to 1ms + - shout: fixed memory leak in the mp3 encoder + - shout: switch to blocking mode + - shout: use libshout's synchronization + - shout: don't postpone metadata + - shout: clear buffer before calling the encoder +* mapper: remove trailing slashes from music_directory +* player: set player error when output device fails +* update: recursively purge deleted directories +* update: free deleted subdirectories + +ver 0.14.1 (2009/01/17) +* decoders: + - mp4: support the writer/composer tag + - id3: strip leading and trailing whitespace from ID3 tags + - oggvorbis: fix tremor support + - oggvorbis: disable seeking on remote files +* audio outputs: + - jack: allocate default port names (fixes a crash) +* update: + - refresh stats after update + - save the database even if it is empty +* input_curl: + - use select() to eliminate busy loop during connect + - honour http_proxy_* config directives + - fix assertion failure on "connection refused" + - fix assertion failure with empty HTTP responses +* corrected the sample calculation in the fallback resampler +* log: automatically append newline +* fix setenv() conflict on Solaris +* configure.ac: check for pkg-config before using it +* fix minor memory leak in decoder_tag() +* fix cross-fading bug: it used to play some chunks of the new song twice +* playlist + - fix assertion failure during playlist load + - implement Fisher-Yates shuffle properly + - safely search the playlist for deleted song +* use custom PRNG for volume dithering (speedup) +* detect libid3tag without pkg-config + +ver 0.14 (2008/12/25) +* audio outputs: + - wait 10 seconds before reopening a failed device + - fifo: new plugin + - null: new plugin + - shout: block while trying to connect instead of failing + - shout: new timeout parameter + - shout: support mp3 encoding and the shoutcast protocol + - shout: send silence during pause, so clients don't get disconnected +* decoders: + - ffmpeg: new plugin + - wavpack: new plugin + - aac: stream support added + - mod: disabled by default due to critical bugs in all libmikmod versions +* commands: + - "addid" takes optional second argument to specify position + - "idle" notifies the client when a notable change occurs +* Zeroconf support using Bonjour +* New zeroconf_enabled option so that Zeroconf support can be disabled +* Stop the player/decode processes when not playing to allow the CPU to sleep +* Fix a bug where closing an ALSA dmix device could cause MPD to hang +* Support for reading ReplayGain from LAME tags on MP3s +* MPD is now threaded, which greatly improves performance and stability +* memory usage reduced by merging duplicate tags in the database +* support connecting via unix domain socket +* allow authenticated local users to add any local file to the playlist +* 24 bit audio support +* optimized PCM conversions and dithering +* much code has been replaced by using GLib +* the HTTP client has been replaced with libcurl +* symbolic links in the music directory can be disabled; the default + is to ignore symlinks pointing outside the music directory + +ver 0.13.0 (2007/5/28) +* New JACK audio output +* Support for "file" as an alternative to "filename" in search, find, and list +* FLAC 1.1.3 API support +* New playlistadd command for adding to stored playlists +* New playlistclear command for clearing stored playlists +* Fix a bug where "find any" and "list any" wouldn't return any results +* Make "list any" return an error instead of no results and an OK +* New gapless_mp3_playback option to disable gapless MP3 playback +* Support for seeking HTTP streams +* Zeroconf support using Avahi +* libsamplerate support for high quality audio resampling +* ID3v2 "Original Artist/Performer" tag support +* New playlistsearch command for searching the playlist (similar to "search") +* New playlistfind command for finding songs in the playlist (similar to "find") +* libmikmod 3.2.0 beta support +* New tagtypes command for retrieving a list of available tag types +* Fix a bug where no ACK was returned if loading a playlist failed +* Fix a bug where db_update in stats would be 0 after initial database creation +* New count command for getting stats on found songs (similar to "find") +* New playlistmove command for moving songs in stored playlists +* New playlistdelete command for deleting songs from stored playlists +* New rename command for renaming stored playlists +* Increased default buffer_before_play from 0% to 10% to prevent skipping +* Lots of bug fixes, cleaned up code, and performance improvements + +ver 0.12.2 (2007/3/20) +* Fix a bug where clients could cause MPD to segfault + +ver 0.12.1 (2006/10/10) +* Fix segfault when scanning an MP3 that has a Xing tag with 0 frames +* Fix segfault when there's no audio output specified and one can't be detected +* Fix handling of escaping in quotes +* Allow a quality of -1 to be specified for shout outputs +* A few minor cleanups + +ver 0.12.0 (2006/9/22) +* New audio output code which supports: + * A plugin-like architecture + * Non-libao ("native") outputs: + * ALSA + * OSS + * OS X + * Media MVP + * PulseAudio + * Shout (Icecast or Shoutcast) + * Playing through multiple outputs at once + * Enabling/disabling outputs while MPD is running + * Saving output state (enabled/disabled) to the state_file +* OggFLAC support +* Musepack support +* Gapless MP3 playback +* MP3 ReplayGain support (using ID3v2 tags only) +* Support for MP2 files if MP3 support is enabled +* Composer, Performer, Comment, and Disc metadata support +* New outputs command for listing available audio outputs +* New enableoutput and disableoutput commands for enabling/disabling outputs +* New plchangesposid command for a stripped down version of plchanges +* New addid command for adding to the playlist and returning a song ID +* New commands and notcommands commands for checking available commands +* Can now specify any supported metadata type or "any" in search, find, and list +* New volume_normalization parameter for enabling Audio Compress normalization +* New metadata_to_use parameter for choosing supported metadata types +* New pid_file parameter for saving the MPD process ID to the specified file +* The db_file parameter is now required +* The port parameter is now optional (defaults to 6600) +* Can specify bind_to_address multiple times +* New --kill argument for killing MPD if pid_file is specified +* Removed --update-db argument (use the update function in your client instead) +* New mpdconf.example +* New mpd.conf man page +* Removed bundled libmad and libid3tag +* Lots of bug fixes, cleaned up code, and performance improvements + +ver 0.11.5 (2004/11/1) +1) New id3v1_encoding config option to configure the id3v1 tag encoding (patch +from dottedmag) +2) Strip '\r' from m3u playlists (thank you windows) +3) Use random() instead of rand() for playlist randomizing +4) Fix a bug trying skipping some commented lines in m3u playlist files +5) Fix a bug when fetching metadata from streams that may cause certain +weirdnesses +6) Fix a bug where replaygain preamp was used on files w/o replaygain tags +7) Fix a busy loop when trying to prebuffer a nonexistant or missing stream +8) Fix a bug in forgetting to remove leading ' ' in content-type for http +streams +9) Check for ice-name in http headers +10) Be sure the strip all '\n' chars in tags +11) Set $HOME env variable when setuid'ing, this should fix the /root/.mcop +errors triggered by arts/libao + +ver 0.11.4 (2004/7/26) +1) Fixed a segfault when decoding mp3's with corrupt id3v2 tags +2) Fixed a memory leak when encountering id3v2 tags in mp3 decoder + +ver 0.11.3 (2004/7/21) +1) Add support for http authentication for streams +2) Added replaygain pre-amp support +3) Better error handling for fread() in inputStream_file +4) Fixed a bug so that when a freeAllInterfaces is called, it sets +max_interface_connections to 0. This prevents potential segfaults and other +nastiness for forked processes, like the player and update-er (do to +interfacePrintWithFD()). +5) Allow blockingWrite() to handle errors more gracefully (for example, if the +disc is full, and thus the write() fails or can't be completed, we just skip +this write() and continue, instead of getting stuck in an infinite loop until +the write() becomes successful) +6) Updated mpdconf.example from sbh/avuton +7) If "user" is specified, then convert ~ in paths to the user's home path +specified by "user" config paramter (not the actual current user running mpd). + +ver 0.11.2 (2004/7/5) +1) Work around in computing total time for mp3's whose first valid mpeg frame is +not layer III +2) Fix mp3 and mp4 decoders when seeking past the end of the file +3) Fix replaygain for flac and vorbis +4) Fix memory leaks in flac decoder (from normalperson) +5) Fix Several other bugs in playlist.c and directory.c (from normalperson) + +ver 0.11.1 (2004/6/24) +1) Fix a bug that caused "popping" at the beginning of mp3's +2) Fix playlistid command +3) Fix move commands so they don't mess up the song id's +4) Added support for HTTP Proxy +5) Detect and skip recursive links in the music directory +6) Fix addPathToDB() so updating on a specific path doesn't exist correctly adds +the parent directories to the DB + +ver 0.11.0 (2004/6/18) +1) Support for playing mp3 and Ogg Vorbis streams +2) Non-blocking Update +3) Replaygain support for Ogg Vorbis and FLAC (by Eric Moore aka AliasMrJones) +4) audio_output_format option that allows for all audio output to be converted +to a format compatible with any sound card +5) Own routines for to always support UTF-8 <-> ISO-8859-1 conversion +6) Added "Id" and "Pos" metadata for songs in playlist +7) Added commands: plchanges, currentsong, playid, seekid, playlistid, moveid, +swapid, deleteid +8) UTF-8 validation of all tags +9) Update specific files/directories (for fast, incremental updating) +10) Added ACK error codes +11) Mod file support +12) Added command_list_ok_begin +13) Play after stop resumes from last position in the playlist +14) Play while pause resumes playback +15) Better signal handling by mackstann +16) Cleanup decoder interface (now called InputPlugins) +17) --create-db no long starts the daemon +18) --no-daemon outputs to log files +19) --stdout sends output to stdout/stderr +20) Default port is now 6600 +21) Lots of other cleanups and Bugfixes + +ver 0.10.4 (2004/5/26) +1) Fix configure problems on OpenBSD with langinfo and iconv +2) Fix an infinte loop when writing to an interface and it has expired +3) Fix a segfault in decoding flac's +4) Ingore CRC stuff in mp3's since some encoders did not compute the CRC +correctly +5) Fix a segfault in processing faulty mp4 metadata + +ver 0.10.3 (2004/4/2) +1) Fix a segfault when a blanck line is sent from a client +2) Fix for loading playlists on platforms where char is unsigned +3) When pausing, release audio device after we say pause is successful (this +makes pause appear to not lag) +4) When returning errors for unknown types by player, be sure to copy the +filename +5) add --disable-alsa for disabling alsa mixer support +6) Use select() for a portable usleep() +7) For alsa mixer, default to "Master' element, not first element + +ver 0.10.2 (2004/3/25) +1) Add suport for AAC +2) Substitute '\n' with ' ' in tag info +3) Remove empty directories from db +4) Resume from current position in song when using state file +5) Pause now closes the music device, and reopens it on resuming +6) Fix unnecessary big endian byte swapping +7) If locale is "C" or "POSIX", then use ISO-8859-1 as the fs charset +8) Fix a bug where alsa mixer wasn't detecting volume changes +9) For alsa and software mixer, show volume to be the same as it was set (even +if its not the exact volume) +10) Report bitrate for wave files +11) Compute song length of CBR mp3's more accurately + +ver 0.10.1 (2004/3/7) +1) Check to see if we need to add "-lm" when linking mpd +2) Fix issues with skipping bad frames in an mp3 (this way we get the correct +samplerate and such) +3) Fix crossfading bug with ogg's +4) Updated libmad and libid3tag included w/ source to 0.15.1b + +ver 0.10.0 (2004/3/3) +1) Use UTF-8 for all client communications +2) Crossfading support +3) Password Authentication (all in plaintext) +4) Software mixer +5) Buffer Size is configurable +6) Reduced Memory consumption (use directory tree for search and find) +7) Bitrate support for Flac +8) setvol command (deprecates volume command) +9) add command takes directories +10) Path's in config file now work with ~ +11) Add samplerate,bits, and channels to status +12) Reenable playTime in stats display +13) Fix a segfault when doing: add "" +14) Fix a segfault with flac vorbis comments simply being "=" +15) Fix a segfault/bug in queueNextSong with repeat+random +16) Fix a bug, where one process may segfault, and cause more processes to spawn +w/o killing ones that lost their parent. +17) Fix a bug when the OSS device was unable to fetch the current volume, +it would close the device (when it maybe previously closed by the exact same +code) +18) command.c cleanup by mackstann +19) directory.c and command.c cleanup by tw-nym + +ver 0.9.4 (2004/1/21) +1) Fix a bug where updated tag info wasn't being detected +2) Set the default audio write size to 1024 bytes (should decrease cpu load a +bit on some machines). +3) Make audio write size configurable via "audio_write_size" config option +4) Tweak output buffer size for connections by detecting the kernel output +buffer size. + +ver 0.9.3 (2003/10/31) +1) Store total time/length of songs in db and display in *info commands +2) Display instantaneous bitrate in status command +3) Add Wave Support using libaudiofile (Patch from normalperson) +4) Command code cleanup (Patch from tw-nym) +5) Optimize listing of playlists (10-100x faster) +6) Optimize interface output (write in 4kB chunks instead of on every '\n') +7) Fix bug that prevented rm command from working +8) Fix bug where deleting current song skips the next song +9) Use iconv to convert vorbis comments from UTF-8 to Latin1 + +ver 0.9.2 (2003/10/6) +1) Fix FreeBSD Compilation Problems +2) Fix bug in move command +3) Add mixer_control options to configure which mixer control/device mpd +controls +4) Randomize on play -1 +5) Fix a bug in toggling repeat off and at the end of the playlist + +ver 0.9.1 (2003/9/30) +1) Fix a statement in the middle of declarations in listen.c, causes error for +gcc 2.7 + +ver 0.9.0 (2003/9/30) +1) Random play mode +2) Alsa Mixer Support +3) Save and Restore "state" +4) Default config file locations (.mpdconf and /etc/mpd.conf) +5) Make db file locations configurable +6) Move songs around in the playlist +7) Gapless playback +8) Use Xing tags for mp3's +9) Remove stop_on_error +10) Seeking support +11) Playlists can be loaded and deleted from subdirectories +12) Complete rewrite of player layer (fork()'s only once, opens and closes +audio device as needed). +13) Eliminate use and dependence of SIGIO +14) IPv6 support +15) Solaris compilations fixes +16) Support for different log levels +17) Timestamps for log entries +18) "user" config parameter for setuid (patch from Nagilum) +19) Other misc features and bug fixes + +ver 0.8.7 (2003/9/3) +1) Fix a memory leak. When closing a interface, was called close() on the fd +instead of calling fclose() on the fp that was opened with fdopen(). + +ver 0.8.6 (2003/8/25) +1) Fix a memory leak when a buffered existed, and a connection was unexpectedly +closed, and i wasn't free'ing the buffer apropriatly. + +ver 0.8.5 (2003/8/17) +1) Fix a bug where an extra end of line is returned when attempting to play a +non existing file. This causes parsing errors for clients. + +ver 0.8.4 (2003/8/13) +1) Fix a bug where garbage is returned with errors in "list" command + +ver 0.8.3 (2003/8/12) +1) Fix a compilation error on older linux systems +2) Fix a bug in searching by title +3) Add "list" command +4) Add config options for specifying libao driver/plugin and options +5) Add config option to specify which address to bind to +6) Add support for loading and saving absolute pathnames in saved playlists +7) Playlist no longer creates duplicate entries for song data (more me +efficient) +8) Songs deleted from the db are now removed for the playlist as well + +ver 0.8.2 (2003/7/22) +1) Increased the connection que for listen() from 0 to 5 +2) Cleanup configure makefiles so that mpd uses MPD_LIBS and MPD_CFLAGS +rather than LIBS and CFLAGS +3) Put a cap on the number of commands per command list +4) Put a cap on the maximum number of buffered output lines +5) Get rid of TIME_WAIT/EADDRINUSE socket problem +6) Use asynchronious IO (i.e. trigger SIGIO instead so we can sleep in +select() calls longer) + +ver 0.8.1 (2003/7/11) +1) FreeBSD fixes +2) Fix for rare segfault when updating +3) Fix bug where client was being hungup on when done playing current song +4) Fix bug when playing flac's where it incorrectly reports an error +5) Make stop playlist on error configurable +6) Configure checks for installed libmad and libid3tag and uses those if found +7) Use buffer->finished in *_decode's instead of depending on catching signals + +ver 0.8.0 (2003/7/6) +1) Flac support +2) Make playlist max length configurable +3) New backward compatible status (backward compatible for 0.8.0 on) +4) listall command now can take a directory as an argument +5) Buffer rewritten to use shared memory instead of sockets +6) Playlist adding done using db +7) Add sort to list, and use binary search for finding +8) New "stats" command +9) Command list (for faster adding of large batches of files) +10) Add buffered chunks before play +11) Useful error reporting to clients (part of status command) +12) Use libid3tag for reading id3 tags (more stable) +13) Non-blocking output to clients +14) Fix bug when removing items from directory +15) Fix bug when playing mono mp3's +16) Fix bug when attempting to delete files when using samba +17) Lots of other bug fixes I can't remember + +ver 0.7.0 (2003/6/20) +1) use mad instead of mpg123 for mp3 decoding +2) volume support +3) repeate playlist support +4) use autoconf/automake (i.e. "configure") +5) configurable max connections + +ver 0.6.2 (2003/6/11) +1) Buffer support for ogg +2) new config file options: "connection_timeout" and "mpg123_ignore_junk" +3) new commands: "next", "previous", and "listall" +Thanks to Niklas Hofer for "next" and "previous" patches! +4) Search by filename +5) bug fix for pause when playing mp3's + +ver 0.6.1 (2003/5/29) +1) Add conf file support +2) Fix a bug when doing mp3stop (do wait3(NULL,WNOHANG|WUNTRACED,NULL)) +3) Fix a bug when fork'ing, fflush file buffers before forking so the +child doesn't print the same stuff in the buffer. + +ver 0.6.0 (2003/5/25) +1) Add ogg vorbis support +2) Fix two bugs relating to tables, one for search by title, and one where we +freed the tables before directories, causing a segfault +3) The info command has been removed. + +ver 0.5.0-0.5.2 +Initial release(s). Support for MP3 via mpg123 diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..377b2bf --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,24 @@ +*.iml +.gradle +/local.properties +## ignoring .idea completely +# until a good reason emerges not to +/.idea +##-- +## moved the following into .idea/.gitignore +#/.idea/caches +#/.idea/libraries +#/.idea/modules.xml +#/.idea/workspace.xml +#/.idea/navEditor.xml +#/.idea/assetWizardSettings.xml +## -- +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +# both were used: different spelling +app/src/main/jnilibs/ +app/src/main/jniLibs/ diff --git a/android/PrivacyPolicy.rst b/android/PrivacyPolicy.rst new file mode 100644 index 0000000..775983c --- /dev/null +++ b/android/PrivacyPolicy.rst @@ -0,0 +1,8 @@ +MPD for Android Privacy Policy +============================== + +Music Player Daemon is an open source project currently maintained by +`Max Kellermann `__. + +Music Player Daemon does not access, collect, use or share any +personal or sensitive user data. diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..44d93b2 --- /dev/null +++ b/android/README.md @@ -0,0 +1,49 @@ +# Android + +Notes and resources for MPD android maintainers. + +## Build + +See [Compiling for Android](https://github.com/MusicPlayerDaemon/MPD/blob/45cb098cd765af12316f8dca5635ef10a852e013/doc/user.rst#compiling-for-android) + +## Android studio + +### Version control + +git ignoring .idea directory completely until a good reason emerges not to + +* [How to manage projects under Version Control Systems (jetbrains.com)](https://intellij-support.jetbrains.com/hc/en-us/articles/206544839-How-to-manage-projects-under-Version-Control-Systems) + +* [gradle.xml should work like workspace.xml? (jetbrains.com)](https://youtrack.jetbrains.com/issue/IDEA-55923) + +### Native libraries + +* [Include prebuilt native libraries (developer.android.com)](https://developer.android.com/studio/projects/gradle-external-native-builds#jniLibs) + +## Permissions + +### Files access + +The required permission depends on android SDK version: + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) + Manifest.permission.READ_MEDIA_AUDIO + else + Manifest.permission.READ_EXTERNAL_STORAGE + +### Permission request + +[Request runtime permissions](https://developer.android.com/training/permissions/requesting) + +Since Android 6.0 (API level 23): + +Android will ignore permission request and will not show the request dialog +if the user's action implies "don't ask again." +This leaves the app in a crippled state and the user confused. +Google says "don't try to convince the user", so it returns false for `shouldShowRequestPermissionRationale`. + +To help the user proceed, we show the `Request permission` button only if `shouldShowRequestPermissionRationale == true` +because there's a good chance the permission request dialog will not be ignored. + +If `shouldShowRequestPermissionRationale == false` we instead show the "rationale" message and a button to open +the app info dialog where the user can explicitly grand the permission. \ No newline at end of file diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..bcf84c3 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,128 @@ +plugins { + id("com.google.devtools.ksp") + alias(libs.plugins.android.application) + alias(libs.plugins.jetbrains.kotlin.android) + alias(libs.plugins.dagger.hilt.android) +} + +android { + namespace = "org.musicpd" + compileSdk = 35 + + defaultConfig { + applicationId = "org.musicpd" + minSdk = 24 + targetSdk = 34 + versionCode = 1 + versionName = "1.0" + vectorDrawables { + useSupportLibrary = true + } + } + + buildFeatures { + aidl = true + compose = true + } + + composeOptions { + kotlinCompilerExtensionVersion = "1.5.10" + } + + buildTypes { + debug { + isMinifyEnabled = false + } + release { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + // flavors + flavorDimensions += "base" + productFlavors { + create("fail-test") { + // To test System.loadLibrary("mpd") failure + // exclude the native lib from the package + packaging { + jniLibs { + // it appears the 'excludes' is applied to all flavors + // even if it's only inside this flavor. + // this filters by task name to apply the exclusion only + // for this flavor name. + // (clearing the 'abiFilters' will only create a universal apk + // with all of the abi versions) + gradle.startParameter.getTaskNames().forEach { task -> + if (task.contains("fail-test", ignoreCase = true)) { + println("NOTICE: excluding libmpd.so from package $task for testing") + excludes += "**/libmpd.so" + } + } + } + } + } + create("arm64-v8a") { + ndk { + // ABI to include in package + //noinspection ChromeOsAbiSupport + abiFilters += listOf("arm64-v8a") + } + } + create("x86_64") { + ndk { + // ABI to include in package + abiFilters += listOf("x86_64") + } + } + create("universal") { + ndk { + // ABI to include in package + abiFilters += listOf("arm64-v8a", "x86_64") + } + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_9 + targetCompatibility = JavaVersion.VERSION_1_9 + } + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_9.toString() + } + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +dependencies { + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(platform(libs.androidx.compose.bom)) + + implementation(libs.androidx.material3) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.material.icons.extended) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.navigation.compose) + + implementation(libs.compose.settings.ui.m3) + implementation(libs.compose.settings.storage.preferences) + implementation(libs.accompanist.permissions) + + implementation(libs.hilt.android) + ksp(libs.dagger.compiler) + ksp(libs.hilt.compiler) + + implementation(libs.androidx.media3.session) + + // Android Studio Preview support + implementation(libs.androidx.ui.tooling.preview) + debugImplementation(libs.androidx.ui.tooling) + debugImplementation(libs.androidx.ui.test.manifest) + + implementation(libs.androidx.appcompat) +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..7cdbb5e --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/aidl/org/musicpd/IMain.aidl b/android/app/src/main/aidl/org/musicpd/IMain.aidl new file mode 100644 index 0000000..4eaf577 --- /dev/null +++ b/android/app/src/main/aidl/org/musicpd/IMain.aidl @@ -0,0 +1,13 @@ +package org.musicpd; +import org.musicpd.IMainCallback; + +interface IMain +{ + void start(); + void stop(); + void setPauseOnHeadphonesDisconnect(boolean enabled); + void setWakelockEnabled(boolean enabled); + boolean isRunning(); + void registerCallback(IMainCallback cb); + void unregisterCallback(IMainCallback cb); +} diff --git a/android/app/src/main/aidl/org/musicpd/IMainCallback.aidl b/android/app/src/main/aidl/org/musicpd/IMainCallback.aidl new file mode 100644 index 0000000..21e435d --- /dev/null +++ b/android/app/src/main/aidl/org/musicpd/IMainCallback.aidl @@ -0,0 +1,8 @@ +package org.musicpd; + +interface IMainCallback +{ + void onStarted(); + void onStopped(); + void onError(String error); +} diff --git a/android/app/src/main/ic_launcher-playstore.png b/android/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000000000000000000000000000000000000..9c27e1a7ca2c56755c1e500c858b14830ab724bf GIT binary patch literal 49970 zcmeFZ`8$+t_&6mNo>%7k8b-vEm)m@Xbh9ZK}f&c)K zQzws~2LKHp(E!5_|5)_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nhnn24LIv0OS3C@ECL+134{XoTg5|g6 z`}2#qE%*Mo{2{n;dHRiEo3;ibRYKIIJm9uA2gu2Ncy#{mlY}3Bj*gB64HhCGqiS)>yoU1a9}GpRACG9dzOizWeEJ1>q0+LjbI3BA z`_#;xZa85AD%MM{O--Q@?R^dQM_{{sPSbL;>B literal 0 HcmV?d00001 diff --git a/android/app/src/main/java/org/musicpd/AutomationReceiver.kt b/android/app/src/main/java/org/musicpd/AutomationReceiver.kt new file mode 100644 index 0000000..c1a31dc --- /dev/null +++ b/android/app/src/main/java/org/musicpd/AutomationReceiver.kt @@ -0,0 +1,24 @@ +package org.musicpd + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +class AutomationReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + + when(intent.action) { + "org.musicpd.action.StartService" -> { + val wakelock = Preferences.getBoolean( + context, + Preferences.KEY_WAKELOCK, false + ) + Main.startService(context, wakelock) + } + "org.musicpd.action.StopService" -> { + context.startService(Intent(context, Main::class.java) + .setAction(Main.SHUTDOWN_ACTION)) + } + } + } +} diff --git a/android/app/src/main/java/org/musicpd/Bridge.java b/android/app/src/main/java/org/musicpd/Bridge.java new file mode 100644 index 0000000..24b50f8 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/Bridge.java @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +package org.musicpd; + +import android.content.Context; + +/** + * Bridge to native code. + */ +public class Bridge { + + /* used by jni */ + public interface LogListener { + public void onLog(int priority, String msg); + } + + public static native void run(Context context, LogListener logListener); + public static native void shutdown(); + public static native void pause(); + public static native void playPause(); + public static native void playNext(); + public static native void playPrevious(); +} diff --git a/android/app/src/main/java/org/musicpd/Loader.kt b/android/app/src/main/java/org/musicpd/Loader.kt new file mode 100644 index 0000000..2d89d43 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/Loader.kt @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project +package org.musicpd + +import android.content.Context +import android.os.Build +import android.util.Log + +object Loader { + private const val TAG = "Loader" + + private var loaded: Boolean = false + private var error: String? = null + private val failReason: String get() = error ?: "" + + val isLoaded: Boolean get() = loaded + + init { + load() + } + + private fun load() { + if (loaded) return + loaded = try { + error = null + System.loadLibrary("mpd") + Log.i(TAG, "mpd lib loaded") + true + } catch (e: Throwable) { + error = e.message ?: e.javaClass.simpleName + Log.e(TAG, "failed to load mpd lib: $failReason") + false + } + } + + fun loadFailureMessage(context: Context): String { + return context.getString( + R.string.mpd_load_failure_message, + Build.SUPPORTED_ABIS.joinToString(), + Build.PRODUCT, + Build.FINGERPRINT, + failReason + ) + } +} diff --git a/android/app/src/main/java/org/musicpd/MPDApplication.kt b/android/app/src/main/java/org/musicpd/MPDApplication.kt new file mode 100644 index 0000000..94d8709 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/MPDApplication.kt @@ -0,0 +1,9 @@ +package org.musicpd + +import android.app.Application +import dagger.hilt.android.HiltAndroidApp + +@HiltAndroidApp +class MPDApplication : Application() { + +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/MPDPlayer.java b/android/app/src/main/java/org/musicpd/MPDPlayer.java new file mode 100644 index 0000000..9e51f3d --- /dev/null +++ b/android/app/src/main/java/org/musicpd/MPDPlayer.java @@ -0,0 +1,76 @@ +package org.musicpd; + +import android.annotation.SuppressLint; +import android.os.Looper; + +import androidx.annotation.NonNull; +import androidx.media3.common.Player; +import androidx.media3.common.SimpleBasePlayer; +import androidx.media3.common.util.UnstableApi; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; + +import java.util.Arrays; +import java.util.List; + +@UnstableApi +public class MPDPlayer extends SimpleBasePlayer { + + List placeholderItems; + public MPDPlayer(Looper looper) { + super(looper); + + // Dummy items to let us receive next and previous commands + MediaItemData item0 = new MediaItemData.Builder(0) + .build(); + MediaItemData item1 = new MediaItemData.Builder(1) + .build(); + MediaItemData item2 = new MediaItemData.Builder(2) + .build(); + MediaItemData[] items = new MediaItemData[] { item0, item1, item2 }; + + placeholderItems = Arrays.asList(items); + } + + @NonNull + @Override + protected State getState() { + Commands commands = new Commands.Builder().addAll( + COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM, + COMMAND_SEEK_TO_NEXT_MEDIA_ITEM, + COMMAND_PLAY_PAUSE + ).build(); + + return new State.Builder() + .setAvailableCommands(commands) + .setPlaybackState(Player.STATE_READY) + .setPlaylist(placeholderItems) + .setCurrentMediaItemIndex(1) + .build(); + } + + @NonNull + @Override + protected ListenableFuture handleSetPlayWhenReady(boolean playWhenReady) { + Bridge.playPause(); + return Futures.immediateVoidFuture(); + } + + @NonNull + @SuppressLint("SwitchIntDef") + @Override + protected ListenableFuture handleSeek(int mediaItemIndex, long positionMs, int seekCommand) { + switch (seekCommand) { + case COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM: + case COMMAND_SEEK_TO_PREVIOUS: + Bridge.playPrevious(); + break; + case COMMAND_SEEK_TO_NEXT_MEDIA_ITEM: + case COMMAND_SEEK_TO_NEXT: + Bridge.playNext(); + break; + } + return Futures.immediateVoidFuture(); + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/Main.kt b/android/app/src/main/java/org/musicpd/Main.kt new file mode 100644 index 0000000..b7037fe --- /dev/null +++ b/android/app/src/main/java/org/musicpd/Main.kt @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project +package org.musicpd + +import android.app.Notification +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.media.AudioManager +import android.os.Build +import android.os.IBinder +import android.os.Looper +import android.os.PowerManager +import android.os.PowerManager.WakeLock +import android.os.RemoteCallbackList +import android.os.RemoteException +import android.util.Log +import androidx.annotation.OptIn +import androidx.core.app.ServiceCompat +import androidx.media3.common.util.UnstableApi +import androidx.media3.session.MediaSession +import dagger.hilt.android.AndroidEntryPoint +import org.musicpd.Bridge.LogListener +import org.musicpd.data.LoggingRepository +import java.lang.reflect.Constructor +import javax.inject.Inject + +@AndroidEntryPoint +class Main : Service(), Runnable { + companion object { + private const val TAG = "Main" + private const val WAKELOCK_TAG = "mpd:wakelockmain" + + private const val MAIN_STATUS_ERROR = -1 + private const val MAIN_STATUS_STOPPED = 0 + private const val MAIN_STATUS_STARTED = 1 + + private const val MSG_SEND_STATUS = 0 + + const val SHUTDOWN_ACTION: String = "org.musicpd.action.ShutdownMPD" + + /* + * start Main service without any callback + */ + @JvmStatic + fun startService(context: Context, wakelock: Boolean) { + val intent = Intent(context, Main::class.java) + .putExtra("wakelock", wakelock) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) /* in Android 8+, we need to use this method + or else we'll get "IllegalStateException: + app is in background" */ + context.startForegroundService(intent) + else context.startService(intent) + } + } + + private lateinit var mpdApp: MPDApplication + private lateinit var mpdLoader: Loader + + private var mThread: Thread? = null + private var mStatus = MAIN_STATUS_STOPPED + private var mAbort = false + private var mError: String? = null + private val mCallbacks = RemoteCallbackList() + private val mBinder: IBinder = MainStub(this) + private var mPauseOnHeadphonesDisconnect = false + private var mWakelock: WakeLock? = null + + private var mMediaSession: MediaSession? = null + + @JvmField + @Inject + var logging: LoggingRepository? = null + + internal class MainStub(private val mService: Main) : IMain.Stub() { + override fun start() { + mService.start() + } + + override fun stop() { + mService.stop() + } + + override fun setPauseOnHeadphonesDisconnect(enabled: Boolean) { + mService.setPauseOnHeadphonesDisconnect(enabled) + } + + override fun setWakelockEnabled(enabled: Boolean) { + mService.setWakelockEnabled(enabled) + } + + override fun isRunning(): Boolean { + return mService.isRunning + } + + override fun registerCallback(cb: IMainCallback) { + mService.registerCallback(cb) + } + + override fun unregisterCallback(cb: IMainCallback) { + mService.unregisterCallback(cb) + } + } + + override fun onCreate() { + super.onCreate() + mpdLoader = Loader + } + + @Synchronized + private fun sendMessage( + @Suppress("SameParameterValue") what: Int, + arg1: Int, + arg2: Int, + obj: Any? + ) { + var i = mCallbacks.beginBroadcast() + while (i > 0) { + i-- + val cb = mCallbacks.getBroadcastItem(i) + try { + when (what) { + MSG_SEND_STATUS -> when (arg1) { + MAIN_STATUS_ERROR -> cb.onError(obj as String?) + MAIN_STATUS_STOPPED -> cb.onStopped() + MAIN_STATUS_STARTED -> cb.onStarted() + } + } + } catch (ignored: RemoteException) { + } + } + mCallbacks.finishBroadcast() + } + + private val mLogListener = LogListener { priority, msg -> + logging?.addLogItem(priority, msg) + } + + override fun onBind(intent: Intent): IBinder { + return mBinder + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == SHUTDOWN_ACTION) { + stop() + } else { + start() + if (intent?.getBooleanExtra( + "wakelock", + false + ) == true + ) setWakelockEnabled(true) + } + return START_REDELIVER_INTENT + } + + override fun run() { + synchronized(this) { + if (mAbort) return + setStatus(MAIN_STATUS_STARTED, null) + } + Bridge.run(this, mLogListener) + setStatus(MAIN_STATUS_STOPPED, null) + } + + @Synchronized + private fun setStatus(status: Int, error: String?) { + mStatus = status + mError = error + sendMessage(MSG_SEND_STATUS, mStatus, 0, mError) + } + + private fun createNotificationBuilderWithChannel(): Notification.Builder? { + val notificationManager = getSystemService(NOTIFICATION_SERVICE) as? NotificationManager + ?: return null + + val id = "org.musicpd" + val name = "MPD service" + val importance = 3 /* NotificationManager.IMPORTANCE_DEFAULT */ + + try { + val ncClass = Class.forName("android.app.NotificationChannel") + val ncCtor = ncClass.getConstructor( + String::class.java, + CharSequence::class.java, + Int::class.javaPrimitiveType + ) + val nc = ncCtor.newInstance(id, name, importance) + + val nmCreateNotificationChannelMethod = + NotificationManager::class.java.getMethod("createNotificationChannel", ncClass) + nmCreateNotificationChannelMethod.invoke(notificationManager, nc) + + val nbCtor: Constructor<*> = Notification.Builder::class.java.getConstructor( + Context::class.java, String::class.java + ) + return nbCtor.newInstance(this, id) as Notification.Builder + } catch (e: Exception) { + Log.e(TAG, "error creating the NotificationChannel", e) + return null + } + } + + @OptIn(markerClass = [UnstableApi::class]) + private fun start() { + if (mThread != null) return + + val filter = IntentFilter() + filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY) + registerReceiver(object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (!mPauseOnHeadphonesDisconnect) return + if (intent.action === AudioManager.ACTION_AUDIO_BECOMING_NOISY) pause() + } + }, filter) + + val mainIntent = Intent(this, MainActivity::class.java) + mainIntent.setAction("android.intent.action.MAIN") + mainIntent.addCategory("android.intent.category.LAUNCHER") + val contentIntent = PendingIntent.getActivity( + this, 0, + mainIntent, PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + + val nBuilder: Notification.Builder? + if (Build.VERSION.SDK_INT >= 26 /* Build.VERSION_CODES.O */) { + nBuilder = createNotificationBuilderWithChannel() + if (nBuilder == null) return + } else nBuilder = Notification.Builder(this) + + val notification = + nBuilder.setContentTitle(getText(R.string.notification_title_mpd_running)) + .setContentText(getText(R.string.notification_text_mpd_running)) + .setSmallIcon(R.drawable.notification_icon) + .setContentIntent(contentIntent) + .build() + + if (mpdLoader.isLoaded) { + mThread = Thread(this).apply { start() } + } + + val player = MPDPlayer(Looper.getMainLooper()) + mMediaSession = MediaSession.Builder(this, player).build() + + startForeground(R.string.notification_title_mpd_running, notification) + startService(Intent(this, Main::class.java)) + } + + private fun stop() { + mMediaSession?.let { + it.release() + mMediaSession = null + } + mThread?.let { thread -> + if (thread.isAlive) { + synchronized(this) { + if (mStatus == MAIN_STATUS_STARTED) Bridge.shutdown() + else mAbort = true + } + } + try { + thread.join() + mThread = null + mAbort = false + } catch (ie: InterruptedException) { + Log.e(TAG, "failed to join", ie) + } + } + setWakelockEnabled(false) + ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) + stopSelf() + } + + private fun pause() { + if (mThread?.isAlive == true) { + synchronized(this) { + if (mStatus == MAIN_STATUS_STARTED) Bridge.pause() + } + } + } + + private fun setPauseOnHeadphonesDisconnect(enabled: Boolean) { + mPauseOnHeadphonesDisconnect = enabled + } + + private fun setWakelockEnabled(enabled: Boolean) { + if (enabled) { + val wakeLock = + mWakelock ?: run { + val pm = getSystemService(POWER_SERVICE) as PowerManager + pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG).also { + mWakelock = it + } + } + wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/) + Log.d(TAG, "Wakelock acquired") + } else { + mWakelock?.let { + it.release() + mWakelock = null + } + Log.d(TAG, "Wakelock released") + } + } + + private val isRunning: Boolean + get() = mThread?.isAlive == true + + private fun registerCallback(cb: IMainCallback?) { + if (cb != null) { + mCallbacks.register(cb) + sendMessage(MSG_SEND_STATUS, mStatus, 0, mError) + } + } + + private fun unregisterCallback(cb: IMainCallback?) { + if (cb != null) { + mCallbacks.unregister(cb) + } + } +} diff --git a/android/app/src/main/java/org/musicpd/MainActivity.kt b/android/app/src/main/java/org/musicpd/MainActivity.kt new file mode 100644 index 0000000..de5ae80 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/MainActivity.kt @@ -0,0 +1,57 @@ +package org.musicpd + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.viewModels +import androidx.compose.material3.MaterialTheme +import androidx.core.view.WindowCompat +import dagger.hilt.android.AndroidEntryPoint +import org.musicpd.ui.MPDApp +import org.musicpd.ui.SettingsViewModel + +@AndroidEntryPoint +class MainActivity : ComponentActivity() { + private val settingsViewModel: SettingsViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + WindowCompat.setDecorFitsSystemWindows(window, false) + setContent { + MaterialTheme { + MPDApp(settingsViewModel = settingsViewModel) + } + } + } + + private fun connectClient() { + val client = MainServiceClient(this, object : MainServiceClient.Callback { + override fun onStopped() { + settingsViewModel.updateStatus("", false) + } + + override fun onStarted() { + settingsViewModel.updateStatus("MPD Service Started", true) + } + + override fun onError(error: String) { + settingsViewModel.removeClient() + settingsViewModel.updateStatus(error, false) + connectClient() + } + }) + + settingsViewModel.setClient(client) + } + + override fun onStart() { + //mFirstRun = false + connectClient() + super.onStart() + } + + override fun onStop() { + settingsViewModel.removeClient() + super.onStop() + } +} diff --git a/android/app/src/main/java/org/musicpd/MainServiceClient.java b/android/app/src/main/java/org/musicpd/MainServiceClient.java new file mode 100644 index 0000000..e943649 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/MainServiceClient.java @@ -0,0 +1,157 @@ +package org.musicpd; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.IBinder; +import android.os.RemoteException; + + +/* + * Client that bind the Main Service in order to send commands and receive callback + */ +public class MainServiceClient { + + private static final String REMOTE_ERROR = "MPD process was killed"; + + public interface Callback { + public void onStarted(); + public void onStopped(); + public void onError(String error); + } + + private boolean mBound = false; + private final Context mContext; + private Callback mCallback; + private IMain mIMain = null; + + private final IMainCallback.Stub mICallback = new IMainCallback.Stub() { + + @Override + public void onStopped() throws RemoteException { + mCallback.onStopped(); + } + + @Override + public void onStarted() throws RemoteException { + mCallback.onStarted(); + } + + @Override + public void onError(String error) throws RemoteException { + mCallback.onError(error); + } + }; + + private final ServiceConnection mServiceConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + synchronized (this) { + mIMain = IMain.Stub.asInterface(service); + try { + if (mCallback != null) + mIMain.registerCallback(mICallback); + } catch (RemoteException e) { + if (mCallback != null) + mCallback.onError(REMOTE_ERROR); + } + } + } + + @Override + public void onServiceDisconnected(ComponentName name) { + if (mCallback != null) + mCallback.onError(REMOTE_ERROR); + } + }; + + public MainServiceClient(Context context, Callback cb) throws IllegalArgumentException { + if (context == null) + throw new IllegalArgumentException("Context can't be null"); + mContext = context; + mCallback = cb; + mBound = mContext.bindService(new Intent(mContext, Main.class), mServiceConnection, Context.BIND_AUTO_CREATE); + } + + public boolean start() { + synchronized (this) { + if (mIMain != null) { + try { + mIMain.start(); + return true; + } catch (RemoteException e) { + } + } + return false; + } + } + + public boolean stop() { + synchronized (this) { + if (mIMain != null) { + try { + mIMain.stop(); + return true; + } catch (RemoteException e) { + } + } + return false; + } + } + + public boolean setPauseOnHeadphonesDisconnect(boolean enabled) { + synchronized (this) { + if (mIMain != null) { + try { + mIMain.setPauseOnHeadphonesDisconnect(enabled); + return true; + } catch (RemoteException e) { + } + } + return false; + } + } + + public boolean setWakelockEnabled(boolean enabled) { + synchronized (this) { + if (mIMain != null) { + try { + mIMain.setWakelockEnabled(enabled); + return true; + } catch (RemoteException e) { + } + } + return false; + } + } + + public boolean isRunning() { + synchronized (this) { + if (mIMain != null) { + try { + return mIMain.isRunning(); + } catch (RemoteException e) { + } + } + return false; + } + } + + public void release() { + if (mBound) { + synchronized (this) { + if (mIMain != null && mICallback != null) { + try { + if (mCallback != null) + mIMain.unregisterCallback(mICallback); + } catch (RemoteException e) { + } + } + } + mBound = false; + mContext.unbindService(mServiceConnection); + } + } +} diff --git a/android/app/src/main/java/org/musicpd/NetworkUtil.java b/android/app/src/main/java/org/musicpd/NetworkUtil.java new file mode 100644 index 0000000..7f664ca --- /dev/null +++ b/android/app/src/main/java/org/musicpd/NetworkUtil.java @@ -0,0 +1,34 @@ +package org.musicpd; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.LinkAddress; +import android.net.LinkProperties; + +import androidx.annotation.Nullable; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.util.List; + +public class NetworkUtil { + + @Nullable + public static String getDeviceIPV4Address(Context context) { + ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + LinkProperties linkProperties = connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()); + if (linkProperties != null) { + List linkAddresses = linkProperties.getLinkAddresses(); + for (LinkAddress address : linkAddresses) { + if (!address.getAddress().isLinkLocalAddress() && !address.getAddress().isLoopbackAddress()) { + InetAddress address1 = address.getAddress(); + if (address1 instanceof Inet4Address) { + return address1.getHostAddress(); + } + } + } + } + + return null; + } +} diff --git a/android/app/src/main/java/org/musicpd/Preferences.java b/android/app/src/main/java/org/musicpd/Preferences.java new file mode 100644 index 0000000..61eca83 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/Preferences.java @@ -0,0 +1,34 @@ +package org.musicpd; + +import static android.content.Context.MODE_PRIVATE; + +import android.content.Context; +import android.content.SharedPreferences; + +public class Preferences { + private static final String TAG = "Settings"; + + public static final String KEY_RUN_ON_BOOT ="run_on_boot"; + public static final String KEY_WAKELOCK ="wakelock"; + public static final String KEY_PAUSE_ON_HEADPHONES_DISCONNECT ="pause_on_headphones_disconnect"; + + public static SharedPreferences get(Context context) { + return context.getSharedPreferences(TAG, MODE_PRIVATE); + } + + public static void putBoolean(Context context, String key, boolean value) { + final SharedPreferences prefs = get(context); + + if (prefs == null) + return; + final SharedPreferences.Editor editor = prefs.edit(); + editor.putBoolean(key, value); + editor.apply(); + } + + public static boolean getBoolean(Context context, String key, boolean defValue) { + final SharedPreferences prefs = get(context); + + return prefs != null ? prefs.getBoolean(key, defValue) : defValue; + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/Receiver.java b/android/app/src/main/java/org/musicpd/Receiver.java new file mode 100644 index 0000000..92a6513 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/Receiver.java @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +package org.musicpd; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import java.util.Set; + +public class Receiver extends BroadcastReceiver { + + private static final Set BOOT_ACTIONS = Set.of( + "android.intent.action.BOOT_COMPLETED", + "android.intent.action.QUICKBOOT_POWERON" + ); + + @Override + public void onReceive(Context context, Intent intent) { + Log.d("Receiver", "onReceive: " + intent); + if (BOOT_ACTIONS.contains(intent.getAction())) { + if (Preferences.getBoolean(context, + Preferences.KEY_RUN_ON_BOOT, + false)) { + final boolean wakelock = + Preferences.getBoolean(context, + Preferences.KEY_WAKELOCK, false); + Main.startService(context, wakelock); + } + } + } +} diff --git a/android/app/src/main/java/org/musicpd/data/LoggingRepository.kt b/android/app/src/main/java/org/musicpd/data/LoggingRepository.kt new file mode 100644 index 0000000..9e5dd90 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/data/LoggingRepository.kt @@ -0,0 +1,34 @@ +package org.musicpd.data + +import android.util.Log +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import javax.inject.Inject +import javax.inject.Singleton + +private const val MAX_LOGS = 500 + +@Singleton +class LoggingRepository @Inject constructor() { + + private val _logItemFLow = MutableStateFlow(listOf()) + val logItemFLow: StateFlow> = _logItemFLow + + fun addLogItem(priority: Int, message: String) { + if (_logItemFLow.value.size > MAX_LOGS) { + _logItemFLow.value = _logItemFLow.value.drop(1) + } + + val priorityString: String = when (priority) { + Log.DEBUG -> "D" + Log.ERROR -> "E" + Log.INFO -> "I" + Log.VERBOSE -> "V" + Log.WARN -> "W" + else -> "" + } + + _logItemFLow.value = _logItemFLow.value + ("$priorityString/$message") + } + +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/ui/LogScreen.kt b/android/app/src/main/java/org/musicpd/ui/LogScreen.kt new file mode 100644 index 0000000..d766688 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/LogScreen.kt @@ -0,0 +1,79 @@ +package org.musicpd.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.VerticalAlignBottom +import androidx.compose.material3.FloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +@Composable +fun LogView(messages: List) { + val lazyListState = rememberLazyListState() + + var userScrolled = remember { mutableStateOf(false) } + + LaunchedEffect(lazyListState) { + snapshotFlow { lazyListState.isScrollInProgress } + .collect { + if (it) { + userScrolled.value = true + } + } + } + + Box(Modifier.fillMaxSize()) { + LazyColumn( + Modifier.padding(4.dp), + lazyListState + ) { + items(messages) { message -> + Text(text = message, fontFamily = FontFamily.Monospace) + } + CoroutineScope(Dispatchers.Main).launch { + lazyListState.scrollToItem(messages.count(), 0) + } + } + + if (lazyListState.canScrollForward) { + FloatingActionButton( + onClick = { + userScrolled.value = false + CoroutineScope(Dispatchers.Main).launch { + lazyListState.scrollToItem(messages.count(), 0) + } + }, + modifier = Modifier.padding(16.dp).align(Alignment.BottomEnd) + ) { + Icon(Icons.Filled.VerticalAlignBottom, "Scroll to bottom icon") + } + } + } +} + +@Preview +@Composable +fun LogViewPreview() { + val data = listOf("test", + "test2", + "test3") + LogView(data) +} diff --git a/android/app/src/main/java/org/musicpd/ui/MainScreen.kt b/android/app/src/main/java/org/musicpd/ui/MainScreen.kt new file mode 100644 index 0000000..5c538f2 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/MainScreen.kt @@ -0,0 +1,109 @@ +package org.musicpd.ui + +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Icon +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.navigation.NavController +import androidx.navigation.NavHostController +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.currentBackStackEntryAsState +import androidx.navigation.compose.rememberNavController + +enum class Screen { + HOME, + LOGS, + SETTINGS, +} +sealed class NavigationItem(val route: String, val label: String, val icon: ImageVector) { + data object Home : NavigationItem( + Screen.HOME.name, + "Home", + Icons.Default.Home + ) + data object Logs : NavigationItem( + Screen.LOGS.name, + "Logs", + Icons.AutoMirrored.Filled.List) + data object Settings : NavigationItem( + Screen.SETTINGS.name, + "Settings", + Icons.Default.Settings) +} + +@Composable +fun MPDApp( + navController: NavHostController = rememberNavController(), + settingsViewModel: SettingsViewModel = viewModel() +) { + Scaffold( + topBar = { + + }, + bottomBar = { + BottomNavigationBar(navController) + }, + ) { innerPadding -> + NavHost( + navController = navController, + startDestination = NavigationItem.Home.route, + modifier = Modifier.padding(innerPadding) + ) { + composable(NavigationItem.Home.route) { + StatusScreen(settingsViewModel) + } + composable(NavigationItem.Logs.route) { + LogView(settingsViewModel.getLogs().collectAsStateWithLifecycle().value) + } + composable(NavigationItem.Settings.route) { + MPDSettings(settingsViewModel) + } + } + } +} + +@Composable +fun BottomNavigationBar(navController: NavController) { + val navBackStackEntry by navController.currentBackStackEntryAsState() + val currentRoute = navBackStackEntry?.destination?.route + + val items = listOf( + NavigationItem.Home, + NavigationItem.Logs, + NavigationItem.Settings, + ) + + NavigationBar { + items.forEach { item -> + NavigationBarItem( + icon = { + Icon( + imageVector = item.icon, + contentDescription = null + ) + }, + label = { Text (item.label) }, + onClick = { + navController.navigate(item.route) { + popUpTo(navController.graph.startDestinationId) + launchSingleTop = true + } + }, + selected = currentRoute == item.route, + ) + } + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/ui/NetworkAddress.kt b/android/app/src/main/java/org/musicpd/ui/NetworkAddress.kt new file mode 100644 index 0000000..fd387ca --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/NetworkAddress.kt @@ -0,0 +1,39 @@ +package org.musicpd.ui + +import android.app.Application +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Wifi +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import org.musicpd.NetworkUtil + +@Composable +fun NetworkAddress() { + val address = NetworkUtil.getDeviceIPV4Address(LocalContext.current) + val padding = 4.dp + Row( + Modifier + .padding(padding) + .fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Center + ) { + Icon( + imageVector = Icons.Default.Wifi, + contentDescription = "Wifi") + Spacer(Modifier.size(padding)) + Text(text = address ?: "") + } +} + diff --git a/android/app/src/main/java/org/musicpd/ui/SettingsScreen.kt b/android/app/src/main/java/org/musicpd/ui/SettingsScreen.kt new file mode 100644 index 0000000..2ae0db9 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/SettingsScreen.kt @@ -0,0 +1,77 @@ +package org.musicpd.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.BatteryAlert +import androidx.compose.material.icons.filled.Headphones +import androidx.compose.material.icons.filled.PowerSettingsNew +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import com.alorma.compose.settings.storage.preferences.rememberPreferenceBooleanSettingState +import com.alorma.compose.settings.ui.SettingsSwitch +import org.musicpd.Preferences +import org.musicpd.R + +@Composable +fun MPDSettings(settingsViewModel: SettingsViewModel) { + val context = LocalContext.current + + Column(Modifier.fillMaxSize()) { + SettingsOptions( + onBootChanged = { newValue -> + if (newValue) { + settingsViewModel.startMPD(context) + } + }, + onWakeLockChanged = { newValue -> + settingsViewModel.setWakelockEnabled(newValue) + }, + onHeadphonesChanged = { newValue -> + settingsViewModel.setPauseOnHeadphonesDisconnect(newValue) + } + ) + } +} + +@Composable +fun SettingsOptions( + onBootChanged: (Boolean) -> Unit, + onWakeLockChanged: (Boolean) -> Unit, + onHeadphonesChanged: (Boolean) -> Unit +) { + val bootState = rememberPreferenceBooleanSettingState( + key = Preferences.KEY_RUN_ON_BOOT, + defaultValue = false + ) + val wakelockState = + rememberPreferenceBooleanSettingState(key = Preferences.KEY_WAKELOCK, defaultValue = false) + val headphoneState = rememberPreferenceBooleanSettingState( + key = Preferences.KEY_PAUSE_ON_HEADPHONES_DISCONNECT, + defaultValue = false + ) + + SettingsSwitch( + icon = { Icon(imageVector = Icons.Default.PowerSettingsNew, contentDescription = "Power") }, + title = { Text(text = stringResource(R.string.checkbox_run_on_boot)) }, + onCheckedChange = onBootChanged, + state = bootState + ) + SettingsSwitch( + icon = { Icon(imageVector = Icons.Default.BatteryAlert, contentDescription = "Battery") }, + title = { Text(text = stringResource(R.string.checkbox_wakelock)) }, + onCheckedChange = onWakeLockChanged, + state = wakelockState + ) + SettingsSwitch( + icon = { Icon(imageVector = Icons.Default.Headphones, contentDescription = "Headphones") }, + title = { Text(text = stringResource(R.string.checkbox_pause_on_headphones_disconnect)) }, + onCheckedChange = onHeadphonesChanged, + state = headphoneState + ) + +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/ui/SettingsViewModel.kt b/android/app/src/main/java/org/musicpd/ui/SettingsViewModel.kt new file mode 100644 index 0000000..c6f06ef --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/SettingsViewModel.kt @@ -0,0 +1,73 @@ +package org.musicpd.ui + +import android.content.Context +import androidx.lifecycle.ViewModel +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.musicpd.Loader +import org.musicpd.MainServiceClient +import org.musicpd.Preferences +import org.musicpd.data.LoggingRepository +import javax.inject.Inject + + +@HiltViewModel +class SettingsViewModel @Inject constructor( + private var loggingRepository: LoggingRepository +) : ViewModel() { + private var mClient: MainServiceClient? = null + val mpdLoader = Loader + + data class StatusUiState( + val statusMessage: String = "", + val running: Boolean = false + ) + + private val _statusUIState = MutableStateFlow(StatusUiState()) + val statusUIState: StateFlow = _statusUIState.asStateFlow() + + fun getLogs(): StateFlow> { + return loggingRepository.logItemFLow + } + + fun updateStatus(message: String, running: Boolean) { + _statusUIState.value = StatusUiState(message, running) + } + + fun setClient(client: MainServiceClient) { + mClient = client + } + + fun removeClient() { + mClient?.release() + mClient = null + } + + fun startMPD(context: Context) { + mClient?.start() + if (Preferences.getBoolean( + context, + Preferences.KEY_WAKELOCK, false + ) + ) mClient?.setWakelockEnabled(true) + if (Preferences.getBoolean( + context, + Preferences.KEY_PAUSE_ON_HEADPHONES_DISCONNECT, false + ) + ) mClient?.setPauseOnHeadphonesDisconnect(true) + } + + fun stopMPD() { + mClient?.stop() + } + + fun setWakelockEnabled(enabled: Boolean) { + mClient?.setWakelockEnabled(enabled) + } + + fun setPauseOnHeadphonesDisconnect(enabled: Boolean) { + mClient?.setPauseOnHeadphonesDisconnect(enabled) + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/ui/StatusScreen.kt b/android/app/src/main/java/org/musicpd/ui/StatusScreen.kt new file mode 100644 index 0000000..cbd56a4 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/ui/StatusScreen.kt @@ -0,0 +1,188 @@ +package org.musicpd.ui + +import android.Manifest +import android.content.Context +import android.os.Build +import android.util.TypedValue +import androidx.annotation.AttrRes +import androidx.annotation.ColorInt +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Circle +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.google.accompanist.permissions.ExperimentalPermissionsApi +import com.google.accompanist.permissions.PermissionState +import com.google.accompanist.permissions.isGranted +import com.google.accompanist.permissions.rememberPermissionState +import com.google.accompanist.permissions.shouldShowRationale +import org.musicpd.R +import org.musicpd.utils.openAppSettings + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun StatusScreen(settingsViewModel: SettingsViewModel) { + val storagePermissionState = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + rememberPermissionState( + Manifest.permission.READ_MEDIA_AUDIO + ) + } else { + rememberPermissionState( + Manifest.permission.READ_EXTERNAL_STORAGE + ) + } + + Column( + Modifier + .padding(4.dp) + .fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + NetworkAddress() + ServerStatus(settingsViewModel, storagePermissionState) + AudioMediaPermission(storagePermissionState) + MPDLoaderStatus(settingsViewModel) + } +} + +@ColorInt +fun getThemeColorAttribute(context: Context, @AttrRes attr: Int): Int { + val value = TypedValue() + if (context.theme.resolveAttribute(attr, value, true)) { + return value.data + } + return android.graphics.Color.BLACK +} + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun ServerStatus(settingsViewModel: SettingsViewModel, storagePermissionState: PermissionState) { + val context = LocalContext.current + + val statusUiState by settingsViewModel.statusUIState.collectAsState() + + Column { + Row( + Modifier + .padding(4.dp) + .fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceEvenly + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Default.Circle, + contentDescription = "", + tint = Color( + getThemeColorAttribute( + context, + if (statusUiState.running) R.attr.appColorPositive else R.attr.appColorNegative + ) + ), + modifier = Modifier + .padding(end = 8.dp) + .alpha(0.6f) + ) + Text(text = stringResource(id = if (statusUiState.running) R.string.running else R.string.stopped)) + } + Button( + onClick = { + if (statusUiState.running) + settingsViewModel.stopMPD() + else + settingsViewModel.startMPD(context) + }, + enabled = settingsViewModel.mpdLoader.isLoaded + && storagePermissionState.status.isGranted + ) { + Text( + text = stringResource(id = if (statusUiState.running) R.string.stopMPD else R.string.startMPD) + ) + } + } + Row( + Modifier + .padding(4.dp) + .fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceEvenly + ) { + Text(text = statusUiState.statusMessage) + } + } +} + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun AudioMediaPermission(storagePermissionState: PermissionState) { + val permissionStatus = storagePermissionState.status + if (!permissionStatus.isGranted) { + val context = LocalContext.current + Column( + Modifier + .padding(4.dp) + .fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + stringResource(id = R.string.external_files_permission_request), + Modifier.padding(16.dp) + ) + if (storagePermissionState.status.shouldShowRationale) { + Button(onClick = { + storagePermissionState.launchPermissionRequest() + }) { + Text("Request permission") + } + } else { + OutlinedButton( + onClick = { + openAppSettings(context, context.packageName) + }, + Modifier.padding(16.dp) + ) { + Text( + stringResource(id = R.string.title_open_app_info), + color = MaterialTheme.colorScheme.secondary + ) + } + } + } + } +} + +@Composable +fun MPDLoaderStatus(settingsViewModel: SettingsViewModel) { + val loader = settingsViewModel.mpdLoader + if (!loader.isLoaded) { + val context = LocalContext.current + SelectionContainer { + Text( + loader.loadFailureMessage(context), + Modifier.padding(16.dp), + color = MaterialTheme.colorScheme.error + ) + } + } +} \ No newline at end of file diff --git a/android/app/src/main/java/org/musicpd/utils/IntentUtils.kt b/android/app/src/main/java/org/musicpd/utils/IntentUtils.kt new file mode 100644 index 0000000..b9a7512 --- /dev/null +++ b/android/app/src/main/java/org/musicpd/utils/IntentUtils.kt @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project +package org.musicpd.utils + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.Settings +import android.util.Log + +private const val TAG = "IntentUtils" + +fun openAppSettings( + context: Context, + packageName: String +) { + try { + context.startActivity(Intent().apply { + setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + setData(Uri.parse("package:$packageName")) + addCategory(Intent.CATEGORY_DEFAULT) + addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) + addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) + }) + } catch (e: ActivityNotFoundException) { + Log.e( + TAG, + "failed to open app settings for package: $packageName", e + ) + } +} diff --git a/android/app/src/main/res/drawable/baseline_wifi_24.xml b/android/app/src/main/res/drawable/baseline_wifi_24.xml new file mode 100644 index 0000000..dabd1f1 --- /dev/null +++ b/android/app/src/main/res/drawable/baseline_wifi_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/android/app/src/main/res/drawable/ic_banner_foreground.xml b/android/app/src/main/res/drawable/ic_banner_foreground.xml new file mode 100644 index 0000000..42bded0 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_banner_foreground.xml @@ -0,0 +1,239 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..d62cbb5 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,235 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/notification_icon.png b/android/app/src/main/res/drawable/notification_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e77d87aa877c3a3d38e2ec45f2afebb5766a8974 GIT binary patch literal 1551 zcmZ{kYdF&j9LN85$#QF3e=Fo*mZ8*t7@}O-hD}yRoi0ahLpY6G)+BP7NpqVcYOZM& zg_II0p`s||GN&Zu?ona7xzy3ooAW&9MK6Be&+~opdA{#{;$2J^bro$D007kKu2j}C zp`V9BEayL}B(-J0xNa^~;75|Atzo$-^Xcw1Z~^p z+zmd7jSze-J0Ey1*zMjFw#Weu?DigTp_ z=!}j4REA}7Ts#AE!We+s#xHN0U4A3!pPcS{|EQ1Y?>31ekc{&4+S&%9=6*O##JR`@-5jiC- zQ6_?rUZgg^+{qi)`IRX%Kg=G~sJo}dN6NYjT(Rq!$rQ_HDX)5(YOiAEjihBok^SMD zb5*HpcbzbAfp8w<22E+h^;*&44G5A(UDZ1zMhWqhGUSuNeQ4RSDYJ4kw4(n!)y!_s zQ80#prQ>wo+`1x7k~qA+I4*ekc@*A$aFJKGC3spswUaCcu)9!dpvvT?l2-Pv_KlTQ zf`}k{p=3gl{+GqAve_|r=e36Z#}m}#NNM?mC`o|lY!^Z9<57mE$#s>_52aHBW}LWe z{r;_vE0Eox3Gl4G>_#rx1E@pj@yg5Bq<5Wi!BdEDDlvd5G#hwYyz$yx`YI^aEv3V1)4BQb9&bsj;em;GF$;M5jdwyI`L`OnrAP@#q3~)#js}XBQ_N3 z4`OYW^7iL?{DAMz#XELB;cGACe(pw@;@U`cOO&%vHBm?)+bXzVNW2Z^a7ZW?Hiq43 zu%~dOL4WL_8;{W6q-5L?TE#-P4el6NCv6N%#d=3G8g6&#?jx9VWx=fyzdL8B<(V`V zrK5f)2DD_pTPNK2#aV0AQbdX*Sm|z*e-e^MgJhObVQkpnw5|@l!cHrW$6)4XwnvgW zD2oe@$wzE`eAkX(YRP}AcZZ&20O)EPsxVe`f zA_~eX%E;O|uXMg;$1rsprX{aWhWB?P6K!bLh98QAYHUyY=4p70EI22(QGuq*w#2UC zU4YX-8qU>I3_DRmWru3U#khyOW)-ykRzpVdAxdLyU~bB1EQ z4paGJDq23M(v03FGI6?K(;C4mI#q8%i^I1boT#BFD6(vFki8SpPZV$9j0Q*GD{R`X z^JFJXk)nq$u0HAXY%Xl7ukJ0cgeAlX=TU5#Yq*%wcUUXY7o!Gn`fs+@rVkWQCJGP@ zia#e@_8hx6Lm$q<;-BfiTA-_!E>1U#9fnJiEntjprs3mYZ_a>0e@UPGLr-mhgSR+h z^|M8|($H_(qvd%=>`E8e0)NvC6$a*&GSDW5dVn!=}pb z@1}T;kf)QI#vO0~ni0>6_$+Bpnk&4VIQQ6Pu*d$Zcc)~=8ag*=&K4B)HWe(Yrx7d=bH$adr1liH=toWZ0bksNSaOAHA1_<0;7L5N} e;0Ffzh4VQ + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_banner.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_banner.xml new file mode 100644 index 0000000..a0a0dec --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_banner.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..7353dbd --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..7353dbd --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_banner.png b/android/app/src/main/res/mipmap-hdpi/ic_banner.png new file mode 100644 index 0000000000000000000000000000000000000000..6932f1f5203a5b5e6f773ae2f22516616d203d77 GIT binary patch literal 4779 zcmdT|=Q|q?*QRK#+N-p7m6%1*XoFZ0qqS-lHHu#wBT+lls=asZ7`3-pF{-xG+CL#` zv}Oruh?dxy8eA<3?~ZWt+?w%v9s?#rZpa9 zp;BSNT0B_J^XM=(v#?)u`O)B5=uO4iu|XaHToPj9rCU^*X5)N((Sun2vc1~ug_YaG zOkXA5-2frDHhl6ok;`Mz!fasbhLmz9aCO8DR{Mu+Sxm7-z2WBcR3iQMqA~&;>LD}@ zT(o*o1JCWi5+DBCT7-nvUEaP;Q~VKVjD{_W@CBU|-BtG1b9Wd@NJmUO)~>}6pcdVM z?Rwd=n$!Y1f;18I0!*ZaA>LGNKBNiV;_U4G_V#uoYikKVKffs~77)qEmjMwLY%tez z>$&jmVg`ROUkTW6*N$EM{+)l)#YDv5v6aZP>}r%-LmclTC}8%;bA3?9*f@1&c6P+d zz3aYqB5!)SxY=l#eojewIfVMo1buYxkD#-fCExXU!sQuWSH~jzYfWu(BZ2mU%lpk5p+8zx4*{{m6KZ<#3d0EP5$upAU za!k6%5upD;GEAgCxfOo;?dKBK5@~B@W<6F#wZAjNBE;ges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;HJ{3DbPjp-ZEs(WYT*@y~^Uc;XjMUkvj?*Q;3g|@5E}usC@$i2!d?f90<`Qee{+EU|G@n=6)xmpZTnR1q_<|qH9s)Jls&HqUR09f)XvH$=8 literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..d4214700ea372b6979b76f855bb2a30e931edca1 GIT binary patch literal 3570 zcmVANk&HM4FCXFMM6+kP&iE94FCWyN5Byf^#+5sjU+kc&wBSB2oW&>a?d>~ zXV?7@tJZ|ZBI-k4KA z`qgfXn~A+Rr&Imf-qi7IIdM*eEJ?Oa+uGK(ZQHhO+t0TD{JLP2bo*kUc*hy{Mwr$(Cjl1A|_Y;h)pJv-zZR68y z+qU;ilxy2kBs=@Yw-3c&fgF(qasho{8qtVHUDAk|B3?vB(6Mb>wXO6qzq`8&a9@PO zjc9~4>R+CF`tQJPBt>#&8IJD}aI0-wo}{%+GD4*(k?)SQ&KRNgaz<4BUECY|O63wbhrOusoKHf)PXSOwQ?x@D*6oc< z_0Cu=w>lA_2`1qoyotZD3n!%|Y3-GA(qzWpzvIE$XhKBQT`N`HCPE8r!526t!4aW} zJ>DlkWS-NcktB=p5zr-DeB1$3yuq}~)i6IPwlGMYQ8tQARdwRk2~ zH(VD=ITKW786Fc*xPmGg^t5z^TWC%i@@5;d>XhQ!JmA(^%4%ewfzICv^)nqK9?S`v zvl4v|7}4+0gjf1&Tg^i1K)?bsEOBHYE4Vl}EASR*UpJS!OV@ws0)j|f!1fQ3FWc-)O8!2bRsiY?#k zMy|Gm`+8+-G7yFgD}$QNSjj#BidDFkCuQN2p2*06zblygN!ZoQCB<{?CwVPCgeBdT z*%$~Kvd?$>*ib8phcdKMKBaxoUgKR-;vTtIh&~WPgsZYt$BhK2ksHPz zgTyZyLy)DC;heS5s+T6pp)&_U%yP_itHB#co;(gu!2o%|7;C|c|H!olphArW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a|A=&eNGQ)!$AuO zJX`;}J-@iLX6rnYZa=qM+=Zz>3zP#A=;()91qJn?^z`(Eke}|T4_^FQ93F5s4q*eZ z#XdV@jc6(2;g^@f_CR)^%SfKyRIP0Z*Uc7y_=%tL+$#H&snms`I9;Xd3R&lOdqRJ1 zWT4&^roT|r)6q;z8Re@mEBrJ8K zo;Yc!rF*j->KhnH<}E%^SMz2hfj9BolW9kpszHUYz^W7F5(?V@D!3XR=b|*Ak|$!5=>os~KB5n)mw>4AFaT3yd~Rh2kAV z;2l{jB?7nyH&T)585t&)mRzD(ezu|ayExNTYIoDC!;+Z5 zHN>A!8w3LyLDVGMd1`|&iuk;hbu(eD-LjZkzu#Qf;2)Y=C4SyO*J~(-4=EI_G%r?g z$6)1}6SGV8z`($L=wsTvs)fE}&aEyp?ihbuQgBRb^JLt3=+N@#&}0670m@z>o3+MC z7JCg@${PCQ5+w;J45Wa8%F&Y_uptYBjKDZn$j!$i%T~Hb`b#nGDNv%=|IZ-)7xy`6 Z>?0q`7A<26K6B6jJuM?xt%m)R{{S3%Yy|)S literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..b23f35386c72ab553a3d1042f8364e4137c56d79 GIT binary patch literal 1208 zcmV;p1V{T)Nk&Gn1ONb6MM6+kP&iDZ1ONapFTe{Bl}N(=|7@fjcW<_BpT@RrXF9fR zPcgRbnYC@3C!TD!lSPu}pX~1aKkQBwskLpp+A`1A9}Y(g)Itj&lS>tVe7_^>_ z826l;B*(U`+RB*g5z2|kVT5E5FyQAVgAk*P(ZlFcY(fa3jAX?~VH^(fAmEj9{{8%|sGp=nITppEXL_imf5D{y|bAY;l z%@ema44y|$#-Eqz}U+jr75P;2fxqVNzyxAP{y>Un3g0JKF~^?_joJRe~~pZCE*In~};3 z*+FDr8~l_y*#$jp{`geOgYO9Xjxz?#6|7rC)r98+=lJFL_0$GMK}ryK!3bsq+VpR}+~@*pyw!2totXKxG7N6E#S{aU8)>9FY?vC&v7)^5t`_ z$3+`B0AdCAne3kQo}@mpHHkaCATjU^){A`(+ER!Pu)cj@^63XcJ?)`=Z=PwoyJ!R$ z3wX}3dvbcxdlGAWN5TWQU_A_KJlgoqbUPnv$;)%X97T7a>I^Gd-8 zyC=IRwGvTLSlO^*T*IK1@=XicL89(_>M*3)U;{`F3tF_Q8__5-fdhn zDVt_kqYWgg&XYETz!f_I_?CUFe*H;F{9VGxZI(h)sn2br73teOcErC$j6eOYp?Px&* zYEg+&6oH3yM1g|QFL;CJc!=w`7@QA&bp(Cr$8Zls(gxH+l7s8ugP#A%Hz4UN{@nlS zpZlLb!-B3&Gg~~2Fzli8jTa#ua|**NUb7g%qeSp?5Fzn^^KTFf#S{~Yzv2?t2ub4H zLTm} W2sz3PjmRKrM~Pe_N;wApBS8RQ#XQ&m literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..4e3388e10c022e634683f7f6f1ff1341093b8292 GIT binary patch literal 2112 zcmV-G2*3AINk&FE2mk5#6mnfZq@c_L6b9;>{%XU?D#am`(W@ct)rZCU{|5rSJ58U7v9(hvw6-TlZa7`13 zY8S0K5przXHf`%2Kif7V8<}m}R%WvRwqF%&E5C}L^^J4)WZ<@K9J%-1ZcFzDNf!VR z(sInUZQJc<+qP}nwr$(CZJXJ4+s(cGaB zcQOt6W7q3Pk|f)ztz@l_ySqEI-Jxak9}mw!BpLmK5WtA{EF-sV98oi;?e!6;D?tfH za4veuwOkubO3;EuRYFsk3A^~;kEqH?nobF4Q7k6;A(OEu{?S<0)b5tonM+uRA4NXj z;@>$Kv=m8H2@OQc7`9;07FA4AOT>tx)KGwk-ij(49oqmdqVVUJwZxRl|2Sz$UWRg6 zj_4ZkqKS(PaYZBp`W+`OvL-}V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@Ot4`T(9_Zbxm`Mkc3+&rTNmqUu&p$2Nw? zW{0^SF250#SH#kDYtO8ms`!{S+Q+pXwrCJipOluB>Dz8YzQJNTB7yDP@ArgP{Mt5? z&5*=Z>nj-$=Xb?y0sC#vz*fq8&*G6Qd^>Gq(i{;m?_d{yu@%!d+wv$7(K9Bdd9x*2 z1mQ=zdm_+R5XAY65z{FOhyDNuGg;8A$ZTTyk@Bf~%u72f0giQ|)_ptm^Y#YRo4h~n znWR1|y!JUaSp3M){S%cag-!Z&i*{&2mMxT2t;Nd1bTV8ehd!a&pzlA{ zleV0{@z%&0D015jKQ$LXzauKLET>1DKc><`Nm|D5ThehJ$)<_9ARxZt%fiA!zPGX( zMLIcEo58yRO+iqtRoOM$9+r!M|q%7&9?X_D9^2gAtO zH@0&SvzMze$NyG)ZoC$pKgH*sx1w*Qy=0a!Q&4l&DaF}d>JPeG*5p`LyJ{}jeP&DidFwB(&!Gq+E&d-c*6^hTAXhp^-XJaYh{j{y*e0Wp;3 z9~sr{VV^3#o-nNP^701F5eO6{P_fmO{#s_Xpf(ll^b?zQAUJ|%7nM@#fO22*G5X-X zKTa8ok~DFCcJTXK*&FwqsOlRaW8cGdjm+67ec2i*g|_E}*}1fe!f)ka49rfq>*BtesZd^ZmjLaGu8VYkqqnKqM zOZW7@WRQ;QQ*j_iFHN100;bZ{_;b=hWdp#^s|0s(JdRMc-u1rdnRRwtjE?vZ|p=8D2OaxR&F+Q?(K37`hkR;p682>2fbPSN53 literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..7c4cbb4d5e26ad7129c4569ff94d2b097d64e7a4 GIT binary patch literal 2538 zcmV<|BMM6+kP&iE02><{uU%(d-O)zL1$&n_zU+4G}-hv^b{}Z4! zo)VZSAu$k2>$tgt%2CP|5tB*_H;0*W4<8bd+bHjK-kcXtp(!~|GRg^azJ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V|B_93S`u(_cvbSro&pE~sD97Tw(+w{8U-=jYLhy(y2bT-33v z^FKd}|G%@DumCLs?)0YAp)-Kkqeqlce0z!$ SHsy{O1B~yP-7Pn8j{6^VGI$mM literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..be1eb31b02834226fec0bc33b99820e34151d37c GIT binary patch literal 3976 zcmV;34|niVNk&G14*&pHMM6+kP&iC;4*&o!kH8}kO)zZRHWK8d?cF*1PuveTK}7#2 zfPX3u0;E0ZUIdwWCWEzb1d?{7@z$g^@_l9Fo#Bu~t$4nf>_uYiDsODwfEyMJ4qk39 z6t#`ym_N$pQm)^hRU}ERnjioP_*a*C@k2q|Hj?-7$5;plU^?}G0`O%&SOCok4Nl_@ zCize}8B!?$04-o09l}eqGH9mOatrR)hT^tu9BKc#Q?I-uVgk6MkTIMp-xTSWsmGFK(M{+ssI^!0gyTmznuw zW@ct)#=qcPVrFK(n3>AV+=e-3k}PRKN@GRxwM3t3Dy!g6f7z^@Fu#7!oZ-wga9!#q zcZ%NVMz-zRR(h^;@2~qUf%Y^6gGCUeLDfCa#wG+3f)upY>YcNvtVoho+se9(dajde z?#2`L6yPW0>X-l!KAF}g#<(6(>&U4FgW*$!pdO@-44Xrcup$JmUCtEa844LIjs%;1 zjiC(rNJRu@*Mo*f9AFk>#kF4}fJjFN@{j_DZK47N&!r!|w-$WZb#Z4nl>VWR@H zPm6~ks}dt%lHPx{Z%G{kHAVp>p>~B8uNGg>YvT&dM};|_Z`i~IW+B1DWZ$FMK|8Ax$Cr}C#PWiI0)ghe}Zcp*>Z07kjroXOWXhe;?A z03bE@FRO@o=+3d5XG666cb2k^ZmFNHs zoW$dqg~)G2k4F8R#$A$P-}cbs;;5tM!fFpY3?Al|iR(^oZv=2>phuq-oDb}_)lrY8 zEx6$=s{vr)x|8cQXR>|N>EZVh(Cnp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K#ei! z-?>5;iV)Attdp?iQCTyOS<~@O0~0|8oX8G1O#EETeM;6m0!!vFV+NxpgIhF%t*|Zx zgn~!_M1qJTj2Yy>gVuukEu(uWHG5HfHgZ0I@`~L&3Db)8dH4R^->p@MtXBJKFw>2IfZIUS2=J3lR_rOUx$ z=FJnKKU<46G&Dr0G-Z@==C~doet5m!h1 z1wash&EK1aUHszR=#fqop(|;nl2!;~Ey}+_jWH&UO&rI@7}Z9&$-<#vT%0hS7-nm2 znx-~Qt+kfHn*aa`RaIk*_OdYm?$uh$)>>v}FgB$Mg(`GoC^lyB#$X16u}M|{3IGa# K0e}H8N*VwKcz8Vk literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_banner.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_banner.png new file mode 100644 index 0000000000000000000000000000000000000000..30887f8c8adee97d6becb965ba198328a4a011eb GIT binary patch literal 16542 zcmeIZ^;^^b_Xj*u8Wf~c1XNPG2U60g!03?f?ieAPh;&REL_)e@)Cdvj?p8WRGjiN} zf3N$O`#-pU`1~+-vFEj2=XIVZ9_O6LiPq6lAtj{B+qVDyF|382ce@c83X3ljXHzkqJqM^<&>kc}bQEDdKt z2|6hWiLOg=@k@zFn2<%hcEmrgU)I077|L8eetm4)AW!_}4Xa_^)5EtF6@`^;4;6mq z%cwm)pZ50+Eu~0Q&r3&h5X6IoV_P{+!dn7^IexN?}cQ3?PS03fXZz{MPp zU{PQWg#LH%Kb8Fd+!!KpNw*K1R?|#debXbIrb^xk+6+*6kpKWX+}LXX<9ho<9>ZG2 zG(J;Dtt!*j#?f1Qf-Et&925Wbs9K9IY%gX2AkPRMEa$GvOBAuf9xwfjn1+w%=jrsD zp0#Yhm6tT8-j6LY&Tt+L@K3QHYdz|?9b)4>-;I|iZ*OlO4+zQ{+#GU1HCI&dO1e2* zwQi;v4~4T5000AQfJ>o@ONT;jaz2JDG8S2$hC6~JOC9nw2!cO&otTpV8vuCz7;qac z>bc}KD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FMHN zyOHr5H19ZzOQG};M_p34<|fBjNS&P~&9*kF<{L+c}neE6}*WD~G{I0lBS%z<7 zD+zb-JB_yI9j3SJ`LO=hVijP5VMDhr`K3syvVov-SsTv9S!rrT(O$0MeQ%URC@p~* zo?I$Pc#C57+hyNoCG9>%wdX5 zyOD?aT=Y*9)H?Yff8^TLEy(Qk@C#9rg>7Ecw?=G(;bR~8S}KWeY9%nq0)!Mzt$g%q zoFgYJ+ydHrNC9Uq(#odC1LlqUPvRyiZ=-jYF_&-w3Fti?K2F<$$tbGg# zR;aIKwi<${UtjjL)QHT*Z#NXOQ{!-Zq|nsDRgEt%QxT)Ic(`8gS<>aPG*`n}B6~Au zRYdd``79}g#OvNeXEP#8>T4FYz+ja2;nvKt7A0l{P389>QC;iCGx0G4U;()3nC2_t|jo{nx_kSdS42Uw;0q7x=3y!GQ(Jo>!tR zA?g1%?5Ov@r+wV6l?lCChuZ8;6xu#(kbJm1vRk8bby@1DY)gT~B1Um|!*C^wpK zk|=+IZ&kiaphgtDvk)MuQl0pfTq5n2r=>)5)!d?kpsfmRRHA$ z;{__2J%n6YI-aK5+VKa3*!j%+-IFq1UHA$?&ivYfFcejz|0I+AffifkI=eEJHdIeg zCNyYS^1t1gA$dJVBUOg2imh6;riS>;M#%TuzzGOc%w^#@W0FC0NvFO&-`$}mHfef?nmq!rBJjSFkBC(wXankL7 zn>ibO{Oo0Dv3^%%(KJKMH^`(lt74R?KhM5rqABzy`p4*&p)1ga4`If5!0t caRW5vjP|E$Ao+(XjGq8hm9!Kq-&jQaKgD_~mjD0& literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..0297013ca34c8705193ed3862d568c9b50ee2399 GIT binary patch literal 5882 zcmV@RGV^9*Hz4i{9>7+wO zl2C*;dVh+owBs%bQsgaSSJ(1S8ZO!-&SG+Vp`?){sr;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_round.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..72ea5bcabad54ab46963a476ba081f85883028c5 GIT binary patch literal 10772 zcmV+vD(lr!Nk&EtDgXdiMM6+kP&iBgDgXd4zrZgLO+akhNRk9U^YpqV|A4!u=5P^2 z^nU{Ie?5{$9%u&Joxb2j19z|o0${U)4b*@{8=7CZg*1Cf3a`QY^E_*D->RvGf3QC% z*IG>Q<-EAWE*~5%l3Pvg`}dn9+fCX@qR}Gn`)+`wswzoVV;iqkNTQ9`sFfs=wC$1J z=>1I-`aA(tZ8aj#vjCu~UKVT`Npe(RoT>n@9Cjh6agMM80MBNTv08}Fz;t$9OG6tfW`_Dun1Hccc)Qkx7Kss0g zz=o?A0PscE+P{Dx6p9`MK@hUdiftz-4#sWUNRs+5JLk;o{v%=n_uw;XR#TQgO% zW}V(Xo%1`5hwttlzH~%vvX(Ww!W%hc*%*=Gfw0oCaGAGxjyD&2| zGxM66nXM%;jbM1DFQ(Ofx~E%Lfj2av4rij3T{&xJyG{R$D%O@W^}F&^%^DPD8i(l^ zcIs4_UH>q16j1P#nQ`(fV<&a)V!W~x=80TVO~`f>HLz48o5s~G#HMVWrw$1%H`^mQL-C-MJt1xYrt1=_r3BYy#|2nyCSj-G& zW`~)XnK^f5hDX56%*@P8W(=5_Wl0vZ7A|IH_rJ6I0N$l3$aXGN9ZLa)%D6rCr}*_A=wcBCkwAI`LO28fk}X+x z#{?LNPns|VsiGMf7!g@NDyym*j5z!>2#uus`b$|Aailj`hJe9u@EE**`Y#4~7Yw#R z8`6f|;opZDlF(05 z%*y?VaF_2jY%;7fOgFfJ+l6ypB^hD=j)I)-y``Zm4 z8~zvii_Tb7;=2vI45$7N!&`<=DQQ$JQc#p|nBlPDjZa6C6fy--2*pG9@5b=JaOg0SNQ*+0pq*?toc?qq zxlNfuDIWTV_0u=}hLS{uudIS$X*I_Uvk^B|rjW|$J%|k_J{M6faQ!6=m4^L>6_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!Xy_mLl;jV1BsB_|^pn!;TZVmQ;bYP!}>q~gF0_@!E3ezrDfu&$E zkI&5Y4l+^;h0Zw<3ap4YXV9(*eT2L%x8`wU30+G-3u0un;H1E=d$b}Jg86hEz|D82 zRgP%Jafx$Ma70Lxtic|TZJwzYVqwtievw zAW~QW5phY9Br9B-yO^dNV|F$w(C{lo3a`?7Gun(Z+wEVh1A$j;WB}tMv z5uqT9bI#x-NgH+tdceISZKvbMgJ@lVv+XJ}O4##4c1Z_v+aWj?p!JOW_%1ZNf#11% zl9ZftLSYsWaY<4tC2O&3;Q@IQuAiDOE=b)Wq z_iw>fk!!ETPD-UDaUvpxsk?L9z4w2oB3ociO=vpZ^;m}D4t!P6bWnq#T(&(UWMqV~ zp>6Z&pGWO!`01T#5jP#xh`oZWf=13!&_zJI_jW+Pe7K&8&Ng07!|oz*G{(+C%m%kI zXf2nqc@{DiG$r>DkT{2`fH2kn-$Q zKNqu(#oXD9+l$Hud=20}ht`1q5e?CDI=ikgjf`ML@6_7@cHX;@C#B_N zL`3S~dgvS1k}+t5UAp$QORABoQY5t-AOhocs9LOAL_2&j195b6Uw{cu#FV*An9lI& zluaY&(ECgRN7e!lh!6ss*I_MK45V~`D>s3);G0$vTTa&sf(vPg5?0l@D*2gkf)QZwGkDl^-+QL~1R`)%2~Rvys;ecy<9^o`{!= zh#QQ^bg0~nZpUszC#6#9+NC5(oKrQR$Z9u){_*kg{_*~3GFCmZ+=x+>Xg1y_rr-&v zIU42npF(Lp`E}$N{3+ZuxV~Wgk37g;D=Ga>C)pI~FK!~*#Ndytrhh&i=OuD329}a^ z2=e3XfD5@H%qOv{!A`TIRG?AtU1q39$OM{|Hq^c~a5Q#KW zjnbf?2ncDMh!a$aP*s%mOBF$IXm?Z$3tV-IcTo2x*1xLcs+emlulw literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/values/ic_banner_background.xml b/android/app/src/main/res/values/ic_banner_background.xml new file mode 100644 index 0000000..15db34b --- /dev/null +++ b/android/app/src/main/res/values/ic_banner_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..6c47fa0 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,25 @@ + + + + MPD + Music Player Daemon is running + Touch for MPD options. + MPD is running + MPD is not running + Run MPD automatically on boot + Prevent suspend when MPD is running (Wakelock) + Pause MPD when headphones disconnect + MPD requires access to external files to play local music. Please grant the permission. + Open app info + "Failed to load the native MPD library. +Report this problem to us, and include the following information: +SUPPORTED_ABIS=%1$s +PRODUCT=%2$s +FINGERPRINT=%3$s +error=%4$s" + + Stopped + Running + Stop MPD + Start MPD + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..d53aa8c --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,21 @@ + + + #F44336 + #B71C1C + #81C784 + #388E3C + + @color/red_900 + @color/red_500 + + @color/green_700 + @color/green_300 + + + + + + \ No newline at end of file diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..4452473 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,7 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + id("com.google.devtools.ksp") version "1.9.22-1.0.16" apply false + alias(libs.plugins.android.application) apply false + alias(libs.plugins.jetbrains.kotlin.android) apply false + alias(libs.plugins.dagger.hilt.android) apply false +} \ No newline at end of file diff --git a/android/build.py b/android/build.py new file mode 100755 index 0000000..c8d9507 --- /dev/null +++ b/android/build.py @@ -0,0 +1,82 @@ +#!/usr/bin/env -S python3 -u + +import os, os.path +import shutil +import sys, subprocess + +if len(sys.argv) < 4: + print("Usage: build.py SDK_PATH NDK_PATH ABI [configure_args...]", file=sys.stderr) + sys.exit(1) + +sdk_path = sys.argv[1] +ndk_path = sys.argv[2] +android_abi = sys.argv[3] +configure_args = sys.argv[4:] + +if not os.path.isfile(os.path.join(sdk_path, 'licenses', 'android-sdk-license')): + print("SDK not found in", sdk_path, file=sys.stderr) + sys.exit(1) + +if not os.path.isdir(ndk_path): + print("NDK not found in", ndk_path, file=sys.stderr) + sys.exit(1) + +# the path to the MPD sources +mpd_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]) or '.', '..')) +sys.path[0] = os.path.join(mpd_path, 'python') + +# output directories +from build.dirs import lib_path, tarball_path, src_path +from build.toolchain import AndroidNdkToolchain + +# a list of third-party libraries to be used by MPD on Android +from build.libs import * +thirdparty_libs = [ + libmodplug, + wildmidi, + gme, + ffmpeg, + libnfs, +] + +# build the third-party libraries +for x in thirdparty_libs: + toolchain = AndroidNdkToolchain(mpd_path, lib_path, + tarball_path, src_path, + ndk_path, android_abi, + use_cxx=x.use_cxx) + if not x.is_installed(toolchain): + x.build(toolchain) + +# configure and build MPD +toolchain = AndroidNdkToolchain(mpd_path, lib_path, + tarball_path, src_path, + ndk_path, android_abi, + use_cxx=True) + +configure_args += [ + '-Dandroid_sdk=' + sdk_path, + '-Dandroid_ndk=' + ndk_path, + '-Dandroid_abi=' + android_abi, + '-Dandroid_strip=' + toolchain.strip, + '-Dopenssl:asm=disabled', + '-Dwrap_mode=forcefallback' +] + +from build.meson import configure as run_meson +run_meson(toolchain, mpd_path, '.', configure_args) + +ninja = shutil.which("ninja") +subprocess.check_call([ninja], env=toolchain.env) + +subprocess.check_call([ninja, 'install'], env=toolchain.env) + +print(""" +------------------------------------- +## To build the android app: +# cd ../../android +# ./gradlew assemble{}Debug +## or, for a universal apk (includes both arm64-v8a and x86_64) +# ./gradlew assembleUniversalDebug +------------------------------------- +""".format(android_abi.capitalize())) \ No newline at end of file diff --git a/android/custom_rules.xml b/android/custom_rules.xml new file mode 100644 index 0000000..68db465 --- /dev/null +++ b/android/custom_rules.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/android/gdb.sh b/android/gdb.sh new file mode 100755 index 0000000..5e576c7 --- /dev/null +++ b/android/gdb.sh @@ -0,0 +1,54 @@ +#!/bin/sh + +# This script need the following modification in ANDROID_NDK in order to attach +# to the good :main pid +#--- a/prebuilt/linux-x86_64/bin/ndk-gdb.py +#+++ b/prebuilt/linux-x86_64/bin/ndk-gdb.py +#@@ -669,7 +669,7 @@ +# log("Sleeping for {} seconds.".format(args.delay)) +# time.sleep(args.delay) +# +#- pids = gdbrunner.get_pids(device, pkg_name) +#+ pids = gdbrunner.get_pids(device, pkg_name + ":main") +# if len(pids) == 0: +# error("Failed to find running process '{}'".format(pkg_name)) +# if len(pids) > 1: + +SCRIPT_PATH=$(dirname $0) +BUILD_PATH="`pwd`" +TMP_PATH="$BUILD_PATH/gdb" +NDK_GDB_ARGS="--force" +ANDROID_NDK=$1 + +if [ ! -f $ANDROID_NDK/source.properties ];then + echo "usage: $0 ANDROID_NDK" + exit 1 +fi + +if [ ! -f $BUILD_PATH/libmpd.so ];then + echo "This script need to be executed from the android build directory" + exit 1 +fi + +rm -rf "$TMP_PATH" +mkdir -p "$TMP_PATH" + +ANDROID_MANIFEST="$SCRIPT_PATH/AndroidManifest.xml" +ABI=`ls "$BUILD_PATH/android/apk/apk/lib" --sort=time | head -n 1` + +if [ ! -f "$ANDROID_MANIFEST" -o "$ABI" = "" ]; then + echo "Invalid manifest/ABI, did you try building first ?" + exit 1 +fi + +mkdir -p "$TMP_PATH"/jni +touch "$TMP_PATH"/jni/Android.mk +echo "APP_ABI := $ABI" > "$TMP_PATH"/jni/Application.mk + +DEST=obj/local/$ABI +mkdir -p "$TMP_PATH/$DEST" + +cp "$BUILD_PATH/libmpd.so" "$TMP_PATH/$DEST" +cp "$ANDROID_MANIFEST" "$TMP_PATH" + +(cd "$TMP_PATH" && bash $ANDROID_NDK/ndk-gdb $NDK_GDB_ARGS) diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..a03b354 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,21 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml new file mode 100644 index 0000000..0800b21 --- /dev/null +++ b/android/gradle/libs.versions.toml @@ -0,0 +1,41 @@ +[versions] +androidGradlePlugin = "8.5.2" +accompanistPermissions = "0.33.2-alpha" +activityCompose = "1.10.0" +appcompat = "1.7.0" +composeBom = "2025.01.01" +composeSettingsStoragePreferences = "1.0.3" +composeSettingsUiM3 = "1.0.3" +daggerCompiler = "2.49" +hiltAndroid = "2.49" +hiltCompiler = "2.49" +lifecycleRuntimeKtx = "2.8.7" +media3Session = "1.5.1" +navigationCompose = "2.8.6" +kotlin = "1.9.22" + +[libraries] +accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version.ref = "accompanistPermissions" } +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } +androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" } +androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" } +androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycleRuntimeKtx" } +androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" } +androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" } +androidx-material-icons-extended = { module = "androidx.compose.material:material-icons-extended" } +androidx-material3 = { module = "androidx.compose.material3:material3" } +androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3Session" } +androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigationCompose" } +androidx-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" } +androidx-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } +androidx-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" } +compose-settings-storage-preferences = { module = "com.github.alorma:compose-settings-storage-preferences", version.ref = "composeSettingsStoragePreferences" } +compose-settings-ui-m3 = { module = "com.github.alorma:compose-settings-ui-m3", version.ref = "composeSettingsUiM3" } +dagger-compiler = { module = "com.google.dagger:dagger-compiler", version.ref = "daggerCompiler" } +hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hiltAndroid" } +hilt-compiler = { module = "com.google.dagger:hilt-compiler", version.ref = "hiltCompiler" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" } +jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +dagger-hilt-android = { id = "com.google.dagger.hilt.android", version.ref = "hiltAndroid" } \ No newline at end of file diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e708b1c023ec8b20f512888fe07c5bd3ff77bb8f GIT binary patch literal 59203 zcma&O1C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#S1M7C+*MMqLw78E zhY2dI8@+N^qrMI1+;TUda(vGqGSRyU{Fnm`aqrr7bz42c5xsOO-~oZpkzorD1g}Y<6rk&3>PsSGy}W?MtqFky@A(X# zIuNZK0cK?^=;PUAu>j0#HtjbHCV*6?jzA&OoE$*Jlga*}LF`SF?WLhv1O|zqC<>*> zYB;#lsYKx0&kH@BFpW8n*yDcc6?;_zaJs<-jPSkCsSX-!aV=P5kUgF@Nu<{a%#K*F z134Q{9|YX7X(v$62_cY3^G%t~rD>Q0z@)1|zs)vjJ6Jq9;7#Ki`w+eS**En?7;n&7 zu==V3T&eFboN3ZiMx3D8qYc;VjFUk_H-WWCau(VFXSQf~viH0L$gwD$UfFHqNcgN`x}M+YQ6RnN<+@t>JUp#)9YOkqst-Ga?{FsDpEeX0(5v{0J~SEbWiL zXC2}M4?UH@u&|;%0y`eb33ldo4~z-x8zY!oVmV=c+f$m?RfDC35mdQ2E>Pze7KWP- z>!Bh<&57I+O_^s}9Tg^k)h7{xx@0a0IA~GAOt2yy!X%Q$1rt~LbTB6@Du!_0%HV>N zlf)QI1&gvERKwso23mJ!Ou6ZS#zCS5W`gxE5T>C#E|{i<1D35C222I33?Njaz`On7 zi<+VWFP6D{e-{yiN#M|Jgk<44u1TiMI78S5W`Sdb5f+{zu34s{CfWN7a3Cf^@L%!& zN$?|!!9j2c)j$~+R6n#891w-z8(!oBpL2K=+%a$r2|~8-(vQj5_XT`<0Ksf;oP+tz z9CObS!0m)Tgg`K#xBM8B(|Z)Wb&DYL{WTYv`;A=q6~Nnx2+!lTIXtj8J7dZE!P_{z z#f8w6F}^!?^KE#+ZDv+xd5O&3EmomZzsv?>E-~ygGum45fk!SBN&|eo1rKw^?aZJ4 E2O(~oYXATM literal 0 HcmV?d00001 diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ba1b46d --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Dec 17 15:00:03 CST 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..4f906e0 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/include/meson.build b/android/include/meson.build new file mode 100644 index 0000000..af9f57e --- /dev/null +++ b/android/include/meson.build @@ -0,0 +1,21 @@ +javac = find_program('javac') + +bridge_header = custom_target( + 'org_musicpd_Bridge.h', + output: 'org_musicpd_Bridge.h', + input: [ + '../app/src/main/java/org/musicpd/Bridge.java', + ], + command: [ + javac, + '-source', '1.8', '-target', '1.8', + '-Xlint:-options', + '-cp', join_paths(android_sdk_platform_dir, 'android.jar'), + + # not interested in *.class, we only want the JNI header + '-d', '@PRIVATE_DIR@', + + '-h', '@OUTDIR@', + '@INPUT@', + ], +) diff --git a/android/meson.build b/android/meson.build new file mode 100644 index 0000000..89f7b1b --- /dev/null +++ b/android/meson.build @@ -0,0 +1,17 @@ +android_package = 'org.musicpd' +android_package_path = join_paths(android_package.split('.')) + +android_ndk = get_option('android_ndk') +android_sdk = get_option('android_sdk') +android_abi = get_option('android_abi') + +android_sdk_build_tools_version = '34.0.0' +android_sdk_platform = 'android-34' + +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) + + +android_gradlew = join_paths(meson.current_source_dir(), 'gradlew') + +subdir('include') diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..c86ae33 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "MPD" +include(":app") + \ No newline at end of file diff --git a/doc/_static/css/custom.css b/doc/_static/css/custom.css new file mode 100644 index 0000000..a0c3027 --- /dev/null +++ b/doc/_static/css/custom.css @@ -0,0 +1,3 @@ +/* + * css to override sphinx theme + */ \ No newline at end of file diff --git a/doc/client.rst b/doc/client.rst new file mode 100644 index 0000000..f49b951 --- /dev/null +++ b/doc/client.rst @@ -0,0 +1,66 @@ +Client Developer's Manual +######################### + +Introduction +************ + +MPD is a music player without a user interface. The user interface +will be provided by independent clients, which connect to MPD over +socket connections (TCP or local sockets). + +This chapter describes how to develop a client. + +Before you develop a new client, consider joining an existing client +project. There are many clients, but few are mature; we need fewer, +but better clients. + +Client Libraries +**************** + +There are many libraries which help with connecting to MPD. If you +develop a MPD client, use a library instead of reinventing the wheel. +The MPD website has a list of libraries: https://www.musicpd.org/libs/ + + +Connecting to MPD +***************** + +Do not hard-code your client to connect to ``localhost:6600``. +Instead, use the defaults of the client library. For example, with +:program:`libmpdclient`, don't do:: + + c = mpd_connection_new("localhost", 6600, 30000); + +Instead, do:: + + c = mpd_connection_new(NULL, 0, 0); + +This way, the library can choose the best defaults, maybe derived from +environment variables, so all MPD clients use the same settings. + +If you need to reimplement those defaults (or if you are developing a +client library), this is a good set of addresses to attempt to connect +to: + +- if the environment variable :envvar:`MPD_HOST` is set: + ``$MPD_HOST:$MPD_PORT`` (:envvar:`MPD_PORT` defaulting to 6600) +- if the environment variable :envvar:`XDG_RUNTIME_DIR` is set: + ``$XDG_RUNTIME_DIR/mpd/socket`` +- :file:`/run/mpd/socket` +- ``localhost:$MPD_PORT`` (:envvar:`MPD_PORT` defaulting to 6600) + +Environment Variables +********************* + +The following environment variables should be obeyed by all clients +(preferably by the client library): + +- :envvar:`MPD_HOST`: the host (or local socket path) to connect to; + on Linux, this may start with a ``@`` to connect to an abstract + socket. To use a password with MPD, set :envvar:`MPD_HOST` to + ``password@host`` (then abstract socket requires double ``@``: + ``password@@socket``). +- :envvar:`MPD_PORT`: the port number; defaults to 6600. +- :envvar:`MPD_TIMEOUT`: timeout for connecting to MPD and for waiting + for MPD's response in seconds. A good default is 30 seconds. + diff --git a/doc/conf.py b/doc/conf.py new file mode 100644 index 0000000..156a33f --- /dev/null +++ b/doc/conf.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.intersphinx'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Music Player Daemon' +copyright = '2003-2025 The Music Player Daemon Project' +author = 'Max Kellermann' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +with open('../meson.build') as f: + import re + version = re.match(r"project\([^\)]*\bversion:\s*'([^']+)'", + f.read(4096)).group(1) +# The full version, including alpha/beta/rc tags. +release = version + '~git' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +try: + __import__(html_theme) +except ModuleNotFoundError: + import sys + print(f"Warning: Sphinx theme {html_theme!r} not available, falling back to the default theme", file=sys.stderr) + del html_theme + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} +html_theme_options = { + 'navigation_depth': -1, + 'sticky_navigation': False, + 'includehidden': True, + 'prev_next_buttons_location': 'both', + 'github_url': "https://github.com/MusicPlayerDaemon/" +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = '' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +html_css_files = [ + 'css/custom.css', +] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' +man_pages = [ + ('mpd.1', 'mpd', 'MPD documentation', [author], 1), + ('mpd.conf.5', 'mpd.conf', 'mpd.conf documentation', [author], 5) +] diff --git a/doc/developer.rst b/doc/developer.rst new file mode 100644 index 0000000..f1d6d1f --- /dev/null +++ b/doc/developer.rst @@ -0,0 +1,149 @@ +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 +* comment your code, document your APIs +* the code should be C++23 compliant, and must compile with :program:`GCC` 12 and :program:`clang` 14 +* all code must be exception-safe +* classes and functions names use CamelCase; variables are lower-case with words separated by underscore + +Some example code: + +.. code-block:: c + + int + Foo(const char *abc, int xyz) + { + if (abc == nullptr) { + LogWarning("Foo happened!"); + return -1; + } + + return xyz; + } + + +Error handling +============== + +If an error occurs, throw a C++ exception, preferably derived from +:code:`std::runtime_error`. The function's API documentation should +mention that. If a function cannot throw exceptions, add +:code:`noexcept` to its prototype. + +Some parts of MPD use callbacks to report completion; the handler +classes usually have an "error" callback which receives a +:code:`std::exception_ptr` +(e.g. :code:`BufferedSocket::OnSocketError()`). Wrapping errors in +:code:`std::exception_ptr` allows propagating details about the error +across thread boundaries to the entity which is interested in handling +it (e.g. giving the MPD client details about an I/O error caught by +the decoder thread). + +Out-of-memory errors (i.e. :code:`std::bad_alloc`) do not need to be +handled. Some operating systems such as Linux do not report +out-of-memory to userspace, and instead kill a process to recover. +Even if we know we are out of memory, there is little we can do except +for aborting the process quickly. Any other attempts to give back +memory may cause page faults on the way which make the situation +worse. + +Error conditions which are caused by a bug do not need to be handled +at runtime; instead, use :code:`assert()` to detect them in debug +builds. + + +git Branches +************ + +There are two active branches in the git repository: + +- the "unstable" branch called ``master`` where new features are + merged. This will become the next major release eventually. +- the "stable" branch (currently called ``v0.24.x``) where only bug + fixes are merged. + +Once :program:`MPD` 0.25 is released, a new branch called ``v0.25.x`` +will be created for 0.25 bug-fix releases; after that, ``v0.24.x`` +will eventually cease to be maintained. + +After bug fixes have been added to the "stable" branch, it will be +merged into ``master``. This ensures that all known bugs are fixed in +all active branches. + + +Hacking The Source +****************** + +MPD sources are managed in a git repository on +`Github `_. + +Always write your code against the latest git: + +.. code-block:: none + + git clone https://github.com/MusicPlayerDaemon/MPD.git + +If you already have a clone, update it: + +.. code-block:: none + + git pull --rebase https://github.com/MusicPlayerDaemon/MPD.git master + +You can do without :code:`--rebase`, but we recommend that you rebase +your repository on the "master" repository all the time. + +Configure with the option :code:`--werror`. Enable as many plugins as +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. + +stgit needs to be initialized on a git repository: + +.. code-block:: sh + + stg init + +Before you edit the code, create a patch: + +.. code-block:: sh + + stg new my-patch-name + +stgit now asks you for the commit message. + +Now edit the code. Once you're finished, you have to "refresh" the patch, i.e. your edits are incorporated into the patch you have created: + +.. code-block:: sh + + stg refresh + +You may now continue editing the same patch, and refresh it as often as you like. Create more patches, edit and refresh them. + +To view the list of patches, type stg series. To go back to a specific patch, type stg goto my-patch-name; now you can re-edit it (don't forget stg refresh when you're finished with that patch). + +When the whole patch series is finished, convert stgit patches to git commits: + +.. code-block:: sh + + stg commit + +Submitting Patches +****************** + +Submit pull requests on GitHub: +https://github.com/MusicPlayerDaemon/MPD/pulls diff --git a/doc/doxygen.conf.in b/doc/doxygen.conf.in new file mode 100644 index 0000000..5b8e72e --- /dev/null +++ b/doc/doxygen.conf.in @@ -0,0 +1,2428 @@ +# Doxyfile 1.8.11 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all text +# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv +# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv +# for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = MPD + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = @VERSION@ + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = doc/api + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = @abs_top_srcdir@/src/ + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = YES + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = NO + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = @abs_top_srcdir@/src/ + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: http://www.gnu.org/software/libiconv) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f, *.for, *.tcl, +# *.vhd, *.vhdl, *.ucf, *.qsf, *.as and *.js. + +FILE_PATTERNS = *.h \ + *.hxx + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# function all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see http://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the config file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the +# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the +# cost of reduced performance. This can be particularly helpful with template +# rich C++ code for which doxygen's built-in parser lacks the necessary type +# information. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse-libclang=ON option for CMake. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = NO + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# http://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: http://developer.apple.com/tools/xcode/), introduced with +# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NONE + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# http://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from http://www.mathjax.org before deployment. +# The default value is: http://cdn.mathjax.org/mathjax/latest. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /

(_pipe); + } + + /** + * Start the decoder. + * + * Caller must lock the mutex. + */ + void StartDecoder(std::unique_lock &lock, + std::shared_ptr pipe, + bool initial_seek_essential) noexcept; + + /** + * The decoder has acknowledged the "START" command (see + * ActivateDecoder()). This function checks if the decoder + * initialization has completed yet. If not, it will wait + * some more. + * + * Caller must lock the mutex. + * + * @return false if the decoder has failed, true on success + * (though the decoder startup may or may not yet be finished) + */ + bool CheckDecoderStartup(std::unique_lock &lock) noexcept; + + /** + * Stop the decoder and clears (and frees) its music pipe. + * + * Caller must lock the mutex. + */ + void StopDecoder(std::unique_lock &lock) noexcept; + + /** + * Is the decoder still busy on the same song as the player? + * + * Note: this function does not check if the decoder is already + * finished. + */ + [[nodiscard]] [[gnu::pure]] + bool IsDecoderAtCurrentSong() const noexcept { + assert(pipe != nullptr); + + return dc.pipe == pipe; + } + + /** + * Returns true if the decoder is decoding the next song (or has begun + * decoding it, or has finished doing it), and the player hasn't + * switched to that song yet. + */ + [[nodiscard]] [[gnu::pure]] + bool IsDecoderAtNextSong() const noexcept { + return dc.pipe != nullptr && !IsDecoderAtCurrentSong(); + } + + /** + * Invoke DecoderControl::Seek() and update our state or + * handle errors. + * + * Caller must lock the mutex. + * + * @return false if the decoder has failed + */ + bool SeekDecoder(std::unique_lock &lock, + SongTime seek_time) noexcept; + + /** + * This is the handler for the #PlayerCommand::SEEK command. + * + * Caller must lock the mutex. + * + * @return false if the decoder has failed + */ + bool SeekDecoder(std::unique_lock &lock) noexcept; + + void CancelPendingSeek() noexcept { + pending_seek = SongTime::zero(); + pc.CancelPendingSeek(); + } + + /** + * Check if the decoder has reported an error, and forward it + * to PlayerControl::SetError(). + * + * @return false if an error has occurred + */ + bool ForwardDecoderError() noexcept; + + /** + * After the decoder has been started asynchronously, activate + * it for playback. That is, make the currently decoded song + * active (assign it to #song), clear PlayerControl::next_song + * and #queued, initialize #elapsed_time, and set + * #decoder_starting. + * + * When returning, the decoder may not have completed startup + * yet, therefore we don't know the audio format yet. To + * finish decoder startup, call CheckDecoderStartup(). + * + * Caller must lock the mutex. + */ + void ActivateDecoder() noexcept; + + /** + * Wrapper for MultipleOutputs::Open(). Upon failure, it + * pauses the player. + * + * Caller must lock the mutex. + * + * @return true on success + */ + bool OpenOutput() noexcept; + + std::string UnlockAnalyzeMixRamp(const MusicPipe &pipe, + const AudioFormat &audio_format, + MixRampDirection direction) noexcept; + + /** + * @return false if more chunks of the next song are needed to + * scan for MixRamp data + */ + [[nodiscard]] + bool MixRampScannerReady() noexcept; + + void CheckCrossFade() noexcept; + + /** + * Obtains the next chunk from the music pipe, optionally applies + * cross-fading, and sends it to all audio outputs. + * + * @return true on success, false on error (playback will be stopped) + */ + bool PlayNextChunk() noexcept; + + unsigned UnlockCheckOutputs() noexcept { + const ScopeUnlock unlock(pc.mutex); + return pc.outputs.CheckPipe(); + } + + /** + * Player lock must be held before calling. + * + * @return false to stop playback + */ + bool ProcessCommand(std::unique_lock &lock) noexcept; + + /** + * This is called at the border between two songs: the audio output + * has consumed all chunks of the current song, and we should start + * sending chunks from the next one. + * + * Caller must lock the mutex. + */ + void SongBorder() noexcept; + +public: + /* + * The main loop of the player thread, during playback. This + * is basically a state machine, which multiplexes data + * between the decoder thread and the output threads. + */ + void Run() noexcept; +}; + +void +Player::StartDecoder(std::unique_lock &lock, + std::shared_ptr _pipe, + bool initial_seek_essential) noexcept +{ + assert(!decoder_starting); + assert(queued || pc.command == PlayerCommand::SEEK); + assert(pc.next_song != nullptr); + + /* copy ReplayGain parameters to the decoder */ + dc.replay_gain_mode = pc.replay_gain_mode; + + SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time; + + dc.Start(lock, std::make_unique(*pc.next_song), + start_time, pc.next_song->GetEndTime(), + initial_seek_essential, + buffer, std::move(_pipe)); +} + +void +Player::StopDecoder(std::unique_lock &lock) noexcept +{ + const PlayerControl::ScopeOccupied occupied(pc); + + dc.Stop(lock); + + if (dc.pipe != nullptr) { + /* clear and free the decoder pipe */ + + dc.pipe->Clear(); + dc.pipe.reset(); + + /* just in case we've been cross-fading: cancel it + now, because we just deleted the new song's decoder + pipe */ + ResetCrossFade(); + } + + decoder_starting = false; +} + +bool +Player::ForwardDecoderError() noexcept +{ + try { + dc.CheckRethrowError(); + } catch (...) { + pc.SetError(PlayerError::DECODER, std::current_exception()); + return false; + } + + return true; +} + +void +Player::ActivateDecoder() noexcept +{ + assert(queued || pc.command == PlayerCommand::SEEK); + assert(pc.next_song != nullptr); + + queued = false; + + pc.ClearTaggedSong(); + + song = std::exchange(pc.next_song, nullptr); + + elapsed_time = pc.seek_time; + + /* set the "starting" flag, which will be cleared by + CheckDecoderStartup() */ + decoder_starting = true; + pending_seek = SongTime::zero(); + + /* update PlayerControl's song information */ + pc.total_time = song->GetDuration(); + pc.bit_rate = 0; + pc.audio_format.Clear(); + + { + /* call playlist::SyncWithPlayer() in the main thread */ + const ScopeUnlock unlock(pc.mutex); + pc.listener.OnPlayerSync(); + } +} + +/** + * Returns the real duration of the song, comprising the duration + * indicated by the decoder plugin. + */ +static SignedSongTime +real_song_duration(const DetachedSong &song, + SignedSongTime decoder_duration) noexcept +{ + if (decoder_duration.IsNegative()) + /* the decoder plugin didn't provide information; fall + back to Song::GetDuration() */ + return song.GetDuration(); + + const SongTime start_time = song.GetStartTime(); + const SongTime end_time = song.GetEndTime(); + + if (end_time.IsPositive() && end_time < SongTime(decoder_duration)) + return {end_time - start_time}; + + return {SongTime(decoder_duration) - start_time}; +} + +std::string +Player::UnlockAnalyzeMixRamp(const MusicPipe &_pipe, + const AudioFormat &audio_format, + MixRampDirection direction) noexcept +{ + const ScopeUnlock unlock(pc.mutex); + return AnalyzeMixRamp(_pipe, audio_format, direction); +} + +inline bool +Player::MixRampScannerReady() noexcept +{ + assert(pipe); + assert(dc.pipe); + + if (!pc.cross_fade.IsMixRampEnabled()) + return true; + + if (!pc.config.mixramp_analyzer) + /* always ready if the scanner is disabled */ + return true; + + if (dc.GetMixRampPreviousEnd() == nullptr) { + // TODO: scan incrementally backwards until mixrampdb is reached + auto s = UnlockAnalyzeMixRamp(*pipe, play_audio_format, + MixRampDirection::END); + if (!s.empty()) { + FmtDebug(player_domain, "Analyzed MixRamp end: {}", s); + dc.SetMixRampPreviousEnd(std::move(s)); + } + + if (dc.GetMixRampStart() == nullptr) + /* scan the next song in the next call; first, + let the main loop submit a few more chunks + to the outputs for playback to avoid + xrun */ + return false; + } + + if (dc.GetMixRampStart() == nullptr) { + const std::size_t want_pipe_bytes = + dc.out_audio_format.TimeToSize(std::chrono::seconds{20}); + const std::size_t want_pipe_chunks = + std::min((want_pipe_bytes + sizeof(MusicChunk::data) - 1) + / sizeof(MusicChunk::data), + buffer.GetSize() / std::size_t{3}); + + if (dc.pipe->GetSize() < want_pipe_chunks) { + /* need more data */ + if (!buffer.IsFull()) { + decoder_woken = true; + dc.Signal(); + } + + return false; + } + + // TODO: scan incrementally until mixrampdb is reached + auto s = UnlockAnalyzeMixRamp(*dc.pipe, dc.out_audio_format, + MixRampDirection::START); + if (!s.empty()) { + FmtDebug(player_domain, "Analyzed MixRamp start: {}", s); + dc.SetMixRampStart(std::move(s)); + } + } + + return true; +} + +bool +Player::OpenOutput() noexcept +{ + assert(play_audio_format.IsDefined()); + assert(pc.state == PlayerState::PLAY || + pc.state == PlayerState::PAUSE); + + try { + const ScopeUnlock unlock(pc.mutex); + pc.outputs.Open(play_audio_format); + } catch (...) { + LogError(std::current_exception()); + + output_open = false; + + /* pause: the user may resume playback as soon as an + audio output becomes available */ + paused = true; + + pc.SetOutputError(std::current_exception()); + + return false; + } + + output_open = true; + paused = false; + + pc.state = PlayerState::PLAY; + pc.listener.OnPlayerStateChanged(); + + return true; +} + +inline bool +Player::CheckDecoderStartup(std::unique_lock &lock) noexcept +{ + assert(decoder_starting); + + if (!ForwardDecoderError()) { + /* the decoder failed */ + return false; + } else if (!dc.IsStarting()) { + /* the decoder is ready and ok */ + + if (output_open && + !pc.WaitOutputConsumed(lock, 1)) + /* the output devices havn't finished playing + all chunks yet - wait for that */ + return true; + + pc.total_time = real_song_duration(*dc.song, + dc.total_time); + pc.audio_format = dc.in_audio_format; + play_audio_format = dc.out_audio_format; + decoder_starting = false; + + const size_t buffer_before_play_size = + play_audio_format.TimeToSize(buffer_before_play_duration); + buffer_before_play = + (buffer_before_play_size + sizeof(MusicChunk::data) - 1) + / sizeof(MusicChunk::data); + + pc.listener.OnPlayerStateChanged(); + + if (pending_seek > SongTime::zero()) { + assert(pc.seeking); + + bool success = SeekDecoder(lock, pending_seek); + pc.seeking = false; + pc.ClientSignal(); + if (!success) + return false; + + /* re-fill the buffer after seeking */ + buffering = true; + } else if (pc.seeking) { + pc.seeking = false; + pc.ClientSignal(); + + /* re-fill the buffer after seeking */ + buffering = true; + } + + if (!paused && !OpenOutput()) { + FmtError(player_domain, + "problems opening audio device " + "while playing {:?}", + dc.song->GetURI()); + return true; + } + + return true; + } else { + /* the decoder is not yet ready; wait + some more */ + dc.WaitForDecoder(lock); + + return true; + } +} + +bool +Player::SeekDecoder(std::unique_lock &lock, SongTime seek_time) noexcept +{ + assert(song); + assert(!decoder_starting); + + if (!pc.total_time.IsNegative()) { + const SongTime total_time(pc.total_time); + if (seek_time > total_time) + seek_time = total_time; + } + + try { + const PlayerControl::ScopeOccupied occupied(pc); + + dc.Seek(lock, song->GetStartTime() + seek_time); + } catch (...) { + /* decoder failure */ + pc.SetError(PlayerError::DECODER, std::current_exception()); + return false; + } + + elapsed_time = seek_time; + return true; +} + +inline bool +Player::SeekDecoder(std::unique_lock &lock) 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(); + + { + const ScopeUnlock unlock(pc.mutex); + pc.outputs.Cancel(); + } + + pc.listener.OnPlayerStateChanged(); + + if (!dc.IsSeekableCurrentSong(*pc.next_song)) { + /* the decoder is already decoding the "next" song - + stop it and start the previous song again */ + + StopDecoder(lock); + + /* clear music chunks which might still reside in the + pipe */ + pipe->Clear(); + + /* re-start the decoder */ + StartDecoder(lock, pipe, true); + ActivateDecoder(); + + pc.seeking = true; + pc.CommandFinished(); + + assert(xfade_state == CrossFadeState::UNKNOWN); + + return true; + } else { + if (!IsDecoderAtCurrentSong()) { + /* the decoder is already decoding the "next" song, + but it is the same song file; exchange the pipe */ + ReplacePipe(dc.pipe); + } + + pc.next_song.reset(); + queued = false; + + if (decoder_starting) { + /* wait for the decoder to complete + initialization; postpone the SEEK + command */ + + pending_seek = pc.seek_time; + pc.seeking = true; + pc.CommandFinished(); + return true; + } else { + /* send the SEEK command */ + + if (!SeekDecoder(lock, pc.seek_time)) { + pc.CommandFinished(); + return false; + } + } + } + + pc.CommandFinished(); + + assert(xfade_state == CrossFadeState::UNKNOWN); + + /* re-fill the buffer after seeking */ + buffering = true; + + { + /* call syncPlaylistWithQueue() in the main thread */ + const ScopeUnlock unlock(pc.mutex); + pc.listener.OnPlayerSync(); + } + + return true; +} + +inline bool +Player::ProcessCommand(std::unique_lock &lock) noexcept +{ + switch (pc.command) { + case PlayerCommand::NONE: + break; + + case PlayerCommand::STOP: + case PlayerCommand::EXIT: + case PlayerCommand::CLOSE_AUDIO: + return false; + + case PlayerCommand::UPDATE_AUDIO: + { + const ScopeUnlock unlock(pc.mutex); + pc.outputs.EnableDisable(); + } + + pc.CommandFinished(); + break; + + case PlayerCommand::QUEUE: + assert(pc.next_song != nullptr); + assert(!queued); + assert(!IsDecoderAtNextSong()); + + queued = true; + pc.CommandFinished(); + + if (!decoder_starting && dc.IsIdle()) + StartDecoder(lock, std::make_shared(), + false); + + break; + + case PlayerCommand::PAUSE: + paused = !paused; + if (paused) { + pc.state = PlayerState::PAUSE; + + const ScopeUnlock unlock(pc.mutex); + pc.outputs.Pause(); + } else if (!play_audio_format.IsDefined()) { + /* the decoder hasn't provided an audio format + yet - don't open the audio device yet */ + pc.state = PlayerState::PLAY; + } else { + OpenOutput(); + } + + pc.CommandFinished(); + break; + + case PlayerCommand::SEEK: + return SeekDecoder(lock); + + case PlayerCommand::CANCEL: + if (pc.next_song == nullptr) + /* the cancel request arrived too late, we're + already playing the queued song... stop + everything now */ + return false; + + if (IsDecoderAtNextSong()) + /* the decoder is already decoding the song - + stop it and reset the position */ + StopDecoder(lock); + + pc.next_song.reset(); + queued = false; + pc.CommandFinished(); + break; + + case PlayerCommand::REFRESH: + if (output_open && !paused) { + const ScopeUnlock unlock(pc.mutex); + pc.outputs.CheckPipe(); + } + + pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative() + ? SongTime(pc.outputs.GetElapsedTime()) + : elapsed_time; + + pc.CommandFinished(); + break; + } + + return true; +} + +inline void +Player::CheckCrossFade() noexcept +{ + if (xfade_state != CrossFadeState::UNKNOWN) + /* already decided */ + return; + + if (pc.border_pause) { + /* no cross-fading if MPD is going to pause at the end + of the current song */ + xfade_state = CrossFadeState::UNKNOWN; + return; + } + + if (!IsDecoderAtNextSong() || dc.IsStarting() || dc.pipe->IsEmpty()) + /* we need information about the next song before we + can decide */ + /* the "pipe.empty" check is here so we wait for all + (ReplayGain/MixRamp) metadata to appear, which some + decoders parse only after reporting readiness */ + return; + + if (!pc.cross_fade.CanCrossFade(pc.total_time, dc.total_time, + dc.out_audio_format, + play_audio_format)) { + /* cross fading is disabled or the next song is too + short */ + xfade_state = CrossFadeState::DISABLED; + return; + } + + if (!MixRampScannerReady()) + /* need more chunks for the MixRamp scanner */ + return; + + /* enable cross fading in this song? if yes, calculate how + many chunks will be required for it */ + cross_fade_chunks = + pc.cross_fade.Calculate(dc.replay_gain_db, + dc.replay_gain_prev_db, + dc.GetMixRampStart(), + dc.GetMixRampPreviousEnd(), + play_audio_format, + buffer.GetSize() - + buffer_before_play); + if (cross_fade_chunks > 0) + xfade_state = CrossFadeState::ENABLED; + else + // TODO: eliminate this "else" branch + xfade_state = CrossFadeState::DISABLED; +} + +inline void +PlayerControl::LockUpdateSongTag(DetachedSong &song, + const Tag &new_tag) noexcept +{ + if (song.IsFile()) + /* don't update tags of local files, only remote + streams may change tags dynamically */ + return; + + if (new_tag != song.GetTag()) { + song.SetTag(new_tag); + + LockSetTaggedSong(song); + + /* the main thread will update the playlist version when he + receives this event */ + listener.OnPlayerTagModified(); + } +} + +inline void +PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk, + const AudioFormat &format) +{ + assert(chunk->CheckFormat(format)); + + if (chunk->tag != nullptr) + LockUpdateSongTag(song, *chunk->tag); + + if (chunk->IsEmpty()) + return; + + { + const std::scoped_lock lock{mutex}; + bit_rate = chunk->bit_rate; + } + + /* send the chunk to the audio outputs */ + + const double chunk_length(chunk->length); + + outputs.Play(std::move(chunk)); + total_play_time += format.SizeToTime(chunk_length); +} + +inline bool +Player::PlayNextChunk() noexcept +{ + if (!pc.LockWaitOutputConsumed(64)) + /* the output pipe is still large enough, don't send + another chunk */ + return true; + + /* activate cross-fading? */ + if (xfade_state == CrossFadeState::ENABLED && + IsDecoderAtNextSong() && + pipe->GetSize() <= cross_fade_chunks) { + /* beginning of the cross fade - adjust + cross_fade_chunks which might be bigger than the + remaining number of chunks in the old song */ + cross_fade_chunks = pipe->GetSize(); + xfade_state = CrossFadeState::ACTIVE; + } + + MusicChunkPtr chunk; + if (xfade_state == CrossFadeState::ACTIVE) { + /* perform cross fade */ + + assert(IsDecoderAtNextSong()); + + unsigned cross_fade_position = pipe->GetSize(); + assert(cross_fade_position <= cross_fade_chunks); + + auto other_chunk = dc.pipe->Shift(); + if (other_chunk != nullptr) { + chunk = pipe->Shift(); + assert(chunk != nullptr); + assert(chunk->other == nullptr); + + /* don't send the tags of the new song (which + is being faded in) yet; postpone it until + the current song is faded out */ + cross_fade_tag = Tag::Merge(std::move(cross_fade_tag), + std::move(other_chunk->tag)); + + if (pc.cross_fade.mixramp_delay <= FloatDuration::zero()) { + chunk->mix_ratio = ((float)cross_fade_position) + / cross_fade_chunks; + } else { + chunk->mix_ratio = -1; + } + + if (other_chunk->IsEmpty()) { + /* the "other" chunk was a MusicChunk + which had only a tag, but no music + data - we cannot cross-fade that; + but since this happens only at the + beginning of the new song, we can + easily recover by throwing it away + now */ + other_chunk.reset(); + } + + chunk->other = std::move(other_chunk); + } else { + /* there are not enough decoded chunks yet */ + + std::unique_lock lock{pc.mutex}; + + if (dc.IsIdle()) { + /* the decoder isn't running, abort + cross fading */ + xfade_state = CrossFadeState::DISABLED; + } else { + /* wait for the decoder */ + dc.Signal(); + dc.WaitForDecoder(lock); + + return true; + } + } + } + + if (chunk == nullptr) + chunk = pipe->Shift(); + + assert(chunk != nullptr); + + /* insert the postponed tag if cross-fading is finished */ + + if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) { + chunk->tag = Tag::Merge(std::move(chunk->tag), + std::move(cross_fade_tag)); + cross_fade_tag = nullptr; + } + + /* play the current chunk */ + + try { + pc.PlayChunk(*song, std::move(chunk), + play_audio_format); + } catch (...) { + LogError(std::current_exception()); + + chunk.reset(); + + /* pause: the user may resume playback as soon as an + audio output becomes available */ + paused = true; + + pc.LockSetOutputError(std::current_exception()); + + return false; + } + + const std::scoped_lock lock{pc.mutex}; + + /* this formula should prevent that the decoder gets woken up + with each chunk; it is more efficient to make it decode a + larger block at a time */ + if (!dc.IsIdle() && dc.pipe->GetSize() <= decoder_wakeup_threshold) { + if (!decoder_woken) { + decoder_woken = true; + dc.Signal(); + } + } else + decoder_woken = false; + + return true; +} + +inline void +Player::SongBorder() noexcept +{ + { + const ScopeUnlock unlock(pc.mutex); + + FmtNotice(player_domain, "played {:?}", song->GetURI()); + + ReplacePipe(dc.pipe); + + pc.outputs.SongBorder(); + } + + ActivateDecoder(); + + const bool border_pause = pc.ApplyBorderPause(); + if (border_pause) { + const ScopeUnlock unlock(pc.mutex); + + paused = true; + + pc.listener.OnBorderPause(); + + /* drain all outputs to guarantee the current song is + really being played to the end; without this, the + Pause() call would drop all ring buffers */ + pc.outputs.Drain(); + + pc.outputs.Pause(); + pc.listener.OnPlayerStateChanged(); + } +} + +inline void +Player::Run() noexcept +{ + pipe = std::make_shared(); + + std::unique_lock lock{pc.mutex}; + + StartDecoder(lock, pipe, true); + ActivateDecoder(); + + pc.state = PlayerState::PLAY; + + pc.CommandFinished(); + + while (ProcessCommand(lock)) { + if (decoder_starting) { + /* wait until the decoder is initialized completely */ + + if (!CheckDecoderStartup(lock)) + break; + + continue; + } + + if (buffering) { + /* buffering at the start of the song - wait + until the buffer is large enough, to + prevent stuttering on slow machines */ + + if (pipe->GetSize() < buffer_before_play && + !dc.IsIdle() && !buffer.IsFull()) { + /* not enough decoded buffer space yet */ + + dc.WaitForDecoder(lock); + continue; + } else { + /* buffering is complete */ + buffering = false; + } + } + + if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) { + /* the decoder has finished the current song; + make it decode the next song */ + + assert(dc.pipe == nullptr || dc.pipe == pipe); + + StartDecoder(lock, std::make_shared(), + false); + } + + CheckCrossFade(); + + if (paused) { + if (pc.command == PlayerCommand::NONE) + pc.Wait(lock); + } else if (!pipe->IsEmpty()) { + /* at least one music chunk is ready - send it + to the audio output */ + + const ScopeUnlock unlock(pc.mutex); + PlayNextChunk(); + } else if (UnlockCheckOutputs() > 0) { + /* not enough data from decoder, but the + output thread is still busy, so it's + okay */ + + /* wake up the decoder (just in case it's + waiting for space in the MusicBuffer) and + wait for it */ + // TODO: eliminate this kludge + dc.Signal(); + + dc.WaitForDecoder(lock); + } else if (IsDecoderAtNextSong()) { + /* at the beginning of a new song */ + + 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 */ + if (pipe->IsEmpty()) { + /* wait for the hardware to finish + playback */ + const ScopeUnlock unlock(pc.mutex); + pc.outputs.Drain(); + break; + } + } else if (output_open) { + /* the decoder is too busy and hasn't provided + new PCM data in time: wait for the + decoder */ + + /* wake up the decoder (just in case it's + waiting for space in the MusicBuffer) and + wait for it */ + // TODO: eliminate this kludge + dc.Signal(); + + dc.WaitForDecoder(lock); + } + } + + CancelPendingSeek(); + StopDecoder(lock); + + pipe.reset(); + + cross_fade_tag.reset(); + + if (song != nullptr) { + FmtNotice(player_domain, "played {:?}", song->GetURI()); + song.reset(); + } + + pc.ClearTaggedSong(); + + if (queued) { + assert(pc.next_song != nullptr); + pc.next_song.reset(); + } + + pc.state = PlayerState::STOP; +} + +static void +do_play(PlayerControl &pc, DecoderControl &dc, + MusicBuffer &buffer) noexcept +{ + Player player(pc, dc, buffer); + player.Run(); +} + +void +PlayerControl::RunThread() noexcept +try { + SetThreadName("player"); + + DecoderControl dc(mutex, cond, + input_cache, + config.audio_format, + config.replay_gain); + dc.StartThread(); + + MusicBuffer buffer{config.buffer_chunks}; + + std::unique_lock lock{mutex}; + + while (true) { + switch (command) { + case PlayerCommand::SEEK: + case PlayerCommand::QUEUE: + assert(next_song != nullptr); + + { + const ScopeUnlock unlock(mutex); + do_play(*this, dc, buffer); + + /* give the main thread a chance to + queue another song, just in case + we've stopped playback + spuriously */ + listener.OnPlayerSync(); + } + + break; + + case PlayerCommand::STOP: + { + const ScopeUnlock unlock(mutex); + outputs.Cancel(); + } + + /* fall through */ + [[fallthrough]]; + + case PlayerCommand::PAUSE: + next_song.reset(); + + CommandFinished(); + break; + + case PlayerCommand::CLOSE_AUDIO: + { + const ScopeUnlock unlock(mutex); + outputs.Release(); + } + + CommandFinished(); + + assert(buffer.IsEmptyUnsafe()); + + break; + + case PlayerCommand::UPDATE_AUDIO: + { + const ScopeUnlock unlock(mutex); + outputs.EnableDisable(); + } + + CommandFinished(); + break; + + case PlayerCommand::EXIT: + { + const ScopeUnlock unlock(mutex); + dc.Quit(); + outputs.Close(); + } + + CommandFinished(); + return; + + case PlayerCommand::CANCEL: + next_song.reset(); + + CommandFinished(); + break; + + case PlayerCommand::REFRESH: + /* no-op when not playing */ + CommandFinished(); + break; + + case PlayerCommand::NONE: + Wait(lock); + break; + } + } +} catch (...) { + /* exceptions caught here are thrown during initialization; + the main loop doesn't throw */ + + LogError(std::current_exception()); + + /* TODO: what now? How will the main thread learn about this + failure? */ +} diff --git a/src/playlist/Length.cxx b/src/playlist/Length.cxx new file mode 100644 index 0000000..e16bc10 --- /dev/null +++ b/src/playlist/Length.cxx @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LocateUri.hxx" +#include "Length.hxx" +#include "PlaylistAny.hxx" +#include "PlaylistSong.hxx" +#include "SongEnumerator.hxx" +#include "SongPrint.hxx" +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" +#include "db/Features.hxx" // for ENABLE_DATABASE +#include "input/Error.hxx" +#include "fs/Traits.hxx" +#include "thread/Mutex.hxx" +#include "Partition.hxx" +#include "Instance.hxx" +#include "PlaylistError.hxx" + +#include + +static SignedSongTime get_duration(const DetachedSong &song) { + const auto duration = song.GetDuration(); + return duration.IsNegative() ? (SignedSongTime)0 : duration; +} + +static void +playlist_provider_length(Response &r, + const SongLoader &loader, + const char *uri, + SongEnumerator &e) noexcept +{ + const auto base_uri = uri != nullptr + ? PathTraitsUTF8::GetParent(uri) + : "."; + + std::unique_ptr song; + unsigned i = 0; + std::chrono::milliseconds playtime = (std::chrono::milliseconds)0; + while ((song = e.NextSong()) != nullptr) { + if (playlist_check_translate_song(*song, base_uri, + loader)) + playtime += get_duration(*song); + i++; + } + r.Fmt("songs: {}\n", i); + const auto seconds = std::chrono::round(playtime); + r.Fmt("playtime: {}\n", seconds.count()); +} + +void +playlist_file_length(Response &r, Partition &partition, + const SongLoader &loader, + const LocatedUri &uri) +try { + Mutex mutex; + +#ifndef ENABLE_DATABASE + (void)partition; +#endif + + auto playlist = playlist_open_any(uri, +#ifdef ENABLE_DATABASE + partition.instance.storage, +#endif + mutex); + if (playlist == nullptr) + throw PlaylistError::NoSuchList(); + + playlist_provider_length(r, loader, uri.canonical_uri, *playlist); +} catch (...) { + if (IsFileNotFound(std::current_exception())) + throw PlaylistError::NoSuchList(); + + throw; +} diff --git a/src/playlist/Length.hxx b/src/playlist/Length.hxx new file mode 100644 index 0000000..2245139 --- /dev/null +++ b/src/playlist/Length.hxx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "client/Response.hxx" + +class SongLoader; +struct Partition; + +/** + * Count the number of songs and their total playtime (seconds) in the + * playlist. + * + * Throws on error. + * + * @param uri the URI of the playlist file in UTF-8 encoding + * @return true on success, false if the playlist does not exist + */ +void +playlist_file_length(Response &r, Partition &partition, + const SongLoader &loader, + const LocatedUri &uri); diff --git a/src/playlist/MemorySongEnumerator.cxx b/src/playlist/MemorySongEnumerator.cxx new file mode 100644 index 0000000..789f365 --- /dev/null +++ b/src/playlist/MemorySongEnumerator.cxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "MemorySongEnumerator.hxx" + +std::unique_ptr +MemorySongEnumerator::NextSong() +{ + if (songs.empty()) + return nullptr; + + auto result = std::make_unique(std::move(songs.front())); + songs.pop_front(); + return result; +} diff --git a/src/playlist/MemorySongEnumerator.hxx b/src/playlist/MemorySongEnumerator.hxx new file mode 100644 index 0000000..c9c370a --- /dev/null +++ b/src/playlist/MemorySongEnumerator.hxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_MEMORY_PLAYLIST_PROVIDER_HXX +#define MPD_MEMORY_PLAYLIST_PROVIDER_HXX + +#include "SongEnumerator.hxx" +#include "song/DetachedSong.hxx" + +#include + +class MemorySongEnumerator final : public SongEnumerator { + std::forward_list songs; + +public: + MemorySongEnumerator(std::forward_list &&_songs) + :songs(std::move(_songs)) {} + + std::unique_ptr NextSong() override; +}; + +#endif diff --git a/src/playlist/PlaylistAny.cxx b/src/playlist/PlaylistAny.cxx new file mode 100644 index 0000000..1652050 --- /dev/null +++ b/src/playlist/PlaylistAny.cxx @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LocateUri.hxx" +#include "PlaylistAny.hxx" +#include "PlaylistStream.hxx" +#include "PlaylistMapper.hxx" +#include "SongEnumerator.hxx" + +#include // for std::unreachable() + +std::unique_ptr +playlist_open_any(const LocatedUri &located_uri, +#ifdef ENABLE_DATABASE + Storage *storage, +#endif + Mutex &mutex) +{ + switch (located_uri.type) { + case LocatedUri::Type::ABSOLUTE: + return playlist_open_remote(located_uri.canonical_uri, mutex); + + case LocatedUri::Type::PATH: + return playlist_open_path(located_uri.path, mutex); + + case LocatedUri::Type::RELATIVE: + return playlist_mapper_open(located_uri.canonical_uri, +#ifdef ENABLE_DATABASE + storage, +#endif + mutex); + } + + std::unreachable(); +} diff --git a/src/playlist/PlaylistAny.hxx b/src/playlist/PlaylistAny.hxx new file mode 100644 index 0000000..9c11a17 --- /dev/null +++ b/src/playlist/PlaylistAny.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "thread/Mutex.hxx" +#include "config.h" + +#include + +class SongEnumerator; +class Storage; + +/** + * Opens a playlist from the specified URI, which can be either an + * absolute remote URI (with a scheme) or a relative path to the + * music or playlist directory. + * + * Throws on error. + * + * @return a playlist, or nullptr if the file is not supported + */ +std::unique_ptr +playlist_open_any(const LocatedUri &located_uri, +#ifdef ENABLE_DATABASE + Storage *storage, +#endif + Mutex &mutex); diff --git a/src/playlist/PlaylistMapper.cxx b/src/playlist/PlaylistMapper.cxx new file mode 100644 index 0000000..6abf657 --- /dev/null +++ b/src/playlist/PlaylistMapper.cxx @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistMapper.hxx" +#include "PlaylistFile.hxx" +#include "PlaylistRegistry.hxx" +#include "PlaylistStream.hxx" +#include "SongEnumerator.hxx" +#include "Mapper.hxx" +#include "input/InputStream.hxx" +#include "input/WaitReady.hxx" +#include "fs/AllocatedPath.hxx" +#include "storage/StorageInterface.hxx" +#include "util/UriUtil.hxx" + +#include +#include // for std::exception_ptr + +/** + * Load a playlist from the configured playlist directory. + */ +static std::unique_ptr +playlist_open_in_playlist_dir(const char *uri, Mutex &mutex) +{ + assert(spl_valid_name(uri)); + + const auto path_fs = map_spl_utf8_to_fs(uri); + if (path_fs.IsNull()) + return nullptr; + + return playlist_open_path(path_fs, mutex); +} + +#ifdef ENABLE_DATABASE + +/** + * Load a playlist from the configured music directory. + */ +static std::unique_ptr +playlist_open_in_storage(const char *uri, Storage *storage, Mutex &mutex) +{ + assert(uri_safe_local(uri)); + + if (storage == nullptr) + return nullptr; + + if (const auto path = storage->MapFS(uri); !path.IsNull()) + return playlist_open_path(path, mutex); + + auto is = storage->OpenFile(uri, mutex); + LockWaitReady(*is); + return playlist_list_open_stream(std::move(is), uri); +} + +#endif + +std::unique_ptr +playlist_mapper_open(const char *uri, +#ifdef ENABLE_DATABASE + Storage *storage, +#endif + Mutex &mutex) +{ + std::exception_ptr spl_error; + + if (spl_valid_name(uri)) { + try { + auto playlist = playlist_open_in_playlist_dir(uri, mutex); + if (playlist != nullptr) + return playlist; + } catch (...) { + /* postpone this exception, try playlist in + music_directory first */ + spl_error = std::current_exception(); + } + } + +#ifdef ENABLE_DATABASE + if (uri_safe_local(uri)) { + auto playlist = playlist_open_in_storage(uri, storage, mutex); + if (playlist != nullptr) + return playlist; + } +#endif + + if (spl_error) + std::rethrow_exception(spl_error); + + return nullptr; +} diff --git a/src/playlist/PlaylistMapper.hxx b/src/playlist/PlaylistMapper.hxx new file mode 100644 index 0000000..6fbd0de --- /dev/null +++ b/src/playlist/PlaylistMapper.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "db/Features.hxx" // for ENABLE_DATABASE +#include "thread/Mutex.hxx" + +#include + +class SongEnumerator; +class Storage; + +/** + * Opens a playlist from an URI relative to the playlist or music + * directory. + * + * Throws on error. + * + * @return a playlist, or nullptr if the file is not supported + */ +std::unique_ptr +playlist_mapper_open(const char *uri, +#ifdef ENABLE_DATABASE + Storage *storage, +#endif + Mutex &mutex); diff --git a/src/playlist/PlaylistPlugin.cxx b/src/playlist/PlaylistPlugin.cxx new file mode 100644 index 0000000..fec88c2 --- /dev/null +++ b/src/playlist/PlaylistPlugin.cxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistPlugin.hxx" +#include "util/StringUtil.hxx" + +bool +PlaylistPlugin::SupportsScheme(std::string_view scheme) const noexcept +{ + return schemes != nullptr && + StringArrayContainsCase(schemes, scheme); +} + +bool +PlaylistPlugin::SupportsSuffix(std::string_view suffix) const noexcept +{ + return suffixes != nullptr && + StringArrayContainsCase(suffixes, suffix); +} + +bool +PlaylistPlugin::SupportsMimeType(std::string_view mime_type) const noexcept +{ + return mime_types != nullptr && + StringArrayContainsCase(mime_types, mime_type); +} diff --git a/src/playlist/PlaylistPlugin.hxx b/src/playlist/PlaylistPlugin.hxx new file mode 100644 index 0000000..916cc2f --- /dev/null +++ b/src/playlist/PlaylistPlugin.hxx @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "input/Ptr.hxx" +#include "thread/Mutex.hxx" + +#include + +struct ConfigBlock; +struct Tag; +class SongEnumerator; + +struct PlaylistPlugin { + const char *name; + + /** + * Initialize the plugin. Optional method. + * + * @param block a configuration block for this plugin (may be + * empty if none is configured) + * @return true if the plugin was initialized successfully, + * false if the plugin is not available + */ + bool (*init)(const ConfigBlock &block) = nullptr; + + /** + * Deinitialize a plugin which was initialized successfully. + * Optional method. + */ + void (*finish)() noexcept = nullptr; + + /** + * Opens the playlist on the specified URI. This URI has + * either matched one of the schemes or one of the suffixes. + */ + std::unique_ptr (*open_uri)(const char *uri, + Mutex &mutex) = nullptr; + + /** + * Opens the playlist in the specified input stream. It has + * either matched one of the suffixes or one of the MIME + * types. + * + * @parm is the input stream; the pointer will not be + * invalidated when the function returns nullptr + */ + std::unique_ptr (*open_stream)(InputStreamPtr &&is) = nullptr; + + const char *const*schemes = nullptr; + const char *const*suffixes = nullptr; + const char *const*mime_types = nullptr; + + /** + * If true, then playlists of this type are shown in the + * database as folders. + */ + bool as_folder = false; + + constexpr PlaylistPlugin(const char *_name, + std::unique_ptr (*_open_uri)(const char *uri, + Mutex &mutex)) noexcept + :name(_name), open_uri(_open_uri) {} + + constexpr PlaylistPlugin(const char *_name, + std::unique_ptr (*_open_stream)(InputStreamPtr &&is)) noexcept + :name(_name), open_stream(_open_stream) {} + + constexpr auto WithInit(bool (*_init)(const ConfigBlock &block), + void (*_finish)() noexcept = nullptr) const noexcept { + auto copy = *this; + copy.init = _init; + copy.finish = _finish; + return copy; + } + + constexpr auto WithSchemes(const char *const*_schemes) const noexcept { + auto copy = *this; + copy.schemes = _schemes; + return copy; + } + + constexpr auto WithSuffixes(const char *const*_suffixes) const noexcept { + auto copy = *this; + copy.suffixes = _suffixes; + return copy; + } + + constexpr auto WithMimeTypes(const char *const*_mime_types) const noexcept { + auto copy = *this; + copy.mime_types = _mime_types; + return copy; + } + + constexpr auto WithAsFolder(bool value=true) const noexcept { + auto copy = *this; + copy.as_folder = value; + return copy; + } + + /** + * Does the plugin announce the specified URI scheme? + */ + [[gnu::pure]] + bool SupportsScheme(std::string_view scheme) const noexcept; + + /** + * Does the plugin announce the specified file name suffix? + */ + [[gnu::pure]] + bool SupportsSuffix(std::string_view suffix) const noexcept; + + /** + * Does the plugin announce the specified MIME type? + */ + [[gnu::pure]] + bool SupportsMimeType(std::string_view mime_type) const noexcept; + + /** + * Initialize the plugin. + * + * @param block a configuration block for this plugin, or nullptr if none + * is configured + * @return true if the plugin was initialized successfully, false if + * the plugin is not available + */ + bool Init(const ConfigBlock &block) const { + return init != nullptr + ? init(block) + : true; + } + + /** + * Deinitialize the plugin which was initialized successfully. + */ + void Finish() const noexcept { + if (finish != nullptr) + finish(); + } +}; diff --git a/src/playlist/PlaylistQueue.cxx b/src/playlist/PlaylistQueue.cxx new file mode 100644 index 0000000..5cc0088 --- /dev/null +++ b/src/playlist/PlaylistQueue.cxx @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LocateUri.hxx" +#include "PlaylistQueue.hxx" +#include "PlaylistAny.hxx" +#include "PlaylistSong.hxx" +#include "PlaylistError.hxx" +#include "queue/Playlist.hxx" +#include "SongEnumerator.hxx" +#include "song/DetachedSong.hxx" +#include "input/Error.hxx" +#include "thread/Mutex.hxx" +#include "fs/Traits.hxx" +#include "Log.hxx" + +#include "db/Features.hxx" // for ENABLE_DATABASE +#ifdef ENABLE_DATABASE +#include "SongLoader.hxx" +#endif + +#include + +void +playlist_load_into_queue(const char *uri, SongEnumerator &e, + unsigned start_index, unsigned end_index, + playlist &dest, PlayerControl &pc, + const SongLoader &loader) +{ + const unsigned max_log_msgs = 8; + + const auto base_uri = uri != nullptr + ? PathTraitsUTF8::GetParent(uri) + : "."; + + std::unique_ptr song; + for (unsigned i = 0, failures = 0; + i < end_index && (song = e.NextSong()) != nullptr; + ++i) { + if (i < start_index) { + /* skip songs before the start index */ + continue; + } + + if (!playlist_check_translate_song(*song, base_uri, + loader)) { + failures += 1; + if (failures < max_log_msgs) { + FmtError(playlist_domain, "Failed to load {:?}.", song->GetURI()); + } else if (failures == max_log_msgs) { + LogError(playlist_domain, "Further errors for this playlist will not be logged."); + } + continue; + } + + dest.AppendSong(pc, std::move(*song)); + } + dest.SetLastLoadedPlaylist(uri); +} + +void +playlist_open_into_queue(const LocatedUri &uri, + unsigned start_index, unsigned end_index, + playlist &dest, PlayerControl &pc, + const SongLoader &loader) +try { + Mutex mutex; + + auto playlist = playlist_open_any(uri, +#ifdef ENABLE_DATABASE + loader.GetStorage(), +#endif + mutex); + if (playlist == nullptr) + throw PlaylistError::NoSuchList(); + + playlist_load_into_queue(uri.canonical_uri, *playlist, + start_index, end_index, + dest, pc, loader); +} catch (...) { + if (IsFileNotFound(std::current_exception())) + throw PlaylistError::NoSuchList(); + + throw; +} diff --git a/src/playlist/PlaylistQueue.hxx b/src/playlist/PlaylistQueue.hxx new file mode 100644 index 0000000..e815001 --- /dev/null +++ b/src/playlist/PlaylistQueue.hxx @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +/*! \file + * \brief Glue between playlist plugin and the play queue + */ + +class SongLoader; +class SongEnumerator; +struct playlist; +class PlayerControl; + +/** + * Loads the contents of a playlist and append it to the specified + * play queue. + * + * @param uri the URI of the playlist, used to resolve relative song + * URIs + * @param start_index the index of the first song + * @param end_index the index of the last song (excluding) + */ +void +playlist_load_into_queue(const char *uri, SongEnumerator &e, + unsigned start_index, unsigned end_index, + playlist &dest, PlayerControl &pc, + const SongLoader &loader); + +/** + * Opens a playlist with a playlist plugin and append to the specified + * play queue. + * + * Throws on error. + */ +void +playlist_open_into_queue(const LocatedUri &uri, + unsigned start_index, unsigned end_index, + playlist &dest, PlayerControl &pc, + const SongLoader &loader); diff --git a/src/playlist/PlaylistRegistry.cxx b/src/playlist/PlaylistRegistry.cxx new file mode 100644 index 0000000..19d28ba --- /dev/null +++ b/src/playlist/PlaylistRegistry.cxx @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "PlaylistRegistry.hxx" +#include "PlaylistPlugin.hxx" +#include "SongEnumerator.hxx" +#include "playlist/Features.h" +#include "plugins/ExtM3uPlaylistPlugin.hxx" +#include "plugins/M3uPlaylistPlugin.hxx" +#include "plugins/XspfPlaylistPlugin.hxx" +#include "plugins/PlsPlaylistPlugin.hxx" +#include "plugins/AsxPlaylistPlugin.hxx" +#include "plugins/RssPlaylistPlugin.hxx" +#include "plugins/FlacPlaylistPlugin.hxx" +#include "plugins/CuePlaylistPlugin.hxx" +#include "plugins/EmbeddedCuePlaylistPlugin.hxx" +#include "decoder/Features.h" +#include "input/InputStream.hxx" +#include "util/FilteredContainer.hxx" +#include "util/MimeType.hxx" +#include "util/UriExtract.hxx" +#include "config/Data.hxx" +#include "config/Block.hxx" + +#include +#include + +constinit const PlaylistPlugin *const playlist_plugins[] = { + &extm3u_playlist_plugin, + &m3u_playlist_plugin, + &pls_playlist_plugin, +#ifdef ENABLE_EXPAT + &xspf_playlist_plugin, + &asx_playlist_plugin, + &rss_playlist_plugin, +#endif +#ifdef ENABLE_FLAC + &flac_playlist_plugin, +#endif +#ifdef ENABLE_CUE + &cue_playlist_plugin, + &embcue_playlist_plugin, +#endif + nullptr +}; + +static constexpr unsigned n_playlist_plugins = + std::size(playlist_plugins) - 1; + +/** which plugins have been initialized successfully? */ +static bool playlist_plugins_enabled[n_playlist_plugins]; + +/** which plugins have the "as_folder" option enabled? */ +static bool playlist_plugins_as_folder[n_playlist_plugins]; + +static inline auto +GetEnabledPlaylistPlugins() noexcept +{ + const auto all = GetAllPlaylistPlugins(); + return FilteredContainer{all.begin(), all.end(), playlist_plugins_enabled}; +} + +void +playlist_list_global_init(const ConfigData &config) +{ + const ConfigBlock empty; + + for (unsigned i = 0; playlist_plugins[i] != nullptr; ++i) { + const auto *plugin = playlist_plugins[i]; + const auto *param = + config.FindBlock(ConfigBlockOption::PLAYLIST_PLUGIN, + "name", plugin->name); + if (param == nullptr) + param = ∅ + else if (!param->GetBlockValue("enabled", true)) + /* the plugin is disabled in mpd.conf */ + continue; + + if (param != nullptr) + param->SetUsed(); + + playlist_plugins_enabled[i] = playlist_plugins[i]->Init(*param); + + playlist_plugins_as_folder[i] = + param->GetBlockValue("as_directory", + playlist_plugins[i]->as_folder); + } +} + +void +playlist_list_global_finish() noexcept +{ + for (const auto &plugin : GetEnabledPlaylistPlugins()) { + plugin.Finish(); + } +} + +bool +GetPlaylistPluginAsFolder(const PlaylistPlugin &plugin) noexcept +{ + /* this loop has no end condition because it must finish when + the plugin was found */ + for (std::size_t i = 0;; ++i) + if (playlist_plugins[i] == &plugin) + return playlist_plugins_as_folder[i]; +} + +static std::unique_ptr +playlist_list_open_uri_scheme(const char *uri, Mutex &mutex, + bool *tried) +{ + assert(uri != nullptr); + + const auto scheme = uri_get_scheme(uri); + if (scheme.empty()) + return nullptr; + + for (unsigned i = 0; playlist_plugins[i] != nullptr; ++i) { + const auto *plugin = playlist_plugins[i]; + + assert(!tried[i]); + + if (playlist_plugins_enabled[i] && plugin->open_uri != nullptr && + plugin->SupportsScheme(scheme)) { + auto playlist = plugin->open_uri(uri, mutex); + if (playlist) + return playlist; + + tried[i] = true; + } + } + + return nullptr; +} + +static std::unique_ptr +playlist_list_open_uri_suffix(const char *uri, Mutex &mutex, + const bool *tried) +{ + assert(uri != nullptr); + + const auto suffix = uri_get_suffix(uri); + if (suffix.empty()) + return nullptr; + + for (unsigned i = 0; playlist_plugins[i] != nullptr; ++i) { + const auto *plugin = playlist_plugins[i]; + + if (playlist_plugins_enabled[i] && !tried[i] && + plugin->open_uri != nullptr && + plugin->SupportsSuffix(suffix)) { + auto playlist = plugin->open_uri(uri, mutex); + if (playlist != nullptr) + return playlist; + } + } + + return nullptr; +} + +std::unique_ptr +playlist_list_open_uri(const char *uri, Mutex &mutex) +{ + /** this array tracks which plugins have already been tried by + playlist_list_open_uri_scheme() */ + bool tried[n_playlist_plugins]{}; + + assert(uri != nullptr); + + auto playlist = playlist_list_open_uri_scheme(uri, mutex, tried); + if (playlist == nullptr) + playlist = playlist_list_open_uri_suffix(uri, mutex, + tried); + + return playlist; +} + +static std::unique_ptr +playlist_list_open_stream_mime2(InputStreamPtr &&is, std::string_view mime) +{ + for (const auto &plugin : GetEnabledPlaylistPlugins()) { + if (plugin.open_stream != nullptr && + plugin.SupportsMimeType(mime)) { + /* rewind the stream, so each plugin gets a + fresh start */ + try { + is->LockRewind(); + } catch (...) { + } + + auto playlist = plugin.open_stream(std::move(is)); + if (playlist != nullptr) + return playlist; + } + } + + return nullptr; +} + +static std::unique_ptr +playlist_list_open_stream_mime(InputStreamPtr &&is, std::string_view mime) +{ + /* probe only the portion before the semicolon*/ + return playlist_list_open_stream_mime2(std::move(is), + mime); +} + +std::unique_ptr +playlist_list_open_stream_suffix(InputStreamPtr &&is, std::string_view suffix) +{ + for (const auto &plugin : GetEnabledPlaylistPlugins()) { + if (plugin.open_stream != nullptr && + plugin.SupportsSuffix(suffix)) { + /* rewind the stream, so each plugin gets a + fresh start */ + try { + is->LockRewind(); + } catch (...) { + } + + auto playlist = plugin.open_stream(std::move(is)); + if (playlist != nullptr) + return playlist; + } + } + + return nullptr; +} + +std::unique_ptr +playlist_list_open_stream(InputStreamPtr &&is, const char *uri) +{ + assert(is->IsReady()); + + const char *const mime = is->GetMimeType(); + if (mime != nullptr) { + auto playlist = playlist_list_open_stream_mime(std::move(is), + GetMimeTypeBase(mime)); + if (playlist != nullptr) + return playlist; + } + + if (uri != nullptr) { + const auto suffix = uri_get_suffix(uri); + if (!suffix.empty()) { + auto playlist = playlist_list_open_stream_suffix(std::move(is), + suffix); + if (playlist != nullptr) + return playlist; + } + } + + return nullptr; +} + +const PlaylistPlugin * +FindPlaylistPluginBySuffix(std::string_view suffix) noexcept +{ + for (const auto &plugin : GetEnabledPlaylistPlugins()) { + if (plugin.SupportsSuffix(suffix)) + return &plugin; + } + + return nullptr; +} diff --git a/src/playlist/PlaylistRegistry.hxx b/src/playlist/PlaylistRegistry.hxx new file mode 100644 index 0000000..2ad66a5 --- /dev/null +++ b/src/playlist/PlaylistRegistry.hxx @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "input/Ptr.hxx" +#include "thread/Mutex.hxx" +#include "util/DereferenceIterator.hxx" +#include "util/TerminatedArray.hxx" + +#include + +struct ConfigData; +struct PlaylistPlugin; +class SongEnumerator; + +extern const PlaylistPlugin *const playlist_plugins[]; + +static inline auto +GetAllPlaylistPlugins() noexcept +{ + return DereferenceContainerAdapter{TerminatedArray{playlist_plugins}}; +} + +/** + * Initializes all playlist plugins. + */ +void +playlist_list_global_init(const ConfigData &config); + +/** + * Deinitializes all playlist plugins. + */ +void +playlist_list_global_finish() noexcept; + +class ScopePlaylistPluginsInit { +public: + explicit ScopePlaylistPluginsInit(const ConfigData &config) { + playlist_list_global_init(config); + } + + ~ScopePlaylistPluginsInit() noexcept { + playlist_list_global_finish(); + } +}; + +/** + * Shall this playlists supported by this plugin be represented as + * directories in the database? + */ +[[gnu::const]] +bool +GetPlaylistPluginAsFolder(const PlaylistPlugin &plugin) noexcept; + +/** + * Opens a playlist by its URI. + */ +std::unique_ptr +playlist_list_open_uri(const char *uri, Mutex &mutex); + +std::unique_ptr +playlist_list_open_stream_suffix(InputStreamPtr &&is, std::string_view suffix); + +/** + * Opens a playlist from an input stream. + * + * @param is an #InputStream object which is open and ready + * @param uri optional URI which was used to open the stream; may be + * used to select the appropriate playlist plugin + */ +std::unique_ptr +playlist_list_open_stream(InputStreamPtr &&is, const char *uri); + +[[gnu::pure]] +const PlaylistPlugin * +FindPlaylistPluginBySuffix(std::string_view suffix) noexcept; + +/** + * Determines if there is a playlist plugin which can handle the + * specified file name suffix. + */ +[[gnu::pure]] +inline bool +playlist_suffix_supported(std::string_view suffix) noexcept +{ + return FindPlaylistPluginBySuffix(suffix) != nullptr; +} diff --git a/src/playlist/PlaylistSong.cxx b/src/playlist/PlaylistSong.cxx new file mode 100644 index 0000000..96fae4e --- /dev/null +++ b/src/playlist/PlaylistSong.cxx @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistSong.hxx" +#include "SongLoader.hxx" +#include "tag/Tag.hxx" +#include "tag/Builder.hxx" +#include "fs/Traits.hxx" +#include "song/DetachedSong.hxx" +#include "util/UriExtract.hxx" +#include "util/UriUtil.hxx" + +#include +#include + +#include + +static void +merge_song_metadata(DetachedSong &add, const DetachedSong &base) noexcept +{ + if (base.GetTag().IsDefined()) { + TagBuilder builder(add.GetTag()); + builder.Complement(base.GetTag()); + add.SetTag(builder.Commit()); + } + + add.SetLastModified(base.GetLastModified()); + add.SetAdded(base.GetAdded()); + + if (add.GetStartTime().IsZero()) { + add.SetStartTime(base.GetStartTime()); + } + if (add.GetEndTime().IsZero()) { + add.SetEndTime(base.GetEndTime()); + } + + if (!add.GetAudioFormat().IsDefined()) + add.SetAudioFormat(base.GetAudioFormat()); +} + +static bool +playlist_check_load_song(DetachedSong &song, const SongLoader &loader) noexcept +try { + DetachedSong tmp = loader.LoadSong(song.GetURI()); + + song.SetURI(tmp.GetURI()); + if (!song.HasRealURI() && tmp.HasRealURI()) + song.SetRealURI(tmp.GetRealURI()); + + merge_song_metadata(song, tmp); + return true; +} catch (...) { + return false; +} + +bool +playlist_check_translate_song(DetachedSong &song, std::string_view base_uri, + const SongLoader &loader) noexcept +{ + if (base_uri.compare(".") == 0) + /* PathTraitsUTF8::GetParent() returns "." when there + is no directory name in the given path; clear that + now, because it would break the database lookup + functions */ + base_uri = {}; + + const char *uri = song.GetURI(); + +#ifdef _WIN32 + if (!PathTraitsUTF8::IsAbsolute(uri) && std::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.data() != nullptr && + !PathTraitsUTF8::IsAbsoluteOrHasScheme(uri)) { + song.SetURI(PathTraitsUTF8::Build(base_uri, uri)); + uri = song.GetURI(); + } + + /* Remove dot segments */ + std::string new_uri = uri_squash_dot_segments(uri); + song.SetURI(std::move(new_uri)); + + return playlist_check_load_song(song, loader); +} diff --git a/src/playlist/PlaylistSong.hxx b/src/playlist/PlaylistSong.hxx new file mode 100644 index 0000000..62c33d2 --- /dev/null +++ b/src/playlist/PlaylistSong.hxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PLAYLIST_SONG_HXX +#define MPD_PLAYLIST_SONG_HXX + +#include + +class SongLoader; +class DetachedSong; + +/** + * Verifies the song, returns false if it is unsafe. Translate the + * song to a song within the database, if it is a local file. + * + * @return true on success, false if the song should not be used + */ +bool +playlist_check_translate_song(DetachedSong &song, std::string_view base_uri, + const SongLoader &loader) noexcept; + +#endif diff --git a/src/playlist/PlaylistStream.cxx b/src/playlist/PlaylistStream.cxx new file mode 100644 index 0000000..5db8b9a --- /dev/null +++ b/src/playlist/PlaylistStream.cxx @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistStream.hxx" +#include "PlaylistRegistry.hxx" +#include "SongEnumerator.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "fs/Path.hxx" +#include "util/UriExtract.hxx" + +#include +#include + +static std::unique_ptr +playlist_open_path_suffix(Path path, Mutex &mutex) +{ + assert(!path.IsNull()); + + const auto *suffix = path.GetExtension(); + if (suffix == nullptr) + return nullptr; + + const auto suffix_utf8 = Path::FromFS(suffix).ToUTF8Throw(); + if (!playlist_suffix_supported(suffix_utf8)) + return nullptr; + + auto is = OpenLocalInputStream(path, mutex); + return playlist_list_open_stream_suffix(std::move(is), + suffix_utf8); +} + +std::unique_ptr +playlist_open_path(Path path, Mutex &mutex) +{ + assert(!path.IsNull()); + + const std::string uri_utf8 = path.ToUTF8Throw(); + auto playlist = playlist_list_open_uri(uri_utf8.c_str(), mutex); + if (playlist == nullptr) + playlist = playlist_open_path_suffix(path, mutex); + + return playlist; +} + +std::unique_ptr +playlist_open_remote(const char *uri, Mutex &mutex) +{ + assert(uri_has_scheme(uri)); + + auto playlist = playlist_list_open_uri(uri, mutex); + if (playlist != nullptr) + return playlist; + + auto is = InputStream::OpenReady(uri, mutex); + return playlist_list_open_stream(std::move(is), uri); +} diff --git a/src/playlist/PlaylistStream.hxx b/src/playlist/PlaylistStream.hxx new file mode 100644 index 0000000..4af296a --- /dev/null +++ b/src/playlist/PlaylistStream.hxx @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "thread/Mutex.hxx" + +#include + +class SongEnumerator; +class Path; + +/** + * Opens a playlist from a local file. + * + * Throws on error. + * + * @param path the path of the playlist file + * @return a playlist, or nullptr if the file is not supported + */ +std::unique_ptr +playlist_open_path(Path path, Mutex &mutex); + +/** + * Opens a playlist from a remote file. + * + * Throws on error. + * + * @param uri the absolute URI of the playlist file + * @return a playlist, or nullptr if the file is not supported + */ +[[gnu::nonnull]] +std::unique_ptr +playlist_open_remote(const char *uri, Mutex &mutex); diff --git a/src/playlist/Print.cxx b/src/playlist/Print.cxx new file mode 100644 index 0000000..2947d00 --- /dev/null +++ b/src/playlist/Print.cxx @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "LocateUri.hxx" +#include "Print.hxx" +#include "PlaylistAny.hxx" +#include "PlaylistSong.hxx" +#include "SongEnumerator.hxx" +#include "SongPrint.hxx" +#include "song/Filter.hxx" +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" +#include "input/Error.hxx" +#include "fs/Traits.hxx" +#include "thread/Mutex.hxx" +#include "Partition.hxx" +#include "Instance.hxx" +#include "PlaylistError.hxx" +#include +#include "client/Response.hxx" + +static void +playlist_provider_print(Response &r, + const SongLoader &loader, + const char *uri, + SongEnumerator &e, + unsigned start_index, + unsigned end_index, + bool detail) noexcept +{ + const auto base_uri = uri != nullptr + ? PathTraitsUTF8::GetParent(uri) + : "."; + + std::unique_ptr song; + + for (unsigned i = 0; + i < end_index && (song = e.NextSong()) != nullptr; + ++i) { + if (i < start_index) { + /* skip songs before the start index */ + continue; + } + + if (playlist_check_translate_song(*song, base_uri, + loader) && + detail) + song_print_info(r, *song); + else + /* fallback if no detail was requested or no + detail was available */ + song_print_uri(r, *song); + } +} + +static void +playlist_provider_search_print(Response &r, + const SongLoader &loader, + const char *uri, + SongEnumerator &e, + unsigned start_index, + unsigned end_index, + SongFilter *filter) noexcept +{ + const auto base_uri = uri != nullptr + ? PathTraitsUTF8::GetParent(uri) + : "."; + + std::unique_ptr song; + + unsigned skip = start_index; + unsigned n = end_index - start_index; + unsigned position = 0; + + while ((song = e.NextSong()) != nullptr) { + const bool detail = playlist_check_translate_song(*song, base_uri, + loader); + if (!filter->Match(static_cast(*song))) { + ++position; + continue; + } + + if (skip > 0) { + --skip; + ++position; + continue; + } + + if (detail) { + song_print_info(r, *song); + r.Fmt("Pos: {}\n", position); + } else + /* fallback if no detail was requested or no + detail was available */ + song_print_uri(r, *song); + + if (--n == 0) + break; + + ++position; + } +} + +void +playlist_file_print(Response &r, Partition &partition, + const SongLoader &loader, + const LocatedUri &uri, + unsigned start_index, + unsigned end_index, + bool detail, + SongFilter *filter) +try { + Mutex mutex; + +#ifndef ENABLE_DATABASE + (void)partition; +#endif + + auto playlist = playlist_open_any(uri, +#ifdef ENABLE_DATABASE + partition.instance.storage, +#endif + mutex); + if (playlist == nullptr) + throw PlaylistError::NoSuchList(); + + if (filter == nullptr) + playlist_provider_print(r, loader, uri.canonical_uri, *playlist, + start_index, end_index, detail); + else + playlist_provider_search_print(r, loader, uri.canonical_uri, *playlist, + start_index, end_index, filter); +} catch (...) { + if (IsFileNotFound(std::current_exception())) + throw PlaylistError::NoSuchList(); + + throw; +} diff --git a/src/playlist/Print.hxx b/src/playlist/Print.hxx new file mode 100644 index 0000000..e302189 --- /dev/null +++ b/src/playlist/Print.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +class Response; +class SongLoader; +class SongFilter; +struct Partition; + +/** + * Send the playlist file to the client. + * + * Throws on error. + * + * @param uri the URI of the playlist file in UTF-8 encoding + * @param detail true if all details should be printed + */ +void +playlist_file_print(Response &r, Partition &partition, + const SongLoader &loader, + const LocatedUri &uri, + unsigned start_index, unsigned end_index, + bool detail, + SongFilter *filter); + diff --git a/src/playlist/SongEnumerator.hxx b/src/playlist/SongEnumerator.hxx new file mode 100644 index 0000000..d6a4795 --- /dev/null +++ b/src/playlist/SongEnumerator.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SONG_ENUMERATOR_HXX +#define MPD_SONG_ENUMERATOR_HXX + +#include + +class DetachedSong; + +/** + * An object which provides serial access to a number of #Song + * objects. It is used to enumerate the contents of a playlist file. + */ +class SongEnumerator { +public: + virtual ~SongEnumerator() noexcept = default; + + /** + * Obtain the next song. Returns nullptr if there are no more + * songs. + * + * Throws on error. + */ + virtual std::unique_ptr NextSong() = 0; +}; + +#endif diff --git a/src/playlist/cue/CueParser.cxx b/src/playlist/cue/CueParser.cxx new file mode 100644 index 0000000..3250687 --- /dev/null +++ b/src/playlist/cue/CueParser.cxx @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "CueParser.hxx" +#include "tag/ParseName.hxx" +#include "util/CharUtil.hxx" +#include "util/StringSplit.hxx" +#include "util/StringStrip.hxx" + +#include +#include + +using std::string_view_literals::operator""sv; + +static std::string_view +cue_next_word(std::string_view &src) noexcept +{ + assert(!src.empty()); + assert(!IsWhitespaceNotNull(src.front())); + + auto end = std::find_if(src.begin(), src.end(), + [](char ch){ return IsWhitespaceOrNull(ch); }); + auto word = src.substr(0, std::distance(src.begin(), end)); + src = src.substr(std::distance(src.begin(), end)); + return word; +} + +static std::string_view +cue_next_quoted(std::string_view &src) noexcept +{ + auto [value, rest] = Split(src, '"'); + if (rest.data() == nullptr) + /* syntax error - ignore it silently */ + return std::exchange(src, {}); + + src = rest; + return value; +} + +static std::string_view +cue_next_token(std::string_view &src) noexcept +{ + src = StripLeft(src); + if (src.empty()) + return {}; + + return cue_next_word(src); +} + +static std::string_view +cue_next_value(std::string_view &src) noexcept +{ + src = StripLeft(src); + if (src.empty()) + return {}; + + if (src.front() == '"') { + src.remove_prefix(1); + return cue_next_quoted(src); + } else + return cue_next_word(src); +} + +static void +cue_add_tag(TagBuilder &tag, TagType type, std::string_view src) noexcept +{ + auto value = cue_next_value(src); + if (value.data() != nullptr) + tag.AddItem(type, value); +} + +static void +cue_parse_rem(std::string_view src, TagBuilder &tag) noexcept +{ + auto type = cue_next_token(src); + if (type.data() == nullptr) + return; + + TagType type2 = tag_name_parse_i(type); + if (type2 != TAG_NUM_OF_ITEM_TYPES) + cue_add_tag(tag, type2, src); +} + +TagBuilder * +CueParser::GetCurrentTag() noexcept +{ + if (state == HEADER) + return &header_tag; + else if (state == TRACK) + return &song_tag; + else + return nullptr; +} + +static bool +IsDigit(std::string_view s) noexcept +{ + return !s.empty() && IsDigitASCII(s.front()); +} + +static unsigned +cue_next_unsigned(std::string_view &src) noexcept +{ + if (!IsDigit(src)) { + src = {}; + return 0; + } + + unsigned value = 0; + + do { + char ch = src.front(); + src.remove_prefix(1); + + value = value * 10u + unsigned(ch - '0'); + } while (IsDigit(src)); + + return value; +} + +static int +cue_parse_position(std::string_view src) noexcept +{ + unsigned minutes = cue_next_unsigned(src); + if (src.empty() || src.front() != ':') + return -1; + + src.remove_prefix(1); + unsigned seconds = cue_next_unsigned(src); + if (src.empty() || src.front() != ':') + return -1; + + src.remove_prefix(1); + unsigned long frames = cue_next_unsigned(src); + if (src.data() == nullptr || !src.empty()) + return -1; + + return minutes * 60000 + seconds * 1000 + frames * 1000 / 75; +} + +void +CueParser::Commit() noexcept +{ + /* the caller of this library must call cue_parser_get() often + enough */ + assert(finished == nullptr); + assert(!end); + + if (current == nullptr) + return; + + assert(!current->GetTag().IsDefined()); + current->SetTag(song_tag.Commit()); + + finished = std::move(previous); + previous = std::move(current); +} + +void +CueParser::Feed(std::string_view src) noexcept +{ + assert(!end); + + const auto command = cue_next_token(src); + if (command.data() == nullptr) + return; + + if (command == "REM"sv) { + TagBuilder *tag = GetCurrentTag(); + if (tag != nullptr) + cue_parse_rem(src, *tag); + } else if (command == "PERFORMER"sv) { + /* MPD knows a "performer" tag, but it is not a good + match for this CUE tag; from the Hydrogenaudio + Knowledgebase: "At top-level this will specify the + CD artist, while at track-level it specifies the + track artist." */ + + TagType type = state == TRACK + ? TAG_ARTIST + : TAG_ALBUM_ARTIST; + + TagBuilder *tag = GetCurrentTag(); + if (tag != nullptr) + cue_add_tag(*tag, type, src); + } else if (command == "TITLE"sv) { + if (state == HEADER) + cue_add_tag(header_tag, TAG_ALBUM, src); + else if (state == TRACK) + cue_add_tag(song_tag, TAG_TITLE, src); + } else if (command == "FILE"sv) { + Commit(); + + const auto new_filename = cue_next_value(src); + if (new_filename.data() == nullptr) + return; + + const auto type = cue_next_token(src); + if (type.data() == nullptr) + return; + + if (type != "WAVE"sv && + type != "FLAC"sv && /* non-standard */ + type != "MP3"sv && + type != "AIFF"sv) { + state = IGNORE_FILE; + return; + } + + state = WAVE; + filename = new_filename; + } else if (state == IGNORE_FILE) { + return; + } else if (command == "TRACK"sv) { + Commit(); + + const auto nr = cue_next_token(src); + if (nr.data() == nullptr) + return; + + const auto type = cue_next_token(src); + if (type.data() == nullptr) + return; + + if (type != "AUDIO"sv) { + state = IGNORE_TRACK; + return; + } + + state = TRACK; + ignore_index = false; + current = std::make_unique(filename); + assert(!current->GetTag().IsDefined()); + + song_tag = header_tag; + song_tag.AddItem(TAG_TRACK, nr); + + } else if (state == IGNORE_TRACK) { + return; + } else if (state == TRACK && command == "INDEX"sv) { + if (ignore_index) + return; + + const auto nr = cue_next_token(src); + if (nr.data() == nullptr) + return; + + const auto position = cue_next_token(src); + if (position.data() == nullptr) + return; + + int position_ms = cue_parse_position(position); + if (position_ms < 0) + return; + + if (previous != nullptr && previous->GetStartTime().ToMS() < (unsigned)position_ms) + previous->SetEndTime(SongTime::FromMS(position_ms)); + + if (current != nullptr) + current->SetStartTime(SongTime::FromMS(position_ms)); + + if (nr != "00"sv || previous == nullptr) + ignore_index = true; + } +} + +void +CueParser::Finish() noexcept +{ + if (end) + /* has already been called, ignore */ + return; + + Commit(); + end = true; +} + +std::unique_ptr +CueParser::Get() noexcept +{ + if (finished == nullptr && end) { + /* cue_parser_finish() has been called already: + deliver all remaining (partial) results */ + assert(current == nullptr); + + finished = std::move(previous); + } + + return std::move(finished); +} diff --git a/src/playlist/cue/CueParser.hxx b/src/playlist/cue/CueParser.hxx new file mode 100644 index 0000000..baf7ac5 --- /dev/null +++ b/src/playlist/cue/CueParser.hxx @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_CUE_PARSER_HXX +#define MPD_CUE_PARSER_HXX + +#include "song/DetachedSong.hxx" +#include "tag/Builder.hxx" + +#include +#include +#include + +class CueParser { + enum { + /** + * Parsing the CUE header. + */ + HEADER, + + /** + * Parsing a "FILE ... WAVE". + */ + WAVE, + + /** + * Ignore everything until the next "FILE". + */ + IGNORE_FILE, + + /** + * Parsing a "TRACK ... AUDIO". + */ + TRACK, + + /** + * Ignore everything until the next "TRACK". + */ + IGNORE_TRACK, + } state = HEADER; + + /** + * Tags read from the CUE header. + */ + TagBuilder header_tag; + + /** + * Tags read for the current song (attribute #current). When + * #current gets moved to #previous, TagBuilder::Commit() will + * be called. + */ + TagBuilder song_tag; + + std::string filename; + + /** + * The song currently being edited. + */ + std::unique_ptr current; + + /** + * The previous song. It is remembered because its end_time + * will be set to the current song's start time. + */ + std::unique_ptr previous; + + /** + * A song that is completely finished and can be returned to + * the caller via Get(). + */ + std::unique_ptr finished; + + /** + * Ignore "INDEX" lines? Only up the first one after "00" is + * used. If there is a pregap (INDEX 00..01), it is assigned + * to the previous song. + */ + bool ignore_index; + + /** + * Tracks whether Finish() has been called. If true, then all + * remaining (partial) results will be delivered by Get(). + */ + bool end = false; + +public: + /** + * Feed a text line from the CUE file into the parser. Call + * Get() after this to see if a song has been finished. + */ + void Feed(std::string_view line) noexcept; + + /** + * Tell the parser that the end of the file has been reached. Call + * Get() after this to see if a song has been finished. + * This procedure must be done twice! + */ + void Finish() noexcept; + + /** + * Check if a song was finished by the last Feed() or Finish() + * call. + * + * @return a song object that must be freed by the caller, or NULL if + * no song was finished at this time + */ + std::unique_ptr Get() noexcept; + +private: + [[gnu::pure]] + TagBuilder *GetCurrentTag() noexcept; + + /** + * Commit the current song. It will be moved to "previous", + * so the next song may soon edit its end time (using the next + * song's start time). + */ + void Commit() noexcept; +}; + +#endif diff --git a/src/playlist/meson.build b/src/playlist/meson.build new file mode 100644 index 0000000..6988058 --- /dev/null +++ b/src/playlist/meson.build @@ -0,0 +1,32 @@ +playlist_features = configuration_data() + +playlist_api = static_library( + 'playlist_api', + 'PlaylistPlugin.cxx', + 'MemorySongEnumerator.cxx', + include_directories: inc, +) + +playlist_api_dep = declare_dependency( + link_with: playlist_api, +) + +subdir('plugins') + +playlist_glue = static_library( + 'playlist_glue', + 'PlaylistRegistry.cxx', + include_directories: inc, + dependencies: [ + input_api_dep, + ], +) + +playlist_glue_dep = declare_dependency( + link_with: playlist_glue, + dependencies: [ + playlist_plugins_dep, + ], +) + +configure_file(output: 'Features.h', configuration: playlist_features) diff --git a/src/playlist/plugins/AsxPlaylistPlugin.cxx b/src/playlist/plugins/AsxPlaylistPlugin.cxx new file mode 100644 index 0000000..7ec1fab --- /dev/null +++ b/src/playlist/plugins/AsxPlaylistPlugin.cxx @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "AsxPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../MemorySongEnumerator.hxx" +#include "tag/Builder.hxx" +#include "tag/Table.hxx" +#include "util/ASCII.hxx" +#include "lib/expat/ExpatParser.hxx" + +/** + * This is the state object for our XML parser. + */ +struct AsxParser { + /** + * The list of songs (in reverse order because that's faster + * while adding). + */ + std::forward_list songs; + + /** + * The current position in the XML file. + */ + enum { + ROOT, ENTRY, + TAG, + } state{ROOT}; + + /** + * The current tag within the "entry" element. This is only + * valid if state==ENTRY. TAG_NUM_OF_ITEM_TYPES means there + * is no (known) tag. + */ + TagType tag_type; + + /** + * The current song URI. It is set by the "ref" element. + */ + std::string location; + + TagBuilder tag_builder; + + std::string value; +}; + +static constexpr struct tag_table asx_tag_elements[] = { + /* is that correct? or should it be COMPOSER or PERFORMER? */ + { "author", TAG_ARTIST }, + + { "title", TAG_TITLE }, + { nullptr, TAG_NUM_OF_ITEM_TYPES } +}; + +static void XMLCALL +asx_start_element(void *user_data, const XML_Char *element_name, + const XML_Char **atts) +{ + auto *parser = (AsxParser *)user_data; + parser->value.clear(); + + switch (parser->state) { + case AsxParser::ROOT: + if (StringEqualsCaseASCII(element_name, "entry")) { + parser->state = AsxParser::ENTRY; + parser->location.clear(); + } + + break; + + case AsxParser::ENTRY: + if (StringEqualsCaseASCII(element_name, "ref")) { + const char *href = + ExpatParser::GetAttributeCase(atts, "href"); + if (href != nullptr) + parser->location = href; + } else { + parser->tag_type = tag_table_lookup_i(asx_tag_elements, + element_name); + if (parser->tag_type != TAG_NUM_OF_ITEM_TYPES) + parser->state = AsxParser::TAG; + } + + break; + + case AsxParser::TAG: + break; + } +} + +static void XMLCALL +asx_end_element(void *user_data, const XML_Char *element_name) +{ + auto *parser = (AsxParser *)user_data; + + switch (parser->state) { + case AsxParser::ROOT: + break; + + case AsxParser::ENTRY: + if (StringEqualsCaseASCII(element_name, "entry")) { + if (!parser->location.empty()) + parser->songs.emplace_front(std::move(parser->location), + parser->tag_builder.Commit()); + + parser->state = AsxParser::ROOT; + } + + break; + + case AsxParser::TAG: + if (!parser->value.empty()) + parser->tag_builder.AddItem(parser->tag_type, + parser->value); + parser->state = AsxParser::ENTRY; + break; + } + + parser->value.clear(); +} + +static void XMLCALL +asx_char_data(void *user_data, const XML_Char *s, int len) +{ + auto *parser = (AsxParser *)user_data; + + switch (parser->state) { + case AsxParser::ROOT: + case AsxParser::ENTRY: + break; + + case AsxParser::TAG: + parser->value.append(s, len); + break; + } +} + +/* + * The playlist object + * + */ + +static std::unique_ptr +asx_open_stream(InputStreamPtr &&is) +{ + AsxParser parser; + + { + ExpatParser expat(&parser); + expat.SetElementHandler(asx_start_element, asx_end_element); + expat.SetCharacterDataHandler(asx_char_data); + expat.Parse(*is); + } + + parser.songs.reverse(); + return std::make_unique(std::move(parser.songs)); +} + +static const char *const asx_suffixes[] = { + "asx", + nullptr +}; + +static const char *const asx_mime_types[] = { + "video/x-ms-asf", + nullptr +}; + +const PlaylistPlugin asx_playlist_plugin = + PlaylistPlugin("asx", asx_open_stream) + .WithSuffixes(asx_suffixes) + .WithMimeTypes(asx_mime_types); diff --git a/src/playlist/plugins/AsxPlaylistPlugin.hxx b/src/playlist/plugins/AsxPlaylistPlugin.hxx new file mode 100644 index 0000000..be4f87c --- /dev/null +++ b/src/playlist/plugins/AsxPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ASX_PLAYLIST_PLUGIN_HXX +#define MPD_ASX_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin asx_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/CuePlaylistPlugin.cxx b/src/playlist/plugins/CuePlaylistPlugin.cxx new file mode 100644 index 0000000..06c47fc --- /dev/null +++ b/src/playlist/plugins/CuePlaylistPlugin.cxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "CuePlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../SongEnumerator.hxx" +#include "../cue/CueParser.hxx" +#include "input/TextInputStream.hxx" + +class CuePlaylist final : public SongEnumerator { + TextInputStream tis; + CueParser parser; + + public: + explicit CuePlaylist(InputStreamPtr &&is) + :tis(std::move(is)) { + } + + std::unique_ptr NextSong() override; +}; + +static std::unique_ptr +cue_playlist_open_stream(InputStreamPtr &&is) +{ + return std::make_unique(std::move(is)); +} + +std::unique_ptr +CuePlaylist::NextSong() +{ + auto song = parser.Get(); + if (song != nullptr) + return song; + + const char *line; + while ((line = tis.ReadLine()) != nullptr) { + parser.Feed(line); + song = parser.Get(); + if (song != nullptr) + return song; + } + + parser.Finish(); + return parser.Get(); +} + +static const char *const cue_playlist_suffixes[] = { + "cue", + nullptr +}; + +static const char *const cue_playlist_mime_types[] = { + "application/x-cue", + nullptr +}; + +const PlaylistPlugin cue_playlist_plugin = + PlaylistPlugin("cue", cue_playlist_open_stream) + .WithAsFolder() + .WithSuffixes(cue_playlist_suffixes) + .WithMimeTypes(cue_playlist_mime_types); diff --git a/src/playlist/plugins/CuePlaylistPlugin.hxx b/src/playlist/plugins/CuePlaylistPlugin.hxx new file mode 100644 index 0000000..9c68d64 --- /dev/null +++ b/src/playlist/plugins/CuePlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_CUE_PLAYLIST_PLUGIN_HXX +#define MPD_CUE_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin cue_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/EmbeddedCuePlaylistPlugin.cxx b/src/playlist/plugins/EmbeddedCuePlaylistPlugin.cxx new file mode 100644 index 0000000..7ea64cd --- /dev/null +++ b/src/playlist/plugins/EmbeddedCuePlaylistPlugin.cxx @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/** \file + * + * Playlist plugin that reads embedded cue sheets from the "CUESHEET" + * tag of a music file. + */ + +#include "EmbeddedCuePlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../SongEnumerator.hxx" +#include "../cue/CueParser.hxx" +#include "tag/Handler.hxx" +#include "tag/Generic.hxx" +#include "song/DetachedSong.hxx" +#include "TagFile.hxx" +#include "fs/Traits.hxx" +#include "fs/AllocatedPath.hxx" +#include "util/StringCompare.hxx" + +#include + +#include + +using std::string_view_literals::operator""sv; + +class EmbeddedCuePlaylist final : public SongEnumerator { +public: + /** + * This is an override for the CUE's "FILE". An embedded CUE + * sheet must always point to the song file it is contained + * in. + */ + std::string filename; + + /** + * The value of the file's "CUESHEET" tag. + */ + std::string cuesheet; + + /** + * The offset of the next line within "cuesheet". + */ + char *next; + + std::unique_ptr parser; + + std::unique_ptr NextSong() override; +}; + +class ExtractCuesheetTagHandler final : public NullTagHandler { +public: + std::string cuesheet; + + ExtractCuesheetTagHandler() noexcept:NullTagHandler(WANT_PAIR) {} + + void OnPair(std::string_view key, std::string_view value) noexcept override; +}; + +void +ExtractCuesheetTagHandler::OnPair(std::string_view name, std::string_view value) noexcept +{ + if (cuesheet.empty() && StringIsEqualIgnoreCase(name, "cuesheet"sv)) + cuesheet = value; +} + +static std::unique_ptr +embcue_playlist_open_uri(const char *uri, + [[maybe_unused]] Mutex &mutex) +{ + if (!PathTraitsUTF8::IsAbsolute(uri)) + /* only local files supported */ + return nullptr; + + const auto path_fs = AllocatedPath::FromUTF8Throw(uri); + + ExtractCuesheetTagHandler extract_cuesheet; + ScanFileTagsNoGeneric(path_fs, extract_cuesheet); + if (extract_cuesheet.cuesheet.empty()) + ScanGenericTags(path_fs, extract_cuesheet); + + if (extract_cuesheet.cuesheet.empty()) + /* no "CUESHEET" tag found */ + return nullptr; + + auto playlist = std::make_unique(); + + playlist->filename = PathTraitsUTF8::GetBase(uri); + + playlist->cuesheet = std::move(extract_cuesheet.cuesheet); + + playlist->next = playlist->cuesheet.data(); + playlist->parser = std::make_unique(); + + return playlist; +} + +std::unique_ptr +EmbeddedCuePlaylist::NextSong() +{ + auto song = parser->Get(); + if (song != nullptr) { + song->SetURI(filename); + return song; + } + + while (*next != 0) { + const char *line = next; + char *eol = strpbrk(next, "\r\n"); + if (eol != nullptr) { + /* null-terminate the line */ + *eol = 0; + next = eol + 1; + } else + /* last line; put the "next" pointer to the + end of the buffer */ + next += strlen(line); + + parser->Feed(line); + song = parser->Get(); + if (song != nullptr) { + song->SetURI(filename); + return song; + } + } + + parser->Finish(); + song = parser->Get(); + if (song != nullptr) + song->SetURI(filename); + return song; +} + +static const char *const embcue_playlist_suffixes[] = { + /* a few codecs that are known to be supported; there are + probably many more */ + "flac", + "mp3", "mp2", + "mp4", "mp4a", "m4b", + "ape", + "wv", + "ogg", "oga", + nullptr +}; + +const PlaylistPlugin embcue_playlist_plugin = + PlaylistPlugin("embcue", embcue_playlist_open_uri) + .WithSuffixes(embcue_playlist_suffixes); diff --git a/src/playlist/plugins/EmbeddedCuePlaylistPlugin.hxx b/src/playlist/plugins/EmbeddedCuePlaylistPlugin.hxx new file mode 100644 index 0000000..837ade8 --- /dev/null +++ b/src/playlist/plugins/EmbeddedCuePlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_EMBCUE_PLAYLIST_PLUGIN_HXX +#define MPD_EMBCUE_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin embcue_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/ExtM3uPlaylistPlugin.cxx b/src/playlist/plugins/ExtM3uPlaylistPlugin.cxx new file mode 100644 index 0000000..de282f3 --- /dev/null +++ b/src/playlist/plugins/ExtM3uPlaylistPlugin.cxx @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ExtM3uPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../SongEnumerator.hxx" +#include "song/DetachedSong.hxx" +#include "tag/Tag.hxx" +#include "tag/Builder.hxx" +#include "util/StringStrip.hxx" +#include "util/StringCompare.hxx" +#include "input/TextInputStream.hxx" +#include "input/InputStream.hxx" + +#include +#include + +class ExtM3uPlaylist final : public SongEnumerator { + TextInputStream tis; + +public: + explicit ExtM3uPlaylist(InputStreamPtr &&is) + :tis(std::move(is)) { + } + + /** + * @return nullptr if ExtM3U was recognized, or the original + * InputStream on error + */ + InputStreamPtr CheckFirstLine() { + char *line = tis.ReadLine(); + if (line == nullptr) + return tis.StealInputStream(); + + StripRight(line); + if (strcmp(line, "#EXTM3U") != 0) + return tis.StealInputStream(); + + return nullptr; + } + + std::unique_ptr NextSong() override; +}; + +static std::unique_ptr +extm3u_open_stream(InputStreamPtr &&is) +{ + auto playlist = std::make_unique(std::move(is)); + + is = playlist->CheckFirstLine(); + if (is) + /* no EXTM3U header: fall back to the plain m3u + plugin */ + playlist.reset(); + + return playlist; +} + +/** + * Parse a EXTINF line. + * + * @param line the rest of the input line after the colon + */ +static Tag +extm3u_parse_tag(const char *line) +{ + long duration; + char *endptr; + const char *name; + + duration = strtol(line, &endptr, 10); + if (endptr[0] != ',') + /* malformed line */ + return {}; + + if (duration < 0) + /* 0 means unknown duration */ + duration = 0; + + name = StripLeft(endptr + 1); + if (*name == 0 && duration == 0) + /* no information available; don't allocate a tag + object */ + return {}; + + TagBuilder tag; + tag.SetDuration(SignedSongTime::FromS(unsigned(duration))); + + /* unfortunately, there is no real specification for the + EXTM3U format, so we must assume that the string after the + comma is opaque, and is just the song name*/ + if (*name != 0) + tag.AddItem(TAG_NAME, name); + + return tag.Commit(); +} + +std::unique_ptr +ExtM3uPlaylist::NextSong() +{ + Tag tag; + char *line_s; + + do { + line_s = tis.ReadLine(); + if (line_s == nullptr) + return nullptr; + + StripRight(line_s); + + if (StringStartsWith(line_s, "#EXTINF:")) { + tag = extm3u_parse_tag(line_s + 8); + continue; + } + + line_s = StripLeft(line_s); + } while (line_s[0] == '#' || *line_s == 0); + + return std::make_unique(line_s, std::move(tag)); +} + +static const char *const extm3u_suffixes[] = { + "m3u", + "m3u8", + nullptr +}; + +static const char *const extm3u_mime_types[] = { + "audio/x-mpegurl", + "audio/mpegurl", + nullptr +}; + +constexpr PlaylistPlugin extm3u_playlist_plugin = + PlaylistPlugin("extm3u", extm3u_open_stream) + .WithSuffixes(extm3u_suffixes) + .WithMimeTypes(extm3u_mime_types); diff --git a/src/playlist/plugins/ExtM3uPlaylistPlugin.hxx b/src/playlist/plugins/ExtM3uPlaylistPlugin.hxx new file mode 100644 index 0000000..639a465 --- /dev/null +++ b/src/playlist/plugins/ExtM3uPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_EXTM3U_PLAYLIST_PLUGIN_HXX +#define MPD_EXTM3U_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin extm3u_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/FlacPlaylistPlugin.cxx b/src/playlist/plugins/FlacPlaylistPlugin.cxx new file mode 100644 index 0000000..38d74e9 --- /dev/null +++ b/src/playlist/plugins/FlacPlaylistPlugin.cxx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/** \file + * + * Playlist plugin that reads embedded cue sheets from the "CUESHEET" + * tag of a music file. + */ + +#include "FlacPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../MemorySongEnumerator.hxx" +#include "lib/xiph/FlacMetadataChain.hxx" +#include "lib/xiph/FlacMetadataIterator.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "song/DetachedSong.hxx" +#include "input/InputStream.hxx" + +#include + +static auto +ToSongEnumerator(const char *uri, + const FLAC__StreamMetadata_CueSheet &c, + const unsigned sample_rate, + const FLAC__uint64 total_samples) noexcept +{ + std::forward_list songs; + auto tail = songs.before_begin(); + + for (unsigned i = 0; i < c.num_tracks; ++i) { + const auto &track = c.tracks[i]; + if (track.type != 0) + continue; + + const FLAC__uint64 start = track.offset; + const FLAC__uint64 end = i + 1 < c.num_tracks + ? c.tracks[i + 1].offset + : total_samples; + + tail = songs.emplace_after(tail, uri); + auto &song = *tail; + song.SetStartTime(SongTime::FromScale(start, sample_rate)); + song.SetEndTime(SongTime::FromScale(end, sample_rate)); + } + + return std::make_unique(std::move(songs)); +} + +static std::unique_ptr +flac_playlist_open_stream(InputStreamPtr &&is) +{ + FlacMetadataChain chain; + if (!chain.Read(*is)) + throw FmtRuntimeError("Failed to read FLAC metadata: {}", + chain.GetStatusString()); + + FlacMetadataIterator iterator((FLAC__Metadata_Chain *)chain); + + unsigned sample_rate = 0; + FLAC__uint64 total_samples; + + do { + auto &block = *iterator.GetBlock(); + switch (block.type) { + case FLAC__METADATA_TYPE_STREAMINFO: + sample_rate = block.data.stream_info.sample_rate; + total_samples = block.data.stream_info.total_samples; + break; + + case FLAC__METADATA_TYPE_CUESHEET: + if (sample_rate == 0) + break; + + return ToSongEnumerator("", block.data.cue_sheet, + sample_rate, total_samples); + + default: + break; + } + } while (iterator.Next()); + + return nullptr; +} + +static constexpr const char *flac_playlist_suffixes[] = { + "flac", + nullptr +}; + +const PlaylistPlugin flac_playlist_plugin = + PlaylistPlugin("flac", flac_playlist_open_stream) + .WithSuffixes(flac_playlist_suffixes); diff --git a/src/playlist/plugins/FlacPlaylistPlugin.hxx b/src/playlist/plugins/FlacPlaylistPlugin.hxx new file mode 100644 index 0000000..5a4b6ca --- /dev/null +++ b/src/playlist/plugins/FlacPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_FLAC_PLAYLIST_PLUGIN_HXX +#define MPD_FLAC_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin flac_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/M3uPlaylistPlugin.cxx b/src/playlist/plugins/M3uPlaylistPlugin.cxx new file mode 100644 index 0000000..155f073 --- /dev/null +++ b/src/playlist/plugins/M3uPlaylistPlugin.cxx @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "M3uPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../SongEnumerator.hxx" +#include "song/DetachedSong.hxx" +#include "input/TextInputStream.hxx" +#include "util/StringStrip.hxx" + +class M3uPlaylist final : public SongEnumerator { + TextInputStream tis; + +public: + explicit M3uPlaylist(InputStreamPtr &&is) + :tis(std::move(is)) { + } + + std::unique_ptr NextSong() override; +}; + +static std::unique_ptr +m3u_open_stream(InputStreamPtr &&is) +{ + return std::make_unique(std::move(is)); +} + +std::unique_ptr +M3uPlaylist::NextSong() +{ + char *line_s; + + do { + line_s = tis.ReadLine(); + if (line_s == nullptr) + return nullptr; + + line_s = Strip(line_s); + } while (line_s[0] == '#' || *line_s == 0); + + return std::make_unique(line_s); +} + +static const char *const m3u_suffixes[] = { + "m3u", + "m3u8", + nullptr +}; + +static const char *const m3u_mime_types[] = { + "audio/x-mpegurl", + "audio/mpegurl", + nullptr +}; + +const PlaylistPlugin m3u_playlist_plugin = + PlaylistPlugin("m3u", m3u_open_stream) + .WithSuffixes(m3u_suffixes) + .WithMimeTypes(m3u_mime_types); diff --git a/src/playlist/plugins/M3uPlaylistPlugin.hxx b/src/playlist/plugins/M3uPlaylistPlugin.hxx new file mode 100644 index 0000000..298d361 --- /dev/null +++ b/src/playlist/plugins/M3uPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_M3U_PLAYLIST_PLUGIN_HXX +#define MPD_M3U_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin m3u_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/PlsPlaylistPlugin.cxx b/src/playlist/plugins/PlsPlaylistPlugin.cxx new file mode 100644 index 0000000..3892907 --- /dev/null +++ b/src/playlist/plugins/PlsPlaylistPlugin.cxx @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlsPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../MemorySongEnumerator.hxx" +#include "input/TextInputStream.hxx" +#include "input/InputStream.hxx" +#include "song/DetachedSong.hxx" +#include "tag/Builder.hxx" +#include "util/ASCII.hxx" +#include "util/NumberParser.hxx" +#include "util/StringCompare.hxx" +#include "util/StringSplit.hxx" +#include "util/StringStrip.hxx" + +#include + +using std::string_view_literals::operator""sv; + +static bool +FindPlaylistSection(TextInputStream &is) +{ + char *line; + while ((line = is.ReadLine()) != nullptr) { + line = Strip(line); + if (StringEqualsCaseASCII(line, "[playlist]")) + return true; + } + + return false; +} + +static bool +ParsePls(TextInputStream &is, std::forward_list &songs) +{ + assert(songs.empty()); + + if (!FindPlaylistSection(is)) + return false; + + unsigned n_entries = 0; + + struct Entry { + std::string file, title; + int length{-1}; + + Entry() = default; + }; + + static constexpr unsigned MAX_ENTRIES = 65536; + + std::vector entries; + + char *_line; + while ((_line = is.ReadLine()) != nullptr) { + std::string_view line = Strip(std::string_view{_line}); + + if (line.empty() || line.front() == ';') + continue; + + if (line.front() == '[') + /* another section starts; we only want + [Playlist], so stop here */ + break; + + auto [name, value] = Split(line, '='); + if (value.data() == nullptr) + continue; + + name = Strip(name); + value = Strip(value); + + if (StringIsEqualIgnoreCase(name, "NumberOfEntries"sv)) { + if (!ParseIntegerTo(value, n_entries) || n_entries == 0) + /* empty file - nothing remains to be + done */ + return true; + + if (n_entries > MAX_ENTRIES) + n_entries = MAX_ENTRIES; + entries.resize(n_entries); + } else if (SkipPrefixIgnoreCase(name, "File"sv)) { + unsigned i = 0; + ParseIntegerTo(name, i); + if (i >= 1 && i <= (n_entries > 0 ? n_entries : MAX_ENTRIES)) { + if (entries.size() < i) + entries.resize(i); + entries[i - 1].file = value; + } + } else if (SkipPrefixIgnoreCase(name, "Title"sv)) { + unsigned i = 0; + ParseIntegerTo(name, i); + if (i >= 1 && i <= (n_entries > 0 ? n_entries : MAX_ENTRIES)) { + if (entries.size() < i) + entries.resize(i); + entries[i - 1].title = value; + } + } else if (SkipPrefixIgnoreCase(name, "Length"sv)) { + unsigned i = 0; + ParseIntegerTo(name, i); + if (i >= 1 && i <= (n_entries > 0 ? n_entries : MAX_ENTRIES)) { + if (entries.size() < i) + entries.resize(i); + ParseIntegerTo(value, entries[i - 1].length); + } + } + } + + if (n_entries == 0) + /* no "NumberOfEntries" found */ + return false; + + auto i = songs.before_begin(); + for (const auto &entry : entries) { + const char *uri = entry.file.c_str(); + + TagBuilder tag; + if (!entry.title.empty()) + tag.AddItem(TAG_TITLE, entry.title); + + if (entry.length > 0) + tag.SetDuration(SignedSongTime::FromS(entry.length)); + + i = songs.emplace_after(i, uri, tag.Commit()); + } + + return true; +} + +static bool +ParsePls(InputStreamPtr &&is, std::forward_list &songs) +{ + TextInputStream tis(std::move(is)); + if (!ParsePls(tis, songs)) { + is = tis.StealInputStream(); + return false; + } + + return true; +} + +static std::unique_ptr +pls_open_stream(InputStreamPtr &&is) +{ + std::forward_list songs; + if (!ParsePls(std::move(is), songs)) + return nullptr; + + return std::make_unique(std::move(songs)); +} + +static constexpr const char *pls_suffixes[] = { + "pls", + nullptr +}; + +static constexpr const char *pls_mime_types[] = { + "audio/x-scpls", + nullptr +}; + +const PlaylistPlugin pls_playlist_plugin = + PlaylistPlugin("pls", pls_open_stream) + .WithSuffixes(pls_suffixes) + .WithMimeTypes(pls_mime_types); diff --git a/src/playlist/plugins/PlsPlaylistPlugin.hxx b/src/playlist/plugins/PlsPlaylistPlugin.hxx new file mode 100644 index 0000000..809620a --- /dev/null +++ b/src/playlist/plugins/PlsPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PLS_PLAYLIST_PLUGIN_HXX +#define MPD_PLS_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin pls_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/RssPlaylistPlugin.cxx b/src/playlist/plugins/RssPlaylistPlugin.cxx new file mode 100644 index 0000000..4d47f80 --- /dev/null +++ b/src/playlist/plugins/RssPlaylistPlugin.cxx @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "RssPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../MemorySongEnumerator.hxx" +#include "tag/Builder.hxx" +#include "util/ASCII.hxx" +#include "lib/expat/ExpatParser.hxx" + +/** + * This is the state object for the our XML parser. + */ +struct RssParser { + /** + * The list of songs (in reverse order because that's faster + * while adding). + */ + std::forward_list songs; + + /** + * The current position in the XML file. + */ + enum { + ROOT, ITEM, + } state{ROOT}; + + /** + * The current tag within the "entry" element. This is only + * valid if state==ITEM. TAG_NUM_OF_ITEM_TYPES means there + * is no (known) tag. + */ + TagType tag_type; + + /** + * The current song URI. It is set by the "enclosure" + * element. + */ + std::string location; + + TagBuilder tag_builder; + + RssParser() = default; +}; + +static void XMLCALL +rss_start_element(void *user_data, const XML_Char *element_name, + const XML_Char **atts) +{ + auto *parser = (RssParser *)user_data; + + switch (parser->state) { + case RssParser::ROOT: + if (StringEqualsCaseASCII(element_name, "item")) { + parser->state = RssParser::ITEM; + parser->location.clear(); + parser->tag_type = TAG_NUM_OF_ITEM_TYPES; + } + + break; + + case RssParser::ITEM: + if (StringEqualsCaseASCII(element_name, "enclosure")) { + const char *href = + ExpatParser::GetAttributeCase(atts, "url"); + if (href != nullptr) + parser->location = href; + } else if (StringEqualsCaseASCII(element_name, "title")) + parser->tag_type = TAG_TITLE; + else if (StringEqualsCaseASCII(element_name, "itunes:author")) + parser->tag_type = TAG_ARTIST; + + break; + } +} + +static void XMLCALL +rss_end_element(void *user_data, const XML_Char *element_name) +{ + auto *parser = (RssParser *)user_data; + + switch (parser->state) { + case RssParser::ROOT: + break; + + case RssParser::ITEM: + if (StringEqualsCaseASCII(element_name, "item")) { + if (!parser->location.empty()) + parser->songs.emplace_front(std::move(parser->location), + parser->tag_builder.Commit()); + + parser->state = RssParser::ROOT; + } else + parser->tag_type = TAG_NUM_OF_ITEM_TYPES; + + break; + } +} + +static void XMLCALL +rss_char_data(void *user_data, const XML_Char *s, int len) +{ + auto *parser = (RssParser *)user_data; + + switch (parser->state) { + case RssParser::ROOT: + break; + + case RssParser::ITEM: + if (parser->tag_type != TAG_NUM_OF_ITEM_TYPES) + parser->tag_builder.AddItem(parser->tag_type, + std::string_view(s, len)); + + break; + } +} + +/* + * The playlist object + * + */ + +static std::unique_ptr +rss_open_stream(InputStreamPtr &&is) +{ + RssParser parser; + + { + ExpatParser expat(&parser); + expat.SetElementHandler(rss_start_element, rss_end_element); + expat.SetCharacterDataHandler(rss_char_data); + expat.Parse(*is); + } + + parser.songs.reverse(); + return std::make_unique(std::move(parser.songs)); +} + +static constexpr const char *rss_suffixes[] = { + "rss", + nullptr +}; + +static constexpr const char *rss_mime_types[] = { + "application/rss+xml", + "application/xml", + "text/xml", + nullptr +}; + +const PlaylistPlugin rss_playlist_plugin = + PlaylistPlugin("rss", rss_open_stream) + .WithSuffixes(rss_suffixes) + .WithMimeTypes(rss_mime_types); diff --git a/src/playlist/plugins/RssPlaylistPlugin.hxx b/src/playlist/plugins/RssPlaylistPlugin.hxx new file mode 100644 index 0000000..872f06d --- /dev/null +++ b/src/playlist/plugins/RssPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_RSS_PLAYLIST_PLUGIN_HXX +#define MPD_RSS_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin rss_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/XspfPlaylistPlugin.cxx b/src/playlist/plugins/XspfPlaylistPlugin.cxx new file mode 100644 index 0000000..7fa5d6a --- /dev/null +++ b/src/playlist/plugins/XspfPlaylistPlugin.cxx @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "XspfPlaylistPlugin.hxx" +#include "../PlaylistPlugin.hxx" +#include "../MemorySongEnumerator.hxx" +#include "song/DetachedSong.hxx" +#include "input/InputStream.hxx" +#include "tag/Builder.hxx" +#include "tag/Table.hxx" +#include "lib/expat/ExpatParser.hxx" + +#include + +/** + * This is the state object for our XML parser. + */ +struct XspfParser { + /** + * The list of songs (in reverse order because that's faster + * while adding). + */ + std::forward_list songs; + + /** + * The current position in the XML file. + */ + enum { + ROOT, PLAYLIST, TRACKLIST, TRACK, + TAG, LOCATION, + } state = ROOT; + + /** + * The current tag within the "track" element. This is only + * valid if state==TRACK. TAG_NUM_OF_ITEM_TYPES means there + * is no (known) tag. + */ + TagType tag_type; + + /** + * The current song URI. It is set by the "location" element. + */ + std::string location; + + TagBuilder tag_builder; + + std::string value; +}; + +static constexpr struct tag_table xspf_tag_elements[] = { + { "title", TAG_TITLE }, + + /* TAG_COMPOSER would be more correct according to the XSPF + spec */ + { "creator", TAG_ARTIST }, + + { "annotation", TAG_COMMENT }, + { "album", TAG_ALBUM }, + { "trackNum", TAG_TRACK }, + { nullptr, TAG_NUM_OF_ITEM_TYPES } +}; + +static void XMLCALL +xspf_start_element(void *user_data, const XML_Char *element_name, + [[maybe_unused]] const XML_Char **atts) +{ + auto *parser = (XspfParser *)user_data; + parser->value.clear(); + + switch (parser->state) { + case XspfParser::ROOT: + if (strcmp(element_name, "playlist") == 0) + parser->state = XspfParser::PLAYLIST; + + break; + + case XspfParser::PLAYLIST: + if (strcmp(element_name, "trackList") == 0) + parser->state = XspfParser::TRACKLIST; + + break; + + case XspfParser::TRACKLIST: + if (strcmp(element_name, "track") == 0) { + parser->state = XspfParser::TRACK; + parser->location.clear(); + } + + break; + + case XspfParser::TRACK: + if (strcmp(element_name, "location") == 0) + parser->state = XspfParser::LOCATION; + else if (!parser->location.empty()) { + parser->tag_type = tag_table_lookup(xspf_tag_elements, + element_name); + if (parser->tag_type != TAG_NUM_OF_ITEM_TYPES) + parser->state = XspfParser::TAG; + } + + break; + + case XspfParser::TAG: + case XspfParser::LOCATION: + break; + } +} + +static void XMLCALL +xspf_end_element(void *user_data, const XML_Char *element_name) +{ + auto *parser = (XspfParser *)user_data; + + switch (parser->state) { + case XspfParser::ROOT: + break; + + case XspfParser::PLAYLIST: + if (strcmp(element_name, "playlist") == 0) + parser->state = XspfParser::ROOT; + + break; + + case XspfParser::TRACKLIST: + if (strcmp(element_name, "tracklist") == 0) + parser->state = XspfParser::PLAYLIST; + + break; + + case XspfParser::TRACK: + if (strcmp(element_name, "track") == 0) { + if (!parser->location.empty()) + parser->songs.emplace_front(std::move(parser->location), + parser->tag_builder.Commit()); + + parser->state = XspfParser::TRACKLIST; + } + + break; + + case XspfParser::TAG: + if (!parser->value.empty()) + parser->tag_builder.AddItem(parser->tag_type, + parser->value); + + parser->state = XspfParser::TRACK; + break; + + case XspfParser::LOCATION: + parser->location = std::move(parser->value); + parser->state = XspfParser::TRACK; + break; + } + + parser->value.clear(); +} + +static void XMLCALL +xspf_char_data(void *user_data, const XML_Char *s, int len) +{ + auto *parser = (XspfParser *)user_data; + + switch (parser->state) { + case XspfParser::ROOT: + case XspfParser::PLAYLIST: + case XspfParser::TRACKLIST: + case XspfParser::TRACK: + break; + + case XspfParser::TAG: + case XspfParser::LOCATION: + parser->value.append(s, len); + break; + } +} + +/* + * The playlist object + * + */ + +static std::unique_ptr +xspf_open_stream(InputStreamPtr &&is) +{ + XspfParser parser; + + { + ExpatParser expat(&parser); + expat.SetElementHandler(xspf_start_element, xspf_end_element); + expat.SetCharacterDataHandler(xspf_char_data); + expat.Parse(*is); + } + + parser.songs.reverse(); + return std::make_unique(std::move(parser.songs)); +} + +static constexpr const char *xspf_suffixes[] = { + "xspf", + nullptr +}; + +static constexpr const char *xspf_mime_types[] = { + "application/xspf+xml", + nullptr +}; + +const PlaylistPlugin xspf_playlist_plugin = + PlaylistPlugin("xspf", xspf_open_stream) + .WithSuffixes(xspf_suffixes) + .WithMimeTypes(xspf_mime_types); diff --git a/src/playlist/plugins/XspfPlaylistPlugin.hxx b/src/playlist/plugins/XspfPlaylistPlugin.hxx new file mode 100644 index 0000000..0b52f3f --- /dev/null +++ b/src/playlist/plugins/XspfPlaylistPlugin.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_XSPF_PLAYLIST_PLUGIN_HXX +#define MPD_XSPF_PLAYLIST_PLUGIN_HXX + +extern const struct PlaylistPlugin xspf_playlist_plugin; + +#endif diff --git a/src/playlist/plugins/meson.build b/src/playlist/plugins/meson.build new file mode 100644 index 0000000..c3cb8e9 --- /dev/null +++ b/src/playlist/plugins/meson.build @@ -0,0 +1,49 @@ +playlist_plugins_sources = [ + 'ExtM3uPlaylistPlugin.cxx', + 'M3uPlaylistPlugin.cxx', + 'PlsPlaylistPlugin.cxx', +] + +playlist_plugins_deps = [ + log_dep, + expat_dep, + flac_dep, + input_basic_dep, + config_dep, +] + +playlist_features.set('ENABLE_CUE', get_option('cue')) +if get_option('cue') + playlist_plugins_sources += [ + '../cue/CueParser.cxx', + 'CuePlaylistPlugin.cxx', + 'EmbeddedCuePlaylistPlugin.cxx', + ] +endif + +if expat_dep.found() + playlist_plugins_sources += [ + 'XspfPlaylistPlugin.cxx', + 'AsxPlaylistPlugin.cxx', + 'RssPlaylistPlugin.cxx', + ] +endif + +if flac_dep.found() + playlist_plugins_sources += 'FlacPlaylistPlugin.cxx' +endif + +playlist_plugins = static_library( + 'playlist_plugins', + playlist_plugins_sources, + include_directories: inc, + dependencies: playlist_plugins_deps, +) + +playlist_plugins_dep = declare_dependency( + link_with: playlist_plugins, + dependencies: [ + playlist_api_dep, + tag_dep, + ], +) diff --git a/src/protocol/Ack.hxx b/src/protocol/Ack.hxx new file mode 100644 index 0000000..0ede4b3 --- /dev/null +++ b/src/protocol/Ack.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ACK_H +#define MPD_ACK_H + +#include +#include + +enum ack { + ACK_ERROR_NOT_LIST = 1, + ACK_ERROR_ARG = 2, + ACK_ERROR_PASSWORD = 3, + ACK_ERROR_PERMISSION = 4, + ACK_ERROR_UNKNOWN = 5, + + ACK_ERROR_NO_EXIST = 50, + ACK_ERROR_PLAYLIST_MAX = 51, + ACK_ERROR_SYSTEM = 52, + ACK_ERROR_PLAYLIST_LOAD = 53, + ACK_ERROR_UPDATE_ALREADY = 54, + ACK_ERROR_PLAYER_SYNC = 55, + ACK_ERROR_EXIST = 56, +}; + +class ProtocolError : public std::runtime_error { + enum ack code; + +public: + template + ProtocolError(enum ack _code, M &&msg) noexcept + :std::runtime_error(std::forward(msg)), code(_code) {} + + enum ack GetCode() const noexcept { + return code; + } +}; + +#endif diff --git a/src/protocol/ArgParser.cxx b/src/protocol/ArgParser.cxx new file mode 100644 index 0000000..29b7ec6 --- /dev/null +++ b/src/protocol/ArgParser.cxx @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ArgParser.hxx" +#include "RangeArg.hxx" +#include "Ack.hxx" +#include "Chrono.hxx" +#include "lib/fmt/ToBuffer.hxx" +#include "util/CNumberParser.hxx" + +#include + +static inline ProtocolError +MakeArgError(const char *msg, const char *value) noexcept +{ + return {ACK_ERROR_ARG, FmtBuffer<256>("{}: {}", msg, value)}; +} + +uint32_t +ParseCommandArgU32(const char *s) +{ + char *test; + auto value = strtoul(s, &test, 10); + if (test == s || *test != '\0') + throw MakeArgError("Integer expected", s); + + return value; +} + +int +ParseCommandArgInt(const char *s, int min_value, int max_value) +{ + char *test; + auto value = strtol(s, &test, 10); + if (test == s || *test != '\0') + throw MakeArgError("Integer expected", s); + + if (value < min_value || value > max_value) + throw MakeArgError("Number too large", s); + + return (int)value; +} + +int +ParseCommandArgInt(const char *s) +{ + return ParseCommandArgInt(s, + std::numeric_limits::min(), + std::numeric_limits::max()); +} + +RangeArg +ParseCommandArgRange(const char *s) +{ + char *test, *test2; + auto value = strtol(s, &test, 10); + if (test == s || (*test != '\0' && *test != ':')) + throw MakeArgError("Integer or range expected", s); + + if (value == -1 && *test == 0) + /* compatibility with older MPD versions: specifying + "-1" makes MPD display the whole list */ + return RangeArg::All(); + + if (value < 0) + throw MakeArgError("Number is negative", s); + + if (value > std::numeric_limits::max()) + throw MakeArgError("Number too large", s); + + RangeArg range; + range.start = (unsigned)value; + + if (*test == ':') { + value = strtol(++test, &test2, 10); + if (*test2 != '\0') + throw MakeArgError("Integer or range expected", s); + + if (test == test2) + return RangeArg::OpenEnded(range.start); + + if (value < 0) + throw MakeArgError("Number is negative", s); + + + if (value > std::numeric_limits::max()) + throw MakeArgError("Number too large", s); + + range.end = (unsigned)value; + } else { + return RangeArg::Single(range.start); + } + + if (!range.IsWellFormed()) + throw MakeArgError("Malformed range", s); + + return range; +} + +unsigned +ParseCommandArgUnsigned(const char *s, unsigned max_value) +{ + char *endptr; + auto value = strtoul(s, &endptr, 10); + if (endptr == s || *endptr != 0) + throw MakeArgError("Integer expected", s); + + if (value > max_value) + throw MakeArgError("Number too large", s); + + return (unsigned)value; +} + +unsigned +ParseCommandArgUnsigned(const char *s) +{ + return ParseCommandArgUnsigned(s, + std::numeric_limits::max()); +} + +bool +ParseCommandArgBool(const char *s) +{ + char *endptr; + auto value = strtol(s, &endptr, 10); + if (endptr == s || *endptr != 0 || (value != 0 && value != 1)) + throw MakeArgError("Boolean (0/1) expected", s); + + return !!value; +} + +float +ParseCommandArgFloat(const char *s) +{ + char *endptr; + auto value = ParseFloat(s, &endptr); + if (endptr == s || *endptr != 0) + throw MakeArgError("Float expected", s); + + return value; +} + +SongTime +ParseCommandArgSongTime(const char *s) +{ + auto value = ParseCommandArgFloat(s); + if (value < 0) + throw MakeArgError("Negative value not allowed", s); + + return SongTime::FromS(value); +} + +SignedSongTime +ParseCommandArgSignedSongTime(const char *s) +{ + auto value = ParseCommandArgFloat(s); + return SignedSongTime::FromS(value); +} diff --git a/src/protocol/ArgParser.hxx b/src/protocol/ArgParser.hxx new file mode 100644 index 0000000..66dff17 --- /dev/null +++ b/src/protocol/ArgParser.hxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PROTOCOL_ARGPARSER_HXX +#define MPD_PROTOCOL_ARGPARSER_HXX + +#include + +struct RangeArg; +class SongTime; +class SignedSongTime; + +uint32_t +ParseCommandArgU32(const char *s); + +int +ParseCommandArgInt(const char *s, int min_value, int max_value); + +int +ParseCommandArgInt(const char *s); + +RangeArg +ParseCommandArgRange(const char *s); + +unsigned +ParseCommandArgUnsigned(const char *s, unsigned max_value); + +unsigned +ParseCommandArgUnsigned(const char *s); + +bool +ParseCommandArgBool(const char *s); + +float +ParseCommandArgFloat(const char *s); + +SongTime +ParseCommandArgSongTime(const char *s); + +SignedSongTime +ParseCommandArgSignedSongTime(const char *s); + +#endif diff --git a/src/protocol/IdleFlags.cxx b/src/protocol/IdleFlags.cxx new file mode 100644 index 0000000..ea6bad1 --- /dev/null +++ b/src/protocol/IdleFlags.cxx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Support library for the "idle" command. + * + */ + +#include "protocol/IdleFlags.hxx" +#include "util/ASCII.hxx" + +#include + +static constexpr const char * idle_names[] = { + "database", + "stored_playlist", + "playlist", + "player", + "mixer", + "output", + "options", + "sticker", + "update", + "subscription", + "message", + "neighbor", + "mount", + "partition", + nullptr, +}; + +const char*const* +idle_get_names() noexcept +{ + return idle_names; +} + +unsigned +idle_parse_name(const char *name) noexcept +{ +#if !CLANG_CHECK_VERSION(3,6) + /* disabled on clang due to -Wtautological-pointer-compare */ + assert(name != nullptr); +#endif + + for (unsigned i = 0; idle_names[i] != nullptr; ++i) + if (StringEqualsCaseASCII(name, idle_names[i])) + return 1 << i; + + return 0; +} diff --git a/src/protocol/IdleFlags.hxx b/src/protocol/IdleFlags.hxx new file mode 100644 index 0000000..3e23ae3 --- /dev/null +++ b/src/protocol/IdleFlags.hxx @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Support library for the "idle" command. + * + */ + +#ifndef MPD_IDLE_FLAGS_HXX +#define MPD_IDLE_FLAGS_HXX + +/** song database has been updated*/ +static constexpr unsigned IDLE_DATABASE = 0x1; + +/** a stored playlist has been modified, created, deleted or + renamed */ +static constexpr unsigned IDLE_STORED_PLAYLIST = 0x2; + +/** the current playlist has been modified */ +static constexpr unsigned IDLE_PLAYLIST = 0x4; + +/** the player state has changed: play, stop, pause, seek, ... */ +static constexpr unsigned IDLE_PLAYER = 0x8; + +/** the volume has been modified */ +static constexpr unsigned IDLE_MIXER = 0x10; + +/** an audio output device has been enabled or disabled */ +static constexpr unsigned IDLE_OUTPUT = 0x20; + +/** options have changed: crossfade; random; repeat; ... */ +static constexpr unsigned IDLE_OPTIONS = 0x40; + +/** a sticker has been modified. */ +static constexpr unsigned IDLE_STICKER = 0x80; + +/** a database update has started or finished. */ +static constexpr unsigned IDLE_UPDATE = 0x100; + +/** a client has subscribed or unsubscribed to/from a channel */ +static constexpr unsigned IDLE_SUBSCRIPTION = 0x200; + +/** a message on the subscribed channel was received */ +static constexpr unsigned IDLE_MESSAGE = 0x400; + +/** a neighbor was found or lost */ +static constexpr unsigned IDLE_NEIGHBOR = 0x800; + +/** the mount list has changed */ +static constexpr unsigned IDLE_MOUNT = 0x1000; + +/** the partition list has changed */ +static constexpr unsigned IDLE_PARTITION = 0x2000; + +/** + * Get idle names + */ +[[gnu::const]] +const char*const* +idle_get_names() noexcept; + +/** + * Parse an idle name and return its mask. Returns 0 if the given + * name is unknown. + */ +[[gnu::nonnull]] [[gnu::pure]] +unsigned +idle_parse_name(const char *name) noexcept; + +#endif diff --git a/src/protocol/RangeArg.hxx b/src/protocol/RangeArg.hxx new file mode 100644 index 0000000..205a735 --- /dev/null +++ b/src/protocol/RangeArg.hxx @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PROTOCOL_RANGE_ARG_HXX +#define MPD_PROTOCOL_RANGE_ARG_HXX + +#include + +struct RangeArg { + unsigned start, end; + + /** + * Construct an open-ended range starting at the given index. + */ + static constexpr RangeArg OpenEnded(unsigned start) noexcept { + return { start, std::numeric_limits::max() }; + } + + static constexpr RangeArg All() noexcept { + return OpenEnded(0); + } + + /** + * Construct an instance describing exactly one index. + */ + static constexpr RangeArg Single(unsigned i) noexcept { + return { i, i + 1 }; + } + + constexpr bool operator==(RangeArg other) const noexcept { + return start == other.start && end == other.end; + } + + constexpr bool operator!=(RangeArg other) const noexcept { + return !(*this == other); + } + + constexpr bool IsOpenEnded() const noexcept { + return end == All().end; + } + + constexpr bool IsAll() const noexcept { + return *this == All(); + } + + constexpr bool IsWellFormed() const noexcept { + return start <= end; + } + + /** + * Is this range empty? A malformed range also counts as + * "empty" for this method. + */ + constexpr bool IsEmpty() const noexcept { + return start >= end; + } + + /** + * Check if the range contains at least this number of items. + * Unlike Count(), this allows the object to be malformed. + */ + constexpr bool HasAtLeast(unsigned n) const noexcept { + return start + n <= end; + } + + constexpr bool Contains(unsigned i) const noexcept { + return i >= start && i < end; + } + + /** + * Count the number of items covered by this range. This requires the + * object to be well-formed. + */ + constexpr unsigned Count() const noexcept { + return end - start; + } + + /** + * Make sure that both start and end are within the given + * count. + */ + constexpr void ClipRelaxed(unsigned count) noexcept { + if (end > count) + end = count; + + if (start > end) + start = end; + } + + /** + * Check if the start index is valid and clip the end of the + * range. + * + * @return false if the start is out of range + */ + [[nodiscard]] + constexpr bool CheckClip(unsigned count) noexcept { + if (start > count) + return false; + + if (end > count) + end = count; + + return true; + } + + /** + * Check if start and end index are valid and adjust the end if this + * is an open-ended range. + * + * @return false if start or end is out of range + */ + [[nodiscard]] + constexpr bool CheckAdjustEnd(unsigned count) noexcept { + if (start > count) + return false; + + if (end > count) { + if (!IsOpenEnded()) + return false; + + end = count; + } + + return true; + } +}; + +#endif diff --git a/src/queue/IdTable.hxx b/src/queue/IdTable.hxx new file mode 100644 index 0000000..e58618d --- /dev/null +++ b/src/queue/IdTable.hxx @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ID_TABLE_HXX +#define MPD_ID_TABLE_HXX + +#include + +/** + * A table that maps id numbers to position numbers. + */ +class IdTable { + const unsigned size; + + /** + * How many members of "data" are initialized? + * + * The initial value is 1 and not 0 because the first element + * of the array is never used, because 0 is not a valid song + * id. + */ + unsigned initialized = 1; + + /** + * An incrementing counter helping GenerateId() to generate + * the next id. + */ + unsigned next = 1; + + /** + * A lookup table: the index is the id number and the value is + * the position; -1 means this id is unassigned. + */ + int *const data = new int[size]; + +public: + explicit constexpr IdTable(unsigned _size) noexcept + :size(_size) {} + + constexpr ~IdTable() noexcept { + delete[] data; + } + + IdTable(const IdTable &) = delete; + IdTable &operator=(const IdTable &) = delete; + + constexpr int IdToPosition(unsigned id) const noexcept { + return id < initialized + ? data[id] + : -1; + } + + constexpr unsigned GenerateId() noexcept { + assert(next > 0); + assert(next <= initialized); + + while (true) { + unsigned id = next; + + ++next; + if (next == size) + next = 1; + + if (id == initialized) { + /* the caller will initialize + data[id] */ + ++initialized; + return id; + } + + assert(id < initialized); + + if (data[id] < 0) + return id; + } + } + + constexpr unsigned Insert(unsigned position) noexcept { + unsigned id = GenerateId(); + assert(id < initialized); + data[id] = position; + return id; + } + + constexpr void Move(unsigned id, unsigned position) noexcept { + assert(id < initialized); + assert(data[id] >= 0); + + data[id] = position; + } + + constexpr void Erase(unsigned id) noexcept { + assert(id < initialized); + assert(data[id] >= 0); + + data[id] = -1; + } +}; + +#endif diff --git a/src/queue/Listener.hxx b/src/queue/Listener.hxx new file mode 100644 index 0000000..eca8d45 --- /dev/null +++ b/src/queue/Listener.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_QUEUE_LISTENER_HXX +#define MPD_QUEUE_LISTENER_HXX + +class QueueListener { +public: + /** + * Called after the queue has been modified. + */ + virtual void OnQueueModified() noexcept = 0; + + /** + * Called after a playback options have been changed. + */ + virtual void OnQueueOptionsChanged() noexcept = 0; + + /** + * Called after the player has started playing a new song. + * This gets called by playlist::SyncWithPlayer() after it has + * been notified by the player thread. + */ + virtual void OnQueueSongStarted() noexcept = 0; +}; + +#endif diff --git a/src/queue/Playlist.cxx b/src/queue/Playlist.cxx new file mode 100644 index 0000000..d0707bc --- /dev/null +++ b/src/queue/Playlist.cxx @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Playlist.hxx" +#include "Listener.hxx" +#include "PlaylistError.hxx" +#include "player/Control.hxx" +#include "song/DetachedSong.hxx" +#include "SingleMode.hxx" +#include "ConsumeMode.hxx" +#include "Log.hxx" + +#include + +void +playlist::TagModified(DetachedSong &&song) noexcept +{ + if (!playing) + return; + + assert(current >= 0); + + DetachedSong ¤t_song = queue.GetOrder(current); + if (song.IsSame(current_song)) + current_song.MoveTagItemsFrom(std::move(song)); + + queue.ModifyAtOrder(current); + OnModified(); +} + +void +playlist::TagModified(const char *real_uri, const Tag &tag) noexcept +{ + bool modified = false; + + for (unsigned i = 0; i < queue.length; ++i) { + auto &song = *queue.items[i].song; + if (song.IsRealURI(real_uri)) { + song.SetTag(tag); + queue.ModifyAtPosition(i); + modified = true; + } + } + + if (modified) + OnModified(); +} + +inline void +playlist::QueueSongOrder(PlayerControl &pc, unsigned order) noexcept + +{ + assert(queue.IsValidOrder(order)); + + queued = order; + + const DetachedSong &song = queue.GetOrder(order); + + FmtDebug(playlist_domain, "queue song {}:{:?}", + queued, song.GetURI()); + + pc.LockEnqueueSong(std::make_unique(song)); +} + +void +playlist::SongStarted() noexcept +{ + assert(current >= 0); + + /* reset a song's "priority" when playback starts */ + if (queue.SetPriority(queue.OrderToPosition(current), 0, -1, false)) + OnModified(); +} + +inline void +playlist::QueuedSongStarted(PlayerControl &pc) noexcept +{ + assert(!pc.LockGetSyncInfo().has_next_song); + assert(queued >= -1); + assert(current >= 0); + + /* queued song has started: copy queued to current, + and notify the clients */ + + const int old_current = current; + current = queued; + queued = -1; + + if (queue.consume != ConsumeMode::OFF) + DeleteOrder(pc, old_current); + + if (queue.consume == ConsumeMode::ONE_SHOT) { + queue.consume = ConsumeMode::OFF; + listener.OnQueueOptionsChanged(); + } + + listener.OnQueueSongStarted(); + + SongStarted(); +} + +const DetachedSong * +playlist::GetQueuedSong() const noexcept +{ + return playing && queued >= 0 + ? &queue.GetOrder(queued) + : nullptr; +} + +void +playlist::UpdateQueuedSong(PlayerControl &pc, + const DetachedSong *prev) noexcept +{ + if (!playing) + return; + + if (prev == nullptr && bulk_edit) + /* postponed until CommitBulk() to avoid always + queueing the first song that is being added (in + random mode) */ + return; + + assert(!queue.IsEmpty()); + assert((queued < 0) == (prev == nullptr)); + + const int next_order = current >= 0 + ? queue.GetNextOrder(current) + : 0; + + if (next_order == 0 && queue.random && queue.single == SingleMode::OFF) { + /* shuffle the song order again, so we get a different + order each time the playlist is played + completely */ + const unsigned current_position = + queue.OrderToPosition(current); + + queue.ShuffleOrder(); + + /* make sure that the current still points to + the current song, after the song order has been + shuffled */ + current = queue.PositionToOrder(current_position); + } + + const DetachedSong *const next_song = next_order >= 0 + ? &queue.GetOrder(next_order) + : nullptr; + + if (prev != nullptr && next_song != prev) { + /* clear the currently queued song */ + pc.LockCancel(); + queued = -1; + } + + if (next_order >= 0) { + if (next_song != prev) + QueueSongOrder(pc, next_order); + else + queued = next_order; + } +} + +void +playlist::SyncWithPlayer(PlayerControl &pc) noexcept +{ + if (!playing) + /* this event has reached us out of sync: we aren't + playing anymore; ignore the event */ + return; + + const auto i = pc.LockGetSyncInfo(); + + if (i.state == PlayerState::STOP) + /* the player thread has stopped: check if playback + should be restarted with the next song. That can + happen if the playlist isn't filling the queue fast + enough */ + ResumePlayback(pc); + else { + /* check if the player thread has already started + playing the queued song */ + if (!i.has_next_song && queued != -1) + QueuedSongStarted(pc); + + /* make sure the queued song is always set (if + possible) */ + if (!pc.LockGetSyncInfo().has_next_song && queued < 0) + UpdateQueuedSong(pc, nullptr); + } +} + +inline void +playlist::ResumePlayback(PlayerControl &pc) noexcept +{ + assert(playing); + assert(pc.GetState() == PlayerState::STOP); + + const auto error = pc.GetErrorType(); + if (error == PlayerError::NONE) + error_count = 0; + else + ++error_count; + + if ((stop_on_error && error != PlayerError::NONE) || + error == PlayerError::OUTPUT || + error_count >= queue.GetLength()) + /* too many errors, or critical error: stop + playback */ + Stop(pc); + else + /* continue playback at the next song */ + try { + PlayNext(pc); + } catch (...) { + /* TODO: log error? */ + } +} + +void +playlist::SetRepeat(PlayerControl &pc, bool status) noexcept +{ + if (status == queue.repeat) + return; + + queue.repeat = status; + + pc.LockSetBorderPause(queue.single != SingleMode::OFF && !queue.repeat); + + /* if the last song is currently being played, the "next song" + might change when repeat mode is toggled */ + UpdateQueuedSong(pc, GetQueuedSong()); + + listener.OnQueueOptionsChanged(); +} + +static void +playlist_order(playlist &playlist) noexcept +{ + if (playlist.current >= 0) + /* update playlist.current, order==position now */ + playlist.current = playlist.queue.OrderToPosition(playlist.current); + + playlist.queue.RestoreOrder(); +} + +void +playlist::SetSingle(PlayerControl &pc, SingleMode status) noexcept +{ + if (status == queue.single) + return; + + queue.single = status; + + + pc.LockSetBorderPause(queue.single != SingleMode::OFF && !queue.repeat); + + /* if the last song is currently being played, the "next song" + might change when single mode is toggled */ + UpdateQueuedSong(pc, GetQueuedSong()); + + listener.OnQueueOptionsChanged(); +} + +void +playlist::SetConsume(ConsumeMode status) noexcept +{ + if (status == queue.consume) + return; + + queue.consume = status; + + listener.OnQueueOptionsChanged(); +} + +void +playlist::SetRandom(PlayerControl &pc, bool status) noexcept +{ + if (status == queue.random) + return; + + const DetachedSong *const queued_song = GetQueuedSong(); + + queue.random = status; + + if (queue.random) { + /* shuffle the queue order, but preserve current */ + + const int current_position = playing + ? GetCurrentPosition() + : -1; + + queue.ShuffleOrder(); + + if (current_position >= 0) { + /* make sure the current song is the first in + the order list, so the whole rest of the + playlist is played after that */ + unsigned current_order = + queue.PositionToOrder(current_position); + current = queue.MoveOrder(current_order, 0); + } else + current = -1; + } else + playlist_order(*this); + + UpdateQueuedSong(pc, queued_song); + + listener.OnQueueOptionsChanged(); +} + +int +playlist::GetCurrentPosition() const noexcept +{ + return current >= 0 + ? queue.OrderToPosition(current) + : -1; +} + +int +playlist::GetNextPosition() const noexcept +{ + if (current < 0) + return -1; + + if (queue.single != SingleMode::OFF && queue.repeat) + return queue.OrderToPosition(current); + else if (queue.IsValidOrder(current + 1)) + return queue.OrderToPosition(current + 1); + else if (queue.repeat) + return queue.OrderToPosition(0); + + return -1; +} + +void +playlist::BorderPause(PlayerControl &pc) noexcept +{ + if (queue.single == SingleMode::ONE_SHOT) { + queue.single = SingleMode::OFF; + pc.LockSetBorderPause(false); + + listener.OnQueueOptionsChanged(); + } +} diff --git a/src/queue/Playlist.hxx b/src/queue/Playlist.hxx new file mode 100644 index 0000000..4b08aec --- /dev/null +++ b/src/queue/Playlist.hxx @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "SingleMode.hxx" +#include "ConsumeMode.hxx" +#include "db/Features.hxx" // for ENABLE_DATABASE +#include "queue/Queue.hxx" + +enum TagType : uint8_t; +struct Tag; +struct RangeArg; +class PlayerControl; +class DetachedSong; +class Database; +class SongLoader; +class SongTime; +class SignedSongTime; +class QueueListener; + +struct playlist { + /** + * The song queue - it contains the "real" playlist. + */ + Queue queue; + + QueueListener &listener; + + /** + * This value is true if the player is currently playing (or + * should be playing). + */ + bool playing = false; + + /** + * If true, then any error is fatal; if false, MPD will + * attempt to play the next song on non-fatal errors. During + * seeking, this flag is set. + */ + bool stop_on_error; + + /** + * If true, then a bulk edit has been initiated by + * BeginBulk(), and UpdateQueuedSong() and OnModified() will + * be postponed until CommitBulk() + */ + bool bulk_edit = false; + + /** + * Has the queue been modified during bulk edit mode? + */ + bool bulk_modified; + + /** + * Number of errors since playback was started. If this + * number exceeds the length of the playlist, MPD gives up, + * because all songs have been tried. + */ + unsigned error_count; + + /** + * The "current song pointer" (the order number). This is the + * song which is played when we get the "play" command. It is + * also the song which is currently being played. + */ + int current = -1; + + /** + * The "next" song to be played (the order number), when the + * current one finishes. The decoder thread may start + * decoding and buffering it, while the "current" song is + * still playing. + * + * This variable is only valid if #playing is true. + */ + int queued = -1; + + playlist(unsigned max_length, + QueueListener &_listener) noexcept + :queue(max_length), + listener(_listener) + { + } + + uint32_t GetVersion() const noexcept { + return queue.version; + } + + unsigned GetLength() const noexcept { + return queue.GetLength(); + } + + unsigned PositionToId(unsigned position) const noexcept { + return queue.PositionToId(position); + } + + [[gnu::pure]] + int GetCurrentPosition() const noexcept; + + [[gnu::pure]] + int GetNextPosition() const noexcept; + + const std::string_view GetLastLoadedPlaylist() const noexcept { + return queue.last_loaded_playlist; + } + + void SetLastLoadedPlaylist(const char *playlist_name) noexcept { + queue.last_loaded_playlist = playlist_name; + } + + /** + * Returns the song object which is currently queued. Returns + * none if there is none (yet?) or if MPD isn't playing. + */ + [[gnu::pure]] + const DetachedSong *GetQueuedSong() const noexcept; + + /** + * This is the "PLAYLIST" event handler. It is invoked by the + * player thread whenever it requests a new queued song, or + * when it exits. + */ + void SyncWithPlayer(PlayerControl &pc) noexcept; + + /** + * This is the "BORDER_PAUSE" event handler. It is invoked by + * the player thread whenever playback goes into border pause. + */ + void BorderPause(PlayerControl &pc) noexcept; + +protected: + /** + * Called by all editing methods after a modification. + * Updates the queue version and invokes + * QueueListener::OnQueueModified(). + */ + void OnModified() noexcept; + + /** + * Called when playback of a new song starts. Unlike + * QueuedSongStarted(), this also gets called when the user + * manually switches to another song. It may be used for + * playlist fixups. + * + * The song being started is specified by the #current + * attribute. + */ + void SongStarted() noexcept; + + /** + * Updates the "queued song". Calculates the next song + * according to the current one (if MPD isn't playing, it + * takes the first song), and queues this song. Clears the + * old queued song if there was one. + * + * @param prev the song which was previously queued, as + * determined by playlist_get_queued_song() + */ + void UpdateQueuedSong(PlayerControl &pc, const DetachedSong *prev) noexcept; + + /** + * Queue a song, addressed by its order number. + */ + void QueueSongOrder(PlayerControl &pc, unsigned order) noexcept; + + /** + * Called when the player thread has started playing the + * "queued" song, i.e. it has switched from one song to the + * next automatically. + */ + void QueuedSongStarted(PlayerControl &pc) noexcept; + + /** + * The player has stopped for some reason. Check the error, + * and decide whether to re-start playback. + */ + void ResumePlayback(PlayerControl &pc) noexcept; + +public: + void BeginBulk() noexcept; + void CommitBulk(PlayerControl &pc) noexcept; + + void Clear(PlayerControl &pc) noexcept; + + /** + * A tag in the play queue has been modified by the player + * thread. Apply the given song's tag to the current song if + * the song matches. + */ + void TagModified(DetachedSong &&song) noexcept; + + /** + * @param real_uri the song's "real uri" (see + * DetachedSong::GetRealURI(), DetachedSong::IsRealURI()) + */ + void TagModified(const char *real_uri, const Tag &tag) noexcept; + +#ifdef ENABLE_DATABASE + /** + * The database has been modified. Pull all updates. + */ + void DatabaseModified(const Database &db); +#endif + + /** + * Throws PlaylistError if the queue would be too large. + * + * @return the new song id + */ + unsigned AppendSong(PlayerControl &pc, DetachedSong &&song); + + /** + * Throws #std::runtime_error on error. + * + * @return the new song id + */ + unsigned AppendURI(PlayerControl &pc, + const SongLoader &loader, + const char *uri_utf8); + +protected: + void DeleteInternal(PlayerControl &pc, + unsigned song, const DetachedSong **queued_p) noexcept; + +public: + void DeletePosition(PlayerControl &pc, unsigned position); + + void DeleteOrder(PlayerControl &pc, unsigned order) { + DeletePosition(pc, queue.OrderToPosition(order)); + } + + void DeleteId(PlayerControl &pc, unsigned id); + + /** + * Deletes a range of songs from the playlist. + * + * @param start the position of the first song to delete + * @param end the position after the last song to delete + */ + void DeleteRange(PlayerControl &pc, RangeArg range); + + /** + * Mark the given song as "stale", i.e. as not being available + * anymore. This gets called when a song is removed from the + * database. The method attempts to remove all instances of + * this song from the queue. + */ + void StaleSong(PlayerControl &pc, const char *uri) noexcept; + + void Shuffle(PlayerControl &pc, RangeArg range); + + void MoveRange(PlayerControl &pc, RangeArg range, unsigned to); + + void SwapPositions(PlayerControl &pc, unsigned song1, unsigned song2); + + void SwapIds(PlayerControl &pc, unsigned id1, unsigned id2); + + void SetPriorityRange(PlayerControl &pc, + RangeArg position_range, + uint8_t priority); + + void SetPriorityId(PlayerControl &pc, + unsigned song_id, uint8_t priority); + + /** + * Sets the start_time and end_time attributes on the song + * with the specified id. + * + * Throws on error. + */ + void SetSongIdRange(PlayerControl &pc, unsigned id, + SongTime start, SongTime end); + + /** + * Throws on error. + */ + void AddSongIdTag(unsigned id, TagType tag_type, + const char *value); + + /** + * Throws on error. + */ + void ClearSongIdTag(unsigned id, TagType tag_type); + + void Stop(PlayerControl &pc) noexcept; + + /** + * Play any song ("current" song, or the first song. Resumes + * playback if paused. + * + * Throws on error. + */ + void PlayAny(PlayerControl &pc); + + /** + * Throws on error. + */ + void PlayPosition(PlayerControl &pc, unsigned position); + + /** + * Throws on error. + */ + void PlayOrder(PlayerControl &pc, unsigned order); + + /** + * Throws on error. + */ + void PlayId(PlayerControl &pc, unsigned id); + + /** + * Throws on error. + */ + void PlayNext(PlayerControl &pc); + + /** + * Throws on error. + */ + void PlayPrevious(PlayerControl &pc); + + /** + * Throws on error. + */ + void SeekSongOrder(PlayerControl &pc, + unsigned song_order, + SongTime seek_time); + + /** + * Throws on error. + */ + void SeekSongPosition(PlayerControl &pc, + unsigned sonag_position, + SongTime seek_time); + + /** + * Throws on error. + */ + void SeekSongId(PlayerControl &pc, + unsigned song_id, SongTime seek_time); + + /** + * Seek within the current song. Fails if MPD is not currently + * playing. + * + * Throws on error. + * + * @param seek_time the time + * @param relative if true, then the specified time is relative to the + * current position + */ + void SeekCurrent(PlayerControl &pc, + SignedSongTime seek_time, bool relative); + + bool GetRepeat() const noexcept { + return queue.repeat; + } + + void SetRepeat(PlayerControl &pc, bool new_value) noexcept; + + bool GetRandom() const noexcept { + return queue.random; + } + + void SetRandom(PlayerControl &pc, bool new_value) noexcept; + + SingleMode GetSingle() const noexcept { + return queue.single; + } + + void SetSingle(PlayerControl &pc, SingleMode new_value) noexcept; + + ConsumeMode GetConsume() const noexcept { + return queue.consume; + } + + void SetConsume(ConsumeMode new_value) noexcept; + +private: + /** + * Prepare a manual song change: move the given song to the + * current playback order. This is done to avoid skipping + * upcoming songs in the order list. The newly selected song + * shall be inserted in the order list, and the rest shall be + * played after that as previously planned. + * + * @return the new order number of the given song + */ + unsigned MoveOrderToCurrent(unsigned old_order) noexcept; +}; diff --git a/src/queue/PlaylistControl.cxx b/src/queue/PlaylistControl.cxx new file mode 100644 index 0000000..17ca93b --- /dev/null +++ b/src/queue/PlaylistControl.cxx @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Functions for controlling playback on the playlist level. + * + */ + +#include "Playlist.hxx" +#include "PlaylistError.hxx" +#include "player/Control.hxx" +#include "song/DetachedSong.hxx" +#include "Listener.hxx" +#include "Log.hxx" + +void +playlist::Stop(PlayerControl &pc) noexcept +{ + if (!playing) + return; + + assert(current >= 0); + + LogDebug(playlist_domain, "stop"); + pc.LockStop(); + queued = -1; + playing = false; + + if (queue.random) { + /* shuffle the playlist, so the next playback will + result in a new random order */ + + unsigned current_position = queue.OrderToPosition(current); + + queue.ShuffleOrder(); + + /* make sure that "current" stays valid, and the next + "play" command plays the same song again */ + current = queue.PositionToOrder(current_position); + } +} + +unsigned +playlist::MoveOrderToCurrent(unsigned old_order) noexcept +{ + if (!queue.random) + /* no-op because there is no order list */ + return old_order; + + if (playing) { + /* already playing: move the specified song after the + current one (because the current one has already + been playing and shall not be played again) */ + return queue.MoveOrderAfter(old_order, current); + } else if (current >= 0) { + /* not playing: move the specified song before the + current one, so it will be played eventually */ + return queue.MoveOrderBefore(old_order, current); + } else { + /* not playing anything: move the specified song to + the front */ + return queue.MoveOrderBefore(old_order, 0); + } +} + +void +playlist::PlayOrder(PlayerControl &pc, unsigned order) +{ + playing = true; + queued = -1; + + const DetachedSong &song = queue.GetOrder(order); + + FmtDebug(playlist_domain, "play {}:{:?}", order, song.GetURI()); + + current = order; + + pc.Play(std::make_unique(song)); + + SongStarted(); +} + +void +playlist::PlayAny(PlayerControl &pc) +{ + if (queue.IsEmpty()) + return; + + if (playing) { + /* already playing: unpause playback, just in + case it was paused, and return */ + pc.LockSetPause(false); + return; + } + + pc.LockClearError(); + stop_on_error = false; + error_count = 0; + + /* select a song: "current" song, or the first one */ + unsigned order = current >= 0 + ? static_cast(current) + : 0; + + PlayOrder(pc, order); +} + +void +playlist::PlayPosition(PlayerControl &pc, unsigned position) +{ + pc.LockClearError(); + + if (!queue.IsValidPosition(position)) + throw PlaylistError::BadRange(); + + unsigned order = position; + if (queue.random) { + order = queue.PositionToOrder(position); + order = MoveOrderToCurrent(order); + } + + stop_on_error = false; + error_count = 0; + + PlayOrder(pc, order); +} + +void +playlist::PlayId(PlayerControl &pc, unsigned id) +{ + int position = queue.IdToPosition(id); + if (position < 0) + throw PlaylistError::NoSuchSong(); + + PlayPosition(pc, static_cast(position)); +} + +void +playlist::PlayNext(PlayerControl &pc) +{ + if (!playing) + throw PlaylistError::NotPlaying(); + + assert(!queue.IsEmpty()); + assert(queue.IsValidOrder(current)); + + const int old_current = current; + stop_on_error = false; + + /* determine the next song from the queue's order list */ + + const int next_order = queue.GetNextOrder(current); + if (next_order < 0) { + /* no song after this one: stop playback */ + Stop(pc); + + /* reset "current song" */ + current = -1; + } + else + { + if (next_order == 0 && queue.random) { + /* The queue told us that the next song is the first + song. This means we are in repeat mode. Shuffle + the queue order, so this time, the user hears the + songs in a different than before */ + assert(queue.repeat); + + queue.ShuffleOrder(); + + /* note that current and queued are + now invalid, but PlayOrder() will + discard them anyway */ + } + + PlayOrder(pc, next_order); + } + + /* Consume mode removes each played songs. */ + if (queue.consume != ConsumeMode::OFF) + DeleteOrder(pc, old_current); + + /* Disable consume mode after consuming one song in oneshot mode. */ + if (queue.consume == ConsumeMode::ONE_SHOT) { + queue.consume = ConsumeMode::OFF; + listener.OnQueueOptionsChanged(); + } +} + +void +playlist::PlayPrevious(PlayerControl &pc) +{ + if (!playing) + throw PlaylistError::NotPlaying(); + + assert(!queue.IsEmpty()); + + int order; + if (current > 0) { + /* play the preceding song */ + order = current - 1; + } else if (queue.repeat) { + /* play the last song in "repeat" mode */ + order = queue.GetLength() - 1; + } else { + /* re-start playing the current song if it's + the first one */ + order = current; + } + + PlayOrder(pc, order); +} + +void +playlist::SeekSongOrder(PlayerControl &pc, unsigned i, SongTime seek_time) +{ + assert(queue.IsValidOrder(i)); + + pc.LockClearError(); + stop_on_error = true; + error_count = 0; + + if (!playing || (unsigned)current != i) { + /* seeking is not within the current song - prepare + song change */ + + i = MoveOrderToCurrent(i); + + playing = true; + current = i; + } + + queued = -1; + + try { + pc.LockSeek(std::make_unique(queue.GetOrder(i)), seek_time); + } catch (...) { + UpdateQueuedSong(pc, nullptr); + throw; + } + + UpdateQueuedSong(pc, nullptr); +} + +void +playlist::SeekSongPosition(PlayerControl &pc, unsigned song, + SongTime seek_time) +{ + if (!queue.IsValidPosition(song)) + throw PlaylistError::BadRange(); + + unsigned i = queue.random + ? queue.PositionToOrder(song) + : song; + + SeekSongOrder(pc, i, seek_time); +} + +void +playlist::SeekSongId(PlayerControl &pc, unsigned id, SongTime seek_time) +{ + int song = queue.IdToPosition(id); + if (song < 0) + throw PlaylistError::NoSuchSong(); + + SeekSongPosition(pc, song, seek_time); +} + +void +playlist::SeekCurrent(PlayerControl &pc, + SignedSongTime seek_time, bool relative) +{ + if (!playing) + throw PlaylistError::NotPlaying(); + + if (relative) { + const auto status = pc.LockGetStatus(); + + if (status.state != PlayerState::PLAY && + status.state != PlayerState::PAUSE) + throw PlaylistError::NotPlaying(); + + seek_time += status.elapsed_time; + } + + if (seek_time.IsNegative()) + seek_time = SignedSongTime::zero(); + + SeekSongOrder(pc, current, SongTime(seek_time)); +} diff --git a/src/queue/PlaylistEdit.cxx b/src/queue/PlaylistEdit.cxx new file mode 100644 index 0000000..3b1bd0f --- /dev/null +++ b/src/queue/PlaylistEdit.cxx @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Functions for editing the playlist (adding, removing, reordering + * songs in the queue). + * + */ + +#include "Playlist.hxx" +#include "Listener.hxx" +#include "PlaylistError.hxx" +#include "player/Control.hxx" +#include "protocol/RangeArg.hxx" +#include "song/DetachedSong.hxx" +#include "SongLoader.hxx" + +#include + +void +playlist::OnModified() noexcept +{ + if (bulk_edit) { + /* postponed to CommitBulk() */ + bulk_modified = true; + return; + } + + queue.IncrementVersion(); + + listener.OnQueueModified(); +} + +void +playlist::Clear(PlayerControl &pc) noexcept +{ + Stop(pc); + + queue.Clear(); + current = -1; + + OnModified(); +} + +void +playlist::BeginBulk() noexcept +{ + assert(!bulk_edit); + + bulk_edit = true; + bulk_modified = false; +} + +void +playlist::CommitBulk(PlayerControl &pc) noexcept +{ + assert(bulk_edit); + + bulk_edit = false; + if (!bulk_modified) + return; + + if (queued < 0) + /* if no song was queued, UpdateQueuedSong() is being + ignored in "bulk" edit mode; now that we have + shuffled all new songs, we can pick a random one + (instead of always picking the first one that was + added) */ + UpdateQueuedSong(pc, nullptr); + + OnModified(); +} + +unsigned +playlist::AppendSong(PlayerControl &pc, DetachedSong &&song) +{ + unsigned id; + + if (queue.IsFull()) + throw PlaylistError(PlaylistResult::TOO_LARGE, + "Playlist is too large"); + + const DetachedSong *const queued_song = GetQueuedSong(); + + id = queue.Append(std::move(song), 0); + + if (queue.random) { + /* shuffle the new song into the list of remaining + songs to play */ + + unsigned start; + if (queued >= 0) + start = queued + 1; + else + start = current + 1; + if (start < queue.GetLength()) + queue.ShuffleOrderLastWithPriority(start, queue.GetLength()); + } + + UpdateQueuedSong(pc, queued_song); + OnModified(); + + return id; +} + +unsigned +playlist::AppendURI(PlayerControl &pc, const SongLoader &loader, + const char *uri) +{ + return AppendSong(pc, loader.LoadSong(uri)); +} + +void +playlist::SwapPositions(PlayerControl &pc, unsigned song1, unsigned song2) +{ + if (!queue.IsValidPosition(song1) || !queue.IsValidPosition(song2)) + throw PlaylistError::BadRange(); + + const DetachedSong *const queued_song = GetQueuedSong(); + + queue.SwapPositions(song1, song2); + + if (queue.random) { + /* update the queue order, so that current + still points to the current song order */ + + queue.SwapOrders(queue.PositionToOrder(song1), + queue.PositionToOrder(song2)); + } else if (current >= 0){ + /* correct the "current" song order */ + + if (unsigned(current) == song1) + current = song2; + else if (unsigned(current) == song2) + current = song1; + } + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::SwapIds(PlayerControl &pc, unsigned id1, unsigned id2) +{ + int song1 = queue.IdToPosition(id1); + int song2 = queue.IdToPosition(id2); + + if (song1 < 0 || song2 < 0) + throw PlaylistError::NoSuchSong(); + + SwapPositions(pc, song1, song2); +} + +void +playlist::SetPriorityRange(PlayerControl &pc, + RangeArg range, + uint8_t priority) +{ + if (!range.CheckClip(GetLength())) + throw PlaylistError::BadRange(); + + if (range.IsEmpty()) + return; + + /* remember "current" and "queued" */ + + const int current_position = GetCurrentPosition(); + const DetachedSong *const queued_song = GetQueuedSong(); + + /* apply the priority changes */ + + queue.SetPriorityRange(range.start, range.end, priority, current); + + /* restore "current" and choose a new "queued" */ + + if (current_position >= 0) + current = queue.PositionToOrder(current_position); + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::SetPriorityId(PlayerControl &pc, + unsigned song_id, uint8_t priority) +{ + int song_position = queue.IdToPosition(song_id); + if (song_position < 0) + throw PlaylistError::NoSuchSong(); + + SetPriorityRange(pc, {unsigned(song_position), song_position + 1U}, priority); +} + +void +playlist::DeleteInternal(PlayerControl &pc, + unsigned song, const DetachedSong **queued_p) noexcept +{ + assert(song < GetLength()); + + unsigned songOrder = queue.PositionToOrder(song); + + if (playing && current == (int)songOrder) { + const bool paused = pc.GetState() == PlayerState::PAUSE; + + /* the current song is going to be deleted: see which + song is going to be played instead */ + + current = queue.GetNextOrder(current); + if (current == (int)songOrder) + current = -1; + + if (current >= 0 && !paused) + /* play the song after the deleted one */ + try { + PlayOrder(pc, current); + } catch (...) { + /* TODO: log error? */ + } + else { + /* stop the player */ + + pc.LockStop(); + playing = false; + } + + *queued_p = nullptr; + } else if (current == (int)songOrder) + /* there's a "current song" but we're not playing + currently - clear "current" */ + current = -1; + + /* now do it: remove the song */ + + queue.DeletePosition(song); + + /* update the "current" and "queued" variables */ + + if (current > (int)songOrder) + current--; +} + +void +playlist::DeletePosition(PlayerControl &pc, unsigned song) +{ + if (song >= queue.GetLength()) + throw PlaylistError::BadRange(); + + const DetachedSong *queued_song = GetQueuedSong(); + + DeleteInternal(pc, song, &queued_song); + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::DeleteRange(PlayerControl &pc, RangeArg range) +{ + if (!range.CheckClip(GetLength())) + throw PlaylistError::BadRange(); + + if (range.IsEmpty()) + return; + + const DetachedSong *queued_song = GetQueuedSong(); + + do { + DeleteInternal(pc, --range.end, &queued_song); + } while (range.end != range.start); + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::DeleteId(PlayerControl &pc, unsigned id) +{ + int song = queue.IdToPosition(id); + if (song < 0) + throw PlaylistError::NoSuchSong(); + + DeletePosition(pc, song); +} + +void +playlist::StaleSong(PlayerControl &pc, const char *uri) noexcept +{ + /* don't remove the song if it's currently being played, to + avoid disrupting playback; a deleted file may still be + played if it's still open */ + // TODO: mark the song as "stale" and postpone deletion + int current_position = playing + ? GetCurrentPosition() + : -1; + + for (int i = queue.GetLength() - 1; i >= 0; --i) + if (i != current_position && queue.Get(i).IsURI(uri)) + DeletePosition(pc, i); +} + +void +playlist::MoveRange(PlayerControl &pc, RangeArg range, unsigned to) +{ + if (!queue.IsValidPosition(range.start) || + !queue.IsValidPosition(range.end - 1)) + throw PlaylistError::BadRange(); + + if (to + range.Count() - 1 >= GetLength()) + throw PlaylistError::BadRange(); + + if (range.start == to) + /* nothing happens */ + return; + + const DetachedSong *const queued_song = GetQueuedSong(); + + queue.MoveRange(range.start, range.end, to); + + if (!queue.random && current >= 0) { + /* update current */ + if (range.Contains(current)) + current += to - range.start; + else if (unsigned(current) >= range.end && + unsigned(current) <= to) + current -= range.Count(); + else if (unsigned(current) >= to && + unsigned(current) < range.start) + current += range.Count(); + } + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::Shuffle(PlayerControl &pc, RangeArg range) +{ + if (!range.CheckClip(GetLength())) + throw PlaylistError::BadRange(); + + if (!range.HasAtLeast(2)) + /* needs at least two entries. */ + return; + + const DetachedSong *const queued_song = GetQueuedSong(); + if (playing && current >= 0) { + unsigned current_position = queue.OrderToPosition(current); + + if (range.Contains(current_position)) { + /* put current playing song first */ + queue.SwapPositions(range.start, current_position); + + if (queue.random) { + current = queue.PositionToOrder(range.start); + } else + current = range.start; + + /* start shuffle after the current song */ + range.start++; + } + } else { + /* no playback currently: reset current */ + + current = -1; + } + + queue.ShuffleRange(range.start, range.end); + + UpdateQueuedSong(pc, queued_song); + OnModified(); +} + +void +playlist::SetSongIdRange(PlayerControl &pc, unsigned id, + SongTime start, SongTime end) +{ + assert(end.IsZero() || start < end); + + int position = queue.IdToPosition(id); + if (position < 0) + throw PlaylistError::NoSuchSong(); + + bool was_queued = false; + + if (playing) { + if (position == current) + throw PlaylistError(PlaylistResult::DENIED, + "Cannot edit the current song"); + + if (position == queued) { + /* if we're manipulating the "queued" song, + the decoder thread may be decoding it + already; cancel that */ + pc.LockCancel(); + queued = -1; + + /* schedule a call to UpdateQueuedSong() to + re-queue the song with its new range */ + was_queued = true; + } + } + + DetachedSong &song = queue.Get(position); + + const auto duration = song.GetTag().duration; + if (!duration.IsNegative()) { + /* validate the offsets */ + + if (start > duration) + throw PlaylistError(PlaylistResult::BAD_RANGE, + "Invalid start offset"); + + if (end >= duration) + end = SongTime::zero(); + } + + /* edit it */ + song.SetStartTime(start); + song.SetEndTime(end); + + /* announce the change to all interested subsystems */ + if (was_queued) + UpdateQueuedSong(pc, nullptr); + queue.ModifyAtPosition(position); + OnModified(); +} diff --git a/src/queue/PlaylistState.cxx b/src/queue/PlaylistState.cxx new file mode 100644 index 0000000..d1785dc --- /dev/null +++ b/src/queue/PlaylistState.cxx @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Saving and loading the playlist to/from the state file. + * + */ + +#include "PlaylistState.hxx" +#include "PlaylistError.hxx" +#include "Playlist.hxx" +#include "SingleMode.hxx" +#include "StateFileConfig.hxx" +#include "Save.hxx" +#include "io/LineReader.hxx" +#include "io/BufferedOutputStream.hxx" +#include "player/Control.hxx" +#include "util/CharUtil.hxx" +#include "util/StringAPI.hxx" +#include "util/StringCompare.hxx" +#include "util/CNumberParser.hxx" +#include "Log.hxx" + +#include + +#include +#include + +#define PLAYLIST_STATE_FILE_STATE "state: " +#define PLAYLIST_STATE_FILE_RANDOM "random: " +#define PLAYLIST_STATE_FILE_REPEAT "repeat: " +#define PLAYLIST_STATE_FILE_SINGLE "single: " +#define PLAYLIST_STATE_FILE_CONSUME "consume: " +#define PLAYLIST_STATE_FILE_CURRENT "current: " +#define PLAYLIST_STATE_FILE_TIME "time: " +#define PLAYLIST_STATE_FILE_CROSSFADE "crossfade: " +#define PLAYLIST_STATE_FILE_MIXRAMPDB "mixrampdb: " +#define PLAYLIST_STATE_FILE_MIXRAMPDELAY "mixrampdelay: " +#define PLAYLIST_STATE_FILE_LOADED_PLAYLIST "lastloadedplaylist: " +#define PLAYLIST_STATE_FILE_PLAYLIST_BEGIN "playlist_begin" +#define PLAYLIST_STATE_FILE_PLAYLIST_END "playlist_end" + +#define PLAYLIST_STATE_FILE_STATE_PLAY "play" +#define PLAYLIST_STATE_FILE_STATE_PAUSE "pause" +#define PLAYLIST_STATE_FILE_STATE_STOP "stop" + +void +playlist_state_save(BufferedOutputStream &os, const struct playlist &playlist, + PlayerControl &pc) +{ + const auto player_status = pc.LockGetStatus(); + + os.Write(PLAYLIST_STATE_FILE_STATE); + + if (playlist.playing) { + switch (player_status.state) { + case PlayerState::PAUSE: + os.Write(PLAYLIST_STATE_FILE_STATE_PAUSE "\n"); + break; + default: + os.Write(PLAYLIST_STATE_FILE_STATE_PLAY "\n"); + } + os.Fmt(PLAYLIST_STATE_FILE_CURRENT "{}\n", + playlist.queue.OrderToPosition(playlist.current)); + os.Fmt(PLAYLIST_STATE_FILE_TIME "{}\n", + player_status.elapsed_time.ToDoubleS()); + } else { + os.Write(PLAYLIST_STATE_FILE_STATE_STOP "\n"); + + if (playlist.current >= 0) + os.Fmt(PLAYLIST_STATE_FILE_CURRENT "{}\n", + playlist.queue.OrderToPosition(playlist.current)); + } + + os.Fmt(PLAYLIST_STATE_FILE_RANDOM "{}\n", + (unsigned)playlist.queue.random); + os.Fmt(PLAYLIST_STATE_FILE_REPEAT "{}\n", + (unsigned)playlist.queue.repeat); + os.Fmt(PLAYLIST_STATE_FILE_SINGLE "{}\n", + SingleToString(playlist.queue.single)); + os.Fmt(PLAYLIST_STATE_FILE_CONSUME "{}\n", + ConsumeToString(playlist.queue.consume)); + os.Fmt(PLAYLIST_STATE_FILE_CROSSFADE "{}\n", + pc.GetCrossFade().count()); + os.Fmt(PLAYLIST_STATE_FILE_MIXRAMPDB "{}\n", + pc.GetMixRampDb()); + os.Fmt(PLAYLIST_STATE_FILE_MIXRAMPDELAY "{}\n", + pc.GetMixRampDelay().count()); + os.Fmt(PLAYLIST_STATE_FILE_LOADED_PLAYLIST "{}\n", + playlist.GetLastLoadedPlaylist()); + os.Write(PLAYLIST_STATE_FILE_PLAYLIST_BEGIN "\n"); + queue_save(os, playlist.queue); + os.Write(PLAYLIST_STATE_FILE_PLAYLIST_END "\n"); +} + +static void +playlist_state_load(LineReader &file, const SongLoader &song_loader, + struct playlist &playlist) +{ + const char *line = file.ReadLine(); + if (line == nullptr) { + LogWarning(playlist_domain, "No playlist in state file"); + return; + } + + while (!StringStartsWith(line, PLAYLIST_STATE_FILE_PLAYLIST_END)) { + queue_load_song(file, song_loader, line, playlist.queue); + + line = file.ReadLine(); + if (line == nullptr) { + LogWarning(playlist_domain, + "'" PLAYLIST_STATE_FILE_PLAYLIST_END + "' not found in state file"); + break; + } + } + + playlist.queue.IncrementVersion(); +} + +bool +playlist_state_restore(const StateFileConfig &config, + const char *line, LineReader &file, + const SongLoader &song_loader, + struct playlist &playlist, PlayerControl &pc) +{ + int current = -1; + SongTime seek_time = SongTime::zero(); + bool random_mode = false; + + line = StringAfterPrefix(line, PLAYLIST_STATE_FILE_STATE); + if (line == nullptr) + return false; + + PlayerState state; + if (strcmp(line, PLAYLIST_STATE_FILE_STATE_PLAY) == 0) + state = PlayerState::PLAY; + else if (strcmp(line, PLAYLIST_STATE_FILE_STATE_PAUSE) == 0) + state = PlayerState::PAUSE; + else + state = PlayerState::STOP; + + while ((line = file.ReadLine()) != nullptr) { + const char *p; + if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_TIME))) { + seek_time = SongTime::FromS(ParseDouble(p)); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_REPEAT))) { + playlist.SetRepeat(pc, StringIsEqual(p, "1")); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_SINGLE))) { + playlist.SetSingle(pc, SingleFromString(p)); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_CONSUME))) { + playlist.SetConsume(ConsumeFromString(p)); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_CROSSFADE))) { + pc.SetCrossFade(FloatDuration(atoi(p))); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_MIXRAMPDB))) { + pc.SetMixRampDb(ParseFloat(p)); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_MIXRAMPDELAY))) { + /* this check discards "nan" which was used + prior to MPD 0.18 */ + if (IsDigitASCII(*p)) + pc.SetMixRampDelay(FloatDuration(ParseFloat(p))); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_LOADED_PLAYLIST))) { + playlist.SetLastLoadedPlaylist(p); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_RANDOM))) { + random_mode = StringIsEqual(p, "1"); + } else if ((p = StringAfterPrefix(line, PLAYLIST_STATE_FILE_CURRENT))) { + current = atoi(p); + } else if (StringStartsWith(line, + PLAYLIST_STATE_FILE_PLAYLIST_BEGIN)) { + playlist_state_load(file, song_loader, playlist); + } + } + + playlist.SetRandom(pc, random_mode); + + if (!playlist.queue.IsEmpty()) { + if (!playlist.queue.IsValidPosition(current)) + current = 0; + + if (state == PlayerState::PLAY && config.restore_paused) + /* the user doesn't want MPD to auto-start + playback after startup; fall back to + "pause" */ + state = PlayerState::PAUSE; + + /* enable all devices for the first time; this must be + called here, after the audio output states were + restored, before playback begins */ + if (state != PlayerState::STOP) + pc.LockUpdateAudio(); + + if (state == PlayerState::STOP /* && config_option */) + playlist.current = current; + else if (seek_time.count() == 0) { + try { + playlist.PlayPosition(pc, current); + } catch (...) { + /* TODO: log error? */ + } + } else { + try { + playlist.SeekSongPosition(pc, current, + seek_time); + } catch (...) { + /* TODO: log error? */ + } + } + + if (state == PlayerState::PAUSE) + pc.LockPause(); + } + + return true; +} + +unsigned +playlist_state_get_hash(const playlist &playlist, + PlayerControl &pc) +{ + const auto player_status = pc.LockGetStatus(); + + return playlist.queue.version ^ + (player_status.state != PlayerState::STOP + ? (player_status.elapsed_time.ToS() << 8) + : 0) ^ + (playlist.current >= 0 + ? (playlist.queue.OrderToPosition(playlist.current) << 16) + : 0) ^ + ((int)pc.GetCrossFade().count() << 20) ^ + (unsigned(player_status.state) << 24) ^ + /* note that this takes 2 bits */ + ((int)playlist.queue.single << 25) ^ + (playlist.queue.random << 27) ^ + (playlist.queue.repeat << 28) ^ + /* note that this takes 2 bits */ + ((int)playlist.queue.consume << 29) ^ + (playlist.queue.random << 31); +} diff --git a/src/queue/PlaylistState.hxx b/src/queue/PlaylistState.hxx new file mode 100644 index 0000000..05ba681 --- /dev/null +++ b/src/queue/PlaylistState.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Saving and loading the playlist to/from the state file. + * + */ + +#ifndef MPD_PLAYLIST_STATE_HXX +#define MPD_PLAYLIST_STATE_HXX + +struct StateFileConfig; +struct playlist; +class PlayerControl; +class LineReader; +class BufferedOutputStream; +class SongLoader; + +void +playlist_state_save(BufferedOutputStream &os, const playlist &playlist, + PlayerControl &pc); + +bool +playlist_state_restore(const StateFileConfig &config, + const char *line, LineReader &file, + const SongLoader &song_loader, + playlist &playlist, PlayerControl &pc); + +/** + * Generates a hash number for the current state of the playlist and + * the playback options. This is used by timer_save_state_file() to + * determine whether the state has changed and the state file should + * be saved. + */ +unsigned +playlist_state_get_hash(const playlist &playlist, + PlayerControl &c); + +#endif diff --git a/src/queue/PlaylistTag.cxx b/src/queue/PlaylistTag.cxx new file mode 100644 index 0000000..7d4a55f --- /dev/null +++ b/src/queue/PlaylistTag.cxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Functions for editing the playlist (adding, removing, reordering + * songs in the queue). + * + */ + +#include "Playlist.hxx" +#include "PlaylistError.hxx" +#include "song/DetachedSong.hxx" +#include "tag/Tag.hxx" +#include "tag/Builder.hxx" + +void +playlist::AddSongIdTag(unsigned id, TagType tag_type, const char *value) +{ + const int position = queue.IdToPosition(id); + if (position < 0) + throw PlaylistError::NoSuchSong(); + + DetachedSong &song = queue.Get(position); + if (song.IsFile()) + throw PlaylistError(PlaylistResult::DENIED, + "Cannot edit tags of local file"); + + { + TagBuilder tag(std::move(song.WritableTag())); + tag.AddItem(tag_type, value); + song.SetTag(tag.Commit()); + } + + queue.ModifyAtPosition(position); + OnModified(); +} + +void +playlist::ClearSongIdTag(unsigned id, TagType tag_type) +{ + const int position = queue.IdToPosition(id); + if (position < 0) + throw PlaylistError::NoSuchSong(); + + DetachedSong &song = queue.Get(position); + if (song.IsFile()) + throw PlaylistError(PlaylistResult::DENIED, + "Cannot edit tags of local file"); + + { + TagBuilder tag(std::move(song.WritableTag())); + if (tag_type == TAG_NUM_OF_ITEM_TYPES) + tag.RemoveAll(); + else + tag.RemoveType(tag_type); + song.SetTag(tag.Commit()); + } + + queue.ModifyAtPosition(position); + OnModified(); +} diff --git a/src/queue/PlaylistUpdate.cxx b/src/queue/PlaylistUpdate.cxx new file mode 100644 index 0000000..35a35c8 --- /dev/null +++ b/src/queue/PlaylistUpdate.cxx @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Playlist.hxx" +#include "db/Interface.hxx" +#include "song/LightSong.hxx" +#include "song/DetachedSong.hxx" + +static bool +UpdatePlaylistSong(const Database &db, DetachedSong &song) +{ + if (!song.IsInDatabase() || !song.IsFile()) + /* only update Songs instances that are "detached" + from the Database */ + return false; + + const LightSong *original; + try { + original = db.GetSong(song.GetURI()); + } catch (...) { + /* not found - shouldn't happen, because the update + thread should ensure that all stale Song instances + have been purged */ + return false; + } + + assert(original != nullptr); + + if (original->mtime == song.GetLastModified()) { + /* not modified */ + db.ReturnSong(original); + return false; + } + + song.SetLastModified(original->mtime); + song.SetAdded(original->added); + song.SetTag(original->tag); + + db.ReturnSong(original); + return true; +} + +void +playlist::DatabaseModified(const Database &db) +{ + bool modified = false; + + for (unsigned i = 0, n = queue.GetLength(); i != n; ++i) { + if (UpdatePlaylistSong(db, queue.Get(i))) { + queue.ModifyAtPosition(i); + modified = true; + } + } + + if (modified) + OnModified(); +} diff --git a/src/queue/Print.cxx b/src/queue/Print.cxx new file mode 100644 index 0000000..9ef7031 --- /dev/null +++ b/src/queue/Print.cxx @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Print.hxx" +#include "Queue.hxx" +#include "Selection.hxx" +#include "song/Filter.hxx" +#include "SongPrint.hxx" +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" +#include "tag/Sort.hxx" +#include "client/Response.hxx" +#include "PlaylistError.hxx" + +#include + +#include + +/** + * Send detailed information about a range of songs in the queue to a + * client. + * + * @param client the client which has requested information + * @param start the index of the first song (including) + * @param end the index of the last song (excluding) + */ +static void +queue_print_song_info(Response &r, const Queue &queue, + unsigned position) +{ + song_print_info(r, queue.Get(position)); + r.Fmt("Pos: {}\nId: {}\n", + position, queue.PositionToId(position)); + + uint8_t priority = queue.GetPriorityAtPosition(position); + if (priority != 0) + r.Fmt("Prio: {}\n", priority); +} + +void +queue_print_info(Response &r, const Queue &queue, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; ++i) + queue_print_song_info(r, queue, i); +} + +void +queue_print_uris(Response &r, const Queue &queue, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; ++i) { + r.Fmt("{}:", i); + song_print_uri(r, queue.Get(i)); + } +} + +void +queue_print_changes_info(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; i++) + if (queue.IsNewerAtPosition(i, version)) + queue_print_song_info(r, queue, i); +} + +void +queue_print_changes_position(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; i++) + if (queue.IsNewerAtPosition(i, version)) + r.Fmt("cpos: {}\nId: {}\n", + i, queue.PositionToId(i)); +} + +[[gnu::pure]] +static std::vector +CollectQueue(const Queue &queue, const QueueSelection &selection) noexcept +{ + std::vector v; + + for (unsigned i = 0; i < queue.GetLength(); i++) + if (selection.MatchPosition(queue, i)) + v.emplace_back(i); + + return v; +} + +static void +PrintSortedQueue(Response &r, const Queue &queue, + const QueueSelection &selection) +{ + /* collect all matching songs */ + auto v = CollectQueue(queue, selection); + + auto window = selection.window; + if (!window.CheckClip(v.size())) + throw PlaylistError::BadRange(); + + /* sort them */ + const auto sort = selection.sort; + const auto descending = selection.descending; + + if (sort == TagType(SORT_TAG_LAST_MODIFIED)) + std::stable_sort(v.begin(), v.end(), + [&queue, descending](unsigned a_pos, unsigned b_pos){ + if (descending) + std::swap(a_pos, b_pos); + + const auto &a = queue.Get(a_pos); + const auto &b = queue.Get(b_pos); + + return a.GetLastModified() < b.GetLastModified(); + }); + else if (sort == TagType(SORT_TAG_ADDED)) + std::stable_sort(v.begin(), v.end(), + [&queue, descending](unsigned a_pos, unsigned b_pos){ + if (descending) + std::swap(a_pos, b_pos); + + const auto &a = queue.Get(a_pos); + const auto &b = queue.Get(b_pos); + + return a.GetAdded() < b.GetAdded(); + }); + else if (sort == TagType(SORT_TAG_PRIO)) + std::stable_sort(v.begin(), v.end(), + [&queue, descending](unsigned a_pos, unsigned b_pos){ + if (descending) + std::swap(a_pos, b_pos); + + return queue.GetPriorityAtPosition(a_pos) < + queue.GetPriorityAtPosition(b_pos); + }); + else + std::stable_sort(v.begin(), v.end(), + [&queue, sort, descending](unsigned a_pos, + unsigned b_pos){ + const auto &a = queue.Get(a_pos); + const auto &b = queue.Get(b_pos); + + return CompareTags(sort, descending, + a.GetTag(), + b.GetTag()); + }); + + for (unsigned i = window.start; i < window.end; ++i) + queue_print_song_info(r, queue, v[i]); +} + +void +PrintQueue(Response &r, const Queue &queue, + const QueueSelection &selection) +{ + if (selection.sort != TAG_NUM_OF_ITEM_TYPES) { + PrintSortedQueue(r, queue, selection); + return; + } + + auto window = selection.window; + + if (!window.CheckClip(queue.GetLength())) + throw PlaylistError::BadRange(); + + if (selection.window.IsEmpty()) + return; + + unsigned skip = window.start; + unsigned n = window.Count(); + + for (unsigned i = 0; i < queue.GetLength(); i++) { + if (!selection.MatchPosition(queue, i)) + continue; + + if (skip > 0) { + --skip; + continue; + } + + queue_print_song_info(r, queue, i); + + if (--n == 0) + break; + } +} diff --git a/src/queue/Print.hxx b/src/queue/Print.hxx new file mode 100644 index 0000000..dc9c523 --- /dev/null +++ b/src/queue/Print.hxx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This library sends information about songs in the queue to the + * client. + */ + +#pragma once + +#include + +struct Queue; +struct QueueSelection; +class Response; + +void +queue_print_info(Response &r, const Queue &queue, + unsigned start, unsigned end); + +void +queue_print_uris(Response &r, const Queue &queue, + unsigned start, unsigned end); + +void +queue_print_changes_info(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end); + +void +queue_print_changes_position(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end); + +void +PrintQueue(Response &response, const Queue &queue, + const QueueSelection &selection); diff --git a/src/queue/Queue.cxx b/src/queue/Queue.cxx new file mode 100644 index 0000000..d14c039 --- /dev/null +++ b/src/queue/Queue.cxx @@ -0,0 +1,509 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Queue.hxx" +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" + +#include + +Queue::Queue(unsigned _max_length) noexcept + :max_length(_max_length), + items(new Item[max_length]), + order(new unsigned[max_length]), + id_table(max_length * HASH_MULT) +{ +} + +Queue::~Queue() noexcept +{ + Clear(); + + delete[] items; + delete[] order; +} + +LightSong +Queue::GetLight(unsigned position) const noexcept +{ + assert(position < length); + + LightSong song{Get(position)}; + song.priority = GetPriorityAtPosition(position); + return song; +} + +int +Queue::GetNextOrder(unsigned _order) const noexcept +{ + assert(_order < length); + + if (single != SingleMode::OFF && repeat && consume == ConsumeMode::OFF ) + return _order; + else if (_order + 1 < length) + return _order + 1; + else if (repeat && (_order > 0 || consume == ConsumeMode::OFF)) + /* restart at first song */ + return 0; + else + /* end of queue */ + return -1; +} + +void +Queue::IncrementVersion() noexcept +{ + static unsigned long max = ((uint32_t) 1 << 31) - 1; + + version++; + + if (version >= max) { + for (unsigned i = 0; i < length; i++) + items[i].version = 0; + + version = 1; + } +} + +void +Queue::ModifyAtOrder(unsigned _order) noexcept +{ + assert(_order < length); + + unsigned position = order[_order]; + ModifyAtPosition(position); +} + +unsigned +Queue::Append(DetachedSong &&song, uint8_t priority) noexcept +{ + assert(!IsFull()); + + const unsigned position = length++; + const unsigned id = id_table.Insert(position); + + auto &item = items[position]; + item.song = new DetachedSong(std::move(song)); + item.id = id; + item.version = version; + item.priority = priority; + + order[position] = position; + + return id; +} + +void +Queue::SwapPositions(unsigned position1, unsigned position2) noexcept +{ + unsigned id1 = items[position1].id; + unsigned id2 = items[position2].id; + + std::swap(items[position1], items[position2]); + + items[position1].version = version; + items[position2].version = version; + + id_table.Move(id1, position2); + id_table.Move(id2, position1); +} + +void +Queue::MovePostion(unsigned from, unsigned to) noexcept +{ + const Item tmp = items[from]; + + /* move songs to one less in from->to */ + + for (unsigned i = from; i < to; i++) + MoveItemTo(i + 1, i); + + /* move songs to one more in to->from */ + + for (unsigned i = from; i > to; i--) + MoveItemTo(i - 1, i); + + /* put song at _to_ */ + + id_table.Move(tmp.id, to); + items[to] = tmp; + items[to].version = version; + + /* now deal with order */ + + if (random) { + for (unsigned i = 0; i < length; i++) { + if (order[i] > from && order[i] <= to) + order[i]--; + else if (order[i] < from && + order[i] >= to) + order[i]++; + else if (from == order[i]) + order[i] = to; + } + } +} + +void +Queue::MoveRange(unsigned start, unsigned end, unsigned to) noexcept +{ + const auto tmp = std::make_unique_for_overwrite(end - start); + + // Copy the original block [start,end-1] + for (unsigned i = start; i < end; i++) + tmp[i - start] = items[i]; + + // If to > start, we need to move to-start items to start, starting from end + for (unsigned i = end; i < end + to - start; i++) + MoveItemTo(i, start + i - end); + + // If to < start, we need to move start-to items to newend (= end + to - start), starting from to + // This is the same as moving items from start-1 to to (decreasing), with start-1 going to end-1 + // We have to iterate in this order to avoid writing over something we haven't yet moved + for (int i = start - 1; i >= int(to); i--) + MoveItemTo(i, i + end - start); + + // Copy the original block back in, starting at to. + for (unsigned i = start; i< end; i++) + { + id_table.Move(tmp[i - start].id, to + i - start); + items[to + i - start] = tmp[i-start]; + items[to + i - start].version = version; + } + + if (random) { + // Update the positions in the queue. + // Note that the ranges for these cases are the same as the ranges of + // the loops above. + for (unsigned i = 0; i < length; i++) { + if (order[i] >= end && order[i] < to + end - start) + order[i] -= end - start; + else if (order[i] < start && + order[i] >= to) + order[i] += end - start; + else if (start <= order[i] && order[i] < end) + order[i] += to - start; + } + } +} + +unsigned +Queue::MoveOrder(unsigned from_order, unsigned to_order) noexcept +{ + assert(from_order < length); + assert(to_order <= length); + + const unsigned from_position = OrderToPosition(from_order); + + if (from_order < to_order) { + for (unsigned i = from_order; i < to_order; ++i) + order[i] = order[i + 1]; + } else { + for (unsigned i = from_order; i > to_order; --i) + order[i] = order[i - 1]; + } + + order[to_order] = from_position; + return to_order; +} + +unsigned +Queue::MoveOrderBefore(unsigned from_order, unsigned to_order) noexcept +{ + /* if "from_order" comes before "to_order", then the new + position is "to_order-1"; otherwise the "to_order" song is + moved one ahead */ + return MoveOrder(from_order, to_order - (from_order < to_order)); +} + +unsigned +Queue::MoveOrderAfter(unsigned from_order, unsigned to_order) noexcept +{ + /* if "from_order" comes after "to_order", then the new + position is "to_order+1"; otherwise the "to_order" song is + moved one back */ + return MoveOrder(from_order, to_order + (from_order > to_order)); +} + +void +Queue::DeletePosition(unsigned position) noexcept +{ + assert(position < length); + + delete items[position].song; + + const unsigned id = PositionToId(position); + const unsigned _order = PositionToOrder(position); + + --length; + + /* release the song id */ + + id_table.Erase(id); + + /* delete song from songs array */ + + for (unsigned i = position; i < length; i++) + MoveItemTo(i + 1, i); + + /* delete the entry from the order array */ + + for (unsigned i = _order; i < length; i++) + order[i] = order[i + 1]; + + /* readjust values in the order array */ + + for (unsigned i = 0; i < length; i++) + if (order[i] > position) + --order[i]; +} + +void +Queue::Clear() noexcept +{ + for (unsigned i = 0; i < length; i++) { + Item *item = &items[i]; + + delete item->song; + + id_table.Erase(item->id); + } + + length = 0; + last_loaded_playlist.clear(); +} + +static void +queue_sort_order_by_priority(Queue *queue, + unsigned start, unsigned end) noexcept +{ + assert(queue != nullptr); + assert(queue->random); + assert(start <= end); + assert(end <= queue->length); + + auto cmp = [queue](unsigned a_pos, unsigned b_pos){ + const Queue::Item &a = queue->items[a_pos]; + const Queue::Item &b = queue->items[b_pos]; + + return a.priority > b.priority; + }; + + std::stable_sort(queue->order + start, queue->order + end, cmp); +} + +void +Queue::ShuffleOrderRange(unsigned start, unsigned end) noexcept +{ + assert(random); + assert(start <= end); + assert(end <= length); + + rand.AutoCreate(); + std::shuffle(order + start, order + end, rand); +} + +/** + * Sort the "order" of items by priority, and then shuffle each + * priority group. + */ +void +Queue::ShuffleOrderRangeWithPriority(unsigned start, unsigned end) noexcept +{ + assert(random); + assert(start <= end); + assert(end <= length); + + if (start == end) + return; + + /* first group the range by priority */ + queue_sort_order_by_priority(this, start, end); + + /* now shuffle each priority group */ + unsigned group_start = start; + uint8_t group_priority = GetOrderPriority(start); + + for (unsigned i = start + 1; i < end; ++i) { + const uint8_t priority = GetOrderPriority(i); + assert(priority <= group_priority); + + if (priority != group_priority) { + /* start of a new group - shuffle the one that + has just ended */ + ShuffleOrderRange(group_start, i); + group_start = i; + group_priority = priority; + } + } + + /* shuffle the last group */ + ShuffleOrderRange(group_start, end); +} + +void +Queue::ShuffleOrder() noexcept +{ + ShuffleOrderRangeWithPriority(0, length); +} + +void +Queue::ShuffleOrderFirst(unsigned start, unsigned end) noexcept +{ + rand.AutoCreate(); + + std::uniform_int_distribution distribution(start, end - 1); + SwapOrders(start, distribution(rand)); +} + +void +Queue::ShuffleOrderLastWithPriority(unsigned start, unsigned end) noexcept +{ + assert(end <= length); + assert(start < end); + + /* skip all items at the start which have a higher priority, + because the last item shall only be shuffled within its + priority group */ + const auto last_priority = items[OrderToPosition(end - 1)].priority; + while (items[OrderToPosition(start)].priority != last_priority) { + ++start; + assert(start < end); + } + + rand.AutoCreate(); + + std::uniform_int_distribution distribution(start, end - 1); + SwapOrders(end - 1, distribution(rand)); +} + +void +Queue::ShuffleRange(unsigned start, unsigned end) noexcept +{ + assert(start <= end); + assert(end <= length); + + rand.AutoCreate(); + + for (unsigned i = start; i < end; i++) { + std::uniform_int_distribution distribution(start, + end - 1); + unsigned ri = distribution(rand); + SwapPositions(i, ri); + } +} + +unsigned +Queue::FindPriorityOrder(unsigned start_order, uint8_t priority, + unsigned exclude_order) const noexcept +{ + assert(random); + assert(start_order <= length); + + for (unsigned i = start_order; i < length; ++i) { + const unsigned position = OrderToPosition(i); + const Item *item = &items[position]; + if (item->priority <= priority && i != exclude_order) + return i; + } + + return length; +} + +unsigned +Queue::CountSamePriority(unsigned start_order, uint8_t priority) const noexcept +{ + assert(random); + assert(start_order <= length); + + for (unsigned i = start_order; i < length; ++i) { + const unsigned position = OrderToPosition(i); + const Item *item = &items[position]; + if (item->priority != priority) + return i - start_order; + } + + return length - start_order; +} + +bool +Queue::SetPriority(unsigned position, uint8_t priority, int after_order, + bool reorder) noexcept +{ + assert(position < length); + + Item *item = &items[position]; + uint8_t old_priority = item->priority; + if (old_priority == priority) + return false; + + item->version = version; + item->priority = priority; + + if (!random || !reorder) + /* don't reorder if not in random mode */ + return true; + + unsigned _order = PositionToOrder(position); + if (after_order >= 0) { + if (_order == (unsigned)after_order) + /* don't reorder the current song */ + return true; + + if (_order < (unsigned)after_order) { + /* the specified song has been played already + - enqueue it only if its priority has been + increased and is now bigger than the + current one's */ + + const unsigned after_position = + OrderToPosition(after_order); + const Item *after_item = + &items[after_position]; + if (priority <= old_priority || + priority <= after_item->priority) + /* priority hasn't become bigger */ + return true; + } + } + + /* move the item to the beginning of the priority group (or + create a new priority group) */ + + const unsigned before_order = + FindPriorityOrder(after_order + 1, priority, _order); + const unsigned new_order = before_order > _order + ? before_order - 1 + : before_order; + MoveOrder(_order, new_order); + + /* shuffle the song within that priority group */ + + const unsigned priority_count = CountSamePriority(new_order, priority); + assert(priority_count >= 1); + ShuffleOrderFirst(new_order, new_order + priority_count); + + return true; +} + +bool +Queue::SetPriorityRange(unsigned start_position, unsigned end_position, + uint8_t priority, int after_order) noexcept +{ + assert(start_position <= end_position); + assert(end_position <= length); + + bool modified = false; + int after_position = after_order >= 0 + ? (int)OrderToPosition(after_order) + : -1; + for (unsigned i = start_position; i < end_position; ++i) { + after_order = after_position >= 0 + ? (int)PositionToOrder(after_position) + : -1; + + modified |= SetPriority(i, priority, after_order); + } + + return modified; +} diff --git a/src/queue/Queue.hxx b/src/queue/Queue.hxx new file mode 100644 index 0000000..e670cdb --- /dev/null +++ b/src/queue/Queue.hxx @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_QUEUE_HXX +#define MPD_QUEUE_HXX + +#include "IdTable.hxx" +#include "SingleMode.hxx" +#include "ConsumeMode.hxx" +#include "util/LazyRandomEngine.hxx" + +#include +#include +#include + +struct LightSong; +class DetachedSong; + +/** + * A queue of songs. This is the backend of the playlist: it contains + * an ordered list of songs. + * + * Songs can be addressed in three possible ways: + * + * - the position in the queue + * - the unique id (which stays the same, regardless of moves) + * - the order number (which only differs from "position" in random mode) + */ +struct Queue { + /** + * reserve max_length * HASH_MULT elements in the id + * number space + */ + static constexpr unsigned HASH_MULT = 4; + + /** + * One element of the queue: basically a song plus some queue specific + * information attached. + */ + struct Item { + DetachedSong *song; + + /** the unique id of this item in the queue */ + unsigned id; + + /** when was this item last changed? */ + uint32_t version; + + /** + * The priority of this item, between 0 and 255. High + * priority value means that this song gets played first in + * "random" mode. + */ + uint8_t priority; + }; + + /** configured maximum length of the queue */ + const unsigned max_length; + + /** number of songs in the queue */ + unsigned length = 0; + + /** the current version number */ + uint32_t version = 1; + + /** all songs in "position" order */ + Item *const items; + + /** map order numbers to positions */ + unsigned *const order; + + /** map song ids to positions */ + IdTable id_table; + + /** repeat playback when the end of the queue has been + reached? */ + bool repeat = false; + + /** play only current song. */ + SingleMode single = SingleMode::OFF; + + /** remove each played files. */ + ConsumeMode consume = ConsumeMode::OFF; + + /** play back songs in random order? */ + bool random = false; + + /** Last loaded playlist */ + std::string last_loaded_playlist; + + /** random number generator for shuffle and random mode */ + LazyRandomEngine rand; + + explicit Queue(unsigned max_length) noexcept; + ~Queue() noexcept; + + Queue(const Queue &) = delete; + Queue &operator=(const Queue &) = delete; + + unsigned GetLength() const noexcept { + assert(length <= max_length); + + return length; + } + + /** + * Determine if the queue is empty, i.e. there are no songs. + */ + bool IsEmpty() const noexcept { + return length == 0; + } + + /** + * Determine if the maximum number of songs has been reached. + */ + bool IsFull() const noexcept { + assert(length <= max_length); + + return length >= max_length; + } + + /** + * Is that a valid position number? + */ + bool IsValidPosition(unsigned position) const noexcept { + return position < length; + } + + /** + * Is that a valid order number? + */ + bool IsValidOrder(unsigned _order) const noexcept { + return _order < length; + } + + int IdToPosition(unsigned id) const noexcept { + return id_table.IdToPosition(id); + } + + int PositionToId(unsigned position) const noexcept { + assert(position < length); + + return items[position].id; + } + + [[gnu::pure]] + unsigned OrderToPosition(unsigned _order) const noexcept { + assert(_order < length); + + return order[_order]; + } + + [[gnu::pure]] + unsigned PositionToOrder(unsigned position) const noexcept { + assert(position < length); + + for (unsigned i = 0;; ++i) { + assert(i < length); + + if (order[i] == position) + return i; + } + } + + [[gnu::pure]] + uint8_t GetPriorityAtPosition(unsigned position) const noexcept { + assert(position < length); + + return items[position].priority; + } + + const Item &GetOrderItem(unsigned i) const noexcept { + assert(IsValidOrder(i)); + + return items[OrderToPosition(i)]; + } + + uint8_t GetOrderPriority(unsigned i) const noexcept { + return GetOrderItem(i).priority; + } + + /** + * Returns the song at the specified position. + */ + DetachedSong &Get(unsigned position) const noexcept { + assert(position < length); + + return *items[position].song; + } + + /** + * Like Get(), but return a #LightSong instance. + */ + LightSong GetLight(unsigned position) const noexcept; + + /** + * Returns the song at the specified order number. + */ + DetachedSong &GetOrder(unsigned _order) const noexcept { + return Get(OrderToPosition(_order)); + } + + /** + * Is the song at the specified position newer than the specified + * version? + */ + bool IsNewerAtPosition(unsigned position, + uint32_t _version) const noexcept { + assert(position < length); + + return _version > version || + items[position].version >= _version || + items[position].version == 0; + } + + /** + * Returns the order number following the specified one. This takes + * end of queue and "repeat" mode into account. + * + * @return the next order number, or -1 to stop playback + */ + [[gnu::pure]] + int GetNextOrder(unsigned order) const noexcept; + + /** + * Increments the queue's version number. This handles integer + * overflow well. + */ + void IncrementVersion() noexcept; + + /** + * Marks the specified song as "modified". Call + * IncrementVersion() after all modifications have been made. + * number. + */ + void ModifyAtPosition(unsigned position) noexcept { + assert(position < length); + + items[position].version = version; + } + + /** + * Marks the specified song as "modified". Call + * IncrementVersion() after all modifications have been made. + * number. + */ + void ModifyAtOrder(unsigned order) noexcept; + + /** + * Appends a song to the queue and returns its position. Prior to + * that, the caller must check if the queue is already full. + * + * If a song is not in the database (determined by + * Song::IsInDatabase()), it is freed when removed from the + * queue. + * + * @param priority the priority of this new queue item + */ + unsigned Append(DetachedSong &&song, uint8_t priority) noexcept; + + /** + * Swaps two songs, addressed by their position. + */ + void SwapPositions(unsigned position1, unsigned position2) noexcept; + + /** + * Swaps two songs, addressed by their order number. + */ + void SwapOrders(unsigned order1, unsigned order2) noexcept { + std::swap(order[order1], order[order2]); + } + + /** + * Moves a song to a new position in the "order" list. + * + * @return to_order + */ + unsigned MoveOrder(unsigned from_order, unsigned to_order) noexcept; + + /** + * Moves a song to a new position in the "order" list before + * the given one. + * + * @return the new order number of the given "from" song + */ + unsigned MoveOrderBefore(unsigned from_order, + unsigned to_order) noexcept; + + /** + * Moves a song to a new position in the "order" list after + * the given one. + * + * @return the new order number of the given "from" song + */ + unsigned MoveOrderAfter(unsigned from_order, + unsigned to_order) noexcept; + + /** + * Moves a song to a new position. + */ + void MovePostion(unsigned from, unsigned to) noexcept; + + /** + * Moves a range of songs to a new position. + */ + void MoveRange(unsigned start, unsigned end, unsigned to) noexcept; + + /** + * Removes a song from the playlist. + */ + void DeletePosition(unsigned position) noexcept; + + /** + * Removes all songs from the playlist. + */ + void Clear() noexcept; + + /** + * Initializes the "order" array, and restores "normal" order. + */ + void RestoreOrder() noexcept { + for (unsigned i = 0; i < length; ++i) + order[i] = i; + } + + /** + * Shuffle the order of items in the specified range, ignoring + * their priorities. + */ + void ShuffleOrderRange(unsigned start, unsigned end) noexcept; + + /** + * Shuffle the order of items in the specified range, taking their + * priorities into account. + */ + void ShuffleOrderRangeWithPriority(unsigned start, + unsigned end) noexcept; + + /** + * Shuffles the virtual order of songs, but does not move them + * physically. This is used in random mode. + */ + void ShuffleOrder() noexcept; + + void ShuffleOrderFirst(unsigned start, unsigned end) noexcept; + + /** + * Shuffles the virtual order of the last song in the + * specified (order) range; only songs which match this song's + * priority are considered. This is used in random mode after + * a song has been appended by Append(). + */ + void ShuffleOrderLastWithPriority(unsigned start, unsigned end) noexcept; + + /** + * Shuffles a (position) range in the queue. The songs are physically + * shuffled, not by using the "order" mapping. + */ + void ShuffleRange(unsigned start, unsigned end) noexcept; + + bool SetPriority(unsigned position, uint8_t priority, int after_order, + bool reorder=true) noexcept; + + bool SetPriorityRange(unsigned start_position, unsigned end_position, + uint8_t priority, int after_order) noexcept; + +private: + void MoveItemTo(unsigned from, unsigned to) noexcept { + unsigned from_id = items[from].id; + + items[to] = items[from]; + items[to].version = version; + id_table.Move(from_id, to); + } + + /** + * Find the first item that has this specified priority or + * higher. + */ + [[gnu::pure]] + unsigned FindPriorityOrder(unsigned start_order, uint8_t priority, + unsigned exclude_order) const noexcept; + + [[gnu::pure]] + unsigned CountSamePriority(unsigned start_order, + uint8_t priority) const noexcept; +}; + +#endif diff --git a/src/queue/QueuePrint.cxx b/src/queue/QueuePrint.cxx new file mode 100644 index 0000000..6ee90ce --- /dev/null +++ b/src/queue/QueuePrint.cxx @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "QueuePrint.hxx" +#include "Queue.hxx" +#include "song/Filter.hxx" +#include "SongPrint.hxx" +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" +#include "client/Response.hxx" + +#include + +/** + * Send detailed information about a range of songs in the queue to a + * client. + * + * @param client the client which has requested information + * @param start the index of the first song (including) + * @param end the index of the last song (excluding) + */ +static void +queue_print_song_info(Response &r, const Queue &queue, + unsigned position) +{ + song_print_info(r, queue.Get(position)); + r.Fmt("Pos: {}\nId: {}\n", + position, queue.PositionToId(position)); + + uint8_t priority = queue.GetPriorityAtPosition(position); + if (priority != 0) + r.Fmt("Prio: {}\n", priority); +} + +void +queue_print_info(Response &r, const Queue &queue, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; ++i) + queue_print_song_info(r, queue, i); +} + +void +queue_print_uris(Response &r, const Queue &queue, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; ++i) { + r.Fmt("{}:", i); + song_print_uri(r, queue.Get(i)); + } +} + +void +queue_print_changes_info(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; i++) + if (queue.IsNewerAtPosition(i, version)) + queue_print_song_info(r, queue, i); +} + +void +queue_print_changes_position(Response &r, const Queue &queue, + uint32_t version, + unsigned start, unsigned end) +{ + assert(start <= end); + assert(end <= queue.GetLength()); + + for (unsigned i = start; i < end; i++) + if (queue.IsNewerAtPosition(i, version)) + r.Fmt("cpos: {}\nId: {}\n", + i, queue.PositionToId(i)); +} + +void +queue_find(Response &r, const Queue &queue, + const SongFilter &filter) +{ + for (unsigned i = 0; i < queue.GetLength(); i++) { + const LightSong song{queue.Get(i)}; + + if (filter.Match(song)) + queue_print_song_info(r, queue, i); + } +} diff --git a/src/queue/Save.cxx b/src/queue/Save.cxx new file mode 100644 index 0000000..fd8d9b5 --- /dev/null +++ b/src/queue/Save.cxx @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Save.hxx" +#include "Queue.hxx" +#include "PlaylistError.hxx" +#include "song/DetachedSong.hxx" +#include "SongSave.hxx" +#include "playlist/PlaylistSong.hxx" +#include "io/LineReader.hxx" +#include "io/BufferedOutputStream.hxx" +#include "util/StringCompare.hxx" +#include "Log.hxx" + +#include + +#include + +#include + +#define PRIO_LABEL "Prio: " + +static void +queue_save_database_song(BufferedOutputStream &os, + int idx, const DetachedSong &song) +{ + os.Fmt("{}:{}\n", idx, song.GetURI()); +} + +static void +queue_save_full_song(BufferedOutputStream &os, const DetachedSong &song) +{ + song_save(os, song); +} + +static void +queue_save_song(BufferedOutputStream &os, int idx, const DetachedSong &song) +{ + if (song.IsInDatabase() && + song.GetStartTime().IsZero() && song.GetEndTime().IsZero()) + /* use the brief format (just the URI) for "full" + database songs */ + queue_save_database_song(os, idx, song); + else + /* use the long format (URI, range, tags) for the + rest, so all metadata survives a MPD restart */ + queue_save_full_song(os, song); +} + +void +queue_save(BufferedOutputStream &os, const Queue &queue) +{ + for (unsigned i = 0; i < queue.GetLength(); i++) { + uint8_t prio = queue.GetPriorityAtPosition(i); + if (prio != 0) + os.Fmt(PRIO_LABEL "{}\n", prio); + + queue_save_song(os, i, queue.Get(i)); + } +} + +static DetachedSong +LoadQueueSong(LineReader &file, const char *line) +{ + std::unique_ptr song; + + if (const char *p = StringAfterPrefix(line, SONG_BEGIN)) { + const char *uri = p; + return song_load(file, uri); + } else { + char *endptr; + long ret = strtol(line, &endptr, 10); + if (ret < 0 || *endptr != ':' || endptr[1] == 0) + throw std::runtime_error("Malformed playlist line in state file"); + + const char *uri = endptr + 1; + + return DetachedSong(uri); + } +} + +void +queue_load_song(LineReader &file, const SongLoader &loader, + const char *line, Queue &queue) +{ + if (queue.IsFull()) + return; + + uint8_t priority = 0; + const char *p; + if ((p = StringAfterPrefix(line, PRIO_LABEL))) { + priority = strtoul(p, nullptr, 10); + + line = file.ReadLine(); + if (line == nullptr) + return; + } + + auto song = LoadQueueSong(file, line); + + if (!playlist_check_translate_song(song, {}, loader)) + return; + + queue.Append(std::move(song), priority); +} diff --git a/src/queue/Save.hxx b/src/queue/Save.hxx new file mode 100644 index 0000000..521c699 --- /dev/null +++ b/src/queue/Save.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This library saves the queue into the state file, and also loads it + * back into memory. + */ + +#pragma once + +struct Queue; +class BufferedOutputStream; +class LineReader; +class SongLoader; + +void +queue_save(BufferedOutputStream &os, const Queue &queue); + +/** + * Loads one song from the state file and appends it to the queue. + * + * Throws on error. + */ +void +queue_load_song(LineReader &file, const SongLoader &loader, + const char *line, Queue &queue); diff --git a/src/queue/Selection.cxx b/src/queue/Selection.cxx new file mode 100644 index 0000000..e21da94 --- /dev/null +++ b/src/queue/Selection.cxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Selection.hxx" +#include "Queue.hxx" +#include "song/DetachedSong.hxx" +#include "song/Filter.hxx" +#include "song/LightSong.hxx" + +bool +QueueSelection::MatchPosition(const Queue &queue, + unsigned position) const noexcept +{ + if (filter != nullptr) { + const auto song = queue.GetLight(position); + if (!filter->Match(song)) + return false; + } + + return true; +} diff --git a/src/queue/Selection.hxx b/src/queue/Selection.hxx new file mode 100644 index 0000000..9a0a7fc --- /dev/null +++ b/src/queue/Selection.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "protocol/RangeArg.hxx" +#include "tag/Type.hxx" + +struct Queue; +class SongFilter; + +/** + * Describes what part of and how the client wishes to see the queue. + */ +struct QueueSelection { + /** + * An optional pointer to a #SongFilter (not owned by this + * object). + */ + const SongFilter *filter = nullptr; + + RangeArg window = RangeArg::All(); + + /** + * Sort the result by the given tag. #TAG_NUM_OF_ITEM_TYPES + * means don't sort. #SORT_TAG_LAST_MODIFIED sorts by + * "Last-Modified" (not technically a tag). + */ + TagType sort = TAG_NUM_OF_ITEM_TYPES; + + /** + * If #sort is set, this flag can reverse the sort order. + */ + bool descending = false; + + [[gnu::pure]] + bool MatchPosition(const Queue &queue, + unsigned position) const noexcept; +}; diff --git a/src/song/AddedSinceSongFilter.cxx b/src/song/AddedSinceSongFilter.cxx new file mode 100644 index 0000000..efc394f --- /dev/null +++ b/src/song/AddedSinceSongFilter.cxx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "AddedSinceSongFilter.hxx" +#include "LightSong.hxx" +#include "time/ISO8601.hxx" +#include "util/StringBuffer.hxx" + +#include + +using std::string_view_literals::operator""sv; + +std::string +AddedSinceSongFilter::ToExpression() const noexcept +{ + return fmt::format("(added-since \"{}\")"sv, FormatISO8601(value).c_str()); +} + +bool +AddedSinceSongFilter::Match(const LightSong &song) const noexcept +{ + return song.added >= value; +} diff --git a/src/song/AddedSinceSongFilter.hxx b/src/song/AddedSinceSongFilter.hxx new file mode 100644 index 0000000..c325e0e --- /dev/null +++ b/src/song/AddedSinceSongFilter.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ADDED_SINCE_SONG_FILTER_HXX +#define MPD_ADDED_SINCE_SONG_FILTER_HXX + +#include "ISongFilter.hxx" + +#include + +class AddedSinceSongFilter final : public ISongFilter { + std::chrono::system_clock::time_point value; + +public: + explicit AddedSinceSongFilter(std::chrono::system_clock::time_point _value) noexcept + :value(_value) {} + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/AndSongFilter.cxx b/src/song/AndSongFilter.cxx new file mode 100644 index 0000000..8f5b732 --- /dev/null +++ b/src/song/AndSongFilter.cxx @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "AndSongFilter.hxx" + +#include + +ISongFilterPtr +AndSongFilter::Clone() const noexcept +{ + auto result = std::make_unique(); + + for (const auto &i : items) + result->items.emplace_back(i->Clone()); + + return result; +} + +std::string +AndSongFilter::ToExpression() const noexcept +{ + auto i = items.begin(); + const auto end = items.end(); + + if (std::next(i) == end) + return (*i)->ToExpression(); + + std::string e("("); + e += (*i)->ToExpression(); + + for (++i; i != end; ++i) { + e += " AND "; + e += (*i)->ToExpression(); + } + + e.push_back(')'); + return e; +} + +bool +AndSongFilter::Match(const LightSong &song) const noexcept +{ + return std::all_of(items.begin(), items.end(), [&song](const auto &i) { return i->Match(song); }); +} diff --git a/src/song/AndSongFilter.hxx b/src/song/AndSongFilter.hxx new file mode 100644 index 0000000..f3e4a8a --- /dev/null +++ b/src/song/AndSongFilter.hxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_AND_SONG_FILTER_HXX +#define MPD_AND_SONG_FILTER_HXX + +#include "ISongFilter.hxx" + +#include + +/** + * Combine multiple #ISongFilter instances with logical "and". + */ +class AndSongFilter final : public ISongFilter { + std::list items; + + friend void OptimizeSongFilter(AndSongFilter &) noexcept; + friend ISongFilterPtr OptimizeSongFilter(ISongFilterPtr) noexcept; + +public: + const auto &GetItems() const noexcept { + return items; + } + + template + void AddItem(I &&_item) { + items.emplace_back(std::forward(_item)); + } + + [[gnu::pure]] + bool IsEmpty() const noexcept { + return items.empty(); + } + + /* virtual methods from ISongFilter */ + ISongFilterPtr Clone() const noexcept override; + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/AudioFormatSongFilter.cxx b/src/song/AudioFormatSongFilter.cxx new file mode 100644 index 0000000..69bd2b1 --- /dev/null +++ b/src/song/AudioFormatSongFilter.cxx @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "AudioFormatSongFilter.hxx" +#include "LightSong.hxx" +#include "util/StringBuffer.hxx" + +#include + +using std::string_view_literals::operator""sv; + +std::string +AudioFormatSongFilter::ToExpression() const noexcept +{ + return fmt::format("(AudioFormat {} \"{}\")"sv, + value.IsFullyDefined() ? "==" : "=~", + ToString(value).c_str()); +} + +bool +AudioFormatSongFilter::Match(const LightSong &song) const noexcept +{ + return song.audio_format.IsDefined() && + song.audio_format.MatchMask(value); +} diff --git a/src/song/AudioFormatSongFilter.hxx b/src/song/AudioFormatSongFilter.hxx new file mode 100644 index 0000000..73cc48c --- /dev/null +++ b/src/song/AudioFormatSongFilter.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_AUDIO_FORMAT_SONG_FILTER_HXX +#define MPD_AUDIO_FORMAT_SONG_FILTER_HXX + +#include "ISongFilter.hxx" +#include "pcm/AudioFormat.hxx" + +class AudioFormatSongFilter final : public ISongFilter { + AudioFormat value; + +public: + explicit AudioFormatSongFilter(const AudioFormat &_value) noexcept + :value(_value) {} + + + /* virtual methods from ISongFilter */ + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/BaseSongFilter.cxx b/src/song/BaseSongFilter.cxx new file mode 100644 index 0000000..7693ffc --- /dev/null +++ b/src/song/BaseSongFilter.cxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "BaseSongFilter.hxx" +#include "Escape.hxx" +#include "LightSong.hxx" +#include "util/UriRelative.hxx" + +std::string +BaseSongFilter::ToExpression() const noexcept +{ + return "(base \"" + EscapeFilterString(value) + "\")"; +} + +bool +BaseSongFilter::Match(const LightSong &song) const noexcept +{ + return uri_is_child_or_same(value.c_str(), song.GetURI().c_str()); +} diff --git a/src/song/BaseSongFilter.hxx b/src/song/BaseSongFilter.hxx new file mode 100644 index 0000000..c5ada24 --- /dev/null +++ b/src/song/BaseSongFilter.hxx @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_BASE_SONG_FILTER_HXX +#define MPD_BASE_SONG_FILTER_HXX + +#include "ISongFilter.hxx" + +class BaseSongFilter final : public ISongFilter { + std::string value; + +public: + BaseSongFilter(const BaseSongFilter &) = default; + + template + explicit BaseSongFilter(V &&_value) + :value(std::forward(_value)) {} + + const char *GetValue() const noexcept { + return value.c_str(); + } + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/DetachedSong.cxx b/src/song/DetachedSong.cxx new file mode 100644 index 0000000..b280c90 --- /dev/null +++ b/src/song/DetachedSong.cxx @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "song/DetachedSong.hxx" +#include "song/LightSong.hxx" +#include "util/UriExtract.hxx" +#include "fs/Traits.hxx" + +DetachedSong::DetachedSong(const LightSong &other) noexcept + :uri(other.GetURI()), + real_uri(other.real_uri != nullptr ? other.real_uri : ""), + tag(other.tag), + mtime(other.mtime), + added(other.added), + start_time(other.start_time), + end_time(other.end_time), + audio_format(other.audio_format) {} + +DetachedSong::operator LightSong() const noexcept +{ + LightSong result(uri.c_str(), tag); + result.directory = nullptr; + result.real_uri = real_uri.empty() ? nullptr : real_uri.c_str(); + result.mtime = mtime; + result.added = added; + result.start_time = start_time; + result.end_time = end_time; + return result; +} + +bool +DetachedSong::IsRemote() const noexcept +{ + return uri_has_scheme(GetRealURI()); +} + +bool +DetachedSong::IsAbsoluteFile() const noexcept +{ + return PathTraitsUTF8::IsAbsolute(GetRealURI()); +} + +bool +DetachedSong::IsInDatabase() const noexcept +{ + /* here, we use GetURI() and not GetRealURI() because + GetRealURI() is never relative */ + + const char *_uri = GetURI(); + return !PathTraitsUTF8::IsAbsoluteOrHasScheme(_uri); +} + +SignedSongTime +DetachedSong::GetDuration() const noexcept +{ + SongTime a = start_time, b = end_time; + if (!b.IsPositive()) { + if (tag.duration.IsNegative()) + return tag.duration; + + b = SongTime(tag.duration); + } + + return {b - a}; +} diff --git a/src/song/DetachedSong.hxx b/src/song/DetachedSong.hxx new file mode 100644 index 0000000..debf523 --- /dev/null +++ b/src/song/DetachedSong.hxx @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_DETACHED_SONG_HXX +#define MPD_DETACHED_SONG_HXX + +#include "tag/Tag.hxx" +#include "pcm/AudioFormat.hxx" +#include "Chrono.hxx" +#include "time/ChronoUtil.hxx" + +#include +#include +#include + +struct LightSong; +class Storage; +class Path; + +/** + * A stand-alone description of a song, that is, it manages all + * pointers. It is called "detached" because it is usually a copy of + * a #Song (or #LightSong) instance that was detached from the + * database. + */ +class DetachedSong { + friend DetachedSong DatabaseDetachSong(const Storage &db, + const LightSong &song); + + /** + * An UTF-8-encoded URI referring to the song file. This can + * be one of: + * + * - an absolute URL with a scheme + * (e.g. "http://example.com/foo.mp3") + * + * - an absolute file name + * + * - a file name relative to the music directory + */ + std::string uri; + + /** + * The "real" URI, the one to be used for opening the + * resource. If this attribute is empty, then #uri shall be + * used. + * + * This attribute is used for songs from the database which + * have a relative URI. + */ + std::string real_uri; + + Tag tag; + + /** + * The time stamp of the last file modification. A negative + * value means that this is unknown/unavailable. + */ + std::chrono::system_clock::time_point mtime = + std::chrono::system_clock::time_point::min(); + + /** + * The time stamp when the file was added to db. A negative + * value means that this is unknown/unavailable. + */ + std::chrono::system_clock::time_point added = + std::chrono::system_clock::time_point::min(); + + /** + * Start of this sub-song within the file. + */ + SongTime start_time = SongTime::zero(); + + /** + * End of this sub-song within the file. + * Unused if zero. + */ + SongTime end_time = SongTime::zero(); + + /** + * The audio format of the song, if given by the decoder + * plugin. May be undefined if unknown. + */ + AudioFormat audio_format = AudioFormat::Undefined(); + +public: + explicit DetachedSong(const char *_uri) noexcept + :uri(_uri) {} + + explicit DetachedSong(const std::string &_uri) noexcept + :uri(_uri) {} + + explicit DetachedSong(std::string &&_uri) noexcept + :uri(std::move(_uri)) {} + + template + DetachedSong(U &&_uri, Tag &&_tag) noexcept + :uri(std::forward(_uri)), + tag(std::move(_tag)) {} + + /** + * Copy data from a #LightSong instance. Usually, you should + * call DatabaseDetachSong() instead, which initializes + * #real_uri properly using Storage::MapUTF8(). + */ + explicit DetachedSong(const LightSong &other) noexcept; + + ~DetachedSong() noexcept = default; + + /* these are declared because the user-defined destructor + above prevents them from being generated implicitly */ + explicit DetachedSong(const DetachedSong &) = default; + DetachedSong(DetachedSong &&) = default; + DetachedSong &operator=(DetachedSong &&) = default; + + [[gnu::pure]] + explicit operator LightSong() const noexcept; + + [[gnu::pure]] + const char *GetURI() const noexcept { + return uri.c_str(); + } + + template + void SetURI(T &&_uri) noexcept { + uri = std::forward(_uri); + } + + /** + * Does this object have a "real" URI different from the + * displayed URI? + */ + [[gnu::pure]] + bool HasRealURI() const noexcept { + return !real_uri.empty(); + } + + /** + * Returns "real" URI (#real_uri) and falls back to just + * GetURI(). + */ + [[gnu::pure]] + const char *GetRealURI() const noexcept { + return (HasRealURI() ? real_uri : uri).c_str(); + } + + template + void SetRealURI(T &&_uri) noexcept { + real_uri = std::forward(_uri); + } + + /** + * Returns true if both objects refer to the same physical + * song. + */ + [[gnu::pure]] + bool IsSame(const DetachedSong &other) const noexcept { + return uri == other.uri && + start_time == other.start_time && + end_time == other.end_time; + } + + [[gnu::pure]] [[gnu::nonnull]] + bool IsURI(const char *other_uri) const noexcept { + return uri == other_uri; + } + + [[gnu::pure]] [[gnu::nonnull]] + bool IsRealURI(const char *other_uri) const noexcept { + return (HasRealURI() ? real_uri : uri) == other_uri; + } + + [[gnu::pure]] + bool IsRemote() const noexcept; + + [[gnu::pure]] + bool IsFile() const noexcept { + return !IsRemote(); + } + + [[gnu::pure]] + bool IsAbsoluteFile() const noexcept; + + [[gnu::pure]] + bool IsInDatabase() const noexcept; + + const Tag &GetTag() const noexcept { + return tag; + } + + Tag &WritableTag() noexcept { + return tag; + } + + void SetTag(const Tag &_tag) noexcept { + tag = Tag(_tag); + } + + void SetTag(Tag &&_tag) noexcept { + tag = std::move(_tag); + } + + void MoveTagFrom(DetachedSong &&other) noexcept { + tag = std::move(other.tag); + } + + /** + * Similar to the MoveTagFrom(), but move only the #TagItem + * array. + */ + void MoveTagItemsFrom(DetachedSong &&other) noexcept { + tag.MoveItemsFrom(std::move(other.tag)); + } + + std::chrono::system_clock::time_point GetLastModified() const noexcept { + return mtime; + } + + void SetLastModified(std::chrono::system_clock::time_point _value) noexcept { + mtime = _value; + } + + std::chrono::system_clock::time_point GetAdded() const noexcept { + return IsNegative(added) + ? mtime + : added; + } + + void SetAdded(std::chrono::system_clock::time_point _value) noexcept { + added = _value; + } + + SongTime GetStartTime() const noexcept { + return start_time; + } + + void SetStartTime(SongTime _value) noexcept { + start_time = _value; + } + + SongTime GetEndTime() const noexcept { + return end_time; + } + + void SetEndTime(SongTime _value) noexcept { + end_time = _value; + } + + [[gnu::pure]] + SignedSongTime GetDuration() const noexcept; + + const AudioFormat &GetAudioFormat() const noexcept { + return audio_format; + } + + void SetAudioFormat(const AudioFormat &src) noexcept { + audio_format = src; + } + + /** + * Update the #tag and #mtime. + * + * Throws on error. + * + * @return true on success + */ + bool Update(); + + /** + * Load #tag and #mtime from a local file. + * + * Throws on error. + */ + bool LoadFile(Path path); +}; + +#endif diff --git a/src/song/Escape.cxx b/src/song/Escape.cxx new file mode 100644 index 0000000..034cbfa --- /dev/null +++ b/src/song/Escape.cxx @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Escape.hxx" + +static constexpr bool +MustEscape(char ch) noexcept +{ + return ch == '"' || ch == '\'' || ch == '\\'; +} + +std::string +EscapeFilterString(const std::string &src) noexcept +{ + std::string result; + result.reserve(src.length() + 16); + + for (char ch : src) { + if (MustEscape(ch)) + result.push_back('\\'); + result.push_back(ch); + } + + return result; +} diff --git a/src/song/Escape.hxx b/src/song/Escape.hxx new file mode 100644 index 0000000..88704d6 --- /dev/null +++ b/src/song/Escape.hxx @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SONG_ESCAPE_HXX +#define MPD_SONG_ESCAPE_HXX + +#include + +[[gnu::pure]] +std::string +EscapeFilterString(const std::string &src) noexcept; + +#endif diff --git a/src/song/Filter.cxx b/src/song/Filter.cxx new file mode 100644 index 0000000..0d95341 --- /dev/null +++ b/src/song/Filter.cxx @@ -0,0 +1,606 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "Filter.hxx" +#include "NotSongFilter.hxx" +#include "UriSongFilter.hxx" +#include "BaseSongFilter.hxx" +#include "TagSongFilter.hxx" +#include "ModifiedSinceSongFilter.hxx" +#include "AddedSinceSongFilter.hxx" +#include "AudioFormatSongFilter.hxx" +#include "PrioritySongFilter.hxx" +#include "pcm/AudioParser.hxx" +#include "tag/ParseName.hxx" +#include "tag/Type.hxx" +#include "time/ISO8601.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "util/CharUtil.hxx" +#include "util/StringCompare.hxx" +#include "util/StringStrip.hxx" +#include "util/ASCII.hxx" +#include "util/UriUtil.hxx" + +#include + +#include + +#define LOCATE_TAG_FILE_KEY "file" +#define LOCATE_TAG_FILE_KEY_OLD "filename" +#define LOCATE_TAG_ANY_KEY "any" + +enum { + /** + * Limit the search to files within the given directory. + */ + LOCATE_TAG_BASE_TYPE = TAG_NUM_OF_ITEM_TYPES + 1, + + LOCATE_TAG_MODIFIED_SINCE, + LOCATE_TAG_AUDIO_FORMAT, + LOCATE_TAG_PRIORITY, + LOCATE_TAG_FILE_TYPE, + LOCATE_TAG_ANY_TYPE, + LOCATE_TAG_ADDED_SINCE, +}; + +/** + * @return #TAG_NUM_OF_ITEM_TYPES on error + */ +[[gnu::pure]] +static unsigned +locate_parse_type(const char *str) noexcept +{ + if (StringEqualsCaseASCII(str, LOCATE_TAG_FILE_KEY) || + StringEqualsCaseASCII(str, LOCATE_TAG_FILE_KEY_OLD)) + return LOCATE_TAG_FILE_TYPE; + + if (StringEqualsCaseASCII(str, LOCATE_TAG_ANY_KEY)) + return LOCATE_TAG_ANY_TYPE; + + if (strcmp(str, "base") == 0) + return LOCATE_TAG_BASE_TYPE; + + if (strcmp(str, "modified-since") == 0) + return LOCATE_TAG_MODIFIED_SINCE; + + if (strcmp(str, "added-since") == 0) + return LOCATE_TAG_ADDED_SINCE; + + if (StringEqualsCaseASCII(str, "AudioFormat")) + return LOCATE_TAG_AUDIO_FORMAT; + + if (StringEqualsCaseASCII(str, "prio")) + return LOCATE_TAG_PRIORITY; + + return tag_name_parse_i(str); +} + +SongFilter::SongFilter(TagType tag, const char *value, bool fold_case) +{ + /* for compatibility with MPD 0.20 and older, "fold_case" also + switches on "substring" */ + const auto position = fold_case + ? StringFilter::Position::ANYWHERE + : StringFilter::Position::FULL; + + and_filter.AddItem(std::make_unique(tag, + StringFilter(value, fold_case, position, false))); +} + +/* this destructor exists here just so it won't get inlined */ +SongFilter::~SongFilter() = default; + +std::string +SongFilter::ToExpression() const noexcept +{ + return and_filter.ToExpression(); +} + +static std::chrono::system_clock::time_point +ParseTimeStamp(const char *s) +{ + assert(s != nullptr); + + try { + /* try ISO 8601 */ + return ParseISO8601(s).first; + } catch (...) { + char *endptr; + unsigned long long value = strtoull(s, &endptr, 10); + if (*endptr == 0 && endptr > s) + /* it's an integral UNIX time stamp */ + return std::chrono::system_clock::from_time_t((time_t)value); + + /* rethrow the ParseISO8601() error */ + throw; + } +} + +static constexpr bool +IsTagNameChar(char ch) noexcept +{ + return IsAlphaASCII(ch) || ch == '_' || ch == '-'; +} + +static const char * +FirstNonTagNameChar(const char *s) noexcept +{ + while (IsTagNameChar(*s)) + ++s; + return s; +} + +static auto +ExpectWord(const char *&s) +{ + const char *begin = s; + const char *end = FirstNonTagNameChar(s); + if (end == s) + throw std::runtime_error("Word expected"); + + s = StripLeft(end); + return std::string(begin, end); +} + +static auto +ExpectFilterType(const char *&s) +{ + const auto name = ExpectWord(s); + + const auto type = locate_parse_type(name.c_str()); + if (type == TAG_NUM_OF_ITEM_TYPES) + throw FmtRuntimeError("Unknown filter type: {}", name); + + return type; +} + +static constexpr bool +IsQuote(char ch) noexcept +{ + return ch == '"' || ch == '\''; +} + +static std::string +ExpectQuoted(const char *&s) +{ + const char quote = *s++; + if (!IsQuote(quote)) + throw std::runtime_error("Quoted string expected"); + + char buffer[4096]; + size_t length = 0; + + while (*s != quote) { + if (*s == '\\') + /* backslash escapes the following character */ + ++s; + + if (*s == 0) + throw std::runtime_error("Closing quote not found"); + + buffer[length++] = *s++; + + if (length >= sizeof(buffer)) + throw std::runtime_error("Quoted value is too long"); + } + + s = StripLeft(s + 1); + + return {buffer, length}; +} + +/** + * Operator definition used to parse the operator + * from the command and create the StringFilter + * if it matched the operator prefix. + */ +struct OperatorDef { + const char *prefix; + bool fold_case; + bool negated; + StringFilter::Position position; +}; + +/** + * Pre-defined operators with explicit case-sensitivity. + */ +static constexpr std::array operators = { + // operator prefix fold case negated position + OperatorDef { "contains_cs ", false, false, StringFilter::Position::ANYWHERE }, + OperatorDef { "!contains_cs ", false, true, StringFilter::Position::ANYWHERE }, + OperatorDef { "contains_ci ", true, false, StringFilter::Position::ANYWHERE }, + OperatorDef { "!contains_ci ", true, true, StringFilter::Position::ANYWHERE }, + + OperatorDef { "starts_with_cs ", false, false, StringFilter::Position::PREFIX }, + OperatorDef { "!starts_with_cs ", false, true, StringFilter::Position::PREFIX }, + OperatorDef { "starts_with_ci ", true, false, StringFilter::Position::PREFIX }, + OperatorDef { "!starts_with_ci ", true, true, StringFilter::Position::PREFIX }, + + OperatorDef { "eq_cs ", false, false, StringFilter::Position::FULL }, + OperatorDef { "!eq_cs ", false, true, StringFilter::Position::FULL }, + OperatorDef { "eq_ci ", true, false, StringFilter::Position::FULL }, + OperatorDef { "!eq_ci ", true, true, StringFilter::Position::FULL }, +}; + +/** + * Parse a string operator and its second operand and convert it to a + * #StringFilter. + * + * Throws on error. + */ +static StringFilter +ParseStringFilter(const char *&s, bool fold_case) +{ + for (auto& op: operators) { + if (auto after_prefix = StringAfterPrefixIgnoreCase(s, op.prefix)) { + s = StripLeft(after_prefix); + return StringFilter( + ExpectQuoted(s), + op.fold_case, + op.position, + op.negated); + } + } + + if (auto after_contains = StringAfterPrefixIgnoreCase(s, "contains ")) { + s = StripLeft(after_contains); + auto value = ExpectQuoted(s); + return { + std::move(value), fold_case, + StringFilter::Position::ANYWHERE, + false, + }; + } + + if (auto after_not_contains = StringAfterPrefixIgnoreCase(s, "!contains ")) { + s = StripLeft(after_not_contains); + auto value = ExpectQuoted(s); + return { + std::move(value), fold_case, + StringFilter::Position::ANYWHERE, + true, + }; + } + + if (auto after_starts_with = StringAfterPrefixIgnoreCase(s, "starts_with ")) { + s = StripLeft(after_starts_with); + auto value = ExpectQuoted(s); + return { + std::move(value), fold_case, + StringFilter::Position::PREFIX, + false, + }; + } + + if (auto after_not_starts_with = StringAfterPrefixIgnoreCase(s, "!starts_with ")) { + s = StripLeft(after_not_starts_with); + auto value = ExpectQuoted(s); + return { + std::move(value), fold_case, + StringFilter::Position::PREFIX, + true, + }; + } + + bool negated = false; + +#ifdef HAVE_PCRE + if ((s[0] == '!' || s[0] == '=') && s[1] == '~') { + negated = s[0] == '!'; + s = StripLeft(s + 2); + auto value = ExpectQuoted(s); + StringFilter f{ + std::move(value), fold_case, + StringFilter::Position::FULL, + negated, + }; + f.SetRegex(std::make_shared(f.GetValue().c_str(), + Pcre::CompileOptions{.caseless=fold_case})); + return f; + } +#endif + + if (s[0] == '!' && s[1] == '=') + negated = true; + else if (s[0] != '=' || s[1] != '=') + throw FmtRuntimeError("Unknown filter operator: {}", s); + + s = StripLeft(s + 2); + auto value = ExpectQuoted(s); + + return { + std::move(value), fold_case, + StringFilter::Position::FULL, + negated, + }; +} + +ISongFilterPtr +SongFilter::ParseExpression(const char *&s, bool fold_case) +{ + assert(*s == '('); + + s = StripLeft(s + 1); + + if (*s == '(') { + auto first = ParseExpression(s, fold_case); + if (*s == ')') { + s = StripLeft(s + 1); + return first; + } + + if (ExpectWord(s) != "AND") + throw std::runtime_error("'AND' expected"); + + auto and_filter = std::make_unique(); + and_filter->AddItem(std::move(first)); + + while (true) { + and_filter->AddItem(ParseExpression(s, fold_case)); + + if (*s == ')') { + s = StripLeft(s + 1); + return and_filter; + } + + if (ExpectWord(s) != "AND") + throw std::runtime_error("'AND' expected"); + } + } + + if (*s == '!') { + s = StripLeft(s + 1); + + if (*s != '(') + throw std::runtime_error("'(' expected"); + + auto inner = ParseExpression(s, fold_case); + if (*s != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(s + 1); + + return std::make_unique(std::move(inner)); + } + + auto type = ExpectFilterType(s); + + if (type == LOCATE_TAG_MODIFIED_SINCE) { + const auto value_s = ExpectQuoted(s); + if (*s != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(s + 1); + return std::make_unique(ParseTimeStamp(value_s.c_str())); + } else if (type == LOCATE_TAG_ADDED_SINCE) { + const auto value_s = ExpectQuoted(s); + if (*s != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(s + 1); + return std::make_unique(ParseTimeStamp(value_s.c_str())); + } else if (type == LOCATE_TAG_BASE_TYPE) { + auto value = ExpectQuoted(s); + if (*s != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(s + 1); + + return std::make_unique(std::move(value)); + } else if (type == LOCATE_TAG_AUDIO_FORMAT) { + bool mask; + if (s[0] == '=' && s[1] == '=') + mask = false; + else if (s[0] == '=' && s[1] == '~') + mask = true; + else + throw std::runtime_error("'==' or '=~' expected"); + + s = StripLeft(s + 2); + + const auto value = ParseAudioFormat(ExpectQuoted(s), mask); + + if (*s != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(s + 1); + + return std::make_unique(value); + } else if (type == LOCATE_TAG_PRIORITY) { + if (s[0] == '>' && s[1] == '=') { + // TODO support more operators + } else + throw std::runtime_error("'>=' expected"); + + s = StripLeft(s + 2); + + char *endptr; + const auto value = strtoul(s, &endptr, 10); + if (endptr == s) + throw std::runtime_error("Number expected"); + + if (value > 0xff) + throw std::runtime_error("Invalid priority value"); + + if (*endptr != ')') + throw std::runtime_error("')' expected"); + s = StripLeft(endptr + 1); + + return std::make_unique(value); + } else { + auto string_filter = ParseStringFilter(s, fold_case); + if (*s != ')') + throw std::runtime_error("')' expected"); + + s = StripLeft(s + 1); + + if (type == LOCATE_TAG_ANY_TYPE) + type = TAG_NUM_OF_ITEM_TYPES; + + if (type == LOCATE_TAG_FILE_TYPE) + return std::make_unique(std::move(string_filter)); + + return std::make_unique(TagType(type), + std::move(string_filter)); + } +} + +void +SongFilter::Parse(const char *tag_string, const char *value, bool fold_case) +{ + unsigned tag = locate_parse_type(tag_string); + + switch (tag) { + case TAG_NUM_OF_ITEM_TYPES: + throw std::runtime_error("Unknown filter type"); + + case LOCATE_TAG_BASE_TYPE: + if (!uri_safe_local(value)) + throw std::runtime_error("Bad URI"); + + and_filter.AddItem(std::make_unique(value)); + break; + + case LOCATE_TAG_MODIFIED_SINCE: + and_filter.AddItem(std::make_unique(ParseTimeStamp(value))); + break; + + case LOCATE_TAG_ADDED_SINCE: + and_filter.AddItem(std::make_unique(ParseTimeStamp(value))); + break; + + case LOCATE_TAG_FILE_TYPE: + /* for compatibility with MPD 0.20 and older, + "fold_case" also switches on "substring" */ + and_filter.AddItem(std::make_unique(StringFilter{ + value, + fold_case, + fold_case + ? StringFilter::Position::ANYWHERE + : StringFilter::Position::FULL, + false, + })); + break; + + default: + if (tag == LOCATE_TAG_ANY_TYPE) + tag = TAG_NUM_OF_ITEM_TYPES; + + /* for compatibility with MPD 0.20 and older, + "fold_case" also switches on "substring" */ + and_filter.AddItem(std::make_unique(TagType(tag), StringFilter{ + value, + fold_case, + fold_case + ? StringFilter::Position::ANYWHERE + : StringFilter::Position::FULL, + false, + })); + break; + } +} + +void +SongFilter::Parse(std::span args, bool fold_case) +{ + if (args.empty()) + throw std::runtime_error("Incorrect number of filter arguments"); + + do { + if (*args.front() == '(') { + const char *s = args.front(); + args = args.subspan(1); + const char *end = s; + auto f = ParseExpression(end, fold_case); + if (*end != 0) + throw std::runtime_error("Unparsed garbage after expression"); + + and_filter.AddItem(std::move(f)); + continue; + } + + if (args.size() < 2) + throw std::runtime_error("Incorrect number of filter arguments"); + + const char *tag = args[0]; + const char *value = args[1]; + args = args.subspan(2); + Parse(tag, value, fold_case); + } while (!args.empty()); +} + +void +SongFilter::Optimize() noexcept +{ + OptimizeSongFilter(and_filter); +} + +bool +SongFilter::Match(const LightSong &song) const noexcept +{ + return and_filter.Match(song); +} + +bool +SongFilter::HasFoldCase() const noexcept +{ + return std::any_of( + and_filter.GetItems().begin(), and_filter.GetItems().end(), + [](const auto &item) { + if (auto t = dynamic_cast(item.get())) + return t->GetFoldCase(); + + if (auto u = dynamic_cast(item.get())) + return u->GetFoldCase(); + + return false; + }); +} + +bool +SongFilter::HasOtherThanBase() const noexcept +{ + return std::any_of(and_filter.GetItems().begin(), and_filter.GetItems().end(), + [=](const auto &item) { + return !dynamic_cast( + item.get()); + }); +} + +const char * +SongFilter::GetBase() const noexcept +{ + for (const auto &i : and_filter.GetItems()) { + const auto *f = dynamic_cast(i.get()); + if (f != nullptr) + return f->GetValue(); + } + + return nullptr; +} + +SongFilter +SongFilter::WithoutBasePrefix(const std::string_view prefix) const noexcept +{ + SongFilter result; + + for (const auto &i : and_filter.GetItems()) { + const auto *f = dynamic_cast(i.get()); + if (f != nullptr) { + const char *s = StringAfterPrefix(f->GetValue(), prefix); + if (s != nullptr) { + if (*s == 0) + continue; + + if (*s == '/') { + ++s; + + if (*s != 0) + result.and_filter.AddItem(std::make_unique(s)); + + continue; + } + } + } + + result.and_filter.AddItem(i->Clone()); + } + + return result; +} diff --git a/src/song/Filter.hxx b/src/song/Filter.hxx new file mode 100644 index 0000000..b48f91b --- /dev/null +++ b/src/song/Filter.hxx @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SONG_FILTER_HXX +#define MPD_SONG_FILTER_HXX + +#include "AndSongFilter.hxx" + +#include +#include +#include +#include + +/** + * Special value for the db_selection_print() sort parameter. + */ +#define SORT_TAG_LAST_MODIFIED (TAG_NUM_OF_ITEM_TYPES + 3) + +/** + * Special value for QueueSelection::sort + */ +#define SORT_TAG_PRIO (TAG_NUM_OF_ITEM_TYPES + 4) + +/** + * Special value for the db_selection_print() sort parameter. + */ +#define SORT_TAG_ADDED (TAG_NUM_OF_ITEM_TYPES + 5) + +enum TagType : uint8_t; +struct LightSong; + +class SongFilter { + AndSongFilter and_filter; + +public: + SongFilter() = default; + + SongFilter(TagType tag, const char *value, bool fold_case=false); + + ~SongFilter(); + + SongFilter(SongFilter &&) = default; + SongFilter &operator=(SongFilter &&) = default; + + /** + * Convert this object into an "expression". This is + * only useful for debugging. + */ + std::string ToExpression() const noexcept; + +private: + static ISongFilterPtr ParseExpression(const char *&s, bool fold_case=false); + + void Parse(const char *tag, const char *value, bool fold_case=false); + +public: + /** + * Throws on error. + */ + void Parse(std::span args, bool fold_case=false); + + void Optimize() noexcept; + + [[gnu::pure]] + bool Match(const LightSong &song) const noexcept; + + const auto &GetItems() const noexcept { + return and_filter.GetItems(); + } + + [[gnu::pure]] + bool IsEmpty() const noexcept { + return and_filter.IsEmpty(); + } + + /** + * Is there at least one item with "fold case" enabled? + */ + [[gnu::pure]] + bool HasFoldCase() const noexcept; + + /** + * Does this filter contain constraints other than "base"? + */ + [[gnu::pure]] + bool HasOtherThanBase() const noexcept; + + /** + * Returns the "base" specification (if there is one) or + * nullptr. + */ + [[gnu::pure]] + const char *GetBase() const noexcept; + + /** + * Create a copy of the filter with the given prefix stripped + * from all #LOCATE_TAG_BASE_TYPE items. This is used to + * filter songs in mounted databases. + */ + SongFilter WithoutBasePrefix(std::string_view prefix) const noexcept; +}; + +#endif diff --git a/src/song/ISongFilter.hxx b/src/song/ISongFilter.hxx new file mode 100644 index 0000000..3b470f7 --- /dev/null +++ b/src/song/ISongFilter.hxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_I_SONG_FILTER_HXX +#define MPD_I_SONG_FILTER_HXX + +#include +#include + +struct LightSong; +class ISongFilter; +using ISongFilterPtr = std::unique_ptr; + +class ISongFilter { +public: + virtual ~ISongFilter() noexcept = default; + + virtual ISongFilterPtr Clone() const noexcept = 0; + + /** + * Convert this object into an "expression". This is + * only useful for debugging. + */ + virtual std::string ToExpression() const noexcept = 0; + + [[gnu::pure]] + virtual bool Match(const LightSong &song) const noexcept = 0; +}; + +#endif diff --git a/src/song/LightSong.cxx b/src/song/LightSong.cxx new file mode 100644 index 0000000..64f7ee2 --- /dev/null +++ b/src/song/LightSong.cxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LightSong.hxx" +#include "tag/Tag.hxx" + +SignedSongTime +LightSong::GetDuration() const noexcept +{ + SongTime a = start_time, b = end_time; + if (!b.IsPositive()) { + if (tag.duration.IsNegative()) + return tag.duration; + + b = SongTime(tag.duration); + } + + return {b - a}; +} diff --git a/src/song/LightSong.hxx b/src/song/LightSong.hxx new file mode 100644 index 0000000..e432812 --- /dev/null +++ b/src/song/LightSong.hxx @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_LIGHT_SONG_HXX +#define MPD_LIGHT_SONG_HXX + +#include "Chrono.hxx" +#include "pcm/AudioFormat.hxx" + +#include +#include + +struct Tag; + +/** + * A reference to a song file. Unlike the other "Song" classes in the + * MPD code base, this one consists only of pointers. It is supposed + * to be as light as possible while still providing all the + * information MPD has about a song file. This class does not manage + * any memory, and the pointers become invalid quickly. Only to be + * used to pass around during well-defined situations. + */ +struct LightSong { + /** + * If this is not nullptr, then it denotes a prefix for the + * #uri. To build the full URI, join directory and uri with a + * slash. + */ + const char *directory = nullptr; + + const char *uri; + + /** + * The "real" URI, the one to be used for opening the + * resource. If this attribute is nullptr, then #uri (and + * #directory) shall be used. + * + * This attribute is used for songs from the database which + * have a relative URI. + */ + const char *real_uri = nullptr; + + /** + * Metadata. + */ + const Tag &tag; + + /** + * The time stamp of the last file modification. A negative + * value means that this is unknown/unavailable. + */ + std::chrono::system_clock::time_point mtime = std::chrono::system_clock::time_point::min(); + + /** + * The time stamp when the file was added. A negative + * value means that this is unknown/unavailable. + */ + std::chrono::system_clock::time_point added = std::chrono::system_clock::time_point::min(); + + /** + * Start of this sub-song within the file. + */ + SongTime start_time = SongTime::zero(); + + /** + * End of this sub-song within the file. + * Unused if zero. + */ + SongTime end_time = SongTime::zero(); + + /** + * The audio format of the song, if given by the decoder + * plugin. May be undefined if unknown. + */ + AudioFormat audio_format = AudioFormat::Undefined(); + + /** + * Copy of Queue::Item::priority. + */ + uint8_t priority = 0; + + LightSong(const char *_uri, const Tag &_tag) noexcept + :uri(_uri), tag(_tag) {} + + /** + * A copy constructor which copies all fields, but only sets + * the tag to a caller-provided reference. This is used by + * the #ExportedSong move constructor. + */ + LightSong(const LightSong &src, const Tag &_tag) noexcept + :directory(src.directory), uri(src.uri), + real_uri(src.real_uri), + tag(_tag), + mtime(src.mtime), + start_time(src.start_time), end_time(src.end_time), + audio_format(src.audio_format) {} + + [[gnu::pure]] + std::string GetURI() const noexcept { + if (directory == nullptr) + return std::string(uri); + + std::string result(directory); + result.push_back('/'); + result.append(uri); + return result; + } + + [[gnu::pure]] + SignedSongTime GetDuration() const noexcept; +}; + +#endif diff --git a/src/song/ModifiedSinceSongFilter.cxx b/src/song/ModifiedSinceSongFilter.cxx new file mode 100644 index 0000000..43879c7 --- /dev/null +++ b/src/song/ModifiedSinceSongFilter.cxx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ModifiedSinceSongFilter.hxx" +#include "LightSong.hxx" +#include "time/ISO8601.hxx" +#include "util/StringBuffer.hxx" + +#include + +using std::string_view_literals::operator""sv; + +std::string +ModifiedSinceSongFilter::ToExpression() const noexcept +{ + return fmt::format("(modified-since \"{}\")"sv, FormatISO8601(value).c_str()); +} + +bool +ModifiedSinceSongFilter::Match(const LightSong &song) const noexcept +{ + return song.mtime >= value; +} diff --git a/src/song/ModifiedSinceSongFilter.hxx b/src/song/ModifiedSinceSongFilter.hxx new file mode 100644 index 0000000..a8577ee --- /dev/null +++ b/src/song/ModifiedSinceSongFilter.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_MODIFIED_SINCE_SONG_FILTER_HXX +#define MPD_MODIFIED_SINCE_SONG_FILTER_HXX + +#include "ISongFilter.hxx" + +#include + +class ModifiedSinceSongFilter final : public ISongFilter { + std::chrono::system_clock::time_point value; + +public: + explicit ModifiedSinceSongFilter(std::chrono::system_clock::time_point _value) noexcept + :value(_value) {} + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/NotSongFilter.hxx b/src/song/NotSongFilter.hxx new file mode 100644 index 0000000..536dd02 --- /dev/null +++ b/src/song/NotSongFilter.hxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_NOT_SONG_FILTER_HXX +#define MPD_NOT_SONG_FILTER_HXX + +#include "ISongFilter.hxx" + +/** + * Negate an #ISongFilter. + */ +class NotSongFilter final : public ISongFilter { + ISongFilterPtr child; + + friend ISongFilterPtr OptimizeSongFilter(ISongFilterPtr) noexcept; + +public: + template + explicit NotSongFilter(C &&_child) noexcept + :child(std::forward(_child)) {} + + /* virtual methods from ISongFilter */ + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(child->Clone()); + } + + std::string ToExpression() const noexcept override { + return "(!" + child->ToExpression() + ")"; + } + + bool Match(const LightSong &song) const noexcept override { + return !child->Match(song); + } +}; + +#endif diff --git a/src/song/OptimizeFilter.cxx b/src/song/OptimizeFilter.cxx new file mode 100644 index 0000000..52eae9a --- /dev/null +++ b/src/song/OptimizeFilter.cxx @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "OptimizeFilter.hxx" +#include "AndSongFilter.hxx" +#include "NotSongFilter.hxx" +#include "TagSongFilter.hxx" +#include "UriSongFilter.hxx" + +void +OptimizeSongFilter(AndSongFilter &af) noexcept +{ + for (auto i = af.items.begin(); i != af.items.end();) { + auto f = OptimizeSongFilter(std::move(*i)); + if (auto *nested = dynamic_cast(f.get())) { + /* collapse nested #AndSongFilter instances */ + af.items.splice(i, std::move(nested->items)); + i = af.items.erase(i); + } else { + *i = std::move(f); + ++i; + } + } +} + +ISongFilterPtr +OptimizeSongFilter(ISongFilterPtr f) noexcept +{ + if (auto *af = dynamic_cast(f.get())) { + /* first optimize all items */ + OptimizeSongFilter(*af); + + if (!af->items.empty() && + std::next(af->items.begin()) == af->items.end()) + /* only one item: the containing + #AndSongFilter can be removed */ + return std::move(af->items.front()); + } else if (auto *nf = dynamic_cast(f.get())) { + auto child = OptimizeSongFilter(std::move(nf->child)); + if (auto *tf = dynamic_cast(child.get())) { + /* #TagSongFilter has its own "negated" flag, + so we can drop the #NotSongFilter + container */ + tf->ToggleNegated(); + return child; + } else if (auto *uf = dynamic_cast(child.get())) { + /* same for #UriSongFilter */ + uf->ToggleNegated(); + return child; + } + + nf->child = std::move(child); + } + + return f; +} diff --git a/src/song/OptimizeFilter.hxx b/src/song/OptimizeFilter.hxx new file mode 100644 index 0000000..6a88b52 --- /dev/null +++ b/src/song/OptimizeFilter.hxx @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SONG_OPTIMIZE_FILTER_HXX +#define MPD_SONG_OPTIMIZE_FILTER_HXX + +#include "ISongFilter.hxx" + +class AndSongFilter; + +void +OptimizeSongFilter(AndSongFilter &af) noexcept; + +ISongFilterPtr +OptimizeSongFilter(ISongFilterPtr f) noexcept; + +#endif diff --git a/src/song/PrioritySongFilter.cxx b/src/song/PrioritySongFilter.cxx new file mode 100644 index 0000000..1805f2a --- /dev/null +++ b/src/song/PrioritySongFilter.cxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PrioritySongFilter.hxx" +#include "LightSong.hxx" +#include "time/ISO8601.hxx" +#include "util/StringBuffer.hxx" + +#include + +std::string +PrioritySongFilter::ToExpression() const noexcept +{ + return fmt::format("(prio >= {})", value); +} + +bool +PrioritySongFilter::Match(const LightSong &song) const noexcept +{ + return song.priority >= value; +} diff --git a/src/song/PrioritySongFilter.hxx b/src/song/PrioritySongFilter.hxx new file mode 100644 index 0000000..55cb140 --- /dev/null +++ b/src/song/PrioritySongFilter.hxx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "ISongFilter.hxx" + +#include + +class PrioritySongFilter final : public ISongFilter { + const uint8_t value; + +public: + explicit PrioritySongFilter(uint8_t _value) noexcept + :value(_value) {} + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; diff --git a/src/song/StringFilter.cxx b/src/song/StringFilter.cxx new file mode 100644 index 0000000..e2ea44f --- /dev/null +++ b/src/song/StringFilter.cxx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "StringFilter.hxx" +#include "util/StringAPI.hxx" + +#include + +bool +StringFilter::MatchWithoutNegation(const char *s) const noexcept +{ + assert(s != nullptr); + +#ifdef HAVE_PCRE + if (regex) + return regex->Match(s); +#endif + + if (fold_case) { + switch (position) { + case Position::FULL: + break; + + case Position::ANYWHERE: + return fold_case.IsIn(s); + + case Position::PREFIX: + return fold_case.StartsWith(s); + } + + return fold_case == s; + } else { + switch (position) { + case Position::FULL: + break; + + case Position::ANYWHERE: + return StringFind(s, value.c_str()) != nullptr; + + case Position::PREFIX: + return StringIsEqual(s, value.c_str(), value.length()); + } + + return value == s; + } +} + +bool +StringFilter::Match(const char *s) const noexcept +{ + return MatchWithoutNegation(s) != negated; +} diff --git a/src/song/StringFilter.hxx b/src/song/StringFilter.hxx new file mode 100644 index 0000000..86e419b --- /dev/null +++ b/src/song/StringFilter.hxx @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STRING_FILTER_HXX +#define MPD_STRING_FILTER_HXX + +#include "lib/icu/Compare.hxx" +#include "config.h" + +#ifdef HAVE_PCRE +#include "lib/pcre/UniqueRegex.hxx" +#endif + +#include +#include +#include + +class StringFilter { +public: + enum class Position : uint_least8_t { + /** compare the whole haystack */ + FULL, + + /** find the phrase anywhere in the haystack */ + ANYWHERE, + + /** check if the haystack starts with the given prefix */ + PREFIX, + }; + +private: + std::string value; + + /** + * This value is only set if case folding is enabled. + */ + IcuCompare fold_case; + +#ifdef HAVE_PCRE + std::shared_ptr regex; +#endif + + Position position; + + bool negated; + +public: + template + StringFilter(V &&_value, bool _fold_case, Position _position, bool _negated) + :value(std::forward(_value)), + fold_case(_fold_case + ? IcuCompare(value) + : IcuCompare()), + position(_position), + negated(_negated) {} + + bool empty() const noexcept { + return value.empty(); + } + + bool IsRegex() const noexcept { +#ifdef HAVE_PCRE + return !!regex; +#else + return false; +#endif + } + +#ifdef HAVE_PCRE + template + void SetRegex(R &&_regex) noexcept { + regex = std::forward(_regex); + } +#endif + + const auto &GetValue() const noexcept { + return value; + } + + bool GetFoldCase() const noexcept { + return fold_case; + } + + bool IsNegated() const noexcept { + return negated; + } + + void ToggleNegated() noexcept { + negated = !negated; + } + + const char *GetOperator() const noexcept { + if (IsRegex()) + return negated ? "!~" : "=~"; + + switch (position) { + case Position::FULL: + break; + + case Position::ANYWHERE: + return negated ? "!contains" : "contains"; + + case Position::PREFIX: + return negated ? "!starts_with" : "starts_with"; + } + + return negated ? "!=" : "=="; + } + + [[gnu::pure]] + bool Match(const char *s) const noexcept; + + /** + * Like Match(), but ignore the "negated" flag. + */ + [[gnu::pure]] + bool MatchWithoutNegation(const char *s) const noexcept; +}; + +#endif diff --git a/src/song/TagSongFilter.cxx b/src/song/TagSongFilter.cxx new file mode 100644 index 0000000..13b5d48 --- /dev/null +++ b/src/song/TagSongFilter.cxx @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "TagSongFilter.hxx" +#include "Escape.hxx" +#include "LightSong.hxx" +#include "tag/Names.hxx" +#include "tag/Tag.hxx" +#include "tag/Fallback.hxx" + +std::string +TagSongFilter::ToExpression() const noexcept +{ + const char *name = type == TAG_NUM_OF_ITEM_TYPES + ? "any" + : tag_item_names[type]; + + return std::string("(") + name + " " + filter.GetOperator() + + " \"" + EscapeFilterString(filter.GetValue()) + "\")"; +} + +bool +TagSongFilter::Match(const Tag &tag) const noexcept +{ + bool visited_types[TAG_NUM_OF_ITEM_TYPES]{}; + + for (const auto &i : tag) { + visited_types[i.type] = true; + + if ((type == TAG_NUM_OF_ITEM_TYPES || i.type == type) && + filter.MatchWithoutNegation(i.value)) + return !filter.IsNegated(); + } + + if (type < TAG_NUM_OF_ITEM_TYPES && !visited_types[type]) { + /* if the specified tag is not present, try the + fallback tags */ + + bool result = false; + if (ApplyTagFallback(type, [&](TagType tag2) { + if (!visited_types[tag2]) + /* we already know that this tag type + isn't present, so let's bail out + without checking again */ + return false; + + for (const auto &item : tag) { + if (item.type == tag2 && + filter.MatchWithoutNegation(item.value)) { + result = true; + break; + } + } + + return true; + })) + return result != filter.IsNegated(); + + /* If the search critieron was not visited during the + sweep through the song's tag, it means this field + is absent from the tag or empty. Thus, if the + searched string is also empty + then it's a match as well and we should return + true. */ + if (filter.empty()) + return !filter.IsNegated(); + } + + return filter.IsNegated(); +} + +bool +TagSongFilter::Match(const LightSong &song) const noexcept +{ + return Match(song.tag); +} diff --git a/src/song/TagSongFilter.hxx b/src/song/TagSongFilter.hxx new file mode 100644 index 0000000..1a477c0 --- /dev/null +++ b/src/song/TagSongFilter.hxx @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_SONG_FILTER_HXX +#define MPD_TAG_SONG_FILTER_HXX + +#include "ISongFilter.hxx" +#include "StringFilter.hxx" + +#include + +enum TagType : uint8_t; +struct Tag; +struct LightSong; + +class TagSongFilter final : public ISongFilter { + TagType type; + + StringFilter filter; + +public: + TagSongFilter(TagType _type, StringFilter &&_filter) noexcept + :type(_type), filter(std::move(_filter)) {} + + TagType GetTagType() const { + return type; + } + + const auto &GetValue() const noexcept { + return filter.GetValue(); + } + + bool GetFoldCase() const { + return filter.GetFoldCase(); + } + + bool IsNegated() const noexcept { + return filter.IsNegated(); + } + + void ToggleNegated() noexcept { + filter.ToggleNegated(); + } + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; + +private: + bool Match(const Tag &tag) const noexcept; +}; + +#endif diff --git a/src/song/UriSongFilter.cxx b/src/song/UriSongFilter.cxx new file mode 100644 index 0000000..636d557 --- /dev/null +++ b/src/song/UriSongFilter.cxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "UriSongFilter.hxx" +#include "Escape.hxx" +#include "LightSong.hxx" + +std::string +UriSongFilter::ToExpression() const noexcept +{ + return std::string("(file ") + filter.GetOperator() + + " \"" + EscapeFilterString(filter.GetValue()) + "\")"; +} + +bool +UriSongFilter::Match(const LightSong &song) const noexcept +{ + return filter.Match(song.GetURI().c_str()); +} diff --git a/src/song/UriSongFilter.hxx b/src/song/UriSongFilter.hxx new file mode 100644 index 0000000..7067968 --- /dev/null +++ b/src/song/UriSongFilter.hxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_URI_SONG_FILTER_HXX +#define MPD_URI_SONG_FILTER_HXX + +#include "ISongFilter.hxx" +#include "StringFilter.hxx" + +class UriSongFilter final : public ISongFilter { + StringFilter filter; + +public: + UriSongFilter(StringFilter &&_filter) noexcept + :filter(std::move(_filter)) {} + + const auto &GetValue() const noexcept { + return filter.GetValue(); + } + + bool GetFoldCase() const { + return filter.GetFoldCase(); + } + + bool IsNegated() const noexcept { + return filter.IsNegated(); + } + + void ToggleNegated() noexcept { + filter.ToggleNegated(); + } + + ISongFilterPtr Clone() const noexcept override { + return std::make_unique(*this); + } + + std::string ToExpression() const noexcept override; + bool Match(const LightSong &song) const noexcept override; +}; + +#endif diff --git a/src/song/meson.build b/src/song/meson.build new file mode 100644 index 0000000..1f6863d --- /dev/null +++ b/src/song/meson.build @@ -0,0 +1,33 @@ +song = static_library( + 'song', + 'DetachedSong.cxx', + 'Escape.cxx', + 'StringFilter.cxx', + 'UriSongFilter.cxx', + 'BaseSongFilter.cxx', + 'TagSongFilter.cxx', + 'ModifiedSinceSongFilter.cxx', + 'AddedSinceSongFilter.cxx', + 'PrioritySongFilter.cxx', + 'AudioFormatSongFilter.cxx', + 'AndSongFilter.cxx', + 'OptimizeFilter.cxx', + 'Filter.cxx', + 'LightSong.cxx', + include_directories: inc, + dependencies: [ + pcre_dep, + fmt_dep, + ], +) + +song_dep = declare_dependency( + link_with: song, + dependencies: [ + icu_dep, + pcre_dep, + tag_dep, + time_dep, + util_dep, + ], +) diff --git a/src/sticker/AllowedTags.cxx b/src/sticker/AllowedTags.cxx new file mode 100644 index 0000000..0deec76 --- /dev/null +++ b/src/sticker/AllowedTags.cxx @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "AllowedTags.hxx" +#include "tag/Mask.hxx" + +#include + +static constexpr TagType sticker_allowed_tags_init[] = { + TAG_ARTIST, + TAG_ALBUM, + TAG_ALBUM_ARTIST, + TAG_TITLE, + TAG_GENRE, + TAG_COMPOSER, + TAG_PERFORMER, + TAG_CONDUCTOR, + TAG_WORK, + TAG_ENSEMBLE, + TAG_LOCATION, + TAG_LABEL, + TAG_MUSICBRAINZ_ARTISTID, + TAG_MUSICBRAINZ_ALBUMID, + TAG_MUSICBRAINZ_ALBUMARTISTID, + TAG_MUSICBRAINZ_RELEASETRACKID, + TAG_MUSICBRAINZ_WORKID, +}; + +static constexpr auto +TagArrayToMask() noexcept +{ + auto result = TagMask::None(); + + for (const auto i : sticker_allowed_tags_init) { + /* no duplicates allowed */ + assert(!result.Test(i)); + + result |= i; + } + + return result; +} + +constinit const TagMask sticker_allowed_tags = TagArrayToMask(); diff --git a/src/sticker/AllowedTags.hxx b/src/sticker/AllowedTags.hxx new file mode 100644 index 0000000..db04bab --- /dev/null +++ b/src/sticker/AllowedTags.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +class TagMask; + +/** + * These are the tags that are allowed to have stickers. + */ +extern const TagMask sticker_allowed_tags; diff --git a/src/sticker/CleanupService.cxx b/src/sticker/CleanupService.cxx new file mode 100644 index 0000000..a7b3aed --- /dev/null +++ b/src/sticker/CleanupService.cxx @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "CleanupService.hxx" +#include "Database.hxx" +#include "Sticker.hxx" +#include "TagSticker.hxx" +#include "lib/fmt/ExceptionFormatter.hxx" +#include "song/Filter.hxx" +#include "thread/Name.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" +#include "Instance.hxx" + +static constexpr Domain sticker_domain{"sticker"}; + +StickerCleanupService::StickerCleanupService(Instance &_instance, + StickerDatabase &_sticker_db, + Database &_db) noexcept + :instance(_instance), + sticker_db(_sticker_db.Reopen()), + music_db(_db), + defer(_instance.event_loop, BIND_THIS_METHOD(RunDeferred)) +{ +} + +StickerCleanupService::~StickerCleanupService() noexcept +{ + // call only by the owning instance + assert(GetEventLoop().IsInside()); + + CancelAndJoin(); +} + +void +StickerCleanupService::Start() +{ + // call only by the owning instance + assert(GetEventLoop().IsInside()); + + thread.Start(); + + FmtDebug(sticker_domain, + "spawned thread for cleanup job"); +} + +void +StickerCleanupService::RunDeferred() noexcept +{ + instance.OnStickerCleanupDone(deleted_count != 0); +} + +static std::size_t +DeleteStickers(StickerDatabase &sticker_db, + std::list &stickers) +{ + if (stickers.empty()) + return 0; + sticker_db.BatchDeleteNoIdle(stickers); + auto count = stickers.size(); + stickers.clear(); + return count; +} + +void +StickerCleanupService::Task() noexcept +{ + SetThreadName("sticker"); + + FmtDebug(sticker_domain, "begin cleanup"); + + try { + auto stickers = sticker_db.GetUniqueStickers(); + auto iter = stickers.cbegin(); + std::list batch; + while (!cancel_flag && !stickers.empty()) { + const auto &[sticker_type, sticker_uri] = *iter; + + const auto filter = MakeSongFilterNoThrow(sticker_type.c_str(), sticker_uri.c_str()); + + if (filter.IsEmpty() || FilterMatches(music_db, filter)) + // skip if found a match or if not a valid sticker filter + iter = stickers.erase(iter); + else { + batch.splice(batch.end(), stickers, iter++); + if (batch.size() == DeleteBatchSize) + deleted_count += DeleteStickers(sticker_db, batch); + } + } + + if (!cancel_flag) + deleted_count += DeleteStickers(sticker_db, batch); + } catch (...) { + FmtError(sticker_domain, "cleanup failed: {}", + std::current_exception()); + } + + defer.Schedule(); + + FmtDebug(sticker_domain, "end cleanup: {} stickers deleted", + deleted_count); +} + +void +StickerCleanupService::CancelAndJoin() noexcept +{ + if (thread.IsDefined()) { + cancel_flag = true; + thread.Join(); + } +} + diff --git a/src/sticker/CleanupService.hxx b/src/sticker/CleanupService.hxx new file mode 100644 index 0000000..a50332b --- /dev/null +++ b/src/sticker/CleanupService.hxx @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "Database.hxx" +#include "event/InjectEvent.hxx" +#include "thread/Thread.hxx" + +#include + +class Database; +struct Instance; + +/** + * Delete stickers that no longer match items in the music database. + * + * When done calls Instance::OnSickerCleanupDone() in the instance event loop. + */ +class StickerCleanupService { + /** + * number of stickers to delete in one transaction + */ + static constexpr std::size_t DeleteBatchSize = 50; + + Instance &instance; + StickerDatabase sticker_db; + Database &music_db; + Thread thread{BIND_THIS_METHOD(Task)}; + InjectEvent defer; + std::size_t deleted_count{0}; + std::atomic_bool cancel_flag{false}; + +public: + StickerCleanupService(Instance &_instance, + StickerDatabase &_sticker_db, + Database &_db) noexcept; + + ~StickerCleanupService() noexcept; + + auto &GetEventLoop() const noexcept { + return defer.GetEventLoop(); + } + + void Start(); + +private: + void Task() noexcept; + + void RunDeferred() noexcept; + + void CancelAndJoin() noexcept; +}; diff --git a/src/sticker/Database.cxx b/src/sticker/Database.cxx new file mode 100644 index 0000000..b80e301 --- /dev/null +++ b/src/sticker/Database.cxx @@ -0,0 +1,559 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Database.hxx" +#include "Sticker.hxx" +#include "lib/sqlite/Util.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "Idle.hxx" +#include "util/StringCompare.hxx" +#include "util/ScopeExit.hxx" + +#include +#include +#include // for std::throw_with_nested() +#include +#include +#include +#include // for std::unreachable() + +using namespace Sqlite; + +enum sticker_sql_find { + STICKER_SQL_FIND, + STICKER_SQL_FIND_VALUE, + STICKER_SQL_FIND_LT, + STICKER_SQL_FIND_GT, + + STICKER_SQL_FIND_EQ_INT, + STICKER_SQL_FIND_LT_INT, + STICKER_SQL_FIND_GT_INT, + + STICKER_SQL_FIND_CONTAINS, + STICKER_SQL_FIND_STARTS_WITH, + + STICKER_SQL_FIND_COUNT +}; + +enum sticker_sql { + STICKER_SQL_GET, + STICKER_SQL_LIST, + STICKER_SQL_SET, + STICKER_SQL_DELETE, + STICKER_SQL_DELETE_VALUE, + STICKER_SQL_DISTINCT_TYPE_URI, + STICKER_SQL_TRANSACTION_BEGIN, + STICKER_SQL_TRANSACTION_COMMIT, + STICKER_SQL_TRANSACTION_ROLLBACK, + STICKER_SQL_NAMES, + STICKER_SQL_NAMES_TYPES, + STICKER_SQL_NAMES_TYPES_BY_TYPE, + STICKER_SQL_INC, + STICKER_SQL_DEC, + + STICKER_SQL_COUNT +}; + +static constexpr auto sticker_sql_find = std::array { + //[STICKER_SQL_FIND] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=?", + + //[STICKER_SQL_FIND_VALUE] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND value=?", + + //[STICKER_SQL_FIND_LT] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND value?", + + //[STICKER_SQL_FIND_EQ_INT] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND CAST(value AS INT)=?", + + //[STICKER_SQL_FIND_LT_INT] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND CAST(value AS INT)?", + + //[STICKER_SQL_FIND_CONTAINS] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND value LIKE ('%' || ? || '%')", + + //[STICKER_SQL_FIND_STARTS_WITH] = + "SELECT uri,value FROM sticker WHERE type=? AND uri LIKE (? || '%') AND name=? AND value LIKE (? || '%')", +}; + +static constexpr auto sticker_sql = std::array { + //[STICKER_SQL_GET] = + "SELECT value FROM sticker WHERE type=? AND uri=? AND name=?", + //[STICKER_SQL_LIST] = + "SELECT name,value FROM sticker WHERE type=? AND uri=?", + //[STICKER_SQL_SET] = + "INSERT INTO sticker(type, uri, name, value) VALUES(?, ?, ?, ?) " + "ON CONFLICT(type, uri, name) DO " + "UPDATE set value = ?", + //[STICKER_SQL_DELETE] = + "DELETE FROM sticker WHERE type=? AND uri=?", + //[STICKER_SQL_DELETE_VALUE] = + "DELETE FROM sticker WHERE type=? AND uri=? AND name=?", + + //[STICKER_SQL_DISTINCT_TYPE_URI] = + "SELECT DISTINCT type,uri FROM sticker", + + //[STICKER_SQL_TRANSACTION_BEGIN] + "BEGIN", + + //[STICKER_SQL_TRANSACTION_COMMIT] + "COMMIT", + + //[STICKER_SQL_TRANSACTION_ROLLBACK] + "ROLLBACK", + + //[STICKER_SQL_NAMES] + "SELECT DISTINCT name FROM sticker ORDER BY name", + + //[STICKER_SQL_NAMES_TYPES] + "SELECT name,type FROM sticker GROUP BY name,type ORDER BY name", + + //[STICKER_SQL_NAMES_TYPES_BY_TYPE] + "SELECT name,type FROM sticker WHERE type = ? GROUP BY name,type ORDER BY name", + + //[STICKER_SQL_INC] = + "INSERT INTO sticker (type, uri, name, value) VALUES (?, ?, ?, ?) " + "ON CONFLICT(type, uri, name) DO " + "UPDATE set value = value + ?", + + //[STICKER_SQL_DEC] = + "INSERT INTO sticker (type, uri, name, value) VALUES (?, ?, ?, ?) " + "ON CONFLICT(type, uri, name) DO " + "UPDATE set value = value - ?", +}; + +static constexpr const char sticker_sql_create[] = + "CREATE TABLE IF NOT EXISTS sticker(" + " type VARCHAR NOT NULL, " + " uri VARCHAR NOT NULL, " + " name VARCHAR NOT NULL, " + " value VARCHAR NOT NULL" + ");" + "CREATE UNIQUE INDEX IF NOT EXISTS" + " sticker_value ON sticker(type, uri, name);" + ""; + +StickerDatabase::StickerDatabase(const char *_path) + :path(_path), + db(path.c_str()) +{ + int ret; + + /* create the table and index */ + + ret = sqlite3_exec(db, sticker_sql_create, + nullptr, nullptr, nullptr); + if (ret != SQLITE_OK) + throw SqliteError(db, ret, + "Failed to create sticker table"); + + /* prepare the statements we're going to use */ + + for (size_t i = 0; i < sticker_sql.size(); ++i) { + assert(sticker_sql[i] != nullptr); + + stmt[i] = Prepare(db, sticker_sql[i]); + } +} + +StickerDatabase::StickerDatabase(Path _path) + :StickerDatabase(NarrowPath{_path}) {} + +StickerDatabase::~StickerDatabase() noexcept +{ + if (db == nullptr) + return; + + for (const auto &sticker : stmt) { + assert(sticker != nullptr); + + sqlite3_finalize(sticker); + } +} + +std::string +StickerDatabase::LoadValue(const char *type, const char *uri, const char *name) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_GET]; + + assert(type != nullptr); + assert(uri != nullptr); + assert(name != nullptr); + + if (StringIsEmpty(name)) + return {}; + + BindAll(s, type, uri, name); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + std::string value; + if (ExecuteRow(s)) + value = (const char*)sqlite3_column_text(s, 0); + + return value; +} + +void +StickerDatabase::ListValues(std::map> &table, + const char *type, const char *uri) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_LIST]; + + assert(type != nullptr); + assert(uri != nullptr); + + BindAll(s, type, uri); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + ExecuteForEach(s, [s, &table](){ + const char *name = (const char *)sqlite3_column_text(s, 0); + const char *value = (const char *)sqlite3_column_text(s, 1); + table.emplace(name, value); + }); +} + +void +StickerDatabase::StoreValue(const char *type, const char *uri, + const char *name, const char *value) +{ + assert(type != nullptr); + assert(uri != nullptr); + assert(name != nullptr); + assert(*name != 0); + assert(value != nullptr); + + sqlite3_stmt *const s = stmt[STICKER_SQL_SET]; + + BindAll(s, type, uri, name, value, value); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + ExecuteCommand(s); + idle_add(IDLE_STICKER); +} + +void +StickerDatabase::IncValue(const char *type, const char *uri, + const char *name, const char *value) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_INC]; + + assert(type != nullptr); + assert(uri != nullptr); + assert(name != nullptr); + assert(*name != 0); + assert(value != nullptr); + + BindAll(s, type, uri, name, value, value); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + ExecuteCommand(s); + idle_add(IDLE_STICKER); +} + +void +StickerDatabase::DecValue(const char *type, const char *uri, + const char *name, const char *value) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_DEC]; + + assert(type != nullptr); + assert(uri != nullptr); + assert(name != nullptr); + assert(*name != 0); + assert(value != nullptr); + + BindAll(s, type, uri, name, value, value); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + ExecuteCommand(s); + idle_add(IDLE_STICKER); +} + +bool +StickerDatabase::Delete(const char *type, const char *uri) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_DELETE]; + + assert(type != nullptr); + assert(uri != nullptr); + + BindAll(s, type, uri); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + bool modified = ExecuteModified(s); + if (modified) + idle_add(IDLE_STICKER); + return modified; +} + +bool +StickerDatabase::DeleteValue(const char *type, const char *uri, + const char *name) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_DELETE_VALUE]; + + assert(type != nullptr); + assert(uri != nullptr); + assert(name != nullptr); + + BindAll(s, type, uri, name); + + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + bool modified = ExecuteModified(s); + if (modified) + idle_add(IDLE_STICKER); + return modified; +} + +Sticker +StickerDatabase::Load(const char *type, const char *uri) +{ + Sticker s; + + ListValues(s.table, type, uri); + + return s; +} + +sqlite3_stmt * +StickerDatabase::BindFind(const char *type, const char *base_uri, + const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window) +{ + assert(type != nullptr); + assert(name != nullptr); + + if (base_uri == nullptr) + base_uri = ""; + + auto order_by = StringIsEmpty(sort) + ? std::string() + : StringIsEqual(sort, "value_int") + ? fmt::format("ORDER BY CAST(value AS INT) {}", descending ? "desc" : "asc") + : fmt::format("ORDER BY {} {}", sort, descending ? "desc" : "asc"); + + auto offset = window.IsAll() + ? std::string() + : window.IsOpenEnded() + ? fmt::format("LIMIT -1 OFFSET {}", window.start) + : fmt::format("LIMIT {} OFFSET {}", window.Count(), window.start); + + std::string sql_str; + sqlite3_stmt *sql; + + switch (op) { + case StickerOperator::EXISTS: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name); + return sql; + + case StickerOperator::EQUALS: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_VALUE], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::LESS_THAN: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_LT], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::GREATER_THAN: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_GT], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::EQUALS_INT: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_EQ_INT], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::LESS_THAN_INT: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_LT_INT], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::GREATER_THAN_INT: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_GT_INT], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::CONTAINS: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_CONTAINS], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + + case StickerOperator::STARTS_WITH: + sql_str = fmt::format("{} {} {}", + sticker_sql_find[STICKER_SQL_FIND_STARTS_WITH], order_by, offset); + sql = Prepare(db, sql_str.c_str()); + BindAll(sql, type, base_uri, name, value); + return sql; + } + + std::unreachable(); +} + +void +StickerDatabase::Find(const char *type, const char *base_uri, const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window, + void (*func)(const char *uri, const char *value, + void *user_data), + void *user_data) +{ + assert(func != nullptr); + + sqlite3_stmt *const s = BindFind(type, base_uri, name, op, value, sort, descending, window); + assert(s != nullptr); + + AtScopeExit(s) { + sqlite3_finalize(s); + }; + + ExecuteForEach(s, [s, func, user_data](){ + func((const char*)sqlite3_column_text(s, 0), + (const char*)sqlite3_column_text(s, 1), + user_data); + }); +} + +std::list +StickerDatabase::GetUniqueStickers() +{ + auto result = std::list{}; + sqlite3_stmt *const s = stmt[STICKER_SQL_DISTINCT_TYPE_URI]; + assert(s != nullptr); + AtScopeExit(s) { + sqlite3_reset(s); + }; + ExecuteForEach(s, [&s, &result]() { + result.emplace_back((const char*)sqlite3_column_text(s, 0), + (const char*)sqlite3_column_text(s, 1)); + }); + return result; +} + +void +StickerDatabase::Names(void (*func)(const char *value, void *user_data), void *user_data) +{ + assert(func != nullptr); + + sqlite3_stmt *const s = stmt[STICKER_SQL_NAMES]; + assert(s != nullptr); + + AtScopeExit(s) { + sqlite3_reset(s); + }; + + ExecuteForEach(s, [s, func, user_data](){ + func((const char*)sqlite3_column_text(s, 0), user_data); + }); +} + +void +StickerDatabase::NamesTypes(const char *type, void (*func)(const char *value, const char *type, void *user_data), void *user_data) +{ + assert(func != nullptr); + + sqlite3_stmt *const s = type == nullptr + ? stmt[STICKER_SQL_NAMES_TYPES] + : stmt[STICKER_SQL_NAMES_TYPES_BY_TYPE]; + assert(s != nullptr); + + if (type != nullptr) + BindAll(s, type); + + AtScopeExit(s) { + sqlite3_reset(s); + }; + + ExecuteForEach(s, [s, func, user_data](){ + func((const char*)sqlite3_column_text(s, 0), + (const char*)sqlite3_column_text(s, 1), user_data); + }); +} + +void +StickerDatabase::BatchDeleteNoIdle(const std::list &stickers) +{ + sqlite3_stmt *const s = stmt[STICKER_SQL_DELETE]; + + sqlite3_stmt *const begin = stmt[STICKER_SQL_TRANSACTION_BEGIN]; + sqlite3_stmt *const rollback = stmt[STICKER_SQL_TRANSACTION_ROLLBACK]; + sqlite3_stmt *const commit = stmt[STICKER_SQL_TRANSACTION_COMMIT]; + + try { + ExecuteBusy(begin); + + for (auto &sticker: stickers) { + AtScopeExit(s) { + sqlite3_reset(s); + sqlite3_clear_bindings(s); + }; + + BindAll(s, sticker.first.c_str(), sticker.second.c_str()); + + ExecuteCommand(s); + } + + ExecuteBusy(commit); + } catch (...) { + // "If the transaction has already been rolled back automatically by the error response, + // then the ROLLBACK command will fail with an error, but no harm is caused by this." + ExecuteBusy(rollback); + std::throw_with_nested(std::runtime_error{"failed to batch-delete stickers"}); + } +} diff --git a/src/sticker/Database.hxx b/src/sticker/Database.hxx new file mode 100644 index 0000000..8aedfb9 --- /dev/null +++ b/src/sticker/Database.hxx @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This is the sticker database library. It is the backend of all the + * sticker code in MPD. + * + * "Stickers" are pieces of information attached to existing MPD + * objects (e.g. song files, directories, albums). Clients can create + * arbitrary name/value pairs. MPD itself does not assume any special + * meaning in them. + * + * The goal is to allow clients to share additional (possibly dynamic) + * information about songs, which is neither stored on the client (not + * available to other clients), nor stored in the song files (MPD has + * no write access). + * + * Client developers should create a standard for common sticker + * names, to ensure interoperability. + * + * Examples: song ratings; statistics; deferred tag writes; lyrics; + * ... + * + */ + +#ifndef MPD_STICKER_DATABASE_HXX +#define MPD_STICKER_DATABASE_HXX + +#include "Match.hxx" +#include "lib/sqlite/Database.hxx" +#include "protocol/RangeArg.hxx" + +#include + +#include +#include +#include + +class Path; +struct Sticker; + +class StickerDatabase { + enum SQL { + SQL_GET, + SQL_LIST, + SQL_SET, + SQL_DELETE, + SQL_DELETE_VALUE, + SQL_DISTINCT_TYPE_URI, + SQL_TRANSACTION_BEGIN, + SQL_TRANSACTION_COMMIT, + SQL_TRANSACTION_ROLLBACK, + SQL_NAMES, + SQL_NAMES_TYPES, + SQL_NAMES_TYPES_BY_TYPE, + STICKER_SQL_INC, + STICKER_SQL_DEC, + + SQL_COUNT + }; + + enum SQL_FIND { + SQL_FIND, + SQL_FIND_VALUE, + SQL_FIND_LT, + SQL_FIND_GT, + + SQL_FIND_EQ_INT, + SQL_FIND_LT_INT, + SQL_FIND_GT_INT, + + SQL_FIND_CONTAINS, + SQL_FIND_STARTS_WITH, + + SQL_FIND_COUNT + }; + + std::string path; + + Sqlite::Database db; + sqlite3_stmt *stmt[SQL_COUNT]; + + explicit StickerDatabase(const char *_path); + +public: + /** + * Opens the sticker database. + * + * Throws on error. + */ + StickerDatabase(Path path); + ~StickerDatabase() noexcept; + + StickerDatabase(StickerDatabase &&) noexcept = default; + StickerDatabase &operator=(StickerDatabase &&) noexcept = default; + + /** + * Open another connection to the same database file. + */ + [[nodiscard]] + StickerDatabase Reopen() const { + return StickerDatabase{path.c_str()}; + } + + /** + * Returns one value from an object's sticker record. Returns an + * empty string if the value doesn't exist. + * + * Throws #SqliteError on error. + */ + std::string LoadValue(const char *type, const char *uri, + const char *name); + + /** + * Sets a sticker value in the specified object. Overwrites existing + * values. + * + * Throws #SqliteError on error. + */ + void StoreValue(const char *type, const char *uri, + const char *name, const char *value); + + /** + * Increments a sticker by value in the specified object. Inserts + * the value if object does not exist. + * + * Throws #SqliteError on error. + */ + void IncValue(const char *type, const char *uri, + const char *name, const char *value); + + /** + * Decrements a sticker by value in the specified object. Inserts + * the value if object does not exist. + * + * Throws #SqliteError on error. + */ + void DecValue(const char *type, const char *uri, + const char *name, const char *value); + + /** + * Deletes a sticker from the database. All sticker values of the + * specified object are deleted. + * + * Throws #SqliteError on error. + */ + bool Delete(const char *type, const char *uri); + + /** + * Deletes a sticker value. Fails if no sticker with this name + * exists. + * + * Throws #SqliteError on error. + */ + bool DeleteValue(const char *type, const char *uri, const char *name); + + /** + * Loads the sticker for the specified resource. + * + * Throws #SqliteError on error. + * + * @param type the resource type, e.g. "song" + * @param uri the URI of the resource, e.g. the song path + * @return a sticker object + */ + Sticker Load(const char *type, const char *uri); + + /** + * Finds stickers with the specified name below the specified URI. + * + * @param type the resource type, e.g. "song" + * @param base_uri the URI prefix of the resources, or nullptr if all + * resources should be searched + * @param name the name of the sticker + * @param op the comparison operator + * @param value the operand + */ + void Find(const char *type, const char *base_uri, const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window, + void (*func)(const char *uri, const char *value, + void *user_data), + void *user_data); + + /** + * Uniq and sorted list of all sticker names + */ + void Names(void (*func)(const char *value, void *user_data), void *user_data); + + /** + * Uniq and sorted list of all sticker names by type + */ + void NamesTypes(const char *type, void (*func)(const char *value, const char *type, void *user_data), void *user_data); + + using StickerTypeUriPair = std::pair; + + /** + * @return A list of unique type-uri pairs of all the stickers + * in the database. + */ + std::list GetUniqueStickers(); + + /** + * Delete stickers by type and uri + * @param stickers A list of stickers to delete + */ + void BatchDeleteNoIdle(const std::list &stickers); + +private: + void ListValues(std::map> &table, + const char *type, const char *uri); + + bool UpdateValue(const char *type, const char *uri, + const char *name, const char *value); + + void InsertValue(const char *type, const char *uri, + const char *name, const char *value); + + sqlite3_stmt *BindFind(const char *type, const char *base_uri, + const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window); +}; + +#endif diff --git a/src/sticker/Match.hxx b/src/sticker/Match.hxx new file mode 100644 index 0000000..7c05f6c --- /dev/null +++ b/src/sticker/Match.hxx @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STICKER_MATCH_HXX +#define MPD_STICKER_MATCH_HXX + +enum class StickerOperator { + /** + * Matches if a sticker with the specified name exists. The + * "value" parameter is ignored (must be nullptr). + */ + EXISTS, + + /** + * Matches if a sticker with the specified name and value + * exists. + */ + EQUALS, + + /** + * Matches if a sticker with the specified name exists with a + * value smaller than the specified one. + */ + LESS_THAN, + + /** + * Matches if a sticker with the specified name exists with a + * value bigger than the specified one. + */ + GREATER_THAN, + + /** + * Matches if a sticker with the specified name exists with a + * integer value equal the specified one. + */ + EQUALS_INT, + + /** + * Matches if a sticker with the specified name exists with a + * integer value smaller than the specified one. + */ + LESS_THAN_INT, + + /** + * Matches if a sticker with the specified name exists with a + * integer value bigger than the specified one. + */ + GREATER_THAN_INT, + + /** + * Matches if a sticker with the specified name exists and value + * contains given string. + */ + CONTAINS, + + /** + * Matches if a sticker with the specified name exits and value + * starts with given string. + */ + STARTS_WITH, +}; + +#endif diff --git a/src/sticker/Print.cxx b/src/sticker/Print.cxx new file mode 100644 index 0000000..d40649e --- /dev/null +++ b/src/sticker/Print.cxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Print.hxx" +#include "Sticker.hxx" +#include "client/Response.hxx" + +#include + +void +sticker_print_value(Response &r, + const char *name, const char *value) +{ + r.Fmt("sticker: {}={}\n", name, value); +} + +void +sticker_print(Response &r, const Sticker &sticker) +{ + for (const auto &[name, val] : sticker.table) + sticker_print_value(r, name.c_str(), val.c_str()); +} diff --git a/src/sticker/Print.hxx b/src/sticker/Print.hxx new file mode 100644 index 0000000..be2a146 --- /dev/null +++ b/src/sticker/Print.hxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STICKER_PRINT_HXX +#define MPD_STICKER_PRINT_HXX + +struct Sticker; +class Response; + +/** + * Sends one sticker value to the client. + */ +void +sticker_print_value(Response &r, const char *name, const char *value); + +/** + * Sends all sticker values to the client. + */ +void +sticker_print(Response &r, const Sticker &sticker); + +#endif diff --git a/src/sticker/SongSticker.cxx b/src/sticker/SongSticker.cxx new file mode 100644 index 0000000..b7b695d --- /dev/null +++ b/src/sticker/SongSticker.cxx @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "SongSticker.hxx" +#include "Sticker.hxx" +#include "Database.hxx" +#include "song/LightSong.hxx" +#include "db/Interface.hxx" +#include "util/AllocatedString.hxx" + +#include +#include + +using std::string_view_literals::operator""sv; + +std::string +sticker_song_get_value(StickerDatabase &db, + const LightSong &song, const char *name) +{ + const auto uri = song.GetURI(); + return db.LoadValue("song", uri.c_str(), name); +} + +void +sticker_song_set_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value) +{ + const auto uri = song.GetURI(); + db.StoreValue("song", uri.c_str(), name, value); +} + +void +sticker_song_inc_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value) +{ + const auto uri = song.GetURI(); + db.IncValue("song", uri.c_str(), name, value); +} + +void +sticker_song_dec_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value) +{ + const auto uri = song.GetURI(); + db.DecValue("song", uri.c_str(), name, value); +} + +bool +sticker_song_delete(StickerDatabase &db, const char *uri) +{ + return db.Delete("song", uri); +} + +bool +sticker_song_delete(StickerDatabase &db, const LightSong &song) +{ + return sticker_song_delete(db, song.GetURI().c_str()); +} + +bool +sticker_song_delete_value(StickerDatabase &db, + const LightSong &song, const char *name) +{ + const auto uri = song.GetURI(); + return db.DeleteValue("song", uri.c_str(), name); +} + +Sticker +sticker_song_get(StickerDatabase &db, const LightSong &song) +{ + const auto uri = song.GetURI(); + return db.Load("song", uri.c_str()); +} + +namespace { +struct sticker_song_find_data { + const Database *db; + const char *base_uri; + size_t base_uri_length; + + void (*func)(const LightSong &song, const char *value, + void *user_data); + void *user_data; +}; +} // namespace + +static void +sticker_song_find_cb(const char *uri, const char *value, void *user_data) +{ + auto *data = + (struct sticker_song_find_data *)user_data; + + if (memcmp(uri, data->base_uri, data->base_uri_length) != 0) + /* should not happen, ignore silently */ + return; + + const Database *db = data->db; + try { + const LightSong *song = db->GetSong(uri); + data->func(*song, value, data->user_data); + db->ReturnSong(song); + } catch (...) { + } +} + +void +sticker_song_find(StickerDatabase &sticker_database, const Database &db, + const char *base_uri, const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window, + void (*func)(const LightSong &song, const char *value, + void *user_data), + void *user_data) +{ + struct sticker_song_find_data data; + data.db = &db; + data.func = func; + data.user_data = user_data; + + AllocatedString allocated; + data.base_uri = base_uri; + if (*data.base_uri != 0) { + /* append slash to base_uri */ + allocated = AllocatedString{std::string_view{data.base_uri}, "/"sv}; + data.base_uri = allocated.c_str(); + } else { + /* searching in root directory - no trailing slash */ + } + + data.base_uri_length = strlen(data.base_uri); + + sticker_database.Find("song", data.base_uri, name, op, value, + sort, descending, window, + sticker_song_find_cb, &data); +} diff --git a/src/sticker/SongSticker.hxx b/src/sticker/SongSticker.hxx new file mode 100644 index 0000000..92fbe52 --- /dev/null +++ b/src/sticker/SongSticker.hxx @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SONG_STICKER_HXX +#define MPD_SONG_STICKER_HXX + +#include "Match.hxx" +#include "protocol/RangeArg.hxx" + +#include + +struct LightSong; +struct Sticker; +class Database; +class StickerDatabase; + +/** + * Returns one value from a song's sticker record. + * + * Throws #SqliteError on error. + */ +std::string +sticker_song_get_value(StickerDatabase &db, + const LightSong &song, const char *name); + +/** + * Sets a sticker value in the specified song. Overwrites existing + * values. + * + * Throws #SqliteError on error. + */ +void +sticker_song_set_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value); + +/** + * Increments a sticker by value in the specified object. Inserts + * the value if object does not exist. + * + * Throws #SqliteError on error. + */ +void +sticker_song_inc_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value); + +/** + * Decrements a sticker by value in the specified object. Inserts + * the value if object does not exist. + * + * Throws #SqliteError on error. + */ +void +sticker_song_dec_value(StickerDatabase &db, + const LightSong &song, + const char *name, const char *value); + +/** + * Deletes a sticker from the database. All values are deleted. + * + * Throws #SqliteError on error. + */ +bool +sticker_song_delete(StickerDatabase &db, const char *uri); + +bool +sticker_song_delete(StickerDatabase &db, const LightSong &song); + +/** + * Deletes a sticker value. Does nothing if the sticker did not + * exist. + * + * Throws #SqliteError on error. + */ +bool +sticker_song_delete_value(StickerDatabase &db, + const LightSong &song, const char *name); + +/** + * Loads the sticker for the specified song. + * + * Throws #SqliteError on error. + * + * @param song the song object + * @return a sticker object + */ +Sticker +sticker_song_get(StickerDatabase &db, const LightSong &song); + +/** + * Finds stickers with the specified name below the specified + * directory. + * + * Caller must lock the #db_mutex. + * + * Throws #SqliteError on error. + * + * @param base_uri the base directory to search in + * @param name the name of the sticker + */ +void +sticker_song_find(StickerDatabase &sticker_database, const Database &db, + const char *base_uri, const char *name, + StickerOperator op, const char *value, + const char *sort, bool descending, RangeArg window, + void (*func)(const LightSong &song, const char *value, + void *user_data), + void *user_data); + +#endif diff --git a/src/sticker/Sticker.hxx b/src/sticker/Sticker.hxx new file mode 100644 index 0000000..32c89a2 --- /dev/null +++ b/src/sticker/Sticker.hxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STICKER_HXX +#define MPD_STICKER_HXX + +#include +#include + +struct Sticker { + std::map> table; +}; + +#endif diff --git a/src/sticker/TagSticker.cxx b/src/sticker/TagSticker.cxx new file mode 100644 index 0000000..2c08844 --- /dev/null +++ b/src/sticker/TagSticker.cxx @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "TagSticker.hxx" +#include "Database.hxx" +#include "AllowedTags.hxx" +#include "db/Interface.hxx" +#include "db/Selection.hxx" +#include "tag/Mask.hxx" +#include "tag/Names.hxx" +#include "tag/ParseName.hxx" +#include "song/Filter.hxx" +#include "util/StringAPI.hxx" + +SongFilter +MakeSongFilter(const char *filter_string) +{ + const std::array args{filter_string}; + + auto filter = SongFilter(); + filter.Parse(args, false); + filter.Optimize(); + + return filter; +} + +SongFilter +MakeSongFilter(TagType tag_type, const char *tag_value) +{ + if (!sticker_allowed_tags.Test(tag_type)) + throw std::runtime_error("tag type not allowed for sticker"); + + const std::array args{tag_item_names[tag_type], tag_value}; + + SongFilter filter; + filter.Parse(args, false); + filter.Optimize(); + return filter; +} + +SongFilter +MakeSongFilter(const char *sticker_type, const char *sticker_uri) +{ + if (StringIsEqual(sticker_type, "filter")) + return MakeSongFilter(sticker_uri); + + if (auto tag_type = tag_name_parse_i(sticker_type); tag_type != TAG_NUM_OF_ITEM_TYPES) + return MakeSongFilter(tag_type, sticker_uri); + + return {}; +} + +SongFilter +MakeSongFilterNoThrow(const char *sticker_type, const char *sticker_uri) noexcept +{ + try { + return MakeSongFilter(sticker_type, sticker_uri); + } catch (...) { + return {}; + } +} + +bool +TagExists(const Database &database, TagType tag_type, const char *tag_value) +{ + return FilterMatches(database, MakeSongFilter(tag_type, tag_value)); +} + +bool +FilterMatches(const Database &database, const SongFilter &filter) noexcept +{ + if (filter.IsEmpty()) + return false; + + const DatabaseSelection selection{"", true, &filter}; + + // TODO: we just need to know if the tag selection has a match. + // a visitor callback that can stop the db visit by return value + // may be cleaner than throwing an exception. + struct MatchFoundException {}; + try { + database.Visit(selection, [](const LightSong &) { + throw MatchFoundException{}; + }); + } catch (MatchFoundException) { + return true; + } + + return false; +} diff --git a/src/sticker/TagSticker.hxx b/src/sticker/TagSticker.hxx new file mode 100644 index 0000000..c25be5a --- /dev/null +++ b/src/sticker/TagSticker.hxx @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include + +enum TagType : uint8_t; +class Database; +class StickerDatabase; +class SongFilter; + +/** + * Parse a filter_string. + * + * @param filter_string a valid filter expression + * + * @return SongFilter + * + * @throws std::runtime_error if failed to parse filter string + */ +SongFilter +MakeSongFilter(const char *filter_string); + +/** + * Make a song filter from tag and value e.g. album name + * + * @return SongFilter + * + * @throws std::runtime_error if failed to make song filter or tag type not allowd for sticker + */ +SongFilter +MakeSongFilter(TagType tag_type, const char *tag_value); + +/** + * Make a song filter by sticker type and uri + * + * @param sticker_type either one of the allowed tag names or "filter" + * @param sticker_uri if the type is a tag name then this is the value, + * if the type if "filter" then this is a filter expression + * + * @return SongFilter + * + * @throws std::runtime_error if failed to make song filter or tag type not allowd for sticker + */ +SongFilter +MakeSongFilter(const char *sticker_type, const char *sticker_uri); + +/** + * Like MakeSongFilter(const char *sticker_type, const char *sticker_uri) + * but return an empty filter instead of throwing + * + * @param sticker_type + * @param sticker_uri + * + * @return SongFilter + */ +SongFilter +MakeSongFilterNoThrow(const char *sticker_type, const char *sticker_uri) noexcept; + +/** + * Try to make a selection on the database using the tag type and value + * from a sticker command. + * + * @return true if the selection returned at least one match or false otherwise + * + * @throws std::runtime_error if failed to make song filter + */ +bool +TagExists(const Database &database, TagType tag_type, const char *tag_value); + +/** + * Try to make a selection on the database using a filter + * from a sticker command. + * + * @return true if the selection returned at least one match or false otherwise + */ +bool +FilterMatches(const Database &database, const SongFilter &filter) noexcept; diff --git a/src/storage/CompositeStorage.cxx b/src/storage/CompositeStorage.cxx new file mode 100644 index 0000000..0ccdd91 --- /dev/null +++ b/src/storage/CompositeStorage.cxx @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "CompositeStorage.hxx" +#include "FileInfo.hxx" +#include "fs/AllocatedPath.hxx" +#include "input/InputStream.hxx" +#include "util/IterableSplitString.hxx" +#include "util/StringCompare.hxx" +#include "util/StringSplit.hxx" + +#include // for std::exception_ptr +#include +#include + +#include + +/** + * Combines the directory entries of another #StorageDirectoryReader + * instance and the virtual directory entries. + */ +class CompositeDirectoryReader final : public StorageDirectoryReader { + std::unique_ptr other; + + std::set> names; + std::set>::const_iterator current, next; + +public: + template + CompositeDirectoryReader(O &&_other, const M &map) + :other(std::forward(_other)) { + for (const auto &i : map) + names.insert(i.first); + next = names.begin(); + } + + /* virtual methods from class StorageDirectoryReader */ + const char *Read() noexcept override; + StorageFileInfo GetInfo(bool follow) override; +}; + +const char * +CompositeDirectoryReader::Read() noexcept +{ + if (other != nullptr) { + const char *name = other->Read(); + if (name != nullptr) { + names.erase(name); + return name; + } + + other.reset(); + } + + if (next == names.end()) + return nullptr; + + current = next++; + return current->c_str(); +} + +StorageFileInfo +CompositeDirectoryReader::GetInfo(bool follow) +{ + if (other != nullptr) + return other->GetInfo(follow); + + assert(current != names.end()); + + return StorageFileInfo(StorageFileInfo::Type::DIRECTORY); +} + +static std::string_view +NextSegment(std::string_view &uri_r) noexcept +{ + auto s = Split(uri_r, '/'); + uri_r = s.second; + return s.first; +} + +const CompositeStorage::Directory * +CompositeStorage::Directory::Find(std::string_view uri) const noexcept +{ + const Directory *directory = this; + + for (std::string_view name : IterableSplitString(uri, '/')) { + if (name.empty()) + continue; + + auto i = directory->children.find(name); + if (i == directory->children.end()) + return nullptr; + + directory = &i->second; + } + + return directory; +} + +CompositeStorage::Directory & +CompositeStorage::Directory::Make(std::string_view uri) +{ + Directory *directory = this; + + for (std::string_view name : IterableSplitString(uri, '/')) { + if (name.empty()) + continue; + + auto i = directory->children.emplace(name, Directory()); + directory = &i.first->second; + } + + return *directory; +} + +bool +CompositeStorage::Directory::Unmount() noexcept +{ + if (storage == nullptr) + return false; + + storage.reset(); + return true; +} + +bool +CompositeStorage::Directory::Unmount(std::string_view uri) noexcept +{ + if (uri.empty()) + return Unmount(); + + const auto name = NextSegment(uri); + + auto i = children.find(name); + if (i == children.end() || !i->second.Unmount(uri)) + return false; + + if (i->second.IsEmpty()) + children.erase(i); + + return true; + +} + +bool +CompositeStorage::Directory::MapToRelativeUTF8(std::string &buffer, + std::string_view uri) const noexcept +{ + if (storage != nullptr) { + auto result = storage->MapToRelativeUTF8(uri); + if (result.data() != nullptr) { + buffer = result; + return true; + } + } + + for (const auto &i : children) { + if (i.second.MapToRelativeUTF8(buffer, uri)) { + buffer.insert(buffer.begin(), '/'); + buffer.insert(buffer.begin(), + i.first.begin(), i.first.end()); + return true; + } + } + + return false; +} + +CompositeStorage::CompositeStorage() noexcept +{ + /* note: no "=default" here because members of this class are + allowed to throw during construction according to the C++ + standard (e.g. std::map), but we choose to ignore these + exceptions; if construction of std::map goes wrong, MPD has + no chance to work at all, so it's ok to std::terminate() */ +} + +CompositeStorage::~CompositeStorage() = default; + +Storage * +CompositeStorage::GetMount(std::string_view uri) noexcept +{ + const std::scoped_lock protect{mutex}; + + auto result = FindStorage(uri); + if (!result.uri.empty()) + /* not a mount point */ + return nullptr; + + return result.directory->storage.get(); +} + +void +CompositeStorage::Mount(const char *uri, std::unique_ptr storage) +{ + const std::scoped_lock protect{mutex}; + + Directory &directory = root.Make(uri); + assert(!directory.storage); + directory.storage = std::move(storage); +} + +bool +CompositeStorage::Unmount(const char *uri) +{ + const std::scoped_lock protect{mutex}; + + return root.Unmount(uri); +} + +CompositeStorage::FindResult +CompositeStorage::FindStorage(std::string_view uri) const noexcept +{ + FindResult result{&root, uri}; + + const Directory *directory = &root; + while (!uri.empty()) { + const auto name = NextSegment(uri); + + auto i = directory->children.find(name); + if (i == directory->children.end()) + break; + + directory = &i->second; + if (directory->storage != nullptr) + result = FindResult{directory, uri}; + } + + return result; +} + +StorageFileInfo +CompositeStorage::GetInfo(std::string_view uri, bool follow) +{ + const std::scoped_lock protect{mutex}; + + std::exception_ptr error; + + auto f = FindStorage(uri); + if (f.directory->storage != nullptr) { + try { + return f.directory->storage->GetInfo(f.uri, follow); + } catch (...) { + error = std::current_exception(); + } + } + + const Directory *directory = f.directory->Find(f.uri); + if (directory != nullptr) + return StorageFileInfo(StorageFileInfo::Type::DIRECTORY); + + if (error) + std::rethrow_exception(error); + else + throw std::runtime_error("No such file or directory"); +} + +std::unique_ptr +CompositeStorage::OpenDirectory(std::string_view uri) +{ + const std::scoped_lock protect{mutex}; + + auto f = FindStorage(uri); + const Directory *directory = f.directory->Find(f.uri); + if (directory == nullptr || directory->children.empty()) { + /* no virtual directories here */ + + if (f.directory->storage == nullptr) + throw std::runtime_error("No such directory"); + + return f.directory->storage->OpenDirectory(f.uri); + } + + std::unique_ptr other; + + try { + other = f.directory->storage->OpenDirectory(f.uri); + } catch (...) { + } + + return std::make_unique(std::move(other), + directory->children); +} + +std::string +CompositeStorage::MapUTF8(std::string_view uri) const noexcept +{ + const std::scoped_lock protect{mutex}; + + auto f = FindStorage(uri); + if (f.directory->storage == nullptr) + return {}; + + return f.directory->storage->MapUTF8(f.uri); +} + +AllocatedPath +CompositeStorage::MapFS(std::string_view uri) const noexcept +{ + const std::scoped_lock protect{mutex}; + + auto f = FindStorage(uri); + if (f.directory->storage == nullptr) + return nullptr; + + return f.directory->storage->MapFS(f.uri); +} + +std::string_view +CompositeStorage::MapToRelativeUTF8(std::string_view uri) const noexcept +{ + const std::scoped_lock protect{mutex}; + + if (root.storage != nullptr) { + auto result = root.storage->MapToRelativeUTF8(uri); + if (result.data() != nullptr) + return result; + } + + if (!root.MapToRelativeUTF8(relative_buffer, uri)) + return {}; + + return relative_buffer; +} + +InputStreamPtr +CompositeStorage::OpenFile(std::string_view uri_utf8, Mutex &_mutex) +{ + const std::lock_guard lock{mutex}; + + auto f = FindStorage(uri_utf8); + if (f.directory->storage == nullptr) + return nullptr; + + return f.directory->storage->OpenFile(f.uri, _mutex); +} diff --git a/src/storage/CompositeStorage.hxx b/src/storage/CompositeStorage.hxx new file mode 100644 index 0000000..ff47926 --- /dev/null +++ b/src/storage/CompositeStorage.hxx @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_COMPOSITE_STORAGE_HXX +#define MPD_COMPOSITE_STORAGE_HXX + +#include "StorageInterface.hxx" +#include "thread/Mutex.hxx" + +#include +#include +#include + +/** + * A #Storage implementation that combines multiple other #Storage + * instances in one virtual tree. It is used to "mount" new #Storage + * instances into the storage tree. + * + * This class is thread-safe: mounts may be added and removed at any + * time in any thread. + */ +class CompositeStorage final : public Storage { + /** + * A node in the virtual directory tree. + */ + struct Directory { + /** + * The #Storage mounted in this virtual directory. All + * "leaf" Directory instances must have a #Storage. + * Other Directory instances may have one, and child + * mounts will be "mixed" in. + */ + std::unique_ptr storage; + + std::map> children; + + [[gnu::pure]] + bool IsEmpty() const noexcept { + return storage == nullptr && children.empty(); + } + + [[gnu::pure]] + const Directory *Find(std::string_view uri) const noexcept; + + Directory &Make(std::string_view uri); + + bool Unmount() noexcept; + bool Unmount(std::string_view uri) noexcept; + + [[gnu::pure]] + bool MapToRelativeUTF8(std::string &buffer, + std::string_view uri) const noexcept; + }; + + struct FindResult { + const Directory *directory; + std::string_view uri; + }; + + /** + * Protects the virtual #Directory tree. + * + * TODO: use readers-writer lock + */ + mutable Mutex mutex; + + Directory root; + + mutable std::string relative_buffer; + +public: + CompositeStorage() noexcept; + ~CompositeStorage() override; + + /** + * Get the #Storage at the specified mount point. Returns + * nullptr if the given URI is not a mount point. + * + * The returned pointer is unprotected. No other thread is + * allowed to unmount the given mount point while the return + * value is being used. + */ + [[gnu::pure]] + Storage *GetMount(std::string_view uri) noexcept; + + /** + * Is the given URI a mount point, i.e. is something already + * mounted on this path? + */ + [[gnu::pure]] [[gnu::nonnull]] + bool IsMountPoint(const char *uri) noexcept { + return GetMount(uri) != nullptr; + } + + /** + * Call the given function for each mounted storage, including + * the root storage. Passes mount point URI and the a const + * Storage reference to the function. + */ + template + void VisitMounts(T t) const { + const std::scoped_lock protect{mutex}; + std::string uri; + VisitMounts(uri, root, t); + } + + /** + * Is a storage with the given URI already mounted? + */ + [[gnu::pure]] [[gnu::nonnull]] + bool IsMounted(const char *storage_uri) const noexcept { + const std::scoped_lock protect{mutex}; + return IsMounted(root, storage_uri); + } + + void Mount(const char *uri, std::unique_ptr storage); + bool Unmount(const char *uri); + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri, bool follow) override; + + std::unique_ptr OpenDirectory(std::string_view uri) override; + + std::string MapUTF8(std::string_view uri) const noexcept override; + + AllocatedPath MapFS(std::string_view uri) const noexcept override; + + std::string_view MapToRelativeUTF8(std::string_view uri) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &mutex) override; + +private: + template + void VisitMounts(std::string &uri, const Directory &directory, + T t) const { + if (directory.storage) + t(uri.c_str(), *directory.storage); + + if (!uri.empty()) + uri.push_back('/'); + + const size_t uri_length = uri.length(); + + for (const auto &i : directory.children) { + uri.resize(uri_length); + uri.append(i.first); + + VisitMounts(uri, i.second, t); + } + } + + [[gnu::pure]] [[gnu::nonnull]] + static bool IsMounted(const Directory &directory, + const char *storage_uri) noexcept { + if (directory.storage) { + const auto uri = directory.storage->MapUTF8(""); + if (uri == storage_uri) + return true; + } + + for (const auto &i : directory.children) + if (IsMounted(i.second, storage_uri)) + return true; + + return false; + } + + /** + * Follow the given URI path, and find the outermost directory + * which is a #Storage mount point. If there are no mounts, + * it returns the root directory (with a nullptr "storage" + * attribute, of course). FindResult::uri contains the + * remaining unused part of the URI (may be empty if all of + * the URI was used). + */ + [[gnu::pure]] + FindResult FindStorage(std::string_view uri) const noexcept; + + const char *MapToRelativeUTF8(const Directory &directory, + const char *uri) const; +}; + +#endif diff --git a/src/storage/Configured.cxx b/src/storage/Configured.cxx new file mode 100644 index 0000000..3e6593c --- /dev/null +++ b/src/storage/Configured.cxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Configured.hxx" +#include "Registry.hxx" +#include "StorageInterface.hxx" +#include "plugins/LocalStorage.hxx" +#include "config/Data.hxx" +#include "fs/AllocatedPath.hxx" +#include "fs/glue/StandardDirectory.hxx" +#include "fs/glue/CheckFile.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "util/UriExtract.hxx" + +static std::unique_ptr +CreateConfiguredStorageUri(EventLoop &event_loop, const char *uri) +{ + auto storage = CreateStorageURI(event_loop, uri); + if (storage == nullptr) + throw FmtRuntimeError("Unrecognized storage URI: {}", uri); + + return storage; +} + +static AllocatedPath +GetConfiguredMusicDirectory(const ConfigData &config) +{ + AllocatedPath path = config.GetPath(ConfigOption::MUSIC_DIR); + if (path.IsNull()) + path = GetUserMusicDir(); + + return path; +} + +static std::unique_ptr +CreateConfiguredStorageLocal(const ConfigData &config) +{ + AllocatedPath path = GetConfiguredMusicDirectory(config); + if (path.IsNull()) + return nullptr; + + path.ChopSeparators(); + CheckDirectoryReadable(path); + return CreateLocalStorage(path); +} + +std::unique_ptr +CreateConfiguredStorage(const ConfigData &config, EventLoop &event_loop) +{ + auto uri = config.GetString(ConfigOption::MUSIC_DIR); + if (uri != nullptr && uri_has_scheme(uri)) + return CreateConfiguredStorageUri(event_loop, uri); + + return CreateConfiguredStorageLocal(config); +} + +bool +IsStorageConfigured(const ConfigData &config) noexcept +{ + return config.GetParam(ConfigOption::MUSIC_DIR) != nullptr; +} diff --git a/src/storage/Configured.hxx b/src/storage/Configured.hxx new file mode 100644 index 0000000..e064785 --- /dev/null +++ b/src/storage/Configured.hxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_CONFIG_HXX +#define MPD_STORAGE_CONFIG_HXX + +#include + +struct ConfigData; +class Storage; +class EventLoop; + +/** + * Read storage configuration settings and create a #Storage instance + * from it. Returns nullptr if no storage is configured. + * + * Throws #std::runtime_error on error. + */ +std::unique_ptr +CreateConfiguredStorage(const ConfigData &config, EventLoop &event_loop); + +/** + * Returns true if there is configuration for a #Storage instance. + */ +[[gnu::const]] +bool +IsStorageConfigured(const ConfigData &config) noexcept; + +#endif diff --git a/src/storage/FileInfo.hxx b/src/storage/FileInfo.hxx new file mode 100644 index 0000000..fb8d8e1 --- /dev/null +++ b/src/storage/FileInfo.hxx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_FILE_INFO_HXX +#define MPD_STORAGE_FILE_INFO_HXX + +#include + +#include + +struct StorageFileInfo { + enum class Type : uint8_t { + OTHER, + REGULAR, + DIRECTORY, + }; + + Type type; + + /** + * The file size in bytes. Only valid for #Type::REGULAR. + */ + uint64_t size; + + /** + * The modification time. A negative value means unknown / + * not applicable. + */ + std::chrono::system_clock::time_point mtime; + + /** + * Device id and inode number. 0 means unknown / not + * applicable. + */ + uint64_t device, inode; + + StorageFileInfo() = default; + + explicit constexpr StorageFileInfo(Type _type) + :type(_type), + size(0), + mtime(std::chrono::system_clock::time_point::min()), + device(0), inode(0) {} + + constexpr bool IsRegular() const { + return type == Type::REGULAR; + } + + constexpr bool IsDirectory() const { + return type == Type::DIRECTORY; + } +}; + +#endif diff --git a/src/storage/MemoryDirectoryReader.cxx b/src/storage/MemoryDirectoryReader.cxx new file mode 100644 index 0000000..ff82c9e --- /dev/null +++ b/src/storage/MemoryDirectoryReader.cxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "MemoryDirectoryReader.hxx" + +#include + +const char * +MemoryStorageDirectoryReader::Read() noexcept +{ + if (first) + first = false; + else + entries.pop_front(); + + if (entries.empty()) + return nullptr; + + return entries.front().name.c_str(); +} + +StorageFileInfo +MemoryStorageDirectoryReader::GetInfo([[maybe_unused]] bool follow) +{ + assert(!first); + assert(!entries.empty()); + + return entries.front().info; +} diff --git a/src/storage/MemoryDirectoryReader.hxx b/src/storage/MemoryDirectoryReader.hxx new file mode 100644 index 0000000..d55ec8a --- /dev/null +++ b/src/storage/MemoryDirectoryReader.hxx @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_MEMORY_DIRECTORY_READER_HXX +#define MPD_STORAGE_MEMORY_DIRECTORY_READER_HXX + +#include "StorageInterface.hxx" +#include "FileInfo.hxx" + +#include +#include + +/** + * A #StorageDirectoryReader implementation that returns directory + * entries from a memory allocation. + */ +class MemoryStorageDirectoryReader final : public StorageDirectoryReader { +public: + struct Entry { + std::string name; + + StorageFileInfo info; + + template + explicit Entry(N &&_name):name(std::forward(_name)) {} + }; + + typedef std::forward_list List; + +private: + List entries; + + bool first; + +public: + MemoryStorageDirectoryReader() + :first(true) {} + + MemoryStorageDirectoryReader(MemoryStorageDirectoryReader &&src) + :entries(std::move(src.entries)), first(src.first) {} + + MemoryStorageDirectoryReader(List &&_entries) + :entries(std::move(_entries)), first(true) {} + + /* virtual methods from class StorageDirectoryReader */ + const char *Read() noexcept override; + StorageFileInfo GetInfo(bool follow) override; +}; + +#endif diff --git a/src/storage/Registry.cxx b/src/storage/Registry.cxx new file mode 100644 index 0000000..9d149cd --- /dev/null +++ b/src/storage/Registry.cxx @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Registry.hxx" +#include "StoragePlugin.hxx" +#include "StorageInterface.hxx" +#include "plugins/LocalStorage.hxx" +#include "plugins/UdisksStorage.hxx" +#include "plugins/SmbclientStorage.hxx" +#include "plugins/NfsStorage.hxx" +#include "plugins/CurlStorage.hxx" +#include "config.h" + +#include + +constinit const StoragePlugin *const storage_plugins[] = { + &local_storage_plugin, +#ifdef ENABLE_SMBCLIENT + &smbclient_storage_plugin, +#endif +#ifdef ENABLE_UDISKS + &udisks_storage_plugin, +#endif +#ifdef ENABLE_NFS + &nfs_storage_plugin, +#endif +#ifdef ENABLE_WEBDAV + &curl_storage_plugin, +#endif + nullptr +}; + +const StoragePlugin * +GetStoragePluginByName(const char *name) noexcept +{ + for (auto i = storage_plugins; *i != nullptr; ++i) { + const StoragePlugin &plugin = **i; + if (strcmp(plugin.name, name) == 0) + return *i; + } + + return nullptr; +} + +const StoragePlugin * +GetStoragePluginByUri(const char *uri) noexcept +{ + for (auto i = storage_plugins; *i != nullptr; ++i) { + const StoragePlugin &plugin = **i; + if (plugin.SupportsUri(uri)) + return *i; + } + + return nullptr; +} + +std::unique_ptr +CreateStorageURI(EventLoop &event_loop, const char *uri) +{ + for (auto i = storage_plugins; *i != nullptr; ++i) { + const StoragePlugin &plugin = **i; + + if (plugin.create_uri == nullptr || !plugin.SupportsUri(uri)) + continue; + + auto storage = plugin.create_uri(event_loop, uri); + if (storage != nullptr) + return storage; + } + + return nullptr; +} diff --git a/src/storage/Registry.hxx b/src/storage/Registry.hxx new file mode 100644 index 0000000..3d7a5f9 --- /dev/null +++ b/src/storage/Registry.hxx @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_REGISTRY_HXX +#define MPD_STORAGE_REGISTRY_HXX + +#include + +struct StoragePlugin; +class Storage; +class EventLoop; + +/** + * nullptr terminated list of all storage plugins which were enabled at + * compile time. + */ +extern const StoragePlugin *const storage_plugins[]; + +[[gnu::nonnull]] [[gnu::pure]] +const StoragePlugin * +GetStoragePluginByName(const char *name) noexcept; + +[[gnu::nonnull]] [[gnu::pure]] +const StoragePlugin * +GetStoragePluginByUri(const char *uri) noexcept; + +[[gnu::nonnull]] +std::unique_ptr +CreateStorageURI(EventLoop &event_loop, const char *uri); + +#endif diff --git a/src/storage/StorageInterface.cxx b/src/storage/StorageInterface.cxx new file mode 100644 index 0000000..b816f8c --- /dev/null +++ b/src/storage/StorageInterface.cxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "StorageInterface.hxx" +#include "fs/AllocatedPath.hxx" +#include "fs/Traits.hxx" + +AllocatedPath +Storage::MapFS([[maybe_unused]] std::string_view uri_utf8) const noexcept +{ + return nullptr; +} + +AllocatedPath +Storage::MapChildFS(std::string_view uri_utf8, + std::string_view child_utf8) const noexcept +{ + const auto uri2 = PathTraitsUTF8::Build(uri_utf8, child_utf8); + return MapFS(uri2); +} diff --git a/src/storage/StorageInterface.hxx b/src/storage/StorageInterface.hxx new file mode 100644 index 0000000..772e8c3 --- /dev/null +++ b/src/storage/StorageInterface.hxx @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "input/Ptr.hxx" +#include "thread/Mutex.hxx" + +#include +#include +#include + +struct StorageFileInfo; +class AllocatedPath; + +class StorageDirectoryReader { +public: + StorageDirectoryReader() = default; + StorageDirectoryReader(const StorageDirectoryReader &) = delete; + virtual ~StorageDirectoryReader() noexcept = default; + + [[nodiscard]] + virtual const char *Read() noexcept = 0; + + /** + * Throws #std::runtime_error on error. + */ + [[nodiscard]] + virtual StorageFileInfo GetInfo(bool follow) = 0; +}; + +class Storage { +public: + Storage() = default; + Storage(const Storage &) = delete; + virtual ~Storage() noexcept = default; + + /** + * Throws #std::runtime_error on error. + */ + [[nodiscard]] + virtual StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) = 0; + + /** + * Throws #std::runtime_error on error. + */ + [[nodiscard]] + virtual std::unique_ptr OpenDirectory(std::string_view uri_utf8) = 0; + + /** + * Map the given relative URI to an absolute URI. + */ + [[nodiscard]] [[gnu::pure]] + virtual std::string MapUTF8(std::string_view uri_utf8) const noexcept = 0; + + /** + * Map the given relative URI to a local file path. Returns + * nullptr on error or if this storage does not + * support local files. + */ + [[nodiscard]] [[gnu::pure]] + virtual AllocatedPath MapFS(std::string_view uri_utf8) const noexcept; + + [[nodiscard]] [[gnu::pure]] + AllocatedPath MapChildFS(std::string_view uri_utf8, + std::string_view child_utf8) const noexcept; + + /** + * Check if the given URI points inside this storage. If yes, + * then it returns a relative URI (pointing inside the given + * string); if not, returns nullptr. + */ + [[nodiscard]] [[gnu::pure]] + virtual std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept = 0; + + /** + * Open a file in this storage as an #InputStream. + * + * Throws on error + */ + [[nodiscard]] + virtual InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &mutex) = 0; +}; diff --git a/src/storage/StoragePlugin.cxx b/src/storage/StoragePlugin.cxx new file mode 100644 index 0000000..91d8a56 --- /dev/null +++ b/src/storage/StoragePlugin.cxx @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "StoragePlugin.hxx" +#include "util/StringCompare.hxx" + +bool +StoragePlugin::SupportsUri(const char *uri) const noexcept +{ + if (prefixes == nullptr) + return false; + + for (auto i = prefixes; *i != nullptr; ++i) + if (StringStartsWithIgnoreCase(uri, *i)) + return true; + + return false; +} diff --git a/src/storage/StoragePlugin.hxx b/src/storage/StoragePlugin.hxx new file mode 100644 index 0000000..2b1d007 --- /dev/null +++ b/src/storage/StoragePlugin.hxx @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_PLUGIN_HXX +#define MPD_STORAGE_PLUGIN_HXX + +#include + +class Storage; +class EventLoop; + +struct StoragePlugin { + const char *name; + + /** + * A nullptr-terminated list of URI prefixes handled by this + * plugin. This is usually a string in the form "scheme://". + */ + const char *const*prefixes; + + /** + * Throws #std::runtime_error on error. + */ + std::unique_ptr (*create_uri)(EventLoop &event_loop, + const char *uri); + + [[gnu::pure]] + bool SupportsUri(const char *uri) const noexcept; +}; + +#endif diff --git a/src/storage/StorageState.cxx b/src/storage/StorageState.cxx new file mode 100644 index 0000000..c1b4308 --- /dev/null +++ b/src/storage/StorageState.cxx @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Save and load mounts of the compound storage to/from the state file. + * + */ + +#include "StorageState.hxx" +#include "lib/fmt/ExceptionFormatter.hxx" +#include "io/LineReader.hxx" +#include "io/BufferedOutputStream.hxx" +#include "storage/Registry.hxx" +#include "storage/CompositeStorage.hxx" +#include "db/plugins/simple/SimpleDatabasePlugin.hxx" +#include "util/StringCompare.hxx" +#include "util/Domain.hxx" +#include "Instance.hxx" +#include "Log.hxx" + +#include // for std::hash() + +#define MOUNT_STATE_BEGIN "mount_begin" +#define MOUNT_STATE_END "mount_end" +#define MOUNT_STATE_STORAGE_URI "uri: " +#define MOUNT_STATE_MOUNTED_URL "mounted_url: " + +static constexpr Domain storage_domain("storage"); + +void +storage_state_save(BufferedOutputStream &os, const Instance &instance) +{ + if (instance.storage == nullptr) + return; + + const auto visitor = [&os](const char *mount_uri, const Storage &storage) { + std::string uri = storage.MapUTF8(""); + if (uri.empty() || StringIsEmpty(mount_uri)) + return; + + os.Fmt(MOUNT_STATE_BEGIN "\n" + MOUNT_STATE_STORAGE_URI "{}\n" + MOUNT_STATE_MOUNTED_URL "{}\n" + MOUNT_STATE_END "\n", + mount_uri, uri); + }; + + ((CompositeStorage*)instance.storage)->VisitMounts(visitor); +} + +bool +storage_state_restore(const char *line, LineReader &file, + Instance &instance) noexcept +{ + if (!StringStartsWith(line, MOUNT_STATE_BEGIN)) + return false; + + std::string url; + std::string uri; + const char* value; + + while ((line = file.ReadLine()) != nullptr) { + if (StringStartsWith(line, MOUNT_STATE_END)) + break; + + if ((value = StringAfterPrefix(line, MOUNT_STATE_MOUNTED_URL))) + url = value; + else if ((value = StringAfterPrefix(line, MOUNT_STATE_STORAGE_URI))) + uri = value; + else + FmtError(storage_domain, + "Unrecognized line in mountpoint state: {}", + line); + } + + if (instance.storage == nullptr) + /* without storage (a CompositeStorage instance), we + cannot mount, and therefore we silently ignore the + state file */ + return true; + + if (url.empty() || uri.empty()) { + LogError(storage_domain, "Missing value in mountpoint state."); + return true; + } + + FmtDebug(storage_domain, "Restoring mount {} => {}", uri, url); + + auto &composite_storage = *(CompositeStorage *)instance.storage; + if (composite_storage.IsMountPoint(uri.c_str())) { + LogError(storage_domain, "Mount point busy"); + return true; + } + + if (composite_storage.IsMounted(url.c_str())) { + LogError(storage_domain, "This storage is already mounted"); + return true; + } + + auto &event_loop = instance.io_thread.GetEventLoop(); + auto storage = CreateStorageURI(event_loop, url.c_str()); + if (storage == nullptr) { + FmtError(storage_domain, "Unrecognized storage URI: {}", url); + return true; + } + + if (auto *db = dynamic_cast(instance.GetDatabase())) { + try { + db->Mount(uri.c_str(), url.c_str()); + } catch (...) { + FmtError(storage_domain, + "Failed to restore mount to {}: {}", + url, std::current_exception()); + return true; + } + } + + composite_storage.Mount(uri.c_str(), std::move(storage)); + + return true; +} + +unsigned +storage_state_get_hash(const Instance &instance) noexcept +{ + if (instance.storage == nullptr) + return 0; + + unsigned result = 0; + + const std::hash hash; + + const auto visitor = [&result, &hash](const char *mount_uri, const Storage &storage) { + result = result * 33 + hash(mount_uri); + result = result * 33 + hash(storage.MapUTF8("")); + }; + + ((CompositeStorage*)instance.storage)->VisitMounts(visitor); + + return result; +} diff --git a/src/storage/StorageState.hxx b/src/storage/StorageState.hxx new file mode 100644 index 0000000..db2b5bf --- /dev/null +++ b/src/storage/StorageState.hxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * Saving and loading the playlist to/from the state file. + * + */ + +#ifndef MPD_STORAGE_STATE_HXX +#define MPD_STORAGE_STATE_HXX + +struct Instance; +class BufferedOutputStream; +class LineReader; + +void +storage_state_save(BufferedOutputStream &os, + const Instance &instance); + +bool +storage_state_restore(const char *line, LineReader &file, + Instance &instance) noexcept; + +/** + * Generates a hash number for the current state of the composite storage. + * This is used by timer_save_state_file() to determine whether the state + * has changed and the state file should be saved. + */ +[[gnu::pure]] +unsigned +storage_state_get_hash(const Instance &instance) noexcept; + +#endif diff --git a/src/storage/meson.build b/src/storage/meson.build new file mode 100644 index 0000000..2e523cb --- /dev/null +++ b/src/storage/meson.build @@ -0,0 +1,32 @@ +storage_api = static_library( + 'storage_api', + 'StorageInterface.cxx', + 'StoragePlugin.cxx', + 'MemoryDirectoryReader.cxx', + include_directories: inc, +) + +storage_api_dep = declare_dependency( + link_with: storage_api, +) + +subdir('plugins') + +storage_glue = static_library( + 'storage_glue', + 'Registry.cxx', + 'CompositeStorage.cxx', + 'Configured.cxx', + include_directories: inc, + dependencies: [ + log_dep, + fs_glue_dep, + ], +) + +storage_glue_dep = declare_dependency( + link_with: storage_glue, + dependencies: [ + storage_plugins_dep, + ], +) diff --git a/src/storage/plugins/CurlStorage.cxx b/src/storage/plugins/CurlStorage.cxx new file mode 100644 index 0000000..cbe909b --- /dev/null +++ b/src/storage/plugins/CurlStorage.cxx @@ -0,0 +1,578 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "CurlStorage.hxx" +#include "storage/StoragePlugin.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "storage/MemoryDirectoryReader.hxx" +#include "input/InputStream.hxx" +#include "input/RewindInputStream.hxx" +#include "input/plugins/CurlInputPlugin.hxx" +#include "lib/curl/HttpStatusError.hxx" +#include "lib/curl/Init.hxx" +#include "lib/curl/Global.hxx" +#include "lib/curl/Slist.hxx" +#include "lib/curl/String.hxx" +#include "lib/curl/Request.hxx" +#include "lib/curl/Handler.hxx" +#include "lib/curl/Escape.hxx" +#include "lib/expat/ExpatParser.hxx" +#include "lib/fmt/ToBuffer.hxx" +#include "fs/Traits.hxx" +#include "event/InjectEvent.hxx" +#include "thread/Mutex.hxx" +#include "thread/Cond.hxx" +#include "util/ASCII.hxx" +#include "util/NumberParser.hxx" +#include "util/SpanCast.hxx" +#include "util/StringCompare.hxx" +#include "util/StringSplit.hxx" +#include "util/UriExtract.hxx" + +#include +#include +#include +#include + +using std::string_view_literals::operator""sv; + +class CurlStorage final : public Storage { + const std::string base; + + CurlInit curl; + +public: + CurlStorage(EventLoop &_loop, const char *_base) + :base(_base), + curl(_loop) {} + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override; + + std::unique_ptr OpenDirectory(std::string_view uri_utf8) override; + + [[nodiscard]] std::string MapUTF8(std::string_view uri_utf8) const noexcept override; + + [[nodiscard]] std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &mutex) override; +}; + +std::string +CurlStorage::MapUTF8(std::string_view uri_utf8) const noexcept +{ + if (uri_utf8.empty()) + return base; + + std::string path_esc = CurlEscapeUriPath(uri_utf8); + return PathTraitsUTF8::Build(base, path_esc); +} + +std::string_view +CurlStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept +{ + return PathTraitsUTF8::Relative(base, + CurlUnescape(uri_utf8)); +} + +InputStreamPtr +CurlStorage::OpenFile(std::string_view uri_utf8, Mutex &mutex) +{ + return input_rewind_open(OpenCurlInputStream(MapUTF8(uri_utf8), {}, mutex)); +} + +class BlockingHttpRequest : protected CurlResponseHandler { + InjectEvent defer_start; + + std::exception_ptr postponed_error; + + bool done = false; + +protected: + CurlRequest request; + + Mutex mutex; + Cond cond; + +public: + BlockingHttpRequest(CurlGlobal &curl, const char *uri) + :defer_start(curl.GetEventLoop(), + BIND_THIS_METHOD(OnDeferredStart)), + request(curl, uri, *this) { + // TODO: use CurlInputStream's configuration + } + + void DeferStart() noexcept { + /* start the transfer inside the IOThread */ + defer_start.Schedule(); + } + + void Wait() { + std::unique_lock lock{mutex}; + cond.wait(lock, [this]{ return done; }); + + if (postponed_error) + std::rethrow_exception(postponed_error); + } + + CURL *GetEasy() noexcept { + return request.Get(); + } + +protected: + void SetDone() { + assert(!done); + + request.Stop(); + done = true; + cond.notify_one(); + } + + void LockSetDone() { + const std::scoped_lock lock{mutex}; + SetDone(); + } + +private: + /* InjectEvent callback */ + void OnDeferredStart() noexcept { + assert(!done); + + try { + request.Start(); + } catch (...) { + OnError(std::current_exception()); + } + } + + /* virtual methods from CurlResponseHandler */ + void OnError(std::exception_ptr e) noexcept final { + const std::scoped_lock lock{mutex}; + postponed_error = std::move(e); + SetDone(); + } +}; + +/** + * The (relevant) contents of a "" element. + */ +struct DavResponse { + std::string href; + unsigned status = 0; + bool collection = false; + std::chrono::system_clock::time_point mtime = + std::chrono::system_clock::time_point::min(); + uint64_t length = 0; + + [[nodiscard]] bool Check() const { + return !href.empty(); + } +}; + +[[gnu::pure]] +static unsigned +ParseStatus(std::string_view s) noexcept +{ + /* skip the "HTTP/1.1" prefix */ + const auto [http_1_1, rest] = Split(s, ' '); + + /* skip the string suffix */ + const auto [status_string, _] = Split(rest, ' '); + + if (const auto status = ParseInteger(status_string)) + return *status; + + return 0; +} + +[[gnu::pure]] +static std::chrono::system_clock::time_point +ParseTimeStamp(const char *s) noexcept +{ + return std::chrono::system_clock::from_time_t(curl_getdate(s, nullptr)); +} + +[[gnu::pure]] +static std::chrono::system_clock::time_point +ParseTimeStamp(std::string_view s) noexcept +{ + return ParseTimeStamp(std::string{s}.c_str()); +} + +[[gnu::pure]] +static uint64_t +ParseU64(std::string_view s) noexcept +{ + if (const auto i = ParseInteger(s)) + return *i; + + return 0; +} + +[[gnu::pure]] +static bool +IsXmlContentType(const char *content_type) noexcept +{ + return StringStartsWith(content_type, "text/xml") || + StringStartsWith(content_type, "application/xml"); +} + +[[gnu::pure]] +static bool +IsXmlContentType(const Curl::Headers &headers) noexcept +{ + auto i = headers.find("content-type"); + return i != headers.end() && IsXmlContentType(i->second.c_str()); +} + +/** + * A WebDAV PROPFIND request. Each "response" element will be passed + * to OnDavResponse() (to be implemented by a derived class). + */ +class PropfindOperation : BlockingHttpRequest, CommonExpatParser { + CurlSlist request_headers; + + enum class State { + ROOT, + RESPONSE, + PROPSTAT, + HREF, + STATUS, + TYPE, + MTIME, + LENGTH, + } state = State::ROOT; + + DavResponse response; + +public: + PropfindOperation(CurlGlobal &_curl, const char *_uri, unsigned depth) + :BlockingHttpRequest(_curl, _uri), + CommonExpatParser(ExpatNamespaceSeparator{'|'}) + { + auto &easy = request.GetEasy(); + + easy.SetOption(CURLOPT_CUSTOMREQUEST, "PROPFIND"); + easy.SetOption(CURLOPT_FOLLOWLOCATION, 1L); + easy.SetOption(CURLOPT_MAXREDIRS, 1L); + + /* this option eliminates the probe request when + username/password are specified */ + easy.SetOption(CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + + request_headers.Append(FmtBuffer<40>("depth: {}", depth)); + request_headers.Append("content-type: text/xml"); + + easy.SetRequestHeaders(request_headers.Get()); + + easy.SetRequestBody("\n" + "" + "" + "" + "" + "" + "" + "" + ""sv); + } + + using BlockingHttpRequest::GetEasy; + using BlockingHttpRequest::DeferStart; + using BlockingHttpRequest::Wait; + +protected: + virtual void OnDavResponse(DavResponse &&r) = 0; + +private: + void FinishResponse() { + if (response.Check()) + OnDavResponse(std::move(response)); + response = DavResponse(); + } + + /* virtual methods from CurlResponseHandler */ + void OnHeaders(unsigned status, Curl::Headers &&headers) final { + if (status != 207) + throw HttpStatusError(status, + FmtBuffer<80>("Status {} from WebDAV server; expected \"207 Multi-Status\"", + status)); + + if (!IsXmlContentType(headers)) + throw std::runtime_error("Unexpected Content-Type from WebDAV server"); + } + + void OnData(std::span src) final { + Parse(ToStringView(src)); + } + + void OnEnd() final { + CompleteParse(); + LockSetDone(); + } + + /* virtual methods from CommonExpatParser */ + void StartElement(const XML_Char *name, + [[maybe_unused]] const XML_Char **attrs) final { + switch (state) { + case State::ROOT: + if (strcmp(name, "DAV:|response") == 0) + state = State::RESPONSE; + break; + + case State::RESPONSE: + if (strcmp(name, "DAV:|propstat") == 0) + state = State::PROPSTAT; + else if (strcmp(name, "DAV:|href") == 0) + state = State::HREF; + break; + case State::PROPSTAT: + if (strcmp(name, "DAV:|status") == 0) + state = State::STATUS; + else if (strcmp(name, "DAV:|resourcetype") == 0) + state = State::TYPE; + else if (strcmp(name, "DAV:|getlastmodified") == 0) + state = State::MTIME; + else if (strcmp(name, "DAV:|getcontentlength") == 0) + state = State::LENGTH; + break; + + case State::TYPE: + if (strcmp(name, "DAV:|collection") == 0) + response.collection = true; + break; + + case State::HREF: + case State::STATUS: + case State::LENGTH: + case State::MTIME: + break; + } + } + + void EndElement(const XML_Char *name) final { + switch (state) { + case State::ROOT: + break; + + case State::RESPONSE: + if (strcmp(name, "DAV:|response") == 0) { + state = State::ROOT; + } + break; + + case State::PROPSTAT: + if (strcmp(name, "DAV:|propstat") == 0) { + FinishResponse(); + state = State::RESPONSE; + } + + break; + + case State::HREF: + if (strcmp(name, "DAV:|href") == 0) + state = State::RESPONSE; + break; + + case State::STATUS: + if (strcmp(name, "DAV:|status") == 0) + state = State::PROPSTAT; + break; + + case State::TYPE: + if (strcmp(name, "DAV:|resourcetype") == 0) + state = State::PROPSTAT; + break; + + case State::MTIME: + if (strcmp(name, "DAV:|getlastmodified") == 0) + state = State::PROPSTAT; + break; + + case State::LENGTH: + if (strcmp(name, "DAV:|getcontentlength") == 0) + state = State::PROPSTAT; + break; + } + } + + void CharacterData(std::string_view s) final { + switch (state) { + case State::ROOT: + case State::PROPSTAT: + case State::RESPONSE: + case State::TYPE: + break; + + case State::HREF: + response.href.append(s); + break; + + case State::STATUS: + response.status = ParseStatus(s); + break; + + case State::MTIME: + response.mtime = ParseTimeStamp(s); + break; + + case State::LENGTH: + response.length = ParseU64(s); + break; + } + } +}; + +/** + * Obtain information about a single file using WebDAV PROPFIND. + */ +class HttpGetInfoOperation final : public PropfindOperation { + StorageFileInfo info; + +public: + HttpGetInfoOperation(CurlGlobal &curl, const char *uri) + :PropfindOperation(curl, uri, 0), + info(StorageFileInfo::Type::OTHER) { + } + + const StorageFileInfo &Perform() { + DeferStart(); + Wait(); + return info; + } + +protected: + /* virtual methods from PropfindOperation */ + void OnDavResponse(DavResponse &&r) override { + if (r.status != 200) + return; + + info.type = r.collection + ? StorageFileInfo::Type::DIRECTORY + : StorageFileInfo::Type::REGULAR; + info.size = r.length; + info.mtime = r.mtime; + } +}; + +StorageFileInfo +CurlStorage::GetInfo(std::string_view uri_utf8, [[maybe_unused]] bool follow) +{ + // TODO: escape the given URI + + const auto uri = MapUTF8(uri_utf8); + return HttpGetInfoOperation(*curl, uri.c_str()).Perform(); +} + +[[gnu::pure]] +static std::string_view +UriPathOrSlash(const char *uri) noexcept +{ + auto path = uri_get_path(uri); + if (path.data() == nullptr) + path = "/"; + return path; +} + +/** + * Obtain a directory listing using WebDAV PROPFIND. + */ +class HttpListDirectoryOperation final : public PropfindOperation { + const std::string base_path; + + MemoryStorageDirectoryReader::List entries; + +public: + HttpListDirectoryOperation(CurlGlobal &curl, const char *uri) + :PropfindOperation(curl, uri, 1), + base_path(CurlUnescape(GetEasy(), UriPathOrSlash(uri))) {} + + std::unique_ptr Perform() { + DeferStart(); + Wait(); + return ToReader(); + } + +private: + std::unique_ptr ToReader() { + return std::make_unique(std::move(entries)); + } + + /** + * Convert a "href" attribute (which may be an absolute URI) + * to the base file name. + */ + [[gnu::pure]] + std::string_view HrefToEscapedName(const char *href) const noexcept { + std::string_view path = uri_get_path(href); + if (path.data() == nullptr) + return {}; + + /* kludge: ignoring case in this comparison to avoid + false negatives if the web server uses a different + case */ + path = StringAfterPrefixIgnoreCase(path, base_path.c_str()); + if (path.empty()) + return {}; + + const auto slash = path.find('/'); + if (slash == path.npos) + /* regular file */ + return path; + else if (slash + 1 == path.size()) + /* trailing slash: collection; strip the slash */ + return path.substr(0, slash); + else + /* strange, better ignore it */ + return {}; + } + +protected: + /* virtual methods from PropfindOperation */ + void OnDavResponse(DavResponse &&r) override { + if (r.status != 200) + return; + + std::string href = CurlUnescape(GetEasy(), r.href.c_str()); + const auto name = HrefToEscapedName(href.c_str()); + if (name.data() == nullptr) + return; + + entries.emplace_front(name); + + auto &info = entries.front().info; + info = StorageFileInfo(r.collection + ? StorageFileInfo::Type::DIRECTORY + : StorageFileInfo::Type::REGULAR); + info.size = r.length; + info.mtime = r.mtime; + } +}; + +std::unique_ptr +CurlStorage::OpenDirectory(std::string_view uri_utf8) +{ + std::string uri = MapUTF8(uri_utf8); + + /* collection URIs must end with a slash */ + if (uri.back() != '/') + uri.push_back('/'); + + return HttpListDirectoryOperation(*curl, uri.c_str()).Perform(); +} + +static std::unique_ptr +CreateCurlStorageURI(EventLoop &event_loop, const char *uri) +{ + return std::make_unique(event_loop, uri); +} + +static constexpr const char *curl_prefixes[] = { + "http://", "https://", nullptr +}; + +const StoragePlugin curl_storage_plugin = { + "curl", + curl_prefixes, + CreateCurlStorageURI, +}; diff --git a/src/storage/plugins/CurlStorage.hxx b/src/storage/plugins/CurlStorage.hxx new file mode 100644 index 0000000..70847e6 --- /dev/null +++ b/src/storage/plugins/CurlStorage.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_CURL_HXX +#define MPD_STORAGE_CURL_HXX + +struct StoragePlugin; + +extern const StoragePlugin curl_storage_plugin; + +#endif diff --git a/src/storage/plugins/LocalStorage.cxx b/src/storage/plugins/LocalStorage.cxx new file mode 100644 index 0000000..7d0ae62 --- /dev/null +++ b/src/storage/plugins/LocalStorage.cxx @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LocalStorage.hxx" +#include "storage/StoragePlugin.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "fs/FileInfo.hxx" +#include "fs/AllocatedPath.hxx" +#include "fs/DirectoryReader.hxx" +#include "util/StringCompare.hxx" + +#include + +class LocalDirectoryReader final : public StorageDirectoryReader { + AllocatedPath base_fs; + + DirectoryReader reader; + + std::string name_utf8; + +public: + explicit LocalDirectoryReader(AllocatedPath &&_base_fs) + :base_fs(std::move(_base_fs)), reader(base_fs) {} + + /* virtual methods from class StorageDirectoryReader */ + const char *Read() noexcept override; + StorageFileInfo GetInfo(bool follow) override; +}; + +class LocalStorage final : public Storage { + const AllocatedPath base_fs; + const std::string base_utf8; + +public: + explicit LocalStorage(Path _base_fs) + :base_fs(_base_fs), base_utf8(base_fs.ToUTF8Throw()) { + assert(!base_fs.IsNull()); + assert(!base_utf8.empty()); + } + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override; + + std::unique_ptr OpenDirectory(std::string_view uri_utf8) override; + + [[nodiscard]] std::string MapUTF8(std::string_view uri_utf8) const noexcept override; + + [[nodiscard]] AllocatedPath MapFS(std::string_view uri_utf8) const noexcept override; + + [[nodiscard]] std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &mutex) override; + +private: + [[nodiscard]] AllocatedPath MapFSOrThrow(std::string_view uri_utf8) const; +}; + +static StorageFileInfo +Stat(Path path, bool follow) +{ + const FileInfo src(path, follow); + StorageFileInfo info; + + if (src.IsRegular()) + info.type = StorageFileInfo::Type::REGULAR; + else if (src.IsDirectory()) + info.type = StorageFileInfo::Type::DIRECTORY; + else + info.type = StorageFileInfo::Type::OTHER; + + info.size = src.GetSize(); + info.mtime = src.GetModificationTime(); +#ifdef _WIN32 + info.device = info.inode = 0; +#else + info.device = src.GetDevice(); + info.inode = src.GetInode(); +#endif + return info; +} + +std::string +LocalStorage::MapUTF8(std::string_view uri_utf8) const noexcept +{ + if (uri_utf8.empty()) + return base_utf8; + + return PathTraitsUTF8::Build(base_utf8, uri_utf8); +} + +AllocatedPath +LocalStorage::MapFSOrThrow(std::string_view uri_utf8) const +{ + if (uri_utf8.empty()) + return base_fs; + + return base_fs / AllocatedPath::FromUTF8Throw(uri_utf8); +} + +AllocatedPath +LocalStorage::MapFS(std::string_view uri_utf8) const noexcept +{ + try { + return MapFSOrThrow(uri_utf8); + } catch (...) { + return nullptr; + } +} + +std::string_view +LocalStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept +{ + return PathTraitsUTF8::Relative(base_utf8, uri_utf8); +} + +InputStreamPtr +LocalStorage::OpenFile(std::string_view uri_utf8, Mutex &mutex) +{ + auto path = MapFS(uri_utf8); + if (path == nullptr) + return nullptr; + + return OpenLocalInputStream(path, mutex); +} + +StorageFileInfo +LocalStorage::GetInfo(std::string_view uri_utf8, bool follow) +{ + return Stat(MapFSOrThrow(uri_utf8), follow); +} + +std::unique_ptr +LocalStorage::OpenDirectory(std::string_view uri_utf8) +{ + return std::make_unique(MapFSOrThrow(uri_utf8)); +} + +const char * +LocalDirectoryReader::Read() noexcept +{ + while (reader.ReadEntry()) { + const Path name_fs = reader.GetEntry(); + if (PathTraitsFS::IsSpecialFilename(name_fs.c_str())) + continue; + + try { + name_utf8 = name_fs.ToUTF8Throw(); + return name_utf8.c_str(); + } catch (...) { + } + } + + return nullptr; +} + +StorageFileInfo +LocalDirectoryReader::GetInfo(bool follow) +{ + return Stat(base_fs / reader.GetEntry(), follow); +} + +std::unique_ptr +CreateLocalStorage(Path base_fs) +{ + return std::make_unique(base_fs); +} + +constexpr StoragePlugin local_storage_plugin = { + "local", + nullptr, + nullptr, +}; diff --git a/src/storage/plugins/LocalStorage.hxx b/src/storage/plugins/LocalStorage.hxx new file mode 100644 index 0000000..e1f4078 --- /dev/null +++ b/src/storage/plugins/LocalStorage.hxx @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_LOCAL_HXX +#define MPD_STORAGE_LOCAL_HXX + +#include + +struct StoragePlugin; +class Storage; +class Path; + +extern const StoragePlugin local_storage_plugin; + +std::unique_ptr +CreateLocalStorage(Path base_fs); + +#endif diff --git a/src/storage/plugins/NfsStorage.cxx b/src/storage/plugins/NfsStorage.cxx new file mode 100644 index 0000000..27f72e0 --- /dev/null +++ b/src/storage/plugins/NfsStorage.cxx @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "NfsStorage.hxx" +#include "storage/StoragePlugin.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "storage/MemoryDirectoryReader.hxx" +#include "lib/nfs/Blocking.hxx" +#include "lib/nfs/Base.hxx" +#include "lib/nfs/Lease.hxx" +#include "lib/nfs/Connection.hxx" +#include "lib/nfs/Glue.hxx" +#include "input/InputStream.hxx" +#include "input/plugins/NfsInputPlugin.hxx" +#include "fs/AllocatedPath.hxx" +#include "thread/Mutex.hxx" +#include "thread/Cond.hxx" +#include "event/Loop.hxx" +#include "event/Call.hxx" +#include "event/InjectEvent.hxx" +#include "event/CoarseTimerEvent.hxx" +#include "util/ASCII.hxx" +#include "util/StringCompare.hxx" + +extern "C" { +#include +#include +} + +#include + +#include +#include + +#include +#include + +using std::string_view_literals::operator""sv; + +class NfsStorage final + : public Storage, NfsLease { + + enum class State { + INITIAL, CONNECTING, READY, DELAY, + }; + + /** + * The full configured URL (with all arguemnts). This is used + * to reconnect. + */ + const std::string url; + + /** + * The base URL for building file URLs (without arguments). + */ + const std::string base; + + NfsConnection *connection; + + InjectEvent defer_connect; + CoarseTimerEvent reconnect_timer; + + Mutex mutex; + Cond cond; + State state = State::CONNECTING; + std::exception_ptr last_exception; + +public: + NfsStorage(const char *_url, NfsConnection &_connection) + :url(_url), + base(fmt::format("nfs://{}{}"sv, _connection.GetServer(), _connection.GetExportName())), + connection(&_connection), + defer_connect(_connection.GetEventLoop(), BIND_THIS_METHOD(OnDeferredConnect)), + reconnect_timer(_connection.GetEventLoop(), BIND_THIS_METHOD(OnReconnectTimer)) + { + BlockingCall(GetEventLoop(), [this](){ + connection->AddLease(*this); + }); + } + + ~NfsStorage() override { + BlockingCall(GetEventLoop(), [this](){ Disconnect(); }); + nfs_finish(); + } + + NfsStorage(const NfsStorage &) = delete; + NfsStorage &operator=(const NfsStorage &) = delete; + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override; + + std::unique_ptr OpenDirectory(std::string_view uri_utf8) override; + + [[nodiscard]] std::string MapUTF8(std::string_view uri_utf8) const noexcept override; + + [[nodiscard]] std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &mutex) override; + + /* virtual methods from NfsLease */ + void OnNfsConnectionReady() noexcept final { + assert(state == State::CONNECTING); + + SetState(State::READY); + } + + void OnNfsConnectionFailed(std::exception_ptr e) noexcept final { + assert(state == State::CONNECTING); + + SetState(State::DELAY, std::move(e)); + reconnect_timer.Schedule(std::chrono::minutes(1)); + } + + void OnNfsConnectionDisconnected(std::exception_ptr e) noexcept final { + assert(state == State::READY); + + SetState(State::DELAY, std::move(e)); + reconnect_timer.Schedule(std::chrono::seconds(5)); + } + + /* InjectEvent callback */ + void OnDeferredConnect() noexcept { + if (state == State::INITIAL) + Connect(); + } + + /* callback for #reconnect_timer */ + void OnReconnectTimer() noexcept { + assert(state == State::DELAY); + + Connect(); + } + +private: + [[nodiscard]] EventLoop &GetEventLoop() const noexcept { + return defer_connect.GetEventLoop(); + } + + void SetState(State _state) noexcept { + assert(GetEventLoop().IsInside()); + + const std::scoped_lock protect{mutex}; + state = _state; + cond.notify_all(); + } + + void SetState(State _state, std::exception_ptr &&e) noexcept { + assert(GetEventLoop().IsInside()); + + const std::scoped_lock protect{mutex}; + state = _state; + last_exception = std::move(e); + cond.notify_all(); + } + + void Connect() noexcept { + assert(state != State::READY); + assert(GetEventLoop().IsInside()); + + try { + connection = &nfs_make_connection(url.c_str()); + } catch (...) { + SetState(State::DELAY, std::current_exception()); + reconnect_timer.Schedule(std::chrono::minutes(10)); + return; + } + + connection->AddLease(*this); + + SetState(State::CONNECTING); + } + + void WaitConnected() { + std::unique_lock lock{mutex}; + + while (true) { + switch (state) { + case State::INITIAL: + /* schedule connect */ + { + const ScopeUnlock unlock(mutex); + defer_connect.Schedule(); + } + + if (state == State::INITIAL) + cond.wait(lock); + break; + + case State::CONNECTING: + case State::READY: + return; + + case State::DELAY: + assert(last_exception); + std::rethrow_exception(last_exception); + } + } + } + + void Disconnect() noexcept { + assert(!GetEventLoop().IsAlive() || GetEventLoop().IsInside()); + + switch (state) { + case State::INITIAL: + defer_connect.Cancel(); + break; + + case State::CONNECTING: + case State::READY: + connection->RemoveLease(*this); + SetState(State::INITIAL); + break; + + case State::DELAY: + reconnect_timer.Cancel(); + SetState(State::INITIAL); + break; + } + } +}; + +static std::string +UriToNfsPath(std::string_view _uri_utf8) +{ + /* libnfs paths must begin with a slash */ + std::string uri_utf8("/"); + uri_utf8.append(_uri_utf8); + +#ifdef _WIN32 + /* assume UTF-8 when accessing NFS from Windows */ + return uri_utf8; +#else + return AllocatedPath::FromUTF8Throw(uri_utf8).Steal(); +#endif +} + +std::string +NfsStorage::MapUTF8(std::string_view uri_utf8) const noexcept +{ + if (uri_utf8.empty()) + /* this special case returns the original "nfs://" URI + with all parameters (they are missing in the "base" + variable); this is important because MapUTF8("") is + called for the state file */ + return url; + + return PathTraitsUTF8::Build(base, uri_utf8); +} + +std::string_view +NfsStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept +{ + return PathTraitsUTF8::Relative(base, uri_utf8); +} + +InputStreamPtr +NfsStorage::OpenFile(std::string_view uri_utf8, Mutex &_mutex) +{ + WaitConnected(); + + return OpenNfsInputStream(*connection, uri_utf8, _mutex); +} + +static void +Copy(StorageFileInfo &info, const struct nfs_stat_64 &st) noexcept +{ + if (S_ISREG(st.nfs_mode)) + info.type = StorageFileInfo::Type::REGULAR; + else if (S_ISDIR(st.nfs_mode)) + info.type = StorageFileInfo::Type::DIRECTORY; + else + info.type = StorageFileInfo::Type::OTHER; + + info.size = st.nfs_size; + info.mtime = std::chrono::system_clock::from_time_t(st.nfs_mtime); + info.device = st.nfs_dev; + info.inode = st.nfs_ino; +} + +class NfsGetInfoOperation final : public BlockingNfsOperation { + const char *const path; + StorageFileInfo info; + bool follow; + +public: + NfsGetInfoOperation(NfsConnection &_connection, const char *_path, + bool _follow) + :BlockingNfsOperation(_connection), path(_path), + follow(_follow) {} + + [[nodiscard]] const StorageFileInfo &GetInfo() const { + return info; + } + +protected: + void Start() override { + if (follow) + connection.Stat(path, *this); + else + connection.Lstat(path, *this); + } + + void HandleResult([[maybe_unused]] unsigned status, void *data) noexcept override { + Copy(info, *(const struct nfs_stat_64 *)data); + } +}; + +StorageFileInfo +NfsStorage::GetInfo(std::string_view uri_utf8, bool follow) +{ + const std::string path = UriToNfsPath(uri_utf8); + + WaitConnected(); + + NfsGetInfoOperation operation(*connection, path.c_str(), follow); + operation.Run(); + return operation.GetInfo(); +} + +[[gnu::pure]] +static bool +SkipNameFS(PathTraitsFS::const_pointer name) noexcept +{ + return PathTraitsFS::IsSpecialFilename(name); +} + +static void +Copy(StorageFileInfo &info, const struct nfsdirent &ent) +{ + switch (ent.type) { + case NF3REG: + info.type = StorageFileInfo::Type::REGULAR; + break; + + case NF3DIR: + info.type = StorageFileInfo::Type::DIRECTORY; + break; + + default: + info.type = StorageFileInfo::Type::OTHER; + break; + } + + info.size = ent.size; + info.mtime = std::chrono::system_clock::from_time_t(ent.mtime.tv_sec); + info.device = 0; + info.inode = ent.inode; +} + +class NfsListDirectoryOperation final : public BlockingNfsOperation { + const char *const path; + + MemoryStorageDirectoryReader::List entries; + +public: + NfsListDirectoryOperation(NfsConnection &_connection, + const char *_path) + :BlockingNfsOperation(_connection), path(_path) {} + + std::unique_ptr ToReader() { + return std::make_unique(std::move(entries)); + } + +protected: + void Start() override { + connection.OpenDirectory(path, *this); + } + + void HandleResult([[maybe_unused]] unsigned status, + void *data) noexcept override { + auto *const dir = (struct nfsdir *)data; + + CollectEntries(dir); + connection.CloseDirectory(dir); + } + +private: + void CollectEntries(struct nfsdir *dir); +}; + +inline void +NfsListDirectoryOperation::CollectEntries(struct nfsdir *dir) +{ + assert(entries.empty()); + + const struct nfsdirent *ent; + while ((ent = connection.ReadDirectory(dir)) != nullptr) { +#ifdef _WIN32 + /* assume UTF-8 when accessing NFS from Windows */ + const auto name_fs = AllocatedPath::FromUTF8Throw(ent->name); + if (name_fs.IsNull()) + continue; +#else + const Path name_fs = Path::FromFS(ent->name); +#endif + if (SkipNameFS(name_fs.c_str())) + continue; + + try { + entries.emplace_front(name_fs.ToUTF8Throw()); + Copy(entries.front().info, *ent); + } catch (...) { + /* ignore files whose name cannot be converted + to UTF-8 */ + } + } +} + +std::unique_ptr +NfsStorage::OpenDirectory(std::string_view uri_utf8) +{ + const std::string path = UriToNfsPath(uri_utf8); + + WaitConnected(); + + NfsListDirectoryOperation operation(*connection, path.c_str()); + operation.Run(); + + return operation.ToReader(); +} + +static std::unique_ptr +CreateNfsStorageURI(EventLoop &event_loop, const char *base) +{ + if (!StringStartsWithCaseASCII(base, "nfs://"sv)) + return nullptr; + + nfs_init(event_loop); + + try { + auto &connection = nfs_make_connection(base); + nfs_set_base(connection.GetServer(), connection.GetExportName()); + + return std::make_unique(base, connection); + } catch (...) { + nfs_finish(); + throw; + } +} + +static constexpr const char *nfs_prefixes[] = { "nfs://", nullptr }; + +const StoragePlugin nfs_storage_plugin = { + "nfs", + nfs_prefixes, + CreateNfsStorageURI, +}; diff --git a/src/storage/plugins/NfsStorage.hxx b/src/storage/plugins/NfsStorage.hxx new file mode 100644 index 0000000..f3e41b3 --- /dev/null +++ b/src/storage/plugins/NfsStorage.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_NFS_HXX +#define MPD_STORAGE_NFS_HXX + +struct StoragePlugin; + +extern const StoragePlugin nfs_storage_plugin; + +#endif diff --git a/src/storage/plugins/SmbclientStorage.cxx b/src/storage/plugins/SmbclientStorage.cxx new file mode 100644 index 0000000..f63d0f6 --- /dev/null +++ b/src/storage/plugins/SmbclientStorage.cxx @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "SmbclientStorage.hxx" +#include "storage/StoragePlugin.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "input/InputStream.hxx" +#include "lib/smbclient/Init.hxx" +#include "lib/smbclient/Context.hxx" +#include "fs/Traits.hxx" +#include "thread/Mutex.hxx" +#include "system/Error.hxx" +#include "util/ASCII.hxx" +#include "util/StringCompare.hxx" +#include "util/ScopeExit.hxx" + +#include + +class SmbclientStorage; + +class SmbclientDirectoryReader final : public StorageDirectoryReader { + SmbclientStorage &storage; + const std::string base; + SMBCFILE *const handle; + + const char *name; + +public: + SmbclientDirectoryReader(SmbclientStorage &_storage, + std::string &&_base, + SMBCFILE *_handle) noexcept + :storage(_storage), base(std::move(_base)), handle(_handle) {} + + ~SmbclientDirectoryReader() override; + + /* virtual methods from class StorageDirectoryReader */ + const char *Read() noexcept override; + StorageFileInfo GetInfo(bool follow) override; +}; + +class SmbclientStorage final : public Storage { + friend class SmbclientDirectoryReader; + + const std::string base; + + /** + * This mutex protects all calls into the #SmbclientContext, + * which is not thread-safe. + */ + Mutex mutex; + + SmbclientContext ctx = SmbclientContext::New(); + +public: + explicit SmbclientStorage(const char *_base) + :base(_base) {} + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override; + + std::unique_ptr OpenDirectory(std::string_view uri_utf8) override; + + [[nodiscard]] std::string MapUTF8(std::string_view uri_utf8) const noexcept override; + + [[nodiscard]] std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &file_mutex) override; +}; + +std::string +SmbclientStorage::MapUTF8(std::string_view uri_utf8) const noexcept +{ + if (uri_utf8.empty()) + return base; + + return PathTraitsUTF8::Build(base, uri_utf8); +} + +std::string_view +SmbclientStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept +{ + return PathTraitsUTF8::Relative(base, uri_utf8); +} + +static StorageFileInfo +GetInfo(SmbclientContext &ctx, Mutex &mutex, const char *path) +{ + struct stat st; + + { + const std::scoped_lock protect{mutex}; + if (ctx.Stat(path, st) != 0) + throw MakeErrno("Failed to access file"); + } + + StorageFileInfo info; + if (S_ISREG(st.st_mode)) + info.type = StorageFileInfo::Type::REGULAR; + else if (S_ISDIR(st.st_mode)) + info.type = StorageFileInfo::Type::DIRECTORY; + else + info.type = StorageFileInfo::Type::OTHER; + + info.size = st.st_size; + info.mtime = std::chrono::system_clock::from_time_t(st.st_mtime); + info.device = st.st_dev; + info.inode = st.st_ino; + return info; +} + +StorageFileInfo +SmbclientStorage::GetInfo(std::string_view uri_utf8, [[maybe_unused]] bool follow) +{ + const std::string mapped = MapUTF8(uri_utf8); + return ::GetInfo(ctx, mutex, mapped.c_str()); +} + +InputStreamPtr +SmbclientStorage::OpenFile(std::string_view uri_utf8, Mutex &file_mutex) +{ + return InputStream::Open(MapUTF8(uri_utf8), file_mutex); +} + +std::unique_ptr +SmbclientStorage::OpenDirectory(std::string_view uri_utf8) +{ + std::string mapped = MapUTF8(uri_utf8); + + SMBCFILE *handle; + + { + const std::scoped_lock protect{mutex}; + handle = ctx.OpenDirectory(mapped.c_str()); + } + + if (handle == nullptr) + throw MakeErrno("Failed to open directory"); + + return std::make_unique(*this, + std::move(mapped), + handle); +} + +[[gnu::pure]] +static bool +SkipNameFS(PathTraitsFS::const_pointer name) noexcept +{ + return PathTraitsFS::IsSpecialFilename(name); +} + +SmbclientDirectoryReader::~SmbclientDirectoryReader() +{ + const std::scoped_lock lock{storage.mutex}; + storage.ctx.CloseDirectory(handle); +} + +const char * +SmbclientDirectoryReader::Read() noexcept +{ + const std::scoped_lock protect{storage.mutex}; + + while (auto e = storage.ctx.ReadDirectory(handle)) { + name = e->name; + if (!SkipNameFS(name)) + return name; + } + + return nullptr; +} + +StorageFileInfo +SmbclientDirectoryReader::GetInfo([[maybe_unused]] bool follow) +{ + const std::string path = PathTraitsUTF8::Build(base, name); + return ::GetInfo(storage.ctx, storage.mutex, path.c_str()); +} + +static std::unique_ptr +CreateSmbclientStorageURI([[maybe_unused]] EventLoop &event_loop, const char *base) +{ + SmbclientInit(); + + return std::make_unique(base); +} + +static constexpr const char *smbclient_prefixes[] = { "smb://", nullptr }; + +const StoragePlugin smbclient_storage_plugin = { + "smbclient", + smbclient_prefixes, + CreateSmbclientStorageURI, +}; diff --git a/src/storage/plugins/SmbclientStorage.hxx b/src/storage/plugins/SmbclientStorage.hxx new file mode 100644 index 0000000..37d9a9a --- /dev/null +++ b/src/storage/plugins/SmbclientStorage.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_SMBCLIENT_HXX +#define MPD_STORAGE_SMBCLIENT_HXX + +struct StoragePlugin; + +extern const StoragePlugin smbclient_storage_plugin; + +#endif diff --git a/src/storage/plugins/UdisksStorage.cxx b/src/storage/plugins/UdisksStorage.cxx new file mode 100644 index 0000000..63d28cb --- /dev/null +++ b/src/storage/plugins/UdisksStorage.cxx @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "UdisksStorage.hxx" +#include "LocalStorage.hxx" +#include "storage/StoragePlugin.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "lib/fmt/ExceptionFormatter.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "lib/dbus/Glue.hxx" +#include "lib/dbus/AsyncRequest.hxx" +#include "lib/dbus/Message.hxx" +#include "lib/dbus/AppendIter.hxx" +#include "lib/dbus/ReadIter.hxx" +#include "lib/dbus/ObjectManager.hxx" +#include "lib/dbus/UDisks2.hxx" +#include "thread/Mutex.hxx" +#include "thread/Cond.hxx" +#include "thread/SafeSingleton.hxx" +#include "event/Call.hxx" +#include "event/InjectEvent.hxx" +#include "fs/AllocatedPath.hxx" +#include "util/Domain.hxx" +#include "util/StringCompare.hxx" +#include "Log.hxx" + +#include + +static constexpr Domain udisks_domain("udisks"); + +class UdisksStorage final : public Storage { + const std::string base_uri; + const std::string id; + + const AllocatedPath inside_path; + + std::string dbus_path; + + SafeSingleton dbus_glue; + ODBus::AsyncRequest list_request; + ODBus::AsyncRequest mount_request; + + mutable Mutex mutex; + Cond cond; + + bool want_mount = false; + + std::unique_ptr mounted_storage; + + std::exception_ptr mount_error; + + InjectEvent defer_mount, defer_unmount; + +public: + template + UdisksStorage(EventLoop &_event_loop, B &&_base_uri, I &&_id, + IP &&_inside_path) + :base_uri(std::forward(_base_uri)), + id(std::forward(_id)), + inside_path(std::forward(_inside_path)), + dbus_glue(_event_loop), + defer_mount(_event_loop, BIND_THIS_METHOD(DeferredMount)), + defer_unmount(_event_loop, BIND_THIS_METHOD(DeferredUnmount)) {} + + ~UdisksStorage() noexcept override { + if (list_request || mount_request) + BlockingCall(GetEventLoop(), [this](){ + if (list_request) + list_request.Cancel(); + if (mount_request) + mount_request.Cancel(); + }); + + try { + UnmountWait(); + } catch (...) { + FmtError(udisks_domain, + "Failed to unmount {:?}: {}", + base_uri, std::current_exception()); + } + } + + UdisksStorage(const UdisksStorage &) = delete; + UdisksStorage &operator=(const UdisksStorage &) = delete; + + EventLoop &GetEventLoop() const noexcept { + return defer_mount.GetEventLoop(); + } + + /* virtual methods from class Storage */ + StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override { + MountWait(); + return mounted_storage->GetInfo(uri_utf8, follow); + } + + std::unique_ptr OpenDirectory(std::string_view uri_utf8) override { + MountWait(); + return mounted_storage->OpenDirectory(uri_utf8); + } + + std::string MapUTF8(std::string_view uri_utf8) const noexcept override; + + AllocatedPath MapFS(std::string_view uri_utf8) const noexcept override { + try { + const_cast(this)->MountWait(); + } catch (...) { + return nullptr; + } + + return mounted_storage->MapFS(uri_utf8); + } + + std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override; + + InputStreamPtr OpenFile(std::string_view uri_utf8, Mutex &file_mutex) override { + MountWait(); + const auto path = mounted_storage->MapFS(uri_utf8); + return OpenLocalInputStream(path, file_mutex); + } + +private: + void SetMountPoint(Path mount_point); + void LockSetMountPoint(Path mount_point); + + void OnListReply(ODBus::Message reply) noexcept; + + void MountWait(); + void DeferredMount() noexcept; + void OnMountNotify(ODBus::Message reply) noexcept; + + void UnmountWait(); + void DeferredUnmount() noexcept; + void OnUnmountNotify(ODBus::Message reply) noexcept; +}; + +inline void +UdisksStorage::SetMountPoint(Path mount_point) +{ + mounted_storage = inside_path.IsNull() + ? CreateLocalStorage(mount_point) + : CreateLocalStorage(mount_point / inside_path); + + mount_error = {}; + want_mount = false; + cond.notify_all(); +} + +void +UdisksStorage::LockSetMountPoint(Path mount_point) +{ + const std::scoped_lock lock{mutex}; + SetMountPoint(mount_point); +} + +void +UdisksStorage::OnListReply(ODBus::Message reply) noexcept +{ + using namespace UDisks2; + + try { + std::string mount_point; + + ParseObjects(reply, [this, &mount_point](Object &&o) { + if (!o.IsId(id)) + return; + + dbus_path = std::move(o.path); + mount_point = std::move(o.mount_point); + }); + + if (dbus_path.empty()) + throw FmtRuntimeError("No such UDisks2 object: {}", + id); + + if (!mount_point.empty()) { + /* already mounted: don't attempt to mount + again, because this would result in + org.freedesktop.UDisks2.Error.AlreadyMounted */ + LockSetMountPoint(Path::FromFS(mount_point.c_str())); + return; + } + } catch (...) { + const std::scoped_lock lock{mutex}; + mount_error = std::current_exception(); + want_mount = false; + cond.notify_all(); + return; + } + + DeferredMount(); +} + +void +UdisksStorage::MountWait() +{ + std::unique_lock lock{mutex}; + + if (mounted_storage) + /* already mounted */ + return; + + if (!want_mount) { + want_mount = true; + defer_mount.Schedule(); + } + + cond.wait(lock, [this]{ return !want_mount; }); + + if (mount_error) + std::rethrow_exception(mount_error); +} + +void +UdisksStorage::DeferredMount() noexcept +try { + using namespace ODBus; + + auto &connection = dbus_glue->GetConnection(); + + if (dbus_path.empty()) { + auto msg = Message::NewMethodCall(UDISKS2_INTERFACE, + UDISKS2_PATH, + DBUS_OM_INTERFACE, + "GetManagedObjects"); + list_request.Send(connection, *msg.Get(), + [this](auto o) { return OnListReply(std::move(o)); }); + return; + } + + auto msg = Message::NewMethodCall(UDISKS2_INTERFACE, + dbus_path.c_str(), + UDISKS2_FILESYSTEM_INTERFACE, + "Mount"); + AppendMessageIter(*msg.Get()).AppendEmptyArray>(); + + mount_request.Send(connection, *msg.Get(), + [this](auto o) { return OnMountNotify(std::move(o)); }); +} catch (...) { + const std::scoped_lock lock{mutex}; + mount_error = std::current_exception(); + want_mount = false; + cond.notify_all(); +} + +void +UdisksStorage::OnMountNotify(ODBus::Message reply) noexcept +try { + using namespace ODBus; + reply.CheckThrowError(); + + ReadMessageIter i(*reply.Get()); + if (i.GetArgType() != DBUS_TYPE_STRING) + throw std::runtime_error("Malformed 'Mount' response"); + + const char *mount_path = i.GetString(); + LockSetMountPoint(Path::FromFS(mount_path)); +} catch (...) { + const std::scoped_lock lock{mutex}; + mount_error = std::current_exception(); + want_mount = false; + cond.notify_all(); +} + +void +UdisksStorage::UnmountWait() +{ + std::unique_lock lock{mutex}; + + if (!mounted_storage) + /* not mounted */ + return; + + defer_unmount.Schedule(); + + cond.wait(lock, [this]{ return !mounted_storage; }); + + if (mount_error) + std::rethrow_exception(mount_error); +} + +void +UdisksStorage::DeferredUnmount() noexcept +try { + using namespace ODBus; + + auto &connection = dbus_glue->GetConnection(); + auto msg = Message::NewMethodCall(UDISKS2_INTERFACE, + dbus_path.c_str(), + UDISKS2_FILESYSTEM_INTERFACE, + "Unmount"); + AppendMessageIter(*msg.Get()).AppendEmptyArray>(); + + mount_request.Send(connection, *msg.Get(), + [this](auto u) { return OnUnmountNotify(std::move(u)); }); +} catch (...) { + const std::scoped_lock lock{mutex}; + mount_error = std::current_exception(); + mounted_storage.reset(); + cond.notify_all(); +} + +void +UdisksStorage::OnUnmountNotify(ODBus::Message reply) noexcept +try { + using namespace ODBus; + reply.CheckThrowError(); + + const std::scoped_lock lock{mutex}; + mount_error = {}; + mounted_storage.reset(); + cond.notify_all(); +} catch (...) { + const std::scoped_lock lock{mutex}; + mount_error = std::current_exception(); + mounted_storage.reset(); + cond.notify_all(); +} + +std::string +UdisksStorage::MapUTF8(std::string_view uri_utf8) const noexcept +{ + if (uri_utf8.empty()) + /* kludge for a special case: return the "udisks://" + URI if the parameter is an empty string to fix the + mount URIs in the state file */ + return base_uri; + + try { + const_cast(this)->MountWait(); + + return mounted_storage->MapUTF8(uri_utf8); + } catch (...) { + /* fallback - not usable but the best we can do */ + return PathTraitsUTF8::Build(base_uri, uri_utf8); + } +} + +std::string_view +UdisksStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept +{ + return PathTraitsUTF8::Relative(base_uri, uri_utf8); +} + +static std::unique_ptr +CreateUdisksStorageURI(EventLoop &event_loop, const char *base_uri) +{ + const char *id_begin = StringAfterPrefix(base_uri, "udisks://"); + if (id_begin == nullptr) + return nullptr; + + std::string id; + + const char *relative_path = std::strchr(id_begin, '/'); + if (relative_path == nullptr) { + id = id_begin; + relative_path = ""; + } else { + id = {id_begin, relative_path}; + ++relative_path; + while (*relative_path == '/') + ++relative_path; + } + + auto inside_path = *relative_path != 0 + ? AllocatedPath::FromUTF8Throw(relative_path) + : nullptr; + + return std::make_unique(event_loop, base_uri, + std::move(id), + std::move(inside_path)); +} + +static constexpr const char *udisks_prefixes[] = { "udisks://", nullptr }; + +const StoragePlugin udisks_storage_plugin = { + "udisks", + udisks_prefixes, + CreateUdisksStorageURI, +}; diff --git a/src/storage/plugins/UdisksStorage.hxx b/src/storage/plugins/UdisksStorage.hxx new file mode 100644 index 0000000..98d7766 --- /dev/null +++ b/src/storage/plugins/UdisksStorage.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_STORAGE_UDISKS_HXX +#define MPD_STORAGE_UDISKS_HXX + +struct StoragePlugin; + +extern const StoragePlugin udisks_storage_plugin; + +#endif diff --git a/src/storage/plugins/meson.build b/src/storage/plugins/meson.build new file mode 100644 index 0000000..e4caf07 --- /dev/null +++ b/src/storage/plugins/meson.build @@ -0,0 +1,65 @@ +storage_plugins_sources = [ + 'LocalStorage.cxx', +] + +webdav_option = get_option('webdav') +enable_webdav = false +if not webdav_option.disabled() + enable_webdav = true + + if not curl_dep.found() + if webdav_option.enabled() + error('WebDAV requires CURL') + endif + enable_webdav = false + endif + + if not expat_dep.found() + if webdav_option.enabled() + error('WebDAV requires Expat') + endif + enable_webdav = false + endif + + if enable_webdav + storage_plugins_sources += 'CurlStorage.cxx' + endif +endif +conf.set('ENABLE_WEBDAV', enable_webdav) + +if nfs_dep.found() + storage_plugins_sources += 'NfsStorage.cxx' +endif + +if smbclient_dep.found() + storage_plugins_sources += 'SmbclientStorage.cxx' +endif + +if enable_udisks + storage_plugins_sources += 'UdisksStorage.cxx' +endif + +storage_plugins = static_library( + 'storage_plugins', + storage_plugins_sources, + include_directories: inc, + dependencies: [ + log_dep, + curl_dep, + dbus_dep, + expat_dep, + nfs_dep, + smbclient_dep, + input_glue_dep, + archive_glue_dep, + ], +) + +storage_plugins_dep = declare_dependency( + link_with: storage_plugins, + dependencies: [ + storage_api_dep, + fs_dep, + time_dep, + ], +) diff --git a/src/system/Clock.cxx b/src/system/Clock.cxx new file mode 100644 index 0000000..b611ff0 --- /dev/null +++ b/src/system/Clock.cxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Clock.hxx" + +#ifdef _WIN32 +#include "time/FileTime.hxx" + +#include + +std::chrono::seconds +GetProcessUptimeS() +{ + FILETIME creation_time, exit_time, kernel_time, user_time, now; + GetProcessTimes(GetCurrentProcess(), &creation_time, + &exit_time, &kernel_time, &user_time); + GetSystemTimeAsFileTime(&now); + + return DeltaFileTimeS(now, creation_time); +} + +#endif diff --git a/src/system/Clock.hxx b/src/system/Clock.hxx new file mode 100644 index 0000000..65211b8 --- /dev/null +++ b/src/system/Clock.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_CLOCK_H +#define MPD_CLOCK_H + +#ifdef _WIN32 + +#include + +/** + * Returns the uptime of the current process in seconds. + */ +[[gnu::pure]] +std::chrono::seconds +GetProcessUptimeS(); + +#endif + +#endif diff --git a/src/system/EpollFD.cxx b/src/system/EpollFD.cxx new file mode 100644 index 0000000..a07c187 --- /dev/null +++ b/src/system/EpollFD.cxx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "EpollFD.hxx" +#include "Error.hxx" + +EpollFD::EpollFD() + :fd(AdoptTag{}, ::epoll_create1(EPOLL_CLOEXEC)) +{ + if (!fd.IsDefined()) + throw MakeErrno("epoll_create1() failed"); +} diff --git a/src/system/EpollFD.hxx b/src/system/EpollFD.hxx new file mode 100644 index 0000000..9bcc2d3 --- /dev/null +++ b/src/system/EpollFD.hxx @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "io/UniqueFileDescriptor.hxx" + +#include + +#include + +/** + * A class that wraps Linux epoll. + */ +class EpollFD { + UniqueFileDescriptor fd; + +public: + /** + * Throws on error. + */ + EpollFD(); + + EpollFD(EpollFD &&) = default; + EpollFD &operator=(EpollFD &&) = default; + + FileDescriptor GetFileDescriptor() const noexcept { + return fd; + } + + int Wait(epoll_event *events, int maxevents, int timeout) noexcept { + return ::epoll_wait(fd.Get(), events, maxevents, timeout); + } + + bool Control(int op, int _fd, epoll_event *event) noexcept { + return ::epoll_ctl(fd.Get(), op, _fd, event) >= 0; + } + + bool Add(int _fd, uint32_t events, void *ptr) noexcept { + epoll_event e; + e.events = events; + e.data.ptr = ptr; + + return Control(EPOLL_CTL_ADD, _fd, &e); + } + + bool Modify(int _fd, uint32_t events, void *ptr) noexcept { + epoll_event e; + e.events = events; + e.data.ptr = ptr; + + return Control(EPOLL_CTL_MOD, _fd, &e); + } + + bool Remove(int _fd) noexcept { + return Control(EPOLL_CTL_DEL, _fd, nullptr); + } +}; diff --git a/src/system/Error.hxx b/src/system/Error.hxx new file mode 100644 index 0000000..706c1dd --- /dev/null +++ b/src/system/Error.hxx @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include // IWYU pragma: export +#include + +#ifdef _WIN32 + +#include // for GetLastError() +#include + +/** + * Returns the error_category to be used to wrap WIN32 GetLastError() + * values. The C++ standard does not define this well, and this value + * is mostly guessed. + * + * TODO: verify + */ +[[gnu::const]] +static inline const std::error_category & +LastErrorCategory() noexcept +{ + return std::system_category(); +} + +[[gnu::pure]] +inline bool +IsLastError(const std::system_error &e, DWORD code) noexcept +{ + return e.code().category() == LastErrorCategory() && + (DWORD)e.code().value() == code; +} + +static inline std::system_error +MakeLastError(DWORD code, const char *msg) noexcept +{ + return std::system_error(std::error_code(code, LastErrorCategory()), + msg); +} + +static inline std::system_error +MakeLastError(const char *msg) noexcept +{ + return MakeLastError(GetLastError(), msg); +} + +#endif /* _WIN32 */ + +#include // IWYU pragma: export + +/** + * Returns the error_category to be used to wrap errno values. The + * C++ standard does not define this well, so this code is based on + * observations what C++ standard library implementations actually + * use. + * + * @see https://stackoverflow.com/questions/28746372/system-error-categories-and-standard-system-error-codes + */ +[[gnu::const]] +static inline const std::error_category & +ErrnoCategory() noexcept +{ +#ifdef _WIN32 + /* on Windows, the generic_category() is used for errno + values */ + return std::generic_category(); +#else + /* on POSIX, system_category() appears to be the best + choice */ + return std::system_category(); +#endif +} + +static inline std::system_error +MakeErrno(int code, const char *msg) noexcept +{ + return std::system_error(std::error_code(code, ErrnoCategory()), + msg); +} + +static inline std::system_error +MakeErrno(const char *msg) noexcept +{ + return MakeErrno(errno, msg); +} + +[[gnu::pure]] +inline bool +IsErrno(const std::system_error &e, int code) noexcept +{ + return e.code().category() == ErrnoCategory() && + e.code().value() == code; +} + +[[gnu::pure]] +static inline bool +IsFileNotFound(const std::system_error &e) noexcept +{ +#ifdef _WIN32 + return IsLastError(e, ERROR_FILE_NOT_FOUND); +#else + return IsErrno(e, ENOENT); +#endif +} + +[[gnu::pure]] +static inline bool +IsPathNotFound(const std::system_error &e) noexcept +{ +#ifdef _WIN32 + return IsLastError(e, ERROR_PATH_NOT_FOUND); +#else + return IsErrno(e, ENOTDIR); +#endif +} + +[[gnu::pure]] +static inline bool +IsAccessDenied(const std::system_error &e) noexcept +{ +#ifdef _WIN32 + return IsLastError(e, ERROR_ACCESS_DENIED); +#else + return IsErrno(e, EACCES); +#endif +} diff --git a/src/system/EventFD.cxx b/src/system/EventFD.cxx new file mode 100644 index 0000000..838659d --- /dev/null +++ b/src/system/EventFD.cxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "EventFD.hxx" +#include "system/Error.hxx" +#include "util/SpanCast.hxx" + +#include + +#include + +EventFD::EventFD() + :fd(AdoptTag{}, ::eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC)) +{ + if (!fd.IsDefined()) + throw MakeErrno("eventfd() failed"); +} + +bool +EventFD::Read() noexcept +{ + assert(fd.IsDefined()); + + eventfd_t value; + return fd.Read(std::as_writable_bytes(std::span{&value, 1})) == (ssize_t)sizeof(value); +} + +void +EventFD::Write() noexcept +{ + assert(fd.IsDefined()); + + static constexpr eventfd_t value = 1; + [[maybe_unused]] ssize_t nbytes = + fd.Write(ReferenceAsBytes(value)); +} diff --git a/src/system/EventFD.hxx b/src/system/EventFD.hxx new file mode 100644 index 0000000..283f9d7 --- /dev/null +++ b/src/system/EventFD.hxx @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef EVENT_FD_HXX +#define EVENT_FD_HXX + +#include "io/UniqueFileDescriptor.hxx" + +/** + * A class that wraps eventfd(). + */ +class EventFD { + UniqueFileDescriptor fd; + +public: + /** + * Throws on error. + */ + EventFD(); + + FileDescriptor Get() const noexcept { + return fd; + } + + /** + * Checks if Write() was called at least once since the last + * Read() call. + */ + bool Read() noexcept; + + /** + * Wakes up the reader. Multiple calls to this function will + * be combined to one wakeup. + */ + void Write() noexcept; +}; + +#endif diff --git a/src/system/EventPipe.cxx b/src/system/EventPipe.cxx new file mode 100644 index 0000000..ce5d399 --- /dev/null +++ b/src/system/EventPipe.cxx @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "EventPipe.hxx" +#include "io/FileDescriptor.hxx" +#include "system/Error.hxx" + +#include + +#ifdef _WIN32 +#include "net/IPv4Address.hxx" +#include "net/StaticSocketAddress.hxx" +#include "net/UniqueSocketDescriptor.hxx" +#include "net/SocketError.hxx" +#endif + +#ifdef _WIN32 +static void PoorSocketPair(UniqueSocketDescriptor &socket0, + UniqueSocketDescriptor &socket01); +#endif + +EventPipe::EventPipe() +{ +#ifdef _WIN32 + PoorSocketPair(r, w); +#else + if (!UniqueFileDescriptor::CreatePipeNonBlock(r, w)) + throw MakeErrno("pipe() has failed"); +#endif +} + +EventPipe::~EventPipe() noexcept = default; + +bool +EventPipe::Read() noexcept +{ + assert(r.IsDefined()); + assert(w.IsDefined()); + + std::byte buffer[256]; + return r.Read(buffer) > 0; +} + +void +EventPipe::Write() noexcept +{ + assert(r.IsDefined()); + assert(w.IsDefined()); + + static constexpr std::byte buffer[1]{}; + (void)w.Write(buffer); +} + +#ifdef _WIN32 + +/* Our poor man's socketpair() implementation + * Due to limited protocol/address family support + * it's better to keep this as a private implementation detail of EventPipe + * rather than wide-available API. + */ +static void +PoorSocketPair(UniqueSocketDescriptor &socket0, UniqueSocketDescriptor &socket1) +{ + UniqueSocketDescriptor listen_socket; + if (!listen_socket.Create(AF_INET, SOCK_STREAM, IPPROTO_TCP)) + throw MakeSocketError("Failed to create socket"); + + if (!listen_socket.Bind(IPv4Address(IPv4Address::Loopback(), 0))) + throw MakeSocketError("Failed to create socket"); + + if (!listen_socket.Listen(1)) + throw MakeSocketError("Failed to listen on socket"); + + if (!socket0.Create(AF_INET, SOCK_STREAM, IPPROTO_TCP)) + throw MakeSocketError("Failed to create socket"); + + if (!socket0.Connect(listen_socket.GetLocalAddress())) + throw MakeSocketError("Failed to connect socket"); + + socket0.SetNonBlocking(); + + socket1 = listen_socket.AcceptNonBlock(); + if (!socket1.IsDefined()) + throw MakeSocketError("Failed to accept connection"); +} + +#endif diff --git a/src/system/EventPipe.hxx b/src/system/EventPipe.hxx new file mode 100644 index 0000000..bf60253 --- /dev/null +++ b/src/system/EventPipe.hxx @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_EVENT_PIPE_HXX +#define MPD_EVENT_PIPE_HXX + +#ifdef _WIN32 +#include "net/UniqueSocketDescriptor.hxx" +#else +#include "io/UniqueFileDescriptor.hxx" +#endif + +/** + * A pipe that can be used to trigger an event to the read side. + * + * Errors in the constructor are fatal. + */ +class EventPipe { +#ifdef _WIN32 + UniqueSocketDescriptor r, w; +#else + UniqueFileDescriptor r, w; +#endif + +public: + /** + * Throws on error. + */ + EventPipe(); + + ~EventPipe() noexcept; + + EventPipe(const EventPipe &other) = delete; + EventPipe &operator=(const EventPipe &other) = delete; + +#ifdef _WIN32 + SocketDescriptor Get() const noexcept { + return r; + } +#else + FileDescriptor Get() const noexcept { + return r; + } +#endif + + /** + * Checks if Write() was called at least once since the last + * Read() call. + */ + bool Read() noexcept; + + /** + * Wakes up the reader. Multiple calls to this function will + * be combined to one wakeup. + */ + void Write() noexcept; +}; + +#endif /* MAIN_NOTIFY_H */ diff --git a/src/system/KernelVersion.cxx b/src/system/KernelVersion.cxx new file mode 100644 index 0000000..17de8a7 --- /dev/null +++ b/src/system/KernelVersion.cxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "KernelVersion.hxx" + +#include +#include + +[[gnu::const]] +static KernelVersionCode +GetKernelVersionCode() noexcept +{ + struct utsname u; + if (uname(&u) != 0) + return {}; + + unsigned major, minor, patch; + switch (sscanf(u.release, "%u.%u.%u", &major, &minor, &patch)) { + case 1: + minor = patch = 0; + break; + + case 2: + patch = 0; + break; + + case 3: + break; + + default: + return {}; + } + + return {major, minor, patch}; +} + +bool +IsKernelVersionOrNewer(KernelVersionCode v) noexcept +{ + static const auto kernel_version_code = GetKernelVersionCode(); + return kernel_version_code >= v; +} diff --git a/src/system/KernelVersion.hxx b/src/system/KernelVersion.hxx new file mode 100644 index 0000000..446148b --- /dev/null +++ b/src/system/KernelVersion.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +class KernelVersionCode { + unsigned value = 0; + +public: + constexpr KernelVersionCode() noexcept = default; + + constexpr KernelVersionCode(unsigned major, + unsigned minor=0, + unsigned patch=0) noexcept + :value((major << 16) | (minor << 8) | patch) {} + + constexpr bool operator>=(KernelVersionCode other) const noexcept { + return value >= other.value; + } +}; + +/** + * Is the currently running Linux kernel at least the given version? + */ +[[gnu::const]] +bool +IsKernelVersionOrNewer(KernelVersionCode v) noexcept; diff --git a/src/system/SignalFD.cxx b/src/system/SignalFD.cxx new file mode 100644 index 0000000..2394b30 --- /dev/null +++ b/src/system/SignalFD.cxx @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "SignalFD.hxx" +#include "Error.hxx" +#include "util/SpanCast.hxx" + +#include + +#include + +void +SignalFD::Create(const sigset_t &mask) +{ + int new_fd = ::signalfd(fd.Get(), &mask, SFD_NONBLOCK|SFD_CLOEXEC); + if (new_fd < 0) + throw MakeErrno("signalfd() failed"); + + if (!fd.IsDefined()) { + fd = UniqueFileDescriptor{AdoptTag{}, new_fd}; + } + + assert(new_fd == fd.Get()); +} + +int +SignalFD::Read() noexcept +{ + assert(fd.IsDefined()); + + signalfd_siginfo info; + return fd.Read(ReferenceAsWritableBytes(info)) > 0 + ? info.ssi_signo + : -1; +} diff --git a/src/system/SignalFD.hxx b/src/system/SignalFD.hxx new file mode 100644 index 0000000..215aca5 --- /dev/null +++ b/src/system/SignalFD.hxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef SIGNAL_FD_HXX +#define SIGNAL_FD_HXX + +#include "io/UniqueFileDescriptor.hxx" + +#include + +/** + * A class that wraps signalfd(). + */ +class SignalFD { + UniqueFileDescriptor fd; + +public: + /** + * Create the signalfd or update its mask. + * + * Throws on error. + */ + void Create(const sigset_t &mask); + + void Close() noexcept { + fd.Close(); + } + + int Get() const noexcept { + return fd.Get(); + } + + /** + * Read the next signal from the file descriptor. Returns the + * signal number on success or -1 if there are no more + * signals. + */ + int Read() noexcept; +}; + +#endif diff --git a/src/system/VmaName.hxx b/src/system/VmaName.hxx new file mode 100644 index 0000000..fa9da92 --- /dev/null +++ b/src/system/VmaName.hxx @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#ifdef __linux__ +# include + +/* fallback definitions if our libc is older than the kernel */ +# ifndef PR_SET_VMA +# define PR_SET_VMA 0x53564d41 +# endif +# ifndef PR_SET_VMA_ANON_NAME +# define PR_SET_VMA_ANON_NAME 0 +# endif +#endif // __linux__ + +/** + * Set a name for the specified virtual memory area. + * + * This feature requires Linux 5.17. + */ +inline void +SetVmaName(const void *start, size_t len, const char *name) +{ +#ifdef __linux__ + prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (unsigned long)start, len, + (unsigned long)name); +#else + (void)start; + (void)len; + (void)name; +#endif +} diff --git a/src/system/linux/meson.build b/src/system/linux/meson.build new file mode 100644 index 0000000..36a98f2 --- /dev/null +++ b/src/system/linux/meson.build @@ -0,0 +1,7 @@ +system_linux_features = configuration_data() + +if host_machine.system() == 'linux' + system_linux_features.set('HAVE_OPENAT2', compiler.has_header('linux/openat2.h')) +endif + +configure_file(output: 'Features.h', configuration: system_linux_features) diff --git a/src/system/linux/openat2.h b/src/system/linux/openat2.h new file mode 100644 index 0000000..362ffad --- /dev/null +++ b/src/system/linux/openat2.h @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include // for O_* +#include // for RESOLVE_* +#include +#include + +static inline int +openat2(int dirfd, const char *pathname, + const struct open_how *how, size_t size) +{ + return syscall(__NR_openat2, dirfd, pathname, how, size); +} diff --git a/src/system/meson.build b/src/system/meson.build new file mode 100644 index 0000000..02f2920 --- /dev/null +++ b/src/system/meson.build @@ -0,0 +1,40 @@ +system_sources = [ + 'EventPipe.cxx', +] + +if host_machine.system() == 'linux' + system_sources += [ + 'KernelVersion.cxx', + 'EventFD.cxx', + 'SignalFD.cxx', + 'EpollFD.cxx', + ] +endif + +if host_machine.system() == 'windows' + system_sources += [ + 'Clock.cxx', + ] +endif + +system = static_library( + 'system', + system_sources, + include_directories: inc, + dependencies: [ + fmt_dep, + ], +) + +if is_windows + winsock_dep = c_compiler.find_library('ws2_32') +else + winsock_dep = dependency('', required: false) +endif + +system_dep = declare_dependency( + link_with: system, + dependencies: [ + winsock_dep, + ], +) diff --git a/src/tag/Aiff.cxx b/src/tag/Aiff.cxx new file mode 100644 index 0000000..632a14c --- /dev/null +++ b/src/tag/Aiff.cxx @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Aiff.hxx" +#include "input/InputStream.hxx" +#include "util/ByteOrder.hxx" +#include "util/SpanCast.hxx" + +#include +#include +#include + +#include + +struct aiff_header { + char id[4]; + uint32_t size; + char format[4]; +}; + +struct aiff_chunk_header { + char id[4]; + uint32_t size; +}; + +size_t +aiff_seek_id3(InputStream &is, std::unique_lock &lock) +{ + /* seek to the beginning and read the AIFF header */ + + is.Rewind(lock); + + aiff_header header; + is.ReadFull(lock, ReferenceAsWritableBytes(header)); + if (memcmp(header.id, "FORM", 4) != 0 || + (is.KnownSize() && FromBE32(header.size) > is.GetSize()) || + (memcmp(header.format, "AIFF", 4) != 0 && + memcmp(header.format, "AIFC", 4) != 0)) + throw std::runtime_error("Not an AIFF file"); + + while (true) { + /* read the chunk header */ + + aiff_chunk_header chunk; + is.ReadFull(lock, ReferenceAsWritableBytes(chunk)); + + size_t size = FromBE32(chunk.size); + if (size > size_t(std::numeric_limits::max())) + /* too dangerous, bail out: possible integer + underflow when casting to off_t */ + throw std::runtime_error("AIFF chunk is too large"); + + if (memcmp(chunk.id, "ID3 ", 4) == 0) + /* found it! */ + return size; + + if (size % 2 != 0) + /* pad byte */ + ++size; + + is.Skip(lock, size); + } +} diff --git a/src/tag/Aiff.hxx b/src/tag/Aiff.hxx new file mode 100644 index 0000000..ab0f90e --- /dev/null +++ b/src/tag/Aiff.hxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/** \file + * + * A parser for the AIFF file format. + */ + +#ifndef MPD_AIFF_HXX +#define MPD_AIFF_HXX + +#include "thread/Mutex.hxx" + +#include + +class InputStream; + +/** + * Seeks the AIFF file to the ID3 chunk. + * + * Throws std::runtime_error on error. + * + * @param is a locked #InputStream + * @return the size of the ID3 chunk + */ +size_t +aiff_seek_id3(InputStream &is, std::unique_lock &lock); + +#endif diff --git a/src/tag/ApeLoader.cxx b/src/tag/ApeLoader.cxx new file mode 100644 index 0000000..24c330b --- /dev/null +++ b/src/tag/ApeLoader.cxx @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ApeLoader.hxx" +#include "input/InputStream.hxx" +#include "util/PackedLittleEndian.hxx" +#include "util/SpanCast.hxx" + +#include +#include +#include +#include + +struct ApeFooter { + unsigned char id[8]; + uint32_t version; + uint32_t length; + uint32_t count; + unsigned char flags[4]; + unsigned char reserved[8]; +}; + +bool +tag_ape_scan(InputStream &is, const ApeTagCallback& callback) +try { + std::unique_lock lock{is.mutex}; + + if (!is.KnownSize() || !is.CheapSeeking()) + return false; + + /* determine if file has an apeV2 tag */ + ApeFooter footer; + is.Seek(lock, is.GetSize() - sizeof(footer)); + is.ReadFull(lock, ReferenceAsWritableBytes(footer)); + + if (memcmp(footer.id, "APETAGEX", sizeof(footer.id)) != 0 || + FromLE32(footer.version) != 2000) + return false; + + /* find beginning of ape tag */ + size_t remaining = FromLE32(footer.length); + if (remaining <= sizeof(footer) + 10 || + /* refuse to load more than one megabyte of tag data */ + remaining > 1024 * 1024) + return false; + + is.Seek(lock, is.GetSize() - remaining); + + /* read tag into buffer */ + remaining -= sizeof(footer); + assert(remaining > 10); + + auto buffer = std::make_unique_for_overwrite(remaining); + is.ReadFull(lock, {buffer.get(), remaining}); + + /* read tags */ + unsigned n = FromLE32(footer.count); + const char *p = (const char *)buffer.get(); + while (n-- && remaining > 10) { + size_t size = *(const PackedLE32 *)p; + p += 4; + remaining -= 4; + unsigned long flags = *(const PackedLE32 *)p; + p += 4; + remaining -= 4; + + /* get the key */ + const char *key = p; + const char *key_end = (const char *)std::memchr(p, '\0', remaining); + if (key_end == nullptr) + break; + + p = key_end + 1; + remaining -= p - key; + + /* get the value */ + if (remaining < size) + break; + + if (!callback(flags, key, {p, size})) + break; + + p += size; + remaining -= size; + } + + return true; +} catch (...) { + return false; +} diff --git a/src/tag/ApeLoader.hxx b/src/tag/ApeLoader.hxx new file mode 100644 index 0000000..3ecab26 --- /dev/null +++ b/src/tag/ApeLoader.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_APE_LOADER_HXX +#define MPD_APE_LOADER_HXX + +#include +#include + +class InputStream; + +typedef std::function ApeTagCallback; + +/** + * Scans the APE tag values from a file. + * + * Throws on I/O error. + * + * @return false if the file could not be opened or if no APE tag is + * present + */ +bool +tag_ape_scan(InputStream &is, const ApeTagCallback& callback); + +#endif diff --git a/src/tag/ApeReplayGain.cxx b/src/tag/ApeReplayGain.cxx new file mode 100644 index 0000000..e724038 --- /dev/null +++ b/src/tag/ApeReplayGain.cxx @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ApeReplayGain.hxx" +#include "ApeLoader.hxx" +#include "ReplayGainParser.hxx" + +#include +#include + +#include + +static bool +replay_gain_ape_callback(unsigned long flags, const char *key, + std::string_view _value, + ReplayGainInfo &info) +{ + /* we only care about utf-8 text tags */ + if ((flags & (0x3 << 1)) != 0) + return false; + + char value[16]; + if (_value.size() >= sizeof(value)) + return false; + + *std::copy(_value.begin(), _value.end(), value) = 0; + + return ParseReplayGainTag(info, key, value); +} + +bool +replay_gain_ape_read(InputStream &is, ReplayGainInfo &info) +{ + bool found = false; + + auto callback = [&info, &found] + (unsigned long flags, const char *key, + std::string_view value) { + found |= replay_gain_ape_callback(flags, key, + value, + info); + return true; + }; + + return tag_ape_scan(is, callback) && found; +} diff --git a/src/tag/ApeReplayGain.hxx b/src/tag/ApeReplayGain.hxx new file mode 100644 index 0000000..ea8bb45 --- /dev/null +++ b/src/tag/ApeReplayGain.hxx @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_APE_REPLAY_GAIN_HXX +#define MPD_APE_REPLAY_GAIN_HXX + +class InputStream; +struct ReplayGainInfo; + +/** + * Throws on I/O error. + */ +bool +replay_gain_ape_read(InputStream &is, ReplayGainInfo &info); + +#endif diff --git a/src/tag/ApeTag.cxx b/src/tag/ApeTag.cxx new file mode 100644 index 0000000..1eab29c --- /dev/null +++ b/src/tag/ApeTag.cxx @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ApeTag.hxx" +#include "ApeLoader.hxx" +#include "ParseName.hxx" +#include "Table.hxx" +#include "Handler.hxx" +#include "util/IterableSplitString.hxx" + +static constexpr struct tag_table ape_tags[] = { + { "album artist", TAG_ALBUM_ARTIST }, + { "year", TAG_DATE }, + { nullptr, TAG_NUM_OF_ITEM_TYPES } +}; + +static TagType +tag_ape_name_parse(const char *name) +{ + TagType type = tag_table_lookup_i(ape_tags, name); + if (type == TAG_NUM_OF_ITEM_TYPES) + type = tag_name_parse_i(name); + + return type; +} + +/** + * @return true if the item was recognized + */ +static bool +tag_ape_import_item(unsigned long flags, + const char *key, std::string_view value, + TagHandler &handler) noexcept +{ + /* we only care about utf-8 text tags */ + if ((flags & (0x3 << 1)) != 0) + return false; + + if (handler.WantPair()) + for (const auto i : IterableSplitString(value, '\0')) + handler.OnPair(key, i); + + TagType type = tag_ape_name_parse(key); + if (type == TAG_NUM_OF_ITEM_TYPES) + return false; + + for (const auto i : IterableSplitString(value, '\0')) + handler.OnTag(type, i); + + return true; +} + +bool +tag_ape_scan2(InputStream &is, TagHandler &handler) +{ + bool recognized = false; + + auto callback = [&handler, &recognized] + (unsigned long flags, const char *key, + std::string_view value) { + recognized |= tag_ape_import_item(flags, key, value, handler); + return true; + }; + + return tag_ape_scan(is, callback) && recognized; +} diff --git a/src/tag/ApeTag.hxx b/src/tag/ApeTag.hxx new file mode 100644 index 0000000..b2909b6 --- /dev/null +++ b/src/tag/ApeTag.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_APE_TAG_HXX +#define MPD_APE_TAG_HXX + +class InputStream; +class TagHandler; + +/** + * Scan the APE tags of a stream. + * + * Throws on I/O error. + * + * @param path_fs the path of the file in filesystem encoding + */ +bool +tag_ape_scan2(InputStream &is, TagHandler &handler); + +#endif diff --git a/src/tag/Builder.cxx b/src/tag/Builder.cxx new file mode 100644 index 0000000..6d6af12 --- /dev/null +++ b/src/tag/Builder.cxx @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Builder.hxx" +#include "Settings.hxx" +#include "Pool.hxx" +#include "FixString.hxx" +#include "Tag.hxx" +#include "util/AllocatedArray.hxx" + +#include +#include +#include + +#include + +TagBuilder::TagBuilder(const Tag &other) noexcept + :duration(other.duration), has_playlist(other.has_playlist) +{ + const std::size_t n = other.num_items; + if (n > 0) { + items.reserve(other.num_items); + const std::scoped_lock protect{tag_pool_lock}; + for (std::size_t i = 0; i != n; ++i) + items.push_back(tag_pool_dup_item(other.items[i])); + } +} + +TagBuilder::TagBuilder(Tag &&other) noexcept + :duration(other.duration), has_playlist(other.has_playlist) +{ + /* move all TagItem pointers from the Tag object; we don't + need to contact the tag pool, because all we do is move + references */ + items.reserve(other.num_items); + std::copy_n(other.items, other.num_items, std::back_inserter(items)); + + /* discard the pointers from the Tag object */ + other.num_items = 0; + delete[] other.items; + other.items = nullptr; +} + +TagBuilder & +TagBuilder::operator=(const TagBuilder &other) noexcept +{ + /* copy all attributes */ + duration = other.duration; + has_playlist = other.has_playlist; + + RemoveAll(); + + if (!other.items.empty()) { + items = other.items; + + /* increment the tag pool refcounters */ + const std::scoped_lock protect{tag_pool_lock}; + for (auto &i : items) + i = tag_pool_dup_item(i); + } + + return *this; +} + +TagBuilder & +TagBuilder::operator=(TagBuilder &&other) noexcept +{ + using std::swap; + + duration = other.duration; + has_playlist = other.has_playlist; + + /* swap the two TagItem lists so we don't need to touch the + tag pool just yet */ + swap(items, other.items); + + return *this; +} + +TagBuilder & +TagBuilder::operator=(Tag &&other) noexcept +{ + duration = other.duration; + has_playlist = other.has_playlist; + + /* move all TagItem pointers from the Tag object; we don't + need to contact the tag pool, because all we do is move + references */ + RemoveAll(); + items.reserve(other.num_items); + std::copy_n(other.items, other.num_items, std::back_inserter(items)); + + /* discard the pointers from the Tag object */ + other.num_items = 0; + delete[] other.items; + other.items = nullptr; + + return *this; +} + +void +TagBuilder::Clear() noexcept +{ + duration = SignedSongTime::Negative(); + has_playlist = false; + RemoveAll(); +} + +void +TagBuilder::Commit(Tag &tag) noexcept +{ + tag.Clear(); + + tag.duration = duration; + tag.has_playlist = has_playlist; + + /* move all TagItem pointers to the new Tag object without + touching the TagPool reference counters; the + vector::clear() call is important to detach them from this + object */ + const unsigned n_items = items.size(); + tag.num_items = n_items; + tag.items = new TagItem *[n_items]; + std::copy_n(items.begin(), n_items, tag.items); + items.clear(); + + /* now ensure that this object is fresh (will not delete any + items because we've already moved them out) */ + Clear(); +} + +Tag +TagBuilder::Commit() noexcept +{ + Tag tag; + Commit(tag); + return tag; +} + +std::unique_ptr +TagBuilder::CommitNew() noexcept +{ + auto tag = std::make_unique(); + Commit(*tag); + return tag; +} + +bool +TagBuilder::HasType(TagType type) const noexcept +{ + return std::any_of(items.begin(), items.end(), [type](const auto &i) { return i->type == type; }); +} + +void +TagBuilder::Complement(const Tag &other) noexcept +{ + if (duration.IsNegative()) + duration = other.duration; + + has_playlist |= other.has_playlist; + + const std::size_t n = other.num_items; + if (n > 0) { + /* build a table of tag types that were already present in + this object, which will not be copied from #other */ + std::array present; + present.fill(false); + for (const TagItem *i : items) + present[i->type] = true; + + items.reserve(items.size() + n); + + const std::scoped_lock protect{tag_pool_lock}; + for (std::size_t i = 0; i != n; ++i) { + TagItem *item = other.items[i]; + if (!present[item->type]) + items.push_back(tag_pool_dup_item(item)); + } + } +} + +void +TagBuilder::AddItemUnchecked(TagType type, std::string_view value) noexcept +{ + TagItem *i; + + { + const std::scoped_lock protect{tag_pool_lock}; + i = tag_pool_get_item(type, value); + } + + items.push_back(i); +} + +inline void +TagBuilder::AddItemInternal(TagType type, std::string_view value) noexcept +{ + assert(!value.empty()); + + auto f = FixTagString(value); + if (f != nullptr) + value = { f.data(), f.size() }; + + AddItemUnchecked(type, value); +} + +void +TagBuilder::AddItem(TagType type, std::string_view value) noexcept +{ + if (value.empty() || !IsTagEnabled(type)) + return; + + AddItemInternal(type, value); +} + +void +TagBuilder::AddEmptyItem(TagType type) noexcept +{ + AddItemUnchecked(type, ""); +} + +void +TagBuilder::RemoveAll() noexcept +{ + if (items.empty()) + /* don't acquire the tag_pool_lock if we're not going + to call tag_pool_put_item() anyway */ + return; + + { + const std::scoped_lock protect{tag_pool_lock}; + for (auto i : items) + tag_pool_put_item(i); + } + + items.clear(); +} + +void +TagBuilder::RemoveType(TagType type) noexcept +{ + if (items.empty()) + /* don't acquire the tag_pool_lock if we're not going + to call tag_pool_put_item() anyway */ + return; + + const auto begin = items.begin(), end = items.end(); + + const std::scoped_lock protect{tag_pool_lock}; + items.erase(std::remove_if(begin, end, + [type](TagItem *item) { + if (item->type != type) + return false; + tag_pool_put_item(item); + return true; + }), + end); +} diff --git a/src/tag/Builder.hxx b/src/tag/Builder.hxx new file mode 100644 index 0000000..b16fa96 --- /dev/null +++ b/src/tag/Builder.hxx @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_BUILDER_HXX +#define MPD_TAG_BUILDER_HXX + +#include "Type.hxx" +#include "Chrono.hxx" + +#include +#include +#include + +struct TagItem; +struct Tag; + +/** + * A class that constructs #Tag objects. + */ +class TagBuilder { + /** + * The duration of the song. A negative value means that the + * length is unknown. + */ + SignedSongTime duration = SignedSongTime::Negative(); + + /** + * Does this file have an embedded playlist (e.g. embedded CUE + * sheet)? + */ + bool has_playlist = false; + + /** an array of tag items */ + std::vector items; + +public: + /** + * Create an empty tag. + */ + TagBuilder() noexcept { + items.reserve(64); + } + + ~TagBuilder() noexcept { + Clear(); + } + + TagBuilder(const TagBuilder &other) = delete; + + explicit TagBuilder(const Tag &other) noexcept; + explicit TagBuilder(Tag &&other) noexcept; + + TagBuilder &operator=(const TagBuilder &other) noexcept; + TagBuilder &operator=(TagBuilder &&other) noexcept; + + TagBuilder &operator=(Tag &&other) noexcept; + + /** + * Returns true if the tag contains no items. This ignores + * the "duration" attribute. + */ + bool empty() const { + return items.empty(); + } + + /** + * Returns true if the object contains any information. + */ + [[gnu::pure]] + bool IsDefined() const noexcept { + return !duration.IsNegative() || has_playlist || !empty(); + } + + void Clear() noexcept; + + /** + * Move this object to the given #Tag instance. This object + * is empty afterwards. + */ + void Commit(Tag &tag) noexcept; + + /** + * Create a new #Tag instance from data in this object. This + * object is empty afterwards. + */ + Tag Commit() noexcept; + + /** + * Create a new #Tag instance from data in this object. The + * returned object is owned by the caller. This object is + * empty afterwards. + */ + std::unique_ptr CommitNew() noexcept; + + void SetDuration(SignedSongTime _duration) noexcept { + duration = _duration; + } + + void SetHasPlaylist(bool _has_playlist) noexcept { + has_playlist = _has_playlist; + } + + void Reserve(unsigned n) noexcept { + items.reserve(n); + } + + /** + * Checks whether the tag contains one or more items with + * the specified type. + */ + [[gnu::pure]] + bool HasType(TagType type) const noexcept; + + /** + * Copy attributes and items from the other object that do not + * exist in this object. + */ + void Complement(const Tag &other) noexcept; + + /** + * A variant of AddItem() which does not attempt to fix up the + * value and does not check whether the tag type is disabled. + */ + void AddItemUnchecked(TagType type, std::string_view value) noexcept; + + /** + * Appends a new tag item. + * + * @param type the type of the new tag item + * @param value the value of the tag item (not null-terminated) + * @param length the length of #value + */ + void AddItem(TagType type, std::string_view value) noexcept; + + /** + * Appends a new tag item with an empty value. Do not use + * this unless you know what you're doing - because usually, + * empty values are discarded. + */ + void AddEmptyItem(TagType type) noexcept; + + /** + * Removes all tag items. + */ + void RemoveAll() noexcept; + + /** + * Removes all tag items of the specified type. + */ + void RemoveType(TagType type) noexcept; + +private: + void AddItemInternal(TagType type, std::string_view value) noexcept; +}; + +#endif diff --git a/src/tag/Config.cxx b/src/tag/Config.cxx new file mode 100644 index 0000000..6499f35 --- /dev/null +++ b/src/tag/Config.cxx @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Config.hxx" +#include "Settings.hxx" +#include "ParseName.hxx" +#include "Type.hxx" +#include "config/Data.hxx" +#include "config/Option.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "util/ASCII.hxx" +#include "util/IterableSplitString.hxx" +#include "util/StringCompare.hxx" +#include "util/StringStrip.hxx" + +using std::string_view_literals::operator""sv; + +void +TagLoadConfig(const ConfigData &config) +{ + const char *value = config.GetString(ConfigOption::METADATA_TO_USE); + if (value == nullptr) + return; + + if (StringEqualsCaseASCII(value, "none")) { + global_tag_mask = TagMask::None(); + return; + } + + bool plus = true; + + if (*value != '+' && *value != '-') + /* no "+-": not incremental */ + global_tag_mask = TagMask::None(); + + for (std::string_view name : IterableSplitString(value, ',')) { + name = Strip(name); + + if (SkipPrefix(name, "+"sv)) { + plus = true; + } else if (SkipPrefix(name, "-"sv)) { + plus = false; + } + + const auto type = tag_name_parse_i(name); + if (type == TAG_NUM_OF_ITEM_TYPES) + throw FmtRuntimeError("error parsing metadata item {:?}", + name); + + if (plus) + global_tag_mask.Set(type); + else + global_tag_mask.Unset(type); + } +} diff --git a/src/tag/Config.hxx b/src/tag/Config.hxx new file mode 100644 index 0000000..50d94f7 --- /dev/null +++ b/src/tag/Config.hxx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_CONFIG_HXX +#define MPD_TAG_CONFIG_HXX + +struct ConfigData; + +void +TagLoadConfig(const ConfigData &config); + +#endif diff --git a/src/tag/Fallback.hxx b/src/tag/Fallback.hxx new file mode 100644 index 0000000..483cfde --- /dev/null +++ b/src/tag/Fallback.hxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_FALLBACK_HXX +#define MPD_TAG_FALLBACK_HXX + +#include "Type.hxx" + +#include + +/** + * Invoke the given function for all fallback tags of the given + * #TagType, until the function returns true (or until there are no + * more fallback tags). + */ +template +bool +ApplyTagFallback(TagType type, F &&f) noexcept +{ + if (type == TAG_ALBUM_ARTIST_SORT) { + /* fall back to "AlbumArtist", "ArtistSort" and + "Artist" if no "AlbumArtistSort" was found */ + if (f(TAG_ALBUM_ARTIST)) + return true; + + return ApplyTagFallback(TAG_ARTIST_SORT, std::forward(f)); + } + + if (type == TAG_ALBUM_ARTIST || type == TAG_ARTIST_SORT) + /* fall back to "Artist" if no + "AlbumArtist"/"ArtistSort" was found */ + return f(TAG_ARTIST); + + if (type == TAG_ALBUM_SORT) + /* fall back to "Album" if no "AlbumSort" was found */ + return f(TAG_ALBUM); + + if (type == TAG_TITLE_SORT) + /* fall back to "Title" if no "TitleSort" was found */ + return f(TAG_TITLE); + + if (type == TAG_COMPOSERSORT) + /* fall back to "Composer" if no "ComposerSort" was found */ + return f(TAG_COMPOSER); + + return false; +} + +/** + * Invoke the given function for the given #TagType and all of its + * fallback tags, until the function returns true (or until there are + * no more fallback tags). + */ +template +bool +ApplyTagWithFallback(TagType type, F &&f) noexcept +{ + return f(type) || ApplyTagFallback(type, std::forward(f)); +} + +#endif diff --git a/src/tag/FixString.cxx b/src/tag/FixString.cxx new file mode 100644 index 0000000..dbbfc6e --- /dev/null +++ b/src/tag/FixString.cxx @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "FixString.hxx" +#include "util/AllocatedArray.hxx" +#include "util/CharUtil.hxx" +#include "util/UTF8.hxx" + +#include +#include + +#include + +[[gnu::pure]] +static const char * +FindInvalidUTF8(const char *p, const char *const end) noexcept +{ + while (p < end) { + const size_t s = SequenceLengthUTF8(*p); + if (p + s > end) + /* partial sequence at end of string */ + return p; + + /* now call the other SequenceLengthUTF8() overload + which also validates the continuations */ + const size_t t = SequenceLengthUTF8(p); + if (t == 0) + return p; + assert(s == t); + + p += s; + } + + return nullptr; +} + +/** + * Replace invalid sequences with the question mark. + */ +static AllocatedArray +patch_utf8(std::string_view src, const char *_invalid) noexcept +{ + /* duplicate the string, and replace invalid bytes in that + buffer */ + AllocatedArray dest{src}; + char *const end = dest.data() + src.size(); + + char *invalid = dest.data() + (_invalid - src.data()); + do { + *invalid = '?'; + + const char *__invalid = FindInvalidUTF8(invalid + 1, end); + invalid = const_cast(__invalid); + } while (invalid != nullptr); + + return dest; +} + +static AllocatedArray +fix_utf8(std::string_view p) noexcept +{ + /* check if the string is already valid UTF-8 */ + const char *invalid = FindInvalidUTF8(p.data(), p.data() + p.size()); + if (invalid == nullptr) + return nullptr; + + /* no, broken - patch invalid sequences */ + return patch_utf8(p, invalid); +} + +[[gnu::pure]] +static const char * +find_non_printable(std::string_view p) noexcept +{ + for (const char &ch : p) + if (IsNonPrintableASCII(ch)) + return &ch; + + return nullptr; +} + +/** + * Clears all non-printable characters, convert them to space. + * Returns nullptr if nothing needs to be cleared. + */ +static AllocatedArray +clear_non_printable(std::string_view src) +{ + const char *first = find_non_printable(src); + if (first == nullptr) + return nullptr; + + AllocatedArray dest{src}; + + for (size_t i = first - src.data(); i < src.size(); ++i) + if (IsNonPrintableASCII(dest[i])) + dest[i] = ' '; + + return dest; +} + +[[gnu::pure]] +static bool +IsSafe(std::string_view s) noexcept +{ + return std::all_of(s.begin(), s.end(), + [](char ch){ + return IsASCII(ch) && IsPrintableASCII(ch); + }); +} + +AllocatedArray +FixTagString(std::string_view p) noexcept +{ + if (IsSafe(p)) + /* optimistic optimization for the common case */ + return nullptr; + + auto utf8 = fix_utf8(p); + if (utf8 != nullptr) + p = {utf8.data(), utf8.size()}; + + auto cleared = clear_non_printable(p); + if (cleared == nullptr) + cleared = std::move(utf8); + + return cleared; +} diff --git a/src/tag/FixString.hxx b/src/tag/FixString.hxx new file mode 100644 index 0000000..6edcd98 --- /dev/null +++ b/src/tag/FixString.hxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_STRING_HXX +#define MPD_TAG_STRING_HXX + +#include + +template class AllocatedArray; + +AllocatedArray +FixTagString(std::string_view p) noexcept; + +#endif diff --git a/src/tag/Format.cxx b/src/tag/Format.cxx new file mode 100644 index 0000000..1facb76 --- /dev/null +++ b/src/tag/Format.cxx @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Format.hxx" +#include "Tag.hxx" +#include "ParseName.hxx" +#include "time/Convert.hxx" +#include "util/format.h" +#include "util/TruncateString.hxx" + +#include + +#include +#include + +struct FormatTagContext { + const Tag &tag; + + char buffer[256]; + + explicit FormatTagContext(const Tag &_tag):tag(_tag) {} +}; + +/** + * Is this a character unsafe to use in a path name segment? + */ +static constexpr bool +IsUnsafeChar(char ch) +{ + return + /* disallow characters illegal in file names on + Windows (Linux allows almost anything) */ + ch == '\\' || ch == '/' || ch == ':' || ch == '*' || + ch == '?' || ch == '<' || ch == '>' || ch == '|' || + /* allow space, but disallow all other whitespace */ + (unsigned char)ch < 0x20; +} + +[[gnu::pure]] +static bool +HasUnsafeChar(const char *s) noexcept +{ + for (; *s; ++s) + if (IsUnsafeChar(*s)) + return true; + + return false; +} + +static const char * +SanitizeString(const char *s, char *buffer, size_t buffer_size) noexcept +{ + /* skip leading dots to avoid generating "../" sequences */ + while (*s == '.') + ++s; + + if (!HasUnsafeChar(s)) + return s; + + char *end = CopyTruncateString(buffer, s, buffer_size); + std::replace_if(buffer, end, IsUnsafeChar, ' '); + return buffer; +} + +[[gnu::pure]] [[gnu::nonnull]] +static const char * +TagGetter(const void *object, const char *name) noexcept +{ + const auto &_ctx = *(const FormatTagContext *)object; + auto &ctx = const_cast(_ctx); + + if (strcmp(name, "iso8601") == 0) { + struct tm tm; + + try { + tm = GmTime(std::chrono::system_clock::now()); + } catch (...) { + return ""; + } + + strftime(ctx.buffer, sizeof(ctx.buffer), +#ifdef _WIN32 + /* kludge: use underscore instead of colon on + Windows because colons are not allowed in + file names, and this library is mostly + used to generate file names */ + "%Y-%m-%dT%H_%M_%SZ", +#else + "%FT%TZ", +#endif + &tm); + return ctx.buffer; + } + + const Tag &tag = ctx.tag; + + TagType tag_type = tag_name_parse_i(name); + if (tag_type == TAG_NUM_OF_ITEM_TYPES) + /* unknown tag name */ + return nullptr; + + const char *value = tag.GetValue(tag_type); + if (value == nullptr) + /* known tag name, but not present in this object */ + value = ""; + + // TODO: handle multiple tag values + return SanitizeString(value, ctx.buffer, sizeof(ctx.buffer)); +} + +char * +FormatTag(const Tag &tag, const char *format) noexcept +{ + FormatTagContext ctx(tag); + return format_object(format, &ctx, TagGetter); +} diff --git a/src/tag/Format.hxx b/src/tag/Format.hxx new file mode 100644 index 0000000..3a3b532 --- /dev/null +++ b/src/tag/Format.hxx @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_FORMAT_HXX +#define MPD_TAG_FORMAT_HXX + +struct Tag; + +[[gnu::malloc]] [[gnu::nonnull]] +char * +FormatTag(const Tag &tag, const char *format) noexcept; + +#endif diff --git a/src/tag/GenParseName.cxx b/src/tag/GenParseName.cxx new file mode 100644 index 0000000..7c5b496 --- /dev/null +++ b/src/tag/GenParseName.cxx @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Names.hxx" + +#include +#include +#include + +#include + +/* + + This program generates an optimized parser for tag names, by doign + switch() on the first character. This reduces the number of + strcmp() calls. + + */ + +int +main(int argc, [[maybe_unused]] char **argv) +{ + if (argc != 1) + return EXIT_FAILURE; + + std::map names; + for (unsigned i = 0; i < unsigned(TAG_NUM_OF_ITEM_TYPES); ++i) + names[tag_item_names[i]] = TagType(i); + + printf("#include \"ParseName.hxx\"\n" + "#include \"Type.hxx\"\n" + "\n" + "#include \n" + "#include \n" + "\n" + "TagType\n" + "tag_name_parse(const char *name) noexcept\n" + "{\n" + " assert(name != nullptr);\n" + "\n" + " switch (*name++) {\n"); + + char first = 0; + + for (const auto &[name, tag] : names) { + if (name.front() != first) { + if (first != 0) + printf(" break;\n\n"); + first = name.front(); + printf(" case '%c':\n", first); + } + + printf(" if (strcmp(name, ((const char *)\"%.*s\") + 1) == 0) return TagType(%u);\n", + int(name.size()), name.data(), unsigned(tag)); + } + + printf(" break;\n\n"); + + printf(" }\n" + "\n" + " return TAG_NUM_OF_ITEM_TYPES;\n" + "}\n"); + + return EXIT_SUCCESS; +} diff --git a/src/tag/Generic.cxx b/src/tag/Generic.cxx new file mode 100644 index 0000000..6be7a4d --- /dev/null +++ b/src/tag/Generic.cxx @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Generic.hxx" +#include "Id3Scan.hxx" +#include "ApeTag.hxx" +#include "fs/Path.hxx" +#include "thread/Mutex.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "config.h" + +bool +ScanGenericTags(InputStream &is, TagHandler &handler) +{ + if (!is.IsSeekable()) + return false; + + if (tag_ape_scan2(is, handler)) + return true; + +#ifdef ENABLE_ID3TAG + is.LockRewind(); + + return tag_id3_scan(is, handler); +#else + return false; +#endif +} + +bool +ScanGenericTags(Path path, TagHandler &handler) +{ + Mutex mutex; + + auto is = OpenLocalInputStream(path, mutex); + return ScanGenericTags(*is, handler); +} diff --git a/src/tag/Generic.hxx b/src/tag/Generic.hxx new file mode 100644 index 0000000..22b4e5c --- /dev/null +++ b/src/tag/Generic.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_GENERIC_HXX +#define MPD_TAG_GENERIC_HXX + +class TagHandler; +class InputStream; +class Path; + +/** + * Attempts to scan APE or ID3 tags from the specified stream. The + * stream does not need to be rewound. + * + * Throws on error. + */ +bool +ScanGenericTags(InputStream &is, TagHandler &handler); + +/** + * Attempts to scan APE or ID3 tags from the specified file. + * + * Throws on error. + */ +bool +ScanGenericTags(Path path, TagHandler &handler); + +#endif diff --git a/src/tag/Handler.cxx b/src/tag/Handler.cxx new file mode 100644 index 0000000..248c18f --- /dev/null +++ b/src/tag/Handler.cxx @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Handler.hxx" +#include "Builder.hxx" +#include "pcm/AudioFormat.hxx" +#include "util/CharUtil.hxx" +#include "util/StringCompare.hxx" + +#include + +using std::string_view_literals::operator""sv; + +void +NullTagHandler::OnTag(TagType, std::string_view) noexcept +{ +} + +void +NullTagHandler::OnPair(std::string_view, std::string_view) noexcept +{ +} + +void +NullTagHandler::OnPicture(const char *, std::span) noexcept +{ +} + +void +NullTagHandler::OnAudioFormat([[maybe_unused]] AudioFormat af) noexcept +{ +} + +void +AddTagHandler::OnDuration(SongTime duration) noexcept +{ + tag.SetDuration(duration); +} + +/** + * Skip leading zeroes and a non-decimal suffix. + */ +static std::string_view +NormalizeDecimal(std::string_view s) +{ + auto start = std::find_if(s.begin(), s.end(), + [](char ch){ return ch != '0'; }); + auto end = std::find_if(start, s.end(), + [](char ch){ return !IsDigitASCII(ch); }); + return std::string_view{start, std::size_t(std::distance(start, end))}; +} + +void +AddTagHandler::OnTag(TagType type, std::string_view value) noexcept +{ + if (type == TAG_TRACK || type == TAG_DISC) { + /* filter out this extra data and leading zeroes */ + + value = NormalizeDecimal(value); + } + + tag.AddItem(type, value); +} + +void +FullTagHandler::OnPair(std::string_view name, std::string_view) noexcept +{ + if (StringIsEqualIgnoreCase(name, "cuesheet"sv)) + tag.SetHasPlaylist(true); +} + +void +FullTagHandler::OnAudioFormat(AudioFormat af) noexcept +{ + if (audio_format != nullptr) + *audio_format = af; +} diff --git a/src/tag/Handler.hxx b/src/tag/Handler.hxx new file mode 100644 index 0000000..c81d583 --- /dev/null +++ b/src/tag/Handler.hxx @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_HANDLER_HXX +#define MPD_TAG_HANDLER_HXX + +#include "Chrono.hxx" + +#include +#include +#include +#include + +enum TagType : uint8_t; +struct AudioFormat; +class TagBuilder; + +/** + * An interface for receiving metadata of a song. + */ +class TagHandler { + const unsigned want_mask; + +public: + static constexpr unsigned WANT_DURATION = 0x1; + static constexpr unsigned WANT_TAG = 0x2; + static constexpr unsigned WANT_PAIR = 0x4; + static constexpr unsigned WANT_AUDIO_FORMAT = 0x8; + static constexpr unsigned WANT_PICTURE = 0x10; + + explicit TagHandler(unsigned _want_mask) noexcept + :want_mask(_want_mask) {} + + TagHandler(const TagHandler &) = delete; + TagHandler &operator=(const TagHandler &) = delete; + + bool WantDuration() const noexcept { + return want_mask & WANT_DURATION; + } + + bool WantTag() const noexcept { + return want_mask & WANT_TAG; + } + + bool WantPair() const noexcept { + return want_mask & WANT_PAIR; + } + + bool WantAudioFormat() const noexcept { + return want_mask & WANT_AUDIO_FORMAT; + } + + bool WantPicture() const noexcept { + return want_mask & WANT_PICTURE; + } + + /** + * Declare the duration of a song. Do not call + * this when the duration could not be determined, because + * there is no magic value for "unknown duration". + */ + virtual void OnDuration(SongTime duration) noexcept = 0; + + /** + * A tag has been read. + * + * @param the value of the tag; the pointer will become + * invalid after returning + */ + virtual void OnTag(TagType type, std::string_view value) noexcept = 0; + + /** + * A name-value pair has been read. It is the codec specific + * representation of tags. + */ + virtual void OnPair(std::string_view key, + std::string_view value) noexcept = 0; + + /** + * Declare the audio format of a song. + * + * Because the #AudioFormat type is limited to formats + * supported by MPD, the value passed to this method may be an + * approximation (should be the one passed to + * DecoderClient::Ready()). For example, some codecs such as + * MP3 are bit depth agnostic, so the decoder plugin chooses a + * bit depth depending on what the codec library emits. + * + * This method is only called by those decoder plugins which + * implement it. Some may not have any code for calling it, + * and others may decide that determining the audio format is + * too expensive. + */ + virtual void OnAudioFormat(AudioFormat af) noexcept = 0; + + /** + * A picture has been read. + * + * This method will only be called if #WANT_PICTURE was enabled. + * + * @param mime_type an optional MIME type string + * @param buffer the picture file contents; the buffer will be + * invalidated after this method returns + */ + virtual void OnPicture(const char *mime_type, + std::span buffer) noexcept = 0; +}; + +class NullTagHandler : public TagHandler { +public: + explicit NullTagHandler(unsigned _want_mask) noexcept + :TagHandler(_want_mask) {} + + void OnDuration([[maybe_unused]] SongTime duration) noexcept override {} + void OnTag(TagType type, std::string_view value) noexcept override; + void OnPair(std::string_view key, + std::string_view value) noexcept override; + void OnAudioFormat(AudioFormat af) noexcept override; + void OnPicture(const char *mime_type, + std::span buffer) noexcept override; +}; + +/** + * This #TagHandler implementation adds tag values to a #TagBuilder + * object. + */ +class AddTagHandler : public NullTagHandler { +protected: + TagBuilder &tag; + + AddTagHandler(unsigned _want_mask, TagBuilder &_builder) noexcept + :NullTagHandler(WANT_DURATION|WANT_TAG|_want_mask), + tag(_builder) {} + +public: + explicit AddTagHandler(TagBuilder &_builder) noexcept + :AddTagHandler(0, _builder) {} + + void OnDuration(SongTime duration) noexcept override; + void OnTag(TagType type, std::string_view value) noexcept override; +}; + +/** + * This #TagHandler implementation adds tag values to a #TagBuilder object + * (casted from the context pointer), and supports the has_playlist + * attribute. + */ +class FullTagHandler : public AddTagHandler { + AudioFormat *const audio_format; + +protected: + FullTagHandler(unsigned _want_mask, TagBuilder &_builder, + AudioFormat *_audio_format) noexcept + :AddTagHandler(WANT_PAIR|_want_mask + |(_audio_format ? WANT_AUDIO_FORMAT : 0), + _builder), + audio_format(_audio_format) {} + +public: + explicit FullTagHandler(TagBuilder &_builder, + AudioFormat *_audio_format=nullptr) noexcept + :FullTagHandler(0, _builder, _audio_format) {} + + void OnPair(std::string_view key, + std::string_view value) noexcept override; + void OnAudioFormat(AudioFormat af) noexcept override; +}; + +#endif diff --git a/src/tag/IcyMetaDataParser.cxx b/src/tag/IcyMetaDataParser.cxx new file mode 100644 index 0000000..d033842 --- /dev/null +++ b/src/tag/IcyMetaDataParser.cxx @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "IcyMetaDataParser.hxx" +#include "tag/Builder.hxx" +#include "util/AllocatedString.hxx" +#include "util/StringSplit.hxx" + +#include +#include +#include + +#include + +using std::string_view_literals::operator""sv; + +#ifdef HAVE_ICU_CONVERTER + +void +IcyMetaDataParser::SetCharset(const char *charset) +{ + icu_converter = IcuConverter::Create(charset); +} + +#endif + +void +IcyMetaDataParser::Reset() noexcept +{ + if (!IsDefined()) + return; + + if (data_rest == 0 && meta_size > 0) + delete[] meta_data; + + tag.reset(); + + data_rest = data_size; + meta_size = 0; +} + +size_t +IcyMetaDataParser::Data(size_t length) noexcept +{ + assert(length > 0); + + if (!IsDefined()) + return length; + + if (data_rest == 0) + return 0; + + if (length >= data_rest) { + length = data_rest; + data_rest = 0; + } else + data_rest -= length; + + return length; +} + +static void +icy_add_item(TagBuilder &tag, TagType type, std::string_view value) noexcept +{ + if (value.size() >= 2 && value.front() == '\'' && value.back() == '\'') { + /* strip the single quotes */ + value = value.substr(1, value.size() - 2); + } + + if (!value.empty()) + tag.AddItem(type, value); +} + +static void +icy_parse_tag_item(TagBuilder &tag, +#ifdef HAVE_ICU_CONVERTER + const IcuConverter *icu_converter, +#endif + std::string_view name, std::string_view value) noexcept +{ + if (name == "StreamTitle"sv) { +#ifdef HAVE_ICU_CONVERTER + if (icu_converter != nullptr) { + try { + icy_add_item(tag, TAG_TITLE, + icu_converter->ToUTF8(value).c_str()); + } catch (...) { + } + + return; + } +#endif + + icy_add_item(tag, TAG_TITLE, value); + } +} + +/** + * Find a single quote that is followed by a semicolon (or by the end + * of the string). If that fails, return the first single quote. If + * that also fails, return #end. + */ +static constexpr std::pair +SplitEndQuote(std::string_view s) noexcept +{ + auto quote = s.find('\''); + if (quote == s.npos) + return {}; + + if (const auto i = s.find("';"sv, quote); i != s.npos) + quote = i; + else + quote = s.rfind('\''); + + assert(quote != s.npos); + + return {s.substr(0, quote), s.substr(quote + 1)}; +} + +static std::unique_ptr +icy_parse_tag( +#ifdef HAVE_ICU_CONVERTER + const IcuConverter *icu_converter, +#endif + std::string_view src) noexcept +{ + TagBuilder tag; + + while (!src.empty()) { + const auto [name, rest] = Split(src, '='); + if (rest.empty()) + break; + + if (rest.front() != '\'') { + /* syntax error; skip to the next semicolon, + try to recover */ + src = Split(rest, ';').second; + continue; + } + + src = rest.substr(1); + + const auto [value, after_value] = SplitEndQuote(rest.substr(1)); + if (after_value.data() == nullptr) + break; + + icy_parse_tag_item(tag, +#ifdef HAVE_ICU_CONVERTER + icu_converter, +#endif + name, value); + + src = Split(after_value, ';').second; + } + + return tag.CommitNew(); +} + +std::size_t +IcyMetaDataParser::Meta(std::span src) noexcept +{ + assert(IsDefined()); + assert(data_rest == 0); + assert(!src.empty()); + + std::size_t consumed = 0; + + if (meta_size == 0) { + /* read meta_size from the first byte of a meta + block */ + meta_size = static_cast(src.front()) * 16; + if (meta_size == 0) { + /* special case: no metadata */ + data_rest = data_size; + return 1; + } + + src = src.subspan(1); + + /* 1 byte was consumed */ + ++consumed; + + /* initialize metadata reader, allocate enough + memory (+1 for the null terminator) */ + meta_position = 0; + meta_data = new char[meta_size + 1]; + } + + assert(meta_position < meta_size); + + if (src.size() > meta_size - meta_position) + src = src.first(meta_size - meta_position); + + memcpy(meta_data + meta_position, src.data(), src.size()); + meta_position += src.size(); + consumed += src.size(); + + if (meta_position == meta_size) { + /* parse */ + + tag = icy_parse_tag( +#ifdef HAVE_ICU_CONVERTER + icu_converter.get(), +#endif + {meta_data, meta_size}); + delete[] meta_data; + + /* change back to normal data mode */ + + meta_size = 0; + data_rest = data_size; + } + + return consumed; +} + +size_t +IcyMetaDataParser::ParseInPlace(std::span buffer) noexcept +{ + const auto begin = buffer.begin(); + auto dest = begin; + auto src = buffer; + + while (!src.empty()) { + std::size_t chunk = Data(src.size()); + if (chunk > 0) { + dest = std::copy_n(src.begin(), chunk, dest); + src = src.subspan(chunk); + if (src.empty()) + break; + } + + chunk = Meta(src); + if (chunk > 0) + src = src.subspan(chunk); + } + + return std::distance(begin, dest); +} diff --git a/src/tag/IcyMetaDataParser.hxx b/src/tag/IcyMetaDataParser.hxx new file mode 100644 index 0000000..d5a18bf --- /dev/null +++ b/src/tag/IcyMetaDataParser.hxx @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ICY_META_DATA_PARSER_HXX +#define MPD_ICY_META_DATA_PARSER_HXX + +#include "lib/icu/Converter.hxx" +#include "tag/Tag.hxx" + +#include +#include +#include + +class IcyMetaDataParser { + size_t data_size = 0, data_rest; + + size_t meta_size, meta_position; + char *meta_data; + +#ifdef HAVE_ICU_CONVERTER + std::unique_ptr icu_converter; +#endif + + std::unique_ptr tag; + +public: + ~IcyMetaDataParser() noexcept { + Reset(); + } + +#ifdef HAVE_ICU_CONVERTER + /** + * Throws on error. + */ + void SetCharset(const char *charset); +#endif + + /** + * Initialize an enabled icy_metadata object with the specified + * data_size (from the icy-metaint HTTP response header). + */ + void Start(size_t _data_size) noexcept { + data_size = data_rest = _data_size; + meta_size = 0; + tag = nullptr; + } + + /** + * Resets the icy_metadata. Call this after rewinding the stream. + */ + void Reset() noexcept; + + /** + * Checks whether the icy_metadata object is enabled. + */ + bool IsDefined() const noexcept { + return data_size > 0; + } + + /** + * Evaluates data. Returns the number of bytes of normal data which + * can be read by the caller, but not more than "length". If the + * return value is smaller than "length", the caller should invoke + * icy_meta(). + */ + size_t Data(size_t length) noexcept; + + /** + * Reads metadata from the stream. Returns the number of + * bytes consumed. If the return value is smaller than + * "src.size()", the caller should invoke Data(). + */ + std::size_t Meta(std::span src) noexcept; + + /** + * Parse data and eliminate metadata. + * + * @return the number of data bytes remaining in the buffer + */ + size_t ParseInPlace(std::span buffer) noexcept; + + std::unique_ptr ReadTag() noexcept { + return std::exchange(tag, nullptr); + } +}; + +#endif diff --git a/src/tag/Id3Load.cxx b/src/tag/Id3Load.cxx new file mode 100644 index 0000000..0524c4f --- /dev/null +++ b/src/tag/Id3Load.cxx @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3Load.hxx" +#include "Id3Parse.hxx" +#include "RiffId3.hxx" +#include "Aiff.hxx" +#include "input/InputStream.hxx" + +#include + +#include + +static constexpr size_t ID3V1_SIZE = 128; + +[[gnu::pure]] +static inline bool +tag_is_id3v1(struct id3_tag *tag) noexcept +{ + return (id3_tag_options(tag, 0, 0) & ID3_TAG_OPTION_ID3V1) != 0; +} + +static long +get_id3v2_footer_size(InputStream &is, std::unique_lock &lock, + offset_type offset) +try { + id3_byte_t buf[ID3_TAG_QUERYSIZE]; + is.Seek(lock, offset); + is.ReadFull(lock, std::as_writable_bytes(std::span{buf})); + + return id3_tag_query(buf, sizeof(buf)); +} catch (...) { + return 0; +} + +static UniqueId3Tag +ReadId3Tag(InputStream &is, std::unique_lock &lock) +try { + std::byte query_buffer[ID3_TAG_QUERYSIZE]; + is.ReadFull(lock, query_buffer); + + /* Look for a tag header */ + long query = id3_tag_query(reinterpret_cast(query_buffer), + sizeof(query_buffer)); + if (query <= 0) + return nullptr; + + const std::size_t tag_size = static_cast(query); + + /* Found a tag. Allocate a buffer and read it in. */ + if (tag_size <= sizeof(query_buffer)) + /* we have enough data already */ + return id3_tag_parse(std::span{query_buffer}.first(tag_size)); + + auto tag_buffer = std::make_unique_for_overwrite(tag_size); + + /* copy the start of the tag we already have to the allocated + buffer */ + std::byte *end = std::copy_n(query_buffer, sizeof(query_buffer), + tag_buffer.get()); + + /* now read the remaining bytes */ + const size_t remaining = tag_size - sizeof(query_buffer); + is.ReadFull(lock, std::span{end, remaining}); + + return id3_tag_parse(std::span{tag_buffer.get(), tag_size}); +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +ReadId3Tag(InputStream &is, std::unique_lock &lock, offset_type offset) +try { + is.Seek(lock, offset); + + return ReadId3Tag(is, lock); +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +ReadId3v1Tag(InputStream &is, std::unique_lock &lock) +try { + std::byte buffer[ID3V1_SIZE]; + is.ReadFull(lock, buffer); + return id3_tag_parse(buffer); +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +ReadId3v1Tag(InputStream &is, std::unique_lock &lock, + offset_type offset) +try { + is.Seek(lock, offset); + return ReadId3v1Tag(is, lock); +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +tag_id3_find_from_beginning(InputStream &is, std::unique_lock &lock) +try { + auto tag = ReadId3Tag(is, lock); + if (!tag) { + return nullptr; + } else if (tag_is_id3v1(tag.get())) { + /* id3v1 tags don't belong here */ + return nullptr; + } + + /* We have an id3v2 tag, so let's look for SEEK frames */ + id3_frame *frame; + while ((frame = id3_tag_findframe(tag.get(), "SEEK", 0))) { + /* Found a SEEK frame, get it's value */ + int seek = id3_field_getint(id3_frame_field(frame, 0)); + if (seek < 0) + break; + + /* Get the tag specified by the SEEK frame */ + auto seektag = ReadId3Tag(is, lock, is.GetOffset() + seek); + if (!seektag || tag_is_id3v1(seektag.get())) + break; + + /* Replace the old tag with the new one */ + tag = std::move(seektag); + } + + return tag; +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +tag_id3_find_from_end(InputStream &is, std::unique_lock &lock) +try { + if (!is.KnownSize() || !is.CheapSeeking()) + return nullptr; + + const offset_type size = is.GetSize(); + if (size < ID3V1_SIZE) + return nullptr; + + offset_type offset = size - ID3V1_SIZE; + + /* Get an id3v1 tag from the end of file for later use */ + auto v1tag = ReadId3v1Tag(is, lock, offset); + if (!v1tag) + offset = size; + + /* Get the id3v2 tag size from the footer (located before v1tag) */ + if (offset < ID3_TAG_QUERYSIZE) + return v1tag; + + long tag_offset = + get_id3v2_footer_size(is, lock, offset - ID3_TAG_QUERYSIZE); + if (tag_offset >= 0) + return v1tag; + + offset_type tag_size = -tag_offset; + if (tag_size > offset) + return v1tag; + + /* Get the tag which the footer belongs to */ + auto tag = ReadId3Tag(is, lock, offset - tag_size); + if (!tag) + return v1tag; + + /* We have an id3v2 tag, so ditch v1tag */ + return tag; +} catch (...) { + return nullptr; +} + +static UniqueId3Tag +tag_id3_riff_aiff_load(InputStream &is, std::unique_lock &lock) +try { + size_t size; + try { + size = riff_seek_id3(is, lock); + } catch (...) { + size = aiff_seek_id3(is, lock); + } + + if (size == 0) + return nullptr; + + if (size > 4 * 1024 * 1024) + /* too large, don't allocate so much memory */ + return nullptr; + + auto buffer = std::make_unique_for_overwrite(size); + is.ReadFull(lock, std::span{buffer.get(), size}); + return id3_tag_parse(std::span{buffer.get(), size}); +} catch (...) { + return nullptr; +} + +UniqueId3Tag +tag_id3_load(InputStream &is) +try { + std::unique_lock lock{is.mutex}; + + auto tag = tag_id3_find_from_beginning(is, lock); + if (tag == nullptr && is.CheapSeeking()) { + tag = tag_id3_riff_aiff_load(is, lock); + if (tag == nullptr) + tag = tag_id3_find_from_end(is, lock); + } + + return tag; +} catch (...) { + return nullptr; +} diff --git a/src/tag/Id3Load.hxx b/src/tag/Id3Load.hxx new file mode 100644 index 0000000..d38a2a3 --- /dev/null +++ b/src/tag/Id3Load.hxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3_LOAD_HXX +#define MPD_TAG_ID3_LOAD_HXX + +#include "Id3Unique.hxx" + +class InputStream; + +/** + * Loads the ID3 tags from the #InputStream into a libid3tag object. + * + * @return nullptr on error or if no ID3 tag was found in the file + */ +UniqueId3Tag +tag_id3_load(InputStream &is); + +#endif diff --git a/src/tag/Id3MixRamp.cxx b/src/tag/Id3MixRamp.cxx new file mode 100644 index 0000000..ad69560 --- /dev/null +++ b/src/tag/Id3MixRamp.cxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3MixRamp.hxx" +#include "MixRampParser.hxx" +#include "MixRampInfo.hxx" + +#include + +#include + +MixRampInfo +Id3ToMixRampInfo(const struct id3_tag *tag) noexcept +{ + MixRampInfo result; + + struct id3_frame *frame; + for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) { + if (frame->nfields < 3) + continue; + + char *const key = (char *) + id3_ucs4_latin1duplicate(id3_field_getstring + (&frame->fields[1])); + char *const value = (char *) + id3_ucs4_latin1duplicate(id3_field_getstring + (&frame->fields[2])); + + ParseMixRampTag(result, key, value); + + free(key); + free(value); + } + + return result; +} diff --git a/src/tag/Id3MixRamp.hxx b/src/tag/Id3MixRamp.hxx new file mode 100644 index 0000000..c96c749 --- /dev/null +++ b/src/tag/Id3MixRamp.hxx @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +struct id3_tag; +class MixRampInfo; + +[[gnu::pure]] +MixRampInfo +Id3ToMixRampInfo(const struct id3_tag *tag) noexcept; diff --git a/src/tag/Id3MusicBrainz.cxx b/src/tag/Id3MusicBrainz.cxx new file mode 100644 index 0000000..5b7f2d8 --- /dev/null +++ b/src/tag/Id3MusicBrainz.cxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3MusicBrainz.hxx" +#include "Table.hxx" +#include "Type.hxx" + +const struct tag_table musicbrainz_txxx_tags[] = { + { "ALBUMARTISTSORT", TAG_ALBUM_ARTIST_SORT }, + { "MusicBrainz Artist Id", TAG_MUSICBRAINZ_ARTISTID }, + { "MusicBrainz Album Id", TAG_MUSICBRAINZ_ALBUMID }, + { "MusicBrainz Album Artist Id", + TAG_MUSICBRAINZ_ALBUMARTISTID }, + { "MusicBrainz Track Id", TAG_MUSICBRAINZ_TRACKID }, + { "MusicBrainz Release Track Id", + TAG_MUSICBRAINZ_RELEASETRACKID }, + { "MusicBrainz Work Id", TAG_MUSICBRAINZ_WORKID }, + { "MusicBrainz Release Group Id", + TAG_MUSICBRAINZ_RELEASEGROUPID }, + { nullptr, TAG_NUM_OF_ITEM_TYPES } +}; diff --git a/src/tag/Id3MusicBrainz.hxx b/src/tag/Id3MusicBrainz.hxx new file mode 100644 index 0000000..6f1c2a1 --- /dev/null +++ b/src/tag/Id3MusicBrainz.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3MUSICBRAINZ_HXX +#define MPD_TAG_ID3MUSICBRAINZ_HXX + +extern const struct tag_table musicbrainz_txxx_tags[]; + +#endif diff --git a/src/tag/Id3Parse.hxx b/src/tag/Id3Parse.hxx new file mode 100644 index 0000000..3d8e3d4 --- /dev/null +++ b/src/tag/Id3Parse.hxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "Id3Unique.hxx" + +#include + +#include +#include + +/** + * Wrapper for id3_tag_parse() which accepts a std::span and returns a + * #UniqueId3Tag. + */ +inline UniqueId3Tag +id3_tag_parse(std::span src) noexcept +{ + return UniqueId3Tag{id3_tag_parse(reinterpret_cast(src.data()), src.size())}; +} diff --git a/src/tag/Id3Picture.cxx b/src/tag/Id3Picture.cxx new file mode 100644 index 0000000..ad9bd34 --- /dev/null +++ b/src/tag/Id3Picture.cxx @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3Picture.hxx" +#include "Handler.hxx" +#include "util/PackedBigEndian.hxx" + +#include +#include + +static std::string_view +ReadString(std::span &src) noexcept +{ + if (src.size() < 4) + return {}; + + const size_t length = *(const PackedBE32 *)(const void *)src.data(); + src = src.subspan(4); + + if (src.size() < length) + return {}; + + const std::string_view result{(const char *)src.data(), length}; + src = src.subspan(length); + return result; +} + +void +ScanId3Apic(std::span buffer, TagHandler &handler) noexcept +{ + if (buffer.size() < 4) + return; + + buffer = buffer.subspan(4); /* picture type */ + + const auto mime_type = ReadString(buffer); + if (mime_type.data() == nullptr) + return; + + /* description */ + if (ReadString(buffer).data() == nullptr) + return; + + if (buffer.size() < 20) + return; + + buffer = buffer.subspan(16); + + const size_t image_size = *(const PackedBE32 *)(const void *)buffer.data(); + buffer = buffer.subspan(4); + + if (buffer.size() < image_size) + return; + + const auto image = buffer.first(image_size); + + // TODO: don't copy MIME type, pass std::string_view to TagHandler::OnPicture() + handler.OnPicture(std::string{mime_type}.c_str(), + image); +} diff --git a/src/tag/Id3Picture.hxx b/src/tag/Id3Picture.hxx new file mode 100644 index 0000000..c81e814 --- /dev/null +++ b/src/tag/Id3Picture.hxx @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3_PICTURE_HXX +#define MPD_TAG_ID3_PICTURE_HXX + +#include + +class TagHandler; + +/** + * Scan an "APIC" value and call TagHandler::OnPicture(). + */ +void +ScanId3Apic(std::span buffer, TagHandler &handler) noexcept; + +#endif diff --git a/src/tag/Id3ReplayGain.cxx b/src/tag/Id3ReplayGain.cxx new file mode 100644 index 0000000..487b6fe --- /dev/null +++ b/src/tag/Id3ReplayGain.cxx @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3ReplayGain.hxx" +#include "Rva2.hxx" +#include "ReplayGainParser.hxx" +#include "ReplayGainInfo.hxx" + +#include + +#include + +bool +Id3ToReplayGainInfo(ReplayGainInfo &rgi, const struct id3_tag *tag) noexcept +{ + bool found = false; + + rgi.Clear(); + + struct id3_frame *frame; + for (unsigned i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) { + if (frame->nfields < 3) + continue; + + char *const key = (char *) + id3_ucs4_latin1duplicate(id3_field_getstring + (&frame->fields[1])); + char *const value = (char *) + id3_ucs4_latin1duplicate(id3_field_getstring + (&frame->fields[2])); + + if (ParseReplayGainTag(rgi, key, value)) + found = true; + + free(key); + free(value); + } + + return found || + /* fall back on RVA2 if no replaygain tags found */ + tag_rva2_parse(tag, rgi); +} diff --git a/src/tag/Id3ReplayGain.hxx b/src/tag/Id3ReplayGain.hxx new file mode 100644 index 0000000..154659c --- /dev/null +++ b/src/tag/Id3ReplayGain.hxx @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3_REPLAY_GAIN_HXX +#define MPD_TAG_ID3_REPLAY_GAIN_HXX + +struct id3_tag; +struct ReplayGainInfo; + +bool +Id3ToReplayGainInfo(ReplayGainInfo &rgi, const struct id3_tag *tag) noexcept; + +#endif diff --git a/src/tag/Id3Scan.cxx b/src/tag/Id3Scan.cxx new file mode 100644 index 0000000..9bd14fc --- /dev/null +++ b/src/tag/Id3Scan.cxx @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Id3Scan.hxx" +#include "Id3String.hxx" +#include "Id3Load.hxx" +#include "Handler.hxx" +#include "Table.hxx" +#include "Builder.hxx" +#include "Tag.hxx" +#include "Id3MusicBrainz.hxx" +#include "util/StringAPI.hxx" +#include "util/StringStrip.hxx" + +#include + +#include + +#include +#include + +#ifndef ID3_FRAME_COMPOSER +#define ID3_FRAME_COMPOSER "TCOM" +#endif + +#ifndef ID3_FRAME_DISC +#define ID3_FRAME_DISC "TPOS" +#endif + +#ifndef ID3_FRAME_ARTIST_SORT +#define ID3_FRAME_ARTIST_SORT "TSOP" +#endif + +#ifndef ID3_FRAME_ALBUM_ARTIST_SORT +#define ID3_FRAME_ALBUM_ARTIST_SORT "TSO2" /* this one is unofficial, introduced by Itunes */ +#endif + +#ifndef ID3_FRAME_ALBUM_ARTIST +#define ID3_FRAME_ALBUM_ARTIST "TPE2" +#endif + +#ifndef ID3_FRAME_TITLE_SORT +#define ID3_FRAME_TITLE_SORT "TSOT" +#endif + +#ifndef ID3_FRAME_ORIGINAL_RELEASE_DATE +#define ID3_FRAME_ORIGINAL_RELEASE_DATE "TDOR" +#endif + +#ifndef ID3_FRAME_LABEL +#define ID3_FRAME_LABEL "TPUB" +#endif + +#ifndef ID3_FRAME_MOOD +#define ID3_FRAME_MOOD "TMOO" +#endif + +[[gnu::pure]] +static Id3String +tag_id3_getstring(const struct id3_frame *frame, unsigned i) noexcept +{ + id3_field *field = id3_frame_field(frame, i); + if (field == nullptr) + return {}; + + const id3_ucs4_t *ucs4 = id3_field_getstring(field); + if (ucs4 == nullptr) + return {}; + + return Id3String::FromUCS4(ucs4); +} + +static void +InvokeOnTag(TagHandler &handler, TagType type, const id3_ucs4_t *ucs4) noexcept +{ + assert(type < TAG_NUM_OF_ITEM_TYPES); + assert(ucs4 != nullptr); + + const auto utf8 = Id3String::FromUCS4(ucs4); + if (!utf8) + return; + + handler.OnTag(type, Strip(std::string_view{utf8.c_str()})); +} + +/** + * Import a "Text information frame" (ID3v2.4.0 section 4.2). It + * contains 2 fields: + * + * - encoding + * - string list + */ +static void +tag_id3_import_text_frame(const struct id3_frame *frame, + TagType type, + TagHandler &handler) noexcept +{ + if (frame->nfields != 2) + return; + + /* check the encoding field */ + + const id3_field *field = id3_frame_field(frame, 0); + if (field == nullptr || field->type != ID3_FIELD_TYPE_TEXTENCODING) + return; + + /* process the value(s) */ + + field = id3_frame_field(frame, 1); + if (field == nullptr || field->type != ID3_FIELD_TYPE_STRINGLIST) + return; + + /* Get the number of strings available */ + const unsigned nstrings = id3_field_getnstrings(field); + for (unsigned i = 0; i < nstrings; i++) { + const id3_ucs4_t *ucs4 = id3_field_getstrings(field, i); + if (ucs4 == nullptr) + continue; + + if (type == TAG_GENRE) + ucs4 = id3_genre_name(ucs4); + + InvokeOnTag(handler, type, ucs4); + } +} + +/** + * Import all text frames with the specified id (ID3v2.4.0 section + * 4.2). This is a wrapper for tag_id3_import_text_frame(). + */ +static void +tag_id3_import_text(const struct id3_tag *tag, const char *id, TagType type, + TagHandler &handler) noexcept +{ + const struct id3_frame *frame; + for (unsigned i = 0; + (frame = id3_tag_findframe(tag, id, i)) != nullptr; ++i) + tag_id3_import_text_frame(frame, type, + handler); +} + +/** + * Import a "Comment frame" (ID3v2.4.0 section 4.10). It + * contains 4 fields: + * + * - encoding + * - language + * - string + * - full string (we use this one) + */ +static void +tag_id3_import_comment_frame(const struct id3_frame *frame, TagType type, + TagHandler &handler) noexcept +{ + if (frame->nfields != 4) + return; + + /* for now I only read the 4th field, with the fullstring */ + const id3_field *field = id3_frame_field(frame, 3); + if (field == nullptr) + return; + + const id3_ucs4_t *ucs4 = id3_field_getfullstring(field); + if (ucs4 == nullptr) + return; + + InvokeOnTag(handler, type, ucs4); +} + +/** + * Import all comment frames (ID3v2.4.0 section 4.10). This is a + * wrapper for tag_id3_import_comment_frame(). + */ +static void +tag_id3_import_comment(const struct id3_tag *tag, const char *id, TagType type, + TagHandler &handler) noexcept +{ + const struct id3_frame *frame; + for (unsigned i = 0; + (frame = id3_tag_findframe(tag, id, i)) != nullptr; ++i) + tag_id3_import_comment_frame(frame, type, + handler); +} + +/** + * Parse a TXXX name, and convert it to a TagType enum value. + * Returns TAG_NUM_OF_ITEM_TYPES if the TXXX name is not understood. + */ +[[gnu::pure]] +static TagType +tag_id3_parse_txxx_name(const char *name) noexcept +{ + + return tag_table_lookup(musicbrainz_txxx_tags, name); +} + +/** + * Import all known MusicBrainz tags from TXXX frames. + */ +static void +tag_id3_import_musicbrainz(const struct id3_tag *id3_tag, + TagHandler &handler) noexcept +{ + for (unsigned i = 0;; ++i) { + const id3_frame *frame = id3_tag_findframe(id3_tag, "TXXX", i); + if (frame == nullptr) + break; + + const auto name = tag_id3_getstring(frame, 1); + if (!name) + continue; + + const auto value = tag_id3_getstring(frame, 2); + if (!value) + continue; + + handler.OnPair(name.c_str(), value.c_str()); + + TagType type = tag_id3_parse_txxx_name(name.c_str()); + + if (type != TAG_NUM_OF_ITEM_TYPES) + handler.OnTag(type, value.c_str()); + } +} + +/** + * Imports the MusicBrainz TrackId from the UFID tag. + */ +static void +tag_id3_import_ufid(const struct id3_tag *id3_tag, + TagHandler &handler) noexcept +{ + for (unsigned i = 0;; ++i) { + const id3_frame *frame = id3_tag_findframe(id3_tag, "UFID", i); + if (frame == nullptr) + break; + + id3_field *field = id3_frame_field(frame, 0); + if (field == nullptr) + continue; + + const id3_latin1_t *name = id3_field_getlatin1(field); + if (name == nullptr || + strcmp((const char *)name, "http://musicbrainz.org") != 0) + continue; + + field = id3_frame_field(frame, 1); + if (field == nullptr) + continue; + + id3_length_t length; + const id3_byte_t *value = + id3_field_getbinarydata(field, &length); + if (value == nullptr || length == 0) + continue; + + handler.OnTag(TAG_MUSICBRAINZ_TRACKID, + {(const char *)value, length}); + } +} + +/** + * Handle "APIC" ("attached picture") tags. + */ +static void +tag_id3_handle_apic(const struct id3_tag *id3_tag, + TagHandler &handler) noexcept +{ + if (!handler.WantPicture()) + return; + + for (unsigned i = 0;; ++i) { + const id3_frame *frame = id3_tag_findframe(id3_tag, "APIC", i); + if (frame == nullptr) + break; + + id3_field *mime_type_field = id3_frame_field(frame, 1); + if (mime_type_field == nullptr) + continue; + + const char *mime_type = (const char *) + id3_field_getlatin1(mime_type_field); + if (mime_type != nullptr && + StringIsEqual(mime_type, "-->")) + /* this is a URL, not image data */ + continue; + + id3_field *data_field = id3_frame_field(frame, 4); + if (data_field == nullptr || + data_field->type != ID3_FIELD_TYPE_BINARYDATA) + continue; + + id3_length_t size; + const id3_byte_t *data = + id3_field_getbinarydata(data_field, &size); + if (data == nullptr || size == 0) + continue; + + handler.OnPicture(mime_type, + std::as_bytes(std::span{data, size})); + } +} + +void +scan_id3_tag(const struct id3_tag *tag, TagHandler &handler) noexcept +{ + tag_id3_import_text(tag, ID3_FRAME_ARTIST, TAG_ARTIST, + handler); + tag_id3_import_text(tag, ID3_FRAME_ALBUM_ARTIST, + TAG_ALBUM_ARTIST, handler); + tag_id3_import_text(tag, ID3_FRAME_ARTIST_SORT, + TAG_ARTIST_SORT, handler); + + tag_id3_import_text(tag, "TSOA", TAG_ALBUM_SORT, handler); + + tag_id3_import_text(tag, ID3_FRAME_ALBUM_ARTIST_SORT, + TAG_ALBUM_ARTIST_SORT, handler); + tag_id3_import_text(tag, ID3_FRAME_TITLE, TAG_TITLE, + handler); + tag_id3_import_text(tag, ID3_FRAME_ALBUM, TAG_ALBUM, + handler); + tag_id3_import_text(tag, ID3_FRAME_TRACK, TAG_TRACK, + handler); + tag_id3_import_text(tag, ID3_FRAME_YEAR, TAG_DATE, + handler); + tag_id3_import_text(tag, ID3_FRAME_ORIGINAL_RELEASE_DATE, TAG_ORIGINAL_DATE, + handler); + tag_id3_import_text(tag, ID3_FRAME_GENRE, TAG_GENRE, + handler); + tag_id3_import_text(tag, ID3_FRAME_COMPOSER, TAG_COMPOSER, + handler); + tag_id3_import_text(tag, "TPE3", TAG_CONDUCTOR, + handler); + tag_id3_import_text(tag, "TPE4", TAG_PERFORMER, handler); + tag_id3_import_text(tag, "TIT1", TAG_GROUPING, handler); + tag_id3_import_comment(tag, ID3_FRAME_COMMENT, TAG_COMMENT, + handler); + tag_id3_import_text(tag, ID3_FRAME_DISC, TAG_DISC, + handler); + tag_id3_import_text(tag, ID3_FRAME_LABEL, TAG_LABEL, + handler); + tag_id3_import_text(tag, ID3_FRAME_MOOD, TAG_MOOD, handler); + tag_id3_import_text(tag, ID3_FRAME_TITLE_SORT, TAG_TITLE_SORT, handler); + + tag_id3_import_musicbrainz(tag, handler); + tag_id3_import_ufid(tag, handler); + tag_id3_handle_apic(tag, handler); +} + +Tag +tag_id3_import(const struct id3_tag *tag) noexcept +{ + TagBuilder tag_builder; + AddTagHandler h(tag_builder); + scan_id3_tag(tag, h); + return tag_builder.Commit(); +} + +bool +tag_id3_scan(InputStream &is, TagHandler &handler) +{ + auto tag = tag_id3_load(is); + if (!tag) + return false; + + scan_id3_tag(tag.get(), handler); + return true; +} diff --git a/src/tag/Id3Scan.hxx b/src/tag/Id3Scan.hxx new file mode 100644 index 0000000..5aa3b22 --- /dev/null +++ b/src/tag/Id3Scan.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3_SCAN_HXX +#define MPD_TAG_ID3_SCAN_HXX + +class InputStream; +class TagHandler; +struct Tag; +struct id3_tag; + +/** + * Throws on I/O error. + */ +bool +tag_id3_scan(InputStream &is, TagHandler &handler); + +Tag +tag_id3_import(const struct id3_tag *) noexcept; + +/** + * Import all tags from the provided id3_tag *tag + * + */ +void +scan_id3_tag(const struct id3_tag *tag, TagHandler &handler) noexcept; + +#endif diff --git a/src/tag/Id3String.hxx b/src/tag/Id3String.hxx new file mode 100644 index 0000000..40bb25e --- /dev/null +++ b/src/tag/Id3String.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include + +#include + +/** + * A UTF-8 string allocated by libid3tag. + */ +class Id3String { + id3_utf8_t *p = nullptr; + + Id3String(id3_utf8_t *_p) noexcept:p(_p) {} + +public: + Id3String() noexcept = default; + + ~Id3String() noexcept { + free(p); + } + + Id3String(const Id3String &) = delete; + Id3String &operator=(const Id3String &) = delete; + + static Id3String FromUCS4(const id3_ucs4_t *ucs4) noexcept { + return id3_ucs4_utf8duplicate(ucs4); + } + + operator bool() const noexcept { + return p != nullptr; + } + + const char *c_str() const noexcept { + return (const char *)p; + } +}; diff --git a/src/tag/Id3Unique.hxx b/src/tag/Id3Unique.hxx new file mode 100644 index 0000000..e2a8e7a --- /dev/null +++ b/src/tag/Id3Unique.hxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ID3_UNIQUE_HXX +#define MPD_TAG_ID3_UNIQUE_HXX + +#include + +#include + +struct Id3Delete { + void operator()(struct id3_tag *tag) noexcept { + id3_tag_delete(tag); + } +}; + +using UniqueId3Tag = std::unique_ptr; + +#endif diff --git a/src/tag/Item.hxx b/src/tag/Item.hxx new file mode 100644 index 0000000..b67eac4 --- /dev/null +++ b/src/tag/Item.hxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_ITEM_HXX +#define MPD_TAG_ITEM_HXX + +#include +#include + +enum TagType : uint8_t; + +/** + * One tag value. It is a mapping of #TagType to am arbitrary string + * value. Each tag can have multiple items of one tag type (although + * few clients support that). + */ +struct TagItem { + /** the type of this item */ + TagType type; + + /** + * the value of this tag; this is a variable length string + */ + char value[1]; + + bool operator==(const TagItem &other) const noexcept { + return (this == &other) ? true : + type == other.type && std::strcmp(value, other.value) == 0; + } + +private: + /* making the constructor private + to only allow construction by TagPoolItem. */ + friend struct TagPoolItem; + TagItem() = default; + TagItem(const TagItem &other) = delete; + TagItem &operator=(const TagItem &other) = delete; +}; + +static_assert(sizeof(TagItem) == 2, "Unexpected size"); +static_assert(alignof(TagItem) == 1, "Unexpected alignment"); + +#endif diff --git a/src/tag/Mask.hxx b/src/tag/Mask.hxx new file mode 100644 index 0000000..b27ad76 --- /dev/null +++ b/src/tag/Mask.hxx @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "Type.hxx" + +#include + +class TagMask { + using mask_t = uint_least64_t; + + /* the mask must have enough bits to represent all tags + supported by MPD */ + static_assert(TAG_NUM_OF_ITEM_TYPES <= sizeof(mask_t) * 8); + + mask_t value; + + explicit constexpr TagMask(mask_t _value) noexcept + :value(_value) {} + +public: + constexpr TagMask() noexcept = default; + + constexpr TagMask(TagType tag) noexcept + :value(mask_t(1) << mask_t(tag)) {} + + static constexpr TagMask None() noexcept { + return TagMask(mask_t(0)); + } + + static constexpr TagMask All() noexcept { + return ~None(); + } + + constexpr TagMask operator~() const noexcept { + return TagMask(~value); + } + + constexpr TagMask operator&(TagMask other) const noexcept { + return TagMask(value & other.value); + } + + constexpr TagMask operator|(TagMask other) const noexcept { + return TagMask(value | other.value); + } + + constexpr TagMask operator^(TagMask other) const noexcept { + return TagMask(value ^ other.value); + } + + constexpr TagMask &operator&=(TagMask other) noexcept { + value &= other.value; + return *this; + } + + constexpr TagMask &operator|=(TagMask other) noexcept { + value |= other.value; + return *this; + } + + constexpr TagMask &operator^=(TagMask other) noexcept { + value ^= other.value; + return *this; + } + + constexpr bool TestAny() const noexcept { + return value != 0; + } + + constexpr bool Test(TagType tag) const noexcept { + return (*this & tag).TestAny(); + } + + constexpr void Set(TagType tag) noexcept { + *this |= tag; + } + + constexpr void Unset(TagType tag) noexcept { + *this &= ~TagMask(tag); + } +}; diff --git a/src/tag/MixRampInfo.hxx b/src/tag/MixRampInfo.hxx new file mode 100644 index 0000000..79caeb8 --- /dev/null +++ b/src/tag/MixRampInfo.hxx @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_MIX_RAMP_INFO_HXX +#define MPD_MIX_RAMP_INFO_HXX + +#include + +class MixRampInfo { + std::string start, end; + +public: + MixRampInfo() = default; + + void Clear() noexcept { + start.clear(); + end.clear(); + } + + [[gnu::pure]] + bool IsDefined() const noexcept { + return !start.empty() || !end.empty(); + } + + [[gnu::pure]] + const char *GetStart() const noexcept { + return start.empty() ? nullptr : start.c_str(); + } + + [[gnu::pure]] + const char *GetEnd() const noexcept { + return end.empty() ? nullptr : end.c_str(); + } + + void SetStart(const char *new_value) noexcept { + if (new_value == nullptr) + start.clear(); + else + start = new_value; + } + + void SetStart(std::string &&new_value) noexcept { + start = std::move(new_value); + } + + void SetEnd(const char *new_value) noexcept { + if (new_value == nullptr) + end.clear(); + else + end = new_value; + } + + void SetEnd(std::string &&new_value) noexcept { + end = std::move(new_value); + } +}; + +#endif diff --git a/src/tag/MixRampParser.cxx b/src/tag/MixRampParser.cxx new file mode 100644 index 0000000..c007739 --- /dev/null +++ b/src/tag/MixRampParser.cxx @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "MixRampParser.hxx" +#include "VorbisComment.hxx" +#include "MixRampInfo.hxx" +#include "util/ASCII.hxx" + +#include + +template +static bool +ParseMixRampTagTemplate(MixRampInfo &info, const T t) noexcept +{ + if (const std::string_view value = t["mixramp_start"]; + !value.empty()) { + info.SetStart(std::string{value}); + return true; + } + + if (const std::string_view value = t["mixramp_end"]; + !value.empty()) { + info.SetEnd(std::string{value}); + return true; + } + + return false; +} + +bool +ParseMixRampTag(MixRampInfo &info, + const char *name, const char *value) noexcept +{ + assert(name != nullptr); + assert(value != nullptr); + + struct NameValue { + const char *name; + const char *value; + + [[gnu::pure]] + std::string_view operator[](const char *n) const noexcept { + return StringEqualsCaseASCII(name, n) + ? value + : std::string_view{}; + } + }; + + return ParseMixRampTagTemplate(info, NameValue{name, value}); +} + +bool +ParseMixRampVorbis(MixRampInfo &info, std::string_view entry) noexcept +{ + struct VorbisCommentEntry { + std::string_view entry; + + [[gnu::pure]] + std::string_view operator[](std::string_view n) const noexcept { + return GetVorbisCommentValue(entry, n); + } + }; + + return ParseMixRampTagTemplate(info, VorbisCommentEntry{entry}); +} diff --git a/src/tag/MixRampParser.hxx b/src/tag/MixRampParser.hxx new file mode 100644 index 0000000..65f89ad --- /dev/null +++ b/src/tag/MixRampParser.hxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include + +class MixRampInfo; + +bool +ParseMixRampTag(MixRampInfo &info, + const char *name, const char *value) noexcept; + +bool +ParseMixRampVorbis(MixRampInfo &info, std::string_view entry) noexcept; diff --git a/src/tag/Names.cxx b/src/tag/Names.cxx new file mode 100644 index 0000000..eb6d9c9 --- /dev/null +++ b/src/tag/Names.cxx @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Names.hxx" +#include "Table.hxx" + +#include + +static constexpr struct tag_table tag_item_names_init[] = { + {"Artist", TAG_ARTIST}, + {"ArtistSort", TAG_ARTIST_SORT}, + {"Album", TAG_ALBUM}, + {"AlbumSort", TAG_ALBUM_SORT}, + {"AlbumArtist", TAG_ALBUM_ARTIST}, + {"AlbumArtistSort", TAG_ALBUM_ARTIST_SORT}, + {"Title", TAG_TITLE}, + {"TitleSort", TAG_TITLE_SORT}, + {"Track", TAG_TRACK}, + {"Name", TAG_NAME}, + {"Genre", TAG_GENRE}, + {"Mood", TAG_MOOD}, + {"Date", TAG_DATE}, + {"OriginalDate", TAG_ORIGINAL_DATE}, + {"Composer", TAG_COMPOSER}, + {"ComposerSort", TAG_COMPOSERSORT}, + {"Performer", TAG_PERFORMER}, + {"Conductor", TAG_CONDUCTOR}, + {"Work", TAG_WORK}, + {"Movement", TAG_MOVEMENT}, + {"MovementNumber", TAG_MOVEMENTNUMBER}, + {"ShowMovement", TAG_SHOWMOVEMENT}, + {"Ensemble", TAG_ENSEMBLE}, + {"Location", TAG_LOCATION}, + {"Grouping", TAG_GROUPING}, + {"Comment", TAG_COMMENT}, + {"Disc", TAG_DISC}, + {"Label", TAG_LABEL}, + + /* MusicBrainz tags from http://musicbrainz.org/doc/MusicBrainzTag */ + {"MUSICBRAINZ_ARTISTID", TAG_MUSICBRAINZ_ARTISTID}, + {"MUSICBRAINZ_ALBUMID", TAG_MUSICBRAINZ_ALBUMID}, + {"MUSICBRAINZ_ALBUMARTISTID", TAG_MUSICBRAINZ_ALBUMARTISTID}, + {"MUSICBRAINZ_TRACKID", TAG_MUSICBRAINZ_TRACKID}, + {"MUSICBRAINZ_RELEASETRACKID", TAG_MUSICBRAINZ_RELEASETRACKID}, + {"MUSICBRAINZ_WORKID", TAG_MUSICBRAINZ_WORKID}, + {"MUSICBRAINZ_RELEASEGROUPID", TAG_MUSICBRAINZ_RELEASEGROUPID}, +}; + +/** + * This function converts the #tag_item_names_init array to an + * associative array at compile time. This is a kludge because C++20 + * doesn't support designated initializers for arrays, unlike C99. + */ +static constexpr auto +MakeTagNames() noexcept +{ + std::array result{}; + + static_assert(std::size(tag_item_names_init) == result.size()); + + for (const auto &i : tag_item_names_init) { + /* no duplicates allowed */ + assert(result[i.type] == nullptr); + + result[i.type] = i.name; + } + + return result; +} + +constinit const std::array tag_item_names = MakeTagNames(); diff --git a/src/tag/Names.hxx b/src/tag/Names.hxx new file mode 100644 index 0000000..60bb372 --- /dev/null +++ b/src/tag/Names.hxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "Type.hxx" + +#include + +/** + * An array of strings, which map the #TagType to its machine + * readable name (specific to the MPD protocol). + */ +extern const std::array tag_item_names; diff --git a/src/tag/ParseName.cxx b/src/tag/ParseName.cxx new file mode 100644 index 0000000..333a0fa --- /dev/null +++ b/src/tag/ParseName.cxx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ParseName.hxx" +#include "Names.hxx" +#include "util/ASCII.hxx" +#include "util/StringCompare.hxx" + +#include + +#include + +TagType +tag_name_parse(std::string_view name) noexcept +{ + for (unsigned i = 0; i < TAG_NUM_OF_ITEM_TYPES; ++i) { + assert(tag_item_names[i] != nullptr); + + if (name == tag_item_names[i]) + return (TagType)i; + } + + return TAG_NUM_OF_ITEM_TYPES; +} + +TagType +tag_name_parse_i(const char *name) noexcept +{ + assert(name != nullptr); + + for (unsigned i = 0; i < TAG_NUM_OF_ITEM_TYPES; ++i) { + assert(tag_item_names[i] != nullptr); + + if (StringEqualsCaseASCII(name, tag_item_names[i])) + return (TagType)i; + } + + return TAG_NUM_OF_ITEM_TYPES; +} + +TagType +tag_name_parse_i(std::string_view name) noexcept +{ + for (unsigned i = 0; i < TAG_NUM_OF_ITEM_TYPES; ++i) { + assert(tag_item_names[i] != nullptr); + + if (StringIsEqualIgnoreCase(name, tag_item_names[i])) + return (TagType)i; + } + + return TAG_NUM_OF_ITEM_TYPES; +} diff --git a/src/tag/ParseName.hxx b/src/tag/ParseName.hxx new file mode 100644 index 0000000..b165ac1 --- /dev/null +++ b/src/tag/ParseName.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_PARSE_NAME_HXX +#define MPD_TAG_PARSE_NAME_HXX + +#include + +#include + +enum TagType : uint8_t; + +/** + * Parse the string, and convert it into a #TagType. Returns + * #TAG_NUM_OF_ITEM_TYPES if the string could not be recognized. + */ +[[gnu::pure]] +TagType +tag_name_parse(const char *name) noexcept; + +[[gnu::pure]] +TagType +tag_name_parse(std::string_view name) noexcept; + +/** + * Parse the string, and convert it into a #TagType. Returns + * #TAG_NUM_OF_ITEM_TYPES if the string could not be recognized. + * + * Case does not matter. + */ +[[gnu::pure]] +TagType +tag_name_parse_i(const char *name) noexcept; + +[[gnu::pure]] +TagType +tag_name_parse_i(std::string_view name) noexcept; + +#endif diff --git a/src/tag/Pool.cxx b/src/tag/Pool.cxx new file mode 100644 index 0000000..9d78b56 --- /dev/null +++ b/src/tag/Pool.cxx @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Pool.hxx" +#include "Item.hxx" +#include "util/Cast.hxx" +#include "util/djb_hash.hxx" +#include "util/IntrusiveHashSet.hxx" +#include "util/SpanCast.hxx" +#include "util/VarSize.hxx" + +#include +#include +#include +#include + +Mutex tag_pool_lock; + +struct TagPoolKey { + std::string_view value; + TagType type; + + friend constexpr auto operator<=>(const TagPoolKey &, + const TagPoolKey &) noexcept = default; + + struct Hash { + [[gnu::pure]] + std::size_t operator()(const TagPoolKey &key) const noexcept { + return djb_hash(AsBytes(key.value)) ^ key.type; + } + }; +}; + +struct TagPoolItem { + IntrusiveHashSetHook hash_set_hook; + uint8_t ref = 1; + TagItem item; + + static constexpr unsigned MAX_REF = std::numeric_limits::max(); + + TagPoolItem(TagType type, + std::string_view value) noexcept { + item.type = type; + *std::copy(value.begin(), value.end(), item.value) = 0; + } + + static TagPoolItem *Create(TagType type, + std::string_view value) noexcept; + + struct GetKey { + [[gnu::pure]] + constexpr TagPoolKey operator()(const TagItem &i) const noexcept { + return { i.value, i.type }; + } + + [[gnu::pure]] + constexpr TagPoolKey operator()(const TagPoolItem &i) const noexcept { + return operator()(i.item); + } + }; + + struct CanIncrementRef { + constexpr bool operator()(const TagPoolItem &i) const noexcept { + return i.ref < MAX_REF; + } + }; +}; + +TagPoolItem * +TagPoolItem::Create(TagType type, + std::string_view value) noexcept +{ + TagPoolItem *dummy; + return NewVarSize(sizeof(dummy->item.value), + value.size() + 1, + type, + value); +} + +static IntrusiveHashSet>, + IntrusiveHashSetMemberHookTraits<&TagPoolItem::hash_set_hook>, + IntrusiveHashSetOptions{.zero_initialized = true}> tag_pool; + +static constexpr TagPoolItem * +TagItemToPoolItem(TagItem *item) noexcept +{ + return &ContainerCast(*item, &TagPoolItem::item); +} + +TagItem * +tag_pool_get_item(TagType type, std::string_view value) noexcept +{ + const auto [position, inserted] = + tag_pool.insert_check_if(TagPoolKey{value, type}, + TagPoolItem::CanIncrementRef{}); + + if (inserted) { + auto *pool_item = TagPoolItem::Create(type, value); + tag_pool.insert_commit(position, *pool_item); + return &pool_item->item; + } else { + ++position->ref; + return &position->item; + } +} + +TagItem * +tag_pool_dup_item(TagItem *item) noexcept +{ + TagPoolItem *pool_item = TagItemToPoolItem(item); + + assert(pool_item->ref > 0); + + if (pool_item->ref < TagPoolItem::MAX_REF) { + ++pool_item->ref; + return item; + } else { + /* the reference counter overflows above MAX_REF; + obtain a reference to a different TagPoolItem which + isn't yet "full" */ + return tag_pool_get_item(item->type, item->value); + } +} + +void +tag_pool_put_item(TagItem *item) noexcept +{ + TagPoolItem *const pool_item = TagItemToPoolItem(item); + assert(pool_item->ref > 0); + --pool_item->ref; + + if (pool_item->ref > 0) + return; + + tag_pool.erase(tag_pool.iterator_to(*pool_item)); + DeleteVarSize(pool_item); +} diff --git a/src/tag/Pool.hxx b/src/tag/Pool.hxx new file mode 100644 index 0000000..a5c879f --- /dev/null +++ b/src/tag/Pool.hxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_POOL_HXX +#define MPD_TAG_POOL_HXX + +#include "thread/Mutex.hxx" + +#include +#include + +enum TagType : uint8_t; + +extern Mutex tag_pool_lock; + +struct TagItem; + +[[nodiscard]] +TagItem * +tag_pool_get_item(TagType type, std::string_view value) noexcept; + +[[nodiscard]] +TagItem * +tag_pool_dup_item(TagItem *item) noexcept; + +void +tag_pool_put_item(TagItem *item) noexcept; + +#endif diff --git a/src/tag/ReplayGainInfo.cxx b/src/tag/ReplayGainInfo.cxx new file mode 100644 index 0000000..ea6383f --- /dev/null +++ b/src/tag/ReplayGainInfo.cxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ReplayGainInfo.hxx" +#include "config/ReplayGainConfig.hxx" + +#include + +float +ReplayGainTuple::CalculateScale(const ReplayGainConfig &config) const noexcept +{ + float scale; + + if (IsDefined()) { + scale = std::pow(10.0f, gain / 20.0f); + scale *= config.preamp; + if (scale > 15.0f) + scale = 15.0f; + + if (config.limit && scale * peak > 1.0f) + scale = 1.0f / peak; + } else + scale = config.missing_preamp; + + return scale; +} diff --git a/src/tag/ReplayGainInfo.hxx b/src/tag/ReplayGainInfo.hxx new file mode 100644 index 0000000..de3297c --- /dev/null +++ b/src/tag/ReplayGainInfo.hxx @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_REPLAY_GAIN_INFO_HXX +#define MPD_REPLAY_GAIN_INFO_HXX + +#include "ReplayGainMode.hxx" + +struct ReplayGainConfig; + +struct ReplayGainTuple { + float gain; + float peak; + + void Clear() { + gain = -200; + peak = 0.0; + } + + constexpr bool IsDefined() const { + return gain > -100; + } + + static constexpr ReplayGainTuple Undefined() noexcept { + return {-200.0f, 0.0f}; + } + + [[gnu::pure]] + float CalculateScale(const ReplayGainConfig &config) const noexcept; +}; + +struct ReplayGainInfo { + ReplayGainTuple track, album; + + constexpr bool IsDefined() const noexcept { + 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) + : (track.IsDefined() ? track : album); + } + + void Clear() noexcept { + track.Clear(); + album.Clear(); + } +}; + +#endif diff --git a/src/tag/ReplayGainParser.cxx b/src/tag/ReplayGainParser.cxx new file mode 100644 index 0000000..e940b72 --- /dev/null +++ b/src/tag/ReplayGainParser.cxx @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ReplayGainParser.hxx" +#include "VorbisComment.hxx" +#include "ReplayGainInfo.hxx" +#include "util/ASCII.hxx" +#include "util/CNumberParser.hxx" + +#include + +template +static bool +ParseReplayGainTagTemplate(ReplayGainInfo &info, const T t) noexcept +{ + const char *value; + + if ((value = t["replaygain_track_gain"]) != nullptr) { + info.track.gain = ParseFloat(value); + return true; + } else if ((value = t["replaygain_album_gain"]) != nullptr) { + info.album.gain = ParseFloat(value); + return true; + } else if ((value = t["replaygain_track_peak"]) != nullptr) { + info.track.peak = ParseFloat(value); + return true; + } else if ((value = t["replaygain_album_peak"]) != nullptr) { + info.album.peak = ParseFloat(value); + return true; + } else + return false; + +} + +bool +ParseReplayGainTag(ReplayGainInfo &info, + const char *name, const char *value) noexcept +{ + assert(name != nullptr); + assert(value != nullptr); + + struct NameValue { + const char *name; + const char *value; + + [[gnu::pure]] + const char *operator[](const char *n) const noexcept { + return StringEqualsCaseASCII(name, n) + ? value + : nullptr; + } + }; + + return ParseReplayGainTagTemplate(info, NameValue{name, value}); +} + +bool +ParseReplayGainVorbis(ReplayGainInfo &info, std::string_view entry) noexcept +{ + struct VorbisCommentEntry { + std::string_view entry; + + [[gnu::pure]] + const char *operator[](std::string_view n) const noexcept { + return GetVorbisCommentValue(entry, n).data(); + } + }; + + return ParseReplayGainTagTemplate(info, VorbisCommentEntry{entry}); +} diff --git a/src/tag/ReplayGainParser.hxx b/src/tag/ReplayGainParser.hxx new file mode 100644 index 0000000..8a01632 --- /dev/null +++ b/src/tag/ReplayGainParser.hxx @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_REPLAY_GAIN_HXX +#define MPD_TAG_REPLAY_GAIN_HXX + +#include + +struct ReplayGainInfo; + +bool +ParseReplayGainTag(ReplayGainInfo &info, + const char *name, const char *value) noexcept; + +bool +ParseReplayGainVorbis(ReplayGainInfo &info, std::string_view entry) noexcept; + +#endif diff --git a/src/tag/RiffFormat.hxx b/src/tag/RiffFormat.hxx new file mode 100644 index 0000000..e55a1a0 --- /dev/null +++ b/src/tag/RiffFormat.hxx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_RIFF_FORMAT_HXX +#define MPD_RIFF_FORMAT_HXX + +#include + +struct RiffFileHeader { + char id[4]; + uint32_t size; + char format[4]; +}; + +static_assert(sizeof(RiffFileHeader) == 12); + +struct RiffChunkHeader { + char id[4]; + uint32_t size; +}; + +static_assert(sizeof(RiffChunkHeader) == 8); + +struct RiffFmtChunk { + static constexpr uint16_t TAG_PCM = 1; + + uint16_t tag; + uint16_t channels; + uint32_t sample_rate; + uint32_t byte_rate; + uint16_t block_align; + uint16_t bits_per_sample; +}; + +static_assert(sizeof(RiffFmtChunk) == 16); + +#endif diff --git a/src/tag/RiffId3.cxx b/src/tag/RiffId3.cxx new file mode 100644 index 0000000..9020278 --- /dev/null +++ b/src/tag/RiffId3.cxx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "RiffId3.hxx" +#include "RiffFormat.hxx" +#include "input/InputStream.hxx" +#include "util/ByteOrder.hxx" +#include "util/SpanCast.hxx" + +#include +#include + +#include + +size_t +riff_seek_id3(InputStream &is, std::unique_lock &lock) +{ + /* seek to the beginning and read the RIFF header */ + + is.Rewind(lock); + + RiffFileHeader header; + is.ReadFull(lock, ReferenceAsWritableBytes(header)); + if (memcmp(header.id, "RIFF", 4) != 0 || + (is.KnownSize() && FromLE32(header.size) > is.GetSize())) + throw std::runtime_error("Not a RIFF file"); + + while (true) { + /* read the chunk header */ + + RiffChunkHeader chunk; + is.ReadFull(lock, ReferenceAsWritableBytes(chunk)); + + size_t size = FromLE32(chunk.size); + if (size > size_t(std::numeric_limits::max())) + /* too dangerous, bail out: possible integer + underflow when casting to off_t */ + throw std::runtime_error("RIFF chunk is too large"); + + if (memcmp(chunk.id, "id3 ", 4) == 0 || + memcmp(chunk.id, "ID3 ", 4) == 0) + /* found it! */ + return size; + + if (size % 2 != 0) + /* pad byte */ + ++size; + + is.Skip(lock, size); + } +} diff --git a/src/tag/RiffId3.hxx b/src/tag/RiffId3.hxx new file mode 100644 index 0000000..9c86853 --- /dev/null +++ b/src/tag/RiffId3.hxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/** \file + * + * A parser for the RIFF file format (e.g. WAV). + */ + +#ifndef MPD_RIFF_ID3_HXX +#define MPD_RIFF_ID3_HXX + +#include "thread/Mutex.hxx" + +#include + +class InputStream; + +/** + * Seeks the RIFF file to the ID3 chunk. + * + * Throws std::runtime_error on error. + * + * @param is a locked #InputStream + * @return the size of the ID3 chunk + */ +size_t +riff_seek_id3(InputStream &is, std::unique_lock &lock); + +#endif diff --git a/src/tag/Rva2.cxx b/src/tag/Rva2.cxx new file mode 100644 index 0000000..656a612 --- /dev/null +++ b/src/tag/Rva2.cxx @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Rva2.hxx" +#include "ReplayGainInfo.hxx" + +#include + +#include + +#include + +enum class Rva2Channel : uint8_t { + OTHER = 0x00, + MASTER_VOLUME = 0x01, + FRONT_RIGHT = 0x02, + FRONT_LEFT = 0x03, + BACK_RIGHT = 0x04, + BACK_LEFT = 0x05, + FRONT_CENTRE = 0x06, + BACK_CENTRE = 0x07, + SUBWOOFER = 0x08 +}; + +struct Rva2Data { + Rva2Channel type; + uint8_t volume_adjustment[2]; + uint8_t peak_bits; +}; + +static inline id3_length_t +rva2_peak_bytes(const Rva2Data &data) +{ + return (data.peak_bits + 7) / 8; +} + +static inline int +rva2_fixed_volume_adjustment(const Rva2Data &data) +{ + signed int voladj_fixed; + voladj_fixed = (data.volume_adjustment[0] << 8) | + data.volume_adjustment[1]; + voladj_fixed |= -(voladj_fixed & 0x8000); + return voladj_fixed; +} + +static inline float +rva2_float_volume_adjustment(const Rva2Data &data) +{ + /* + * "The volume adjustment is encoded as a fixed point decibel + * value, 16 bit signed integer representing (adjustment*512), + * giving +/- 64 dB with a precision of 0.001953125 dB." + */ + + return (float)rva2_fixed_volume_adjustment(data) / (float)512; +} + +static inline bool +rva2_apply_data(ReplayGainInfo &rgi, + const Rva2Data &data, const id3_latin1_t *id) +{ + if (data.type != Rva2Channel::MASTER_VOLUME) + return false; + + float volume_adjustment = rva2_float_volume_adjustment(data); + + if (strcmp((const char *)id, "album") == 0) { + rgi.album.gain = volume_adjustment; + } else if (strcmp((const char *)id, "track") == 0) { + rgi.track.gain = volume_adjustment; + } else { + rgi.album.gain = volume_adjustment; + rgi.track.gain = volume_adjustment; + } + + return true; +} + +static bool +rva2_apply_frame(ReplayGainInfo &replay_gain_info, + const struct id3_frame *frame) +{ + const id3_latin1_t *id = id3_field_getlatin1(id3_frame_field(frame, 0)); + id3_length_t length; + const id3_byte_t *data = + id3_field_getbinarydata(id3_frame_field(frame, 1), &length); + + if (id == nullptr || data == nullptr) + return false; + + /* + * "The 'identification' string is used to identify the + * situation and/or device where this adjustment should apply. + * The following is then repeated for every channel + * + * Type of channel $xx + * Volume adjustment $xx xx + * Bits representing peak $xx + * Peak volume $xx (xx ...)" + */ + + while (length >= 4) { + const Rva2Data &d = *(const Rva2Data *)data; + unsigned int peak_bytes = rva2_peak_bytes(d); + if (4 + peak_bytes > length) + break; + + if (rva2_apply_data(replay_gain_info, d, id)) + return true; + + data += 4 + peak_bytes; + length -= 4 + peak_bytes; + } + + return false; +} + +bool +tag_rva2_parse(const struct id3_tag *tag, + ReplayGainInfo &replay_gain_info) noexcept +{ + bool found = false; + + /* Loop through all RVA2 frames as some programs (e.g. mp3gain) store + track and album gain in separate tags */ + const struct id3_frame *frame; + for (unsigned i = 0; + (frame = id3_tag_findframe(tag, "RVA2", i)) != nullptr; + ++i) + if (rva2_apply_frame(replay_gain_info, frame)) + found = true; + + return found; +} diff --git a/src/tag/Rva2.hxx b/src/tag/Rva2.hxx new file mode 100644 index 0000000..6d62dc8 --- /dev/null +++ b/src/tag/Rva2.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_RVA2_HXX +#define MPD_TAG_RVA2_HXX + +struct id3_tag; +struct ReplayGainInfo; + +/** + * Parse the RVA2 tag, and fill the #ReplayGainInfo struct. This is + * used by decoder plugins with ID3 support. + * + * @return true on success + */ +bool +tag_rva2_parse(const struct id3_tag *tag, + ReplayGainInfo &replay_gain_info) noexcept; + +#endif diff --git a/src/tag/Settings.cxx b/src/tag/Settings.cxx new file mode 100644 index 0000000..4c3d6eb --- /dev/null +++ b/src/tag/Settings.cxx @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Settings.hxx" +#include "Type.hxx" + +TagMask global_tag_mask = TagMask::All() & ~TagMask(TAG_COMMENT); diff --git a/src/tag/Settings.hxx b/src/tag/Settings.hxx new file mode 100644 index 0000000..5e6d75b --- /dev/null +++ b/src/tag/Settings.hxx @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_SETTINGS_HXX +#define MPD_TAG_SETTINGS_HXX + +#include "Mask.hxx" + +extern TagMask global_tag_mask; + +[[gnu::const]] +static inline bool +IsTagEnabled(TagType tag) noexcept +{ + return global_tag_mask.Test(tag); +} + +[[gnu::const]] +static inline bool +IsTagEnabled(unsigned tag) noexcept +{ + return IsTagEnabled(TagType(tag)); +} + +#endif diff --git a/src/tag/Sort.cxx b/src/tag/Sort.cxx new file mode 100644 index 0000000..21d4466 --- /dev/null +++ b/src/tag/Sort.cxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Sort.hxx" +#include "Tag.hxx" + +#include + +#include +#include + +[[gnu::pure]] +static bool +CompareNumeric(const char *a, const char *b) noexcept +{ + long a_value = strtol(a, nullptr, 10); + long b_value = strtol(b, nullptr, 10); + + return a_value < b_value; +} + +bool +CompareTags(TagType type, bool descending, const Tag &a, const Tag &b) noexcept +{ + const char *a_value = a.GetSortValue(type); + const char *b_value = b.GetSortValue(type); + + if (descending) { + using std::swap; + swap(a_value, b_value); + } + + switch (type) { + case TAG_DISC: + case TAG_TRACK: + return CompareNumeric(a_value, b_value); + + default: + return strcmp(a_value, b_value) < 0; + } +} diff --git a/src/tag/Sort.hxx b/src/tag/Sort.hxx new file mode 100644 index 0000000..ed1ce48 --- /dev/null +++ b/src/tag/Sort.hxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include + +enum TagType : uint8_t; +struct Tag; + +[[gnu::pure]] +bool +CompareTags(TagType type, bool descending, + const Tag &a, const Tag &b) noexcept; diff --git a/src/tag/Table.cxx b/src/tag/Table.cxx new file mode 100644 index 0000000..d2b3c66 --- /dev/null +++ b/src/tag/Table.cxx @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Table.hxx" +#include "util/ASCII.hxx" +#include "util/StringCompare.hxx" + +#include + +/** + * Looks up a string in a tag translation table (case sensitive). + * Returns TAG_NUM_OF_ITEM_TYPES if the specified name was not found + * in the table. + */ +TagType +tag_table_lookup(const struct tag_table *table, const char *name) noexcept +{ + for (; table->name != nullptr; ++table) + if (strcmp(name, table->name) == 0) + return table->type; + + return TAG_NUM_OF_ITEM_TYPES; +} + +TagType +tag_table_lookup(const struct tag_table *table, std::string_view name) noexcept +{ + for (; table->name != nullptr; ++table) + if (name == table->name) + return table->type; + + return TAG_NUM_OF_ITEM_TYPES; +} + +/** + * Looks up a string in a tag translation table (case insensitive). + * Returns TAG_NUM_OF_ITEM_TYPES if the specified name was not found + * in the table. + */ +TagType +tag_table_lookup_i(const struct tag_table *table, const char *name) noexcept +{ + for (; table->name != nullptr; ++table) + if (StringEqualsCaseASCII(name, table->name)) + return table->type; + + return TAG_NUM_OF_ITEM_TYPES; +} + +TagType +tag_table_lookup_i(const struct tag_table *table, + std::string_view name) noexcept +{ + for (; table->name != nullptr; ++table) + if (StringIsEqualIgnoreCase(name, table->name)) + return table->type; + + return TAG_NUM_OF_ITEM_TYPES; +} + +const char * +tag_table_lookup(const tag_table *table, TagType type) noexcept +{ + for (; table->name != nullptr; ++table) + if (table->type == type) + return table->name; + + return nullptr; +} diff --git a/src/tag/Table.hxx b/src/tag/Table.hxx new file mode 100644 index 0000000..19e9831 --- /dev/null +++ b/src/tag/Table.hxx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_TABLE_HXX +#define MPD_TAG_TABLE_HXX + +#include "Type.hxx" + +#include + +struct tag_table { + const char *name; + + TagType type; +}; + +/** + * Looks up a string in a tag translation table (case sensitive). + * Returns TAG_NUM_OF_ITEM_TYPES if the specified name was not found + * in the table. + */ +[[gnu::pure]] +TagType +tag_table_lookup(const tag_table *table, const char *name) noexcept; + +[[gnu::pure]] +TagType +tag_table_lookup(const tag_table *table, std::string_view name) noexcept; + +/** + * Looks up a string in a tag translation table (case insensitive). + * Returns TAG_NUM_OF_ITEM_TYPES if the specified name was not found + * in the table. + */ +[[gnu::pure]] +TagType +tag_table_lookup_i(const tag_table *table, const char *name) noexcept; + +[[gnu::pure]] +TagType +tag_table_lookup_i(const tag_table *table, std::string_view name) noexcept; + +/** + * Looks up a #TagType in a tag translation table and returns its + * string representation. Returns nullptr if the specified type was + * not found in the table. + */ +[[gnu::pure]] +const char * +tag_table_lookup(const tag_table *table, TagType type) noexcept; + +#endif diff --git a/src/tag/Tag.cxx b/src/tag/Tag.cxx new file mode 100644 index 0000000..4ca50b8 --- /dev/null +++ b/src/tag/Tag.cxx @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Tag.hxx" +#include "Pool.hxx" +#include "Builder.hxx" + +#include + +bool +Tag::operator==(const Tag &other) const noexcept { + return (this == &other) ? true : + duration == other.duration + && has_playlist == other.has_playlist + && num_items == other.num_items + && std::equal(begin(), end(), other.begin(), other.end()); +} + +void +Tag::Clear() noexcept +{ + duration = SignedSongTime::Negative(); + has_playlist = false; + + if (num_items > 0) { + assert(items != nullptr); + const std::scoped_lock protect{tag_pool_lock}; + for (unsigned i = 0; i < num_items; ++i) + tag_pool_put_item(items[i]); + num_items = 0; + } + + delete[] items; + items = nullptr; +} + +Tag::Tag(const Tag &other) noexcept + :duration(other.duration), has_playlist(other.has_playlist), + num_items(other.num_items) +{ + if (num_items > 0) { + items = new TagItem *[num_items]; + + const std::scoped_lock protect{tag_pool_lock}; + for (unsigned i = 0; i < num_items; i++) + items[i] = tag_pool_dup_item(other.items[i]); + } +} + +Tag +Tag::Merge(const Tag &base, const Tag &add) noexcept +{ + TagBuilder builder(add); + builder.Complement(base); + return builder.Commit(); +} + +std::unique_ptr +Tag::MergePtr(const Tag &base, const Tag &add) noexcept +{ + TagBuilder builder(add); + builder.Complement(base); + return builder.CommitNew(); +} + +std::unique_ptr +Tag::Merge(std::unique_ptr base, std::unique_ptr add) noexcept +{ + if (add == nullptr) + return base; + + if (base == nullptr) + return add; + + return MergePtr(*base, *add); +} + +std::unique_ptr +Tag::Merge(const Tag *base, const Tag *add) noexcept +{ + if (base == nullptr && add == nullptr) + /* no tag */ + return nullptr; + + if (base == nullptr) + return std::make_unique(*add); + + if (add == nullptr) + return std::make_unique(*base); + + return MergePtr(*base, *add); +} + +const char * +Tag::GetValue(TagType type) const noexcept +{ + assert(type < TAG_NUM_OF_ITEM_TYPES); + + for (const auto &item : *this) + if (item.type == type) + return item.value; + + return nullptr; +} + +bool +Tag::HasType(TagType type) const noexcept +{ + return GetValue(type) != nullptr; +} + +static TagType +DecaySort(TagType type) noexcept +{ + switch (type) { + case TAG_ARTIST_SORT: + return TAG_ARTIST; + + case TAG_ALBUM_SORT: + return TAG_ALBUM; + + case TAG_ALBUM_ARTIST_SORT: + return TAG_ALBUM_ARTIST; + + default: + return TAG_NUM_OF_ITEM_TYPES; + } +} + +static TagType +Fallback(TagType type) noexcept +{ + switch (type) { + case TAG_ALBUM_ARTIST: + return TAG_ARTIST; + + case TAG_MUSICBRAINZ_ALBUMARTISTID: + return TAG_MUSICBRAINZ_ARTISTID; + + default: + return TAG_NUM_OF_ITEM_TYPES; + } +} + +const char * +Tag::GetSortValue(TagType type) const noexcept +{ + const char *value = GetValue(type); + if (value != nullptr) + return value; + + /* try without *_SORT */ + const auto no_sort_type = DecaySort(type); + if (no_sort_type != TAG_NUM_OF_ITEM_TYPES) { + value = GetValue(no_sort_type); + if (value != nullptr) + return value; + } + + /* fall back from TAG_ALBUM_ARTIST to TAG_ALBUM */ + + type = Fallback(type); + if (type != TAG_NUM_OF_ITEM_TYPES) + return GetSortValue(type); + + if (no_sort_type != TAG_NUM_OF_ITEM_TYPES) { + type = Fallback(no_sort_type); + if (type != TAG_NUM_OF_ITEM_TYPES) + return GetSortValue(type); + } + + /* finally fall back to empty string */ + + return ""; +} diff --git a/src/tag/Tag.hxx b/src/tag/Tag.hxx new file mode 100644 index 0000000..dbfdb49 --- /dev/null +++ b/src/tag/Tag.hxx @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_HXX +#define MPD_TAG_HXX + +#include "Type.hxx" // IWYU pragma: export +#include "Item.hxx" // IWYU pragma: export +#include "Chrono.hxx" +#include "util/DereferenceIterator.hxx" + +#include +#include + +/** + * The meta information about a song file. It is a MPD specific + * subset of tags (e.g. from ID3, vorbis comments, ...). + */ +struct Tag { + /** + * The duration of the song. A negative value means that the + * length is unknown. + */ + SignedSongTime duration = SignedSongTime::Negative(); + + /** + * Does this file have an embedded playlist (e.g. embedded CUE + * sheet)? + */ + bool has_playlist = false; + + /** the total number of tag items in the #items array */ + unsigned short num_items = 0; + + /** an array of tag items */ + TagItem **items = nullptr; + + /** + * Create an empty tag. + */ + Tag() = default; + + Tag(const Tag &other) noexcept; + + Tag(Tag &&other) noexcept + :duration(other.duration), has_playlist(other.has_playlist), + num_items(other.num_items), items(other.items) { + other.items = nullptr; + other.num_items = 0; + } + + /** + * Free the tag object and all its items. + */ + ~Tag() noexcept { + Clear(); + } + + Tag &operator=(const Tag &other) = delete; + + Tag &operator=(Tag &&other) noexcept { + duration = other.duration; + has_playlist = other.has_playlist; + MoveItemsFrom(std::move(other)); + return *this; + } + + bool operator==(const Tag &other) const noexcept; + + /** + * Similar to the move operator, but move only the #TagItem + * array. + */ + void MoveItemsFrom(Tag &&other) noexcept { + std::swap(items, other.items); + std::swap(num_items, other.num_items); + } + + /** + * Returns true if the tag contains no items. This ignores + * the "duration" attribute. + */ + bool IsEmpty() const noexcept { + return num_items == 0; + } + + /** + * Returns true if the tag contains any information. + */ + bool IsDefined() const noexcept { + return !IsEmpty() || !duration.IsNegative(); + } + + /** + * Clear everything, as if this was a new Tag object. + */ + void Clear() noexcept; + + /** + * Merges the data from two tags. If both tags share data for the + * same TagType, only data from "add" is used. + * + * @return a newly allocated tag + */ + static Tag Merge(const Tag &base, + const Tag &add) noexcept; + + static std::unique_ptr MergePtr(const Tag &base, + const Tag &add) noexcept; + + /** + * Merges the data from two tags. Any of the two may be nullptr. Both + * are freed by this function. + * + * @return a newly allocated tag + */ + static std::unique_ptr Merge(std::unique_ptr base, + std::unique_ptr add) noexcept; + + /** + * Merges the data from two tags. Any of the two may be nullptr. + * + * @return a newly allocated tag (or nullptr if both + * parameters are nullptr) + */ + static std::unique_ptr Merge(const Tag *base, + const Tag *add) noexcept; + + /** + * Returns the first value of the specified tag type, or + * nullptr if none is present in this tag object. + */ + [[gnu::pure]] + const char *GetValue(TagType type) const noexcept; + + /** + * Checks whether the tag contains one or more items with + * the specified type. + */ + [[gnu::pure]] + bool HasType(TagType type) const noexcept; + + /** + * Returns a value for sorting on the specified type, with + * automatic fallbacks to the next best tag type + * (e.g. #TAG_ALBUM_ARTIST falls back to #TAG_ARTIST). If + * there is no such value, returns an empty string. + */ + [[gnu::pure]] [[gnu::returns_nonnull]] + const char *GetSortValue(TagType type) const noexcept; + + using const_iterator = DereferenceIterator; + + const_iterator begin() const noexcept { + return const_iterator{items}; + } + + const_iterator end() const noexcept { + return const_iterator{items + num_items}; + } +}; + +#endif diff --git a/src/tag/Type.hxx b/src/tag/Type.hxx new file mode 100644 index 0000000..59e845a --- /dev/null +++ b/src/tag/Type.hxx @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include + +/** + * Codes for the type of a tag item. + */ +enum TagType : uint8_t { + TAG_ARTIST, + TAG_ARTIST_SORT, + TAG_ALBUM, + TAG_ALBUM_SORT, + TAG_ALBUM_ARTIST, + TAG_ALBUM_ARTIST_SORT, + TAG_TITLE, + TAG_TITLE_SORT, + TAG_TRACK, + TAG_NAME, + TAG_GENRE, + TAG_MOOD, + TAG_DATE, + TAG_ORIGINAL_DATE, + TAG_COMPOSER, + TAG_COMPOSERSORT, + TAG_PERFORMER, + TAG_CONDUCTOR, + TAG_WORK, + TAG_MOVEMENT, + TAG_MOVEMENTNUMBER, + TAG_SHOWMOVEMENT, + TAG_ENSEMBLE, + TAG_LOCATION, + TAG_GROUPING, + TAG_COMMENT, + TAG_DISC, + TAG_LABEL, + + TAG_MUSICBRAINZ_ARTISTID, + TAG_MUSICBRAINZ_ALBUMID, + TAG_MUSICBRAINZ_ALBUMARTISTID, + TAG_MUSICBRAINZ_TRACKID, + TAG_MUSICBRAINZ_RELEASETRACKID, + TAG_MUSICBRAINZ_WORKID, + TAG_MUSICBRAINZ_RELEASEGROUPID, + + TAG_NUM_OF_ITEM_TYPES +}; diff --git a/src/tag/VisitFallback.hxx b/src/tag/VisitFallback.hxx new file mode 100644 index 0000000..8c7919d --- /dev/null +++ b/src/tag/VisitFallback.hxx @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_VISIT_FALLBACK_HXX +#define MPD_TAG_VISIT_FALLBACK_HXX + +#include "Fallback.hxx" +#include "Tag.hxx" + +template +bool +VisitTagType(const Tag &tag, TagType type, F &&f) noexcept +{ + bool found = false; + + for (const auto &item : tag) { + if (item.type == type) { + found = true; + f(item.value); + } + } + + return found; +} + +template +bool +VisitTagWithFallback(const Tag &tag, TagType type, F &&f) noexcept +{ + return ApplyTagWithFallback(type, + [&](TagType type2) { + return VisitTagType(tag, type2, f); + }); +} + +template +void +VisitTagWithFallbackOrEmpty(const Tag &tag, TagType type, F &&f) noexcept +{ + if (!VisitTagWithFallback(tag, type, f)) + f(""); +} + +#endif diff --git a/src/tag/VorbisComment.cxx b/src/tag/VorbisComment.cxx new file mode 100644 index 0000000..837b5e9 --- /dev/null +++ b/src/tag/VorbisComment.cxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "VorbisComment.hxx" +#include "util/StringCompare.hxx" + +#include + +std::string_view +GetVorbisCommentValue(std::string_view entry, std::string_view name) noexcept +{ + assert(!name.empty()); + + if (StringStartsWithIgnoreCase(entry, name) && + entry.size() > name.size() && + entry[name.size()] == '=') + return entry.substr(name.size() + 1); + + return {}; +} diff --git a/src/tag/VorbisComment.hxx b/src/tag/VorbisComment.hxx new file mode 100644 index 0000000..0065329 --- /dev/null +++ b/src/tag/VorbisComment.hxx @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TAG_VORBIS_COMMENT_HXX +#define MPD_TAG_VORBIS_COMMENT_HXX + +#include + +/** + * Checks if the specified name matches the entry's name, and if yes, + * returns the comment value. + */ +[[gnu::pure]] +std::string_view +GetVorbisCommentValue(std::string_view entry, std::string_view name) noexcept; + +#endif diff --git a/src/tag/meson.build b/src/tag/meson.build new file mode 100644 index 0000000..99affde --- /dev/null +++ b/src/tag/meson.build @@ -0,0 +1,73 @@ +generate_parse_name = executable( + 'GenParseName', + 'GenParseName.cxx', + 'Names.cxx', + native: true, +) + +parse_name_cxx = custom_target( + 'RunGenParseName', + output: ['ParseName2.cxx'], + capture: true, + command : [ + generate_parse_name, + ], +) + +tag_sources = [ + 'Tag.cxx', + 'Builder.cxx', + 'Handler.cxx', + 'Settings.cxx', + 'Sort.cxx', + 'Config.cxx', + 'ParseName.cxx', + parse_name_cxx, + 'Names.cxx', + 'FixString.cxx', + 'Pool.cxx', + 'Table.cxx', + 'Format.cxx', + 'VorbisComment.cxx', + 'ReplayGainInfo.cxx', + 'ReplayGainParser.cxx', + 'MixRampParser.cxx', + 'Generic.cxx', + 'Id3MusicBrainz.cxx', + 'Id3Picture.cxx', + 'ApeLoader.cxx', + 'ApeReplayGain.cxx', + 'ApeTag.cxx', +] + +libid3tag_dep = dependency('id3tag', required: get_option('id3tag')) +conf.set('ENABLE_ID3TAG', libid3tag_dep.found()) +if libid3tag_dep.found() + tag_sources += [ + 'Id3Load.cxx', + 'Id3Scan.cxx', + 'Id3MixRamp.cxx', + 'Id3ReplayGain.cxx', + 'Rva2.cxx', + 'RiffId3.cxx', + 'Aiff.cxx', + ] +endif + +tag = static_library( + 'tag', + tag_sources, + include_directories: inc, + dependencies: [ + fmt_dep, + libid3tag_dep, + ], +) + +tag_dep = declare_dependency( + link_with: tag, + dependencies: [ + time_dep, + util_dep, + ], +) diff --git a/src/thread/AsyncWaiter.hxx b/src/thread/AsyncWaiter.hxx new file mode 100644 index 0000000..6c9f4f3 --- /dev/null +++ b/src/thread/AsyncWaiter.hxx @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef ASYNC_WAITER_HXX +#define ASYNC_WAITER_HXX + +#include "Mutex.hxx" +#include "Cond.hxx" + +#include + +/** + * A helper class which can be used to implement asynchronous + * operations which can be waited on. Errors are rethrown into the + * waiting thread. + */ +class AsyncWaiter { + mutable Mutex mutex; + Cond cond; + + std::exception_ptr error; + + bool done = false; + +public: + bool IsDone() const noexcept { + const std::scoped_lock lock{mutex}; + return done; + } + + void Wait() { + std::unique_lock lock(mutex); + cond.wait(lock, [this]{ return done; }); + + if (error) + std::rethrow_exception(error); + } + + void SetDone() noexcept { + const std::scoped_lock lock{mutex}; + done = true; + cond.notify_one(); + } + + void SetError(std::exception_ptr e) noexcept { + const std::scoped_lock lock{mutex}; + error = std::move(e); + done = true; + cond.notify_one(); + } +}; + +#endif diff --git a/src/thread/Cond.hxx b/src/thread/Cond.hxx new file mode 100644 index 0000000..dccd258 --- /dev/null +++ b/src/thread/Cond.hxx @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_COND_HXX +#define THREAD_COND_HXX + +#ifdef _WIN32 + +#include "WindowsCond.hxx" +class Cond : public WindowsCond {}; + +#else + +#include +using Cond = std::condition_variable; + +#endif + +#endif diff --git a/src/thread/CriticalSection.hxx b/src/thread/CriticalSection.hxx new file mode 100644 index 0000000..43bd024 --- /dev/null +++ b/src/thread/CriticalSection.hxx @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_CRITICAL_SECTION_HXX +#define THREAD_CRITICAL_SECTION_HXX + +#include + +/** + * Wrapper for a CRITICAL_SECTION, backend for the Mutex class. + */ +class CriticalSection { + friend class WindowsCond; + + CRITICAL_SECTION critical_section; + +public: + CriticalSection() noexcept { + ::InitializeCriticalSection(&critical_section); + } + + ~CriticalSection() noexcept { + ::DeleteCriticalSection(&critical_section); + } + + CriticalSection(const CriticalSection &other) = delete; + CriticalSection &operator=(const CriticalSection &other) = delete; + + void lock() noexcept { + ::EnterCriticalSection(&critical_section); + } + + bool try_lock() noexcept { + return ::TryEnterCriticalSection(&critical_section) != 0; + } + + void unlock() noexcept { + ::LeaveCriticalSection(&critical_section); + } +}; + +#endif diff --git a/src/thread/Future.hxx b/src/thread/Future.hxx new file mode 100644 index 0000000..3e4306d --- /dev/null +++ b/src/thread/Future.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef THREAD_FUTURE_HXX +#define THREAD_FUTURE_HXX + +#ifdef _WIN32 + +#include "WindowsFuture.hxx" + +template +using Future = WinFuture; +template +using Promise = WinPromise; + +#else + +#include + +template +using Future = std::future; +template +using Promise = std::promise; + +#endif + +#endif diff --git a/src/thread/Id.hxx b/src/thread/Id.hxx new file mode 100644 index 0000000..74e706b --- /dev/null +++ b/src/thread/Id.hxx @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_ID_HXX +#define THREAD_ID_HXX + +#ifdef _WIN32 +#include +#else +#include +#endif + +/** + * A low-level identification for a thread. Designed to work with + * existing threads, such as the main thread. Mostly useful for + * debugging code. + */ +class ThreadId { +#ifdef _WIN32 + DWORD id; +#else + pthread_t id; +#endif + +public: + /** + * No initialisation. + */ + ThreadId() noexcept = default; + +#ifdef _WIN32 + constexpr ThreadId(DWORD _id) noexcept:id(_id) {} +#else + constexpr ThreadId(pthread_t _id) noexcept:id(_id) {} +#endif + + static constexpr ThreadId Null() noexcept { +#ifdef _WIN32 + return 0; +#else + return pthread_t(); +#endif + } + + [[gnu::pure]] + bool IsNull() const noexcept { + return *this == Null(); + } + + /** + * Return the current thread's id . + */ + [[gnu::pure]] + static const ThreadId GetCurrent() noexcept { +#ifdef _WIN32 + return ::GetCurrentThreadId(); +#else + return pthread_self(); +#endif + } + + [[gnu::pure]] + bool operator==(const ThreadId &other) const noexcept { + /* note: not using pthread_equal() because that + function "is undefined if either thread ID is not + valid so we can't safely use it on + default-constructed values" (comment from + libstdc++) - and if both libstdc++ and libc++ get + away with this, we can do it as well */ + return id == other.id; + } + + /** + * Check if this thread is the current thread. + */ + bool IsInside() const noexcept { + return *this == GetCurrent(); + } +}; + +#endif diff --git a/src/thread/Mutex.hxx b/src/thread/Mutex.hxx new file mode 100644 index 0000000..d08e7ae --- /dev/null +++ b/src/thread/Mutex.hxx @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_MUTEX_HXX +#define THREAD_MUTEX_HXX + +#include + +#ifdef _WIN32 + +#include "CriticalSection.hxx" +using Mutex = CriticalSection; +using RecursiveMutex = CriticalSection; + +#else + +using Mutex = std::mutex; +using RecursiveMutex = std::recursive_mutex; + +#endif + +/** + * Within the scope of an instance, this class will keep a #Mutex + * unlocked. + */ +class ScopeUnlock { + Mutex &mutex; + +public: + explicit ScopeUnlock(Mutex &_mutex) noexcept:mutex(_mutex) { + mutex.unlock(); + } + + ~ScopeUnlock() noexcept { + mutex.lock(); + } + + ScopeUnlock(const ScopeUnlock &other) = delete; + ScopeUnlock &operator=(const ScopeUnlock &other) = delete; +}; + +#endif diff --git a/src/thread/Name.hxx b/src/thread/Name.hxx new file mode 100644 index 0000000..113713d --- /dev/null +++ b/src/thread/Name.hxx @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_THREAD_NAME_HXX +#define MPD_THREAD_NAME_HXX + +#include "config.h" + +#if defined(HAVE_PTHREAD_SETNAME_NP) && !defined(__NetBSD__) +# define HAVE_THREAD_NAME +# include +#elif defined(HAVE_PRCTL) +# include +# ifdef PR_SET_NAME +# define HAVE_THREAD_NAME +# endif +#endif + +#ifdef HAVE_THREAD_NAME +#include "lib/fmt/ToBuffer.hxx" +#endif + +static inline void +SetThreadName(const char *name) noexcept +{ +#if defined(HAVE_PTHREAD_SETNAME_NP) && !defined(__NetBSD__) + /* not using pthread_setname_np() on NetBSD because it + requires a non-const pointer argument, which we don't have + here */ + +#ifdef __APPLE__ + pthread_setname_np(name); +#else + pthread_setname_np(pthread_self(), name); +#endif +#elif defined(HAVE_PRCTL) && defined(PR_SET_NAME) + prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); +#else + (void)name; +#endif +} + +template +static inline void +FmtThreadName(const char *fmt, [[maybe_unused]] Args&&... args) noexcept +{ +#ifdef HAVE_THREAD_NAME + SetThreadName(FmtBuffer<16>(fmt, args...)); +#else + (void)fmt; +#endif +} + +#endif diff --git a/src/thread/SafeSingleton.hxx b/src/thread/SafeSingleton.hxx new file mode 100644 index 0000000..373e821 --- /dev/null +++ b/src/thread/SafeSingleton.hxx @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SAFE_SINGLETON_HXX +#define MPD_SAFE_SINGLETON_HXX + +#include "Mutex.hxx" + +/** + * This class manages at most one instance of a specific type. All + * instances of this class share the one object which gets deleted + * when the last instance of this class is destructed. + * + * This class is thread-safe, but the contained class may not be. + */ +template +class SafeSingleton { + static Mutex mutex; + static unsigned ref; + static T *instance; + +public: + template + explicit SafeSingleton(Args&&... args) { + const std::scoped_lock lock{mutex}; + + if (ref == 0) + instance = new T(std::forward(args)...); + + /* increment after creating the instance; this way is + exception-safe, because we must not increment the + reference counter if we throw */ + ++ref; + } + + ~SafeSingleton() noexcept { + const std::scoped_lock lock{mutex}; + if (--ref > 0) + return; + + delete std::exchange(instance, nullptr); + } + + SafeSingleton(const SafeSingleton &) = delete; + SafeSingleton &operator=(const SafeSingleton &) = delete; + + T *get() { + return instance; + } + + T &operator*() noexcept { + return *instance; + } + + T *operator->() noexcept { + return instance; + } +}; + +template +Mutex SafeSingleton::mutex; + +template +unsigned SafeSingleton::ref; + +template +T *SafeSingleton::instance; + +#endif diff --git a/src/thread/Slack.hxx b/src/thread/Slack.hxx new file mode 100644 index 0000000..c140229 --- /dev/null +++ b/src/thread/Slack.hxx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_THREAD_SLACK_HXX +#define MPD_THREAD_SLACK_HXX + +#include "config.h" + +#include + +#ifdef HAVE_PRCTL +#include +#endif + +/** + * Set the current thread's timer slack to the specified number of + * nanoseconds (requires Linux 2.6.28). This allows the kernel to + * merge multiple wakeups, which is a trick to save energy. + */ +static inline void +SetThreadTimerSlackNS(unsigned long slack_ns) noexcept +{ +#if defined(HAVE_PRCTL) && defined(PR_SET_TIMERSLACK) + prctl(PR_SET_TIMERSLACK, slack_ns, 0, 0, 0); +#else + (void)slack_ns; +#endif +} + +template +static inline auto +SetThreadTimerSlack(const std::chrono::duration &slack) noexcept +{ + SetThreadTimerSlackNS(std::chrono::duration_cast(slack).count()); +} + +#endif diff --git a/src/thread/Thread.cxx b/src/thread/Thread.cxx new file mode 100644 index 0000000..ff472df --- /dev/null +++ b/src/thread/Thread.cxx @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Thread.hxx" +#include "system/Error.hxx" + +#ifdef ANDROID +#include "java/Global.hxx" +#endif + +#ifdef _WIN32 +#include // for WaitForSingleObject() +#include // for HWND (needed by winbase.h) +#include // for INFINITE +#endif + +void +Thread::Start() +{ + assert(!IsDefined()); + +#ifdef _WIN32 + handle = ::CreateThread(nullptr, 0, ThreadProc, this, 0, &id); + if (handle == nullptr) + throw MakeLastError("Failed to create thread"); +#else + int e = pthread_create(&handle, nullptr, ThreadProc, this); + + if (e != 0) + throw MakeErrno(e, "Failed to create thread"); +#endif +} + +void +Thread::Join() noexcept +{ + assert(IsDefined()); + assert(!IsInside()); + +#ifdef _WIN32 + ::WaitForSingleObject(handle, INFINITE); + ::CloseHandle(handle); + handle = nullptr; +#else + pthread_join(handle, nullptr); + handle = pthread_t(); +#endif +} + +inline void +Thread::Run() noexcept +{ + f(); + +#ifdef ANDROID + Java::DetachCurrentThread(); +#endif +} + +#ifdef _WIN32 + +DWORD WINAPI +Thread::ThreadProc(LPVOID ctx) noexcept +{ + Thread &thread = *(Thread *)ctx; + + thread.Run(); + return 0; +} + +#else + +void * +Thread::ThreadProc(void *ctx) noexcept +{ + Thread &thread = *(Thread *)ctx; + +#ifndef NDEBUG + thread.inside_handle = pthread_self(); +#endif + + thread.Run(); + + return nullptr; +} + +#endif diff --git a/src/thread/Thread.hxx b/src/thread/Thread.hxx new file mode 100644 index 0000000..bf9f38c --- /dev/null +++ b/src/thread/Thread.hxx @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_THREAD_HXX +#define MPD_THREAD_HXX + +#include "util/BindMethod.hxx" + +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +class Thread { + typedef BoundMethod Function; + const Function f; + +#ifdef _WIN32 + HANDLE handle = nullptr; + DWORD id; +#else + pthread_t handle = pthread_t(); + +#ifndef NDEBUG + /** + * This handle is only used by IsInside(), and is set by the + * thread function. Since #handle is set by pthread_create() + * which is racy, we need this attribute for early checks + * inside the thread function. + */ + pthread_t inside_handle = pthread_t(); +#endif +#endif + +public: + explicit Thread(Function _f) noexcept:f(_f) {} + + Thread(const Thread &) = delete; + Thread &operator=(const Thread &) = delete; + +#ifndef NDEBUG + ~Thread() noexcept { + /* all Thread objects must be destructed manually by calling + Join(), to clean up */ + assert(!IsDefined()); + } +#endif + + bool IsDefined() const noexcept { +#ifdef _WIN32 + return handle != nullptr; +#else + return handle != pthread_t(); +#endif + } + +#ifndef NDEBUG + /** + * Check if this thread is the current thread. + */ + [[gnu::pure]] + bool IsInside() const noexcept { +#ifdef _WIN32 + return GetCurrentThreadId() == id; +#else + /* note: not using pthread_equal() because that + function "is undefined if either thread ID is not + valid so we can't safely use it on + default-constructed values" (comment from + libstdc++) - and if both libstdc++ and libc++ get + away with this, we can do it as well */ + return pthread_self() == inside_handle; +#endif + } +#endif + + /** + * Start the thread. + * + * Throws on error. + */ + void Start(); + + void Join() noexcept; + +private: + void Run() noexcept; + +#ifdef _WIN32 + static DWORD WINAPI ThreadProc(LPVOID ctx) noexcept; +#else + static void *ThreadProc(void *ctx) noexcept; +#endif + +}; + +#endif diff --git a/src/thread/Util.cxx b/src/thread/Util.cxx new file mode 100644 index 0000000..50bd95a --- /dev/null +++ b/src/thread/Util.cxx @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "Util.hxx" +#include "system/Error.hxx" + +#ifdef __linux__ +#include +#include +#include +#elif defined(_WIN32) +#include +#endif + +#ifdef __linux__ + +#ifndef ANDROID + +static int +linux_ioprio_set(int which, int who, int ioprio) noexcept +{ + return syscall(__NR_ioprio_set, which, who, ioprio); +} + +static void +ioprio_set_idle() noexcept +{ + static constexpr int _IOPRIO_WHO_PROCESS = 1; + static constexpr int _IOPRIO_CLASS_IDLE = 3; + static constexpr int _IOPRIO_CLASS_SHIFT = 13; + static constexpr int _IOPRIO_IDLE = + (_IOPRIO_CLASS_IDLE << _IOPRIO_CLASS_SHIFT) | 7; + + linux_ioprio_set(_IOPRIO_WHO_PROCESS, 0, _IOPRIO_IDLE); +} + +#endif /* !ANDROID */ + +/** + * Wrapper for the "sched_setscheduler" system call. We don't use the + * one from the C library because Musl has an intentionally broken + * implementation. + */ +static int +linux_sched_setscheduler(pid_t pid, int sched, + const struct sched_param *param) noexcept +{ + return syscall(__NR_sched_setscheduler, pid, sched, param); +} + +#endif + +void +SetThreadIdlePriority() noexcept +{ +#ifdef __linux__ +#ifdef SCHED_IDLE + static struct sched_param sched_param; + linux_sched_setscheduler(0, SCHED_IDLE, &sched_param); +#endif + +#ifndef ANDROID + /* this system call is forbidden via seccomp on Android 8 and + leads to crash (SIGSYS) */ + ioprio_set_idle(); +#endif + +#elif defined(_WIN32) + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); +#endif +} + +void +SetThreadRealtime() +{ +#ifdef __linux__ + struct sched_param sched_param; + sched_param.sched_priority = 40; + + int policy = SCHED_FIFO; +#ifdef SCHED_RESET_ON_FORK + policy |= SCHED_RESET_ON_FORK; +#endif + + if (linux_sched_setscheduler(0, policy, &sched_param) < 0) + throw MakeErrno("sched_setscheduler failed"); +#endif // __linux__ +} diff --git a/src/thread/Util.hxx b/src/thread/Util.hxx new file mode 100644 index 0000000..f83cc96 --- /dev/null +++ b/src/thread/Util.hxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_UTIL_HXX +#define THREAD_UTIL_HXX + +/** + * Lower the current thread's priority to "idle" (very low). + */ +void +SetThreadIdlePriority() noexcept; + +/** + * Raise the current thread's priority to "real-time" (very high). + * + * Throws std::system_error on error. + */ +void +SetThreadRealtime(); + +#endif diff --git a/src/thread/WindowsCond.hxx b/src/thread/WindowsCond.hxx new file mode 100644 index 0000000..60d199b --- /dev/null +++ b/src/thread/WindowsCond.hxx @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef THREAD_WINDOWS_COND_HXX +#define THREAD_WINDOWS_COND_HXX + +#include "CriticalSection.hxx" + +#include // for HWND (needed by winbase.h) +#include // for INFINITE + +#include +#include + +/** + * Wrapper for a CONDITION_VARIABLE, backend for the Cond class. + */ +class WindowsCond { + CONDITION_VARIABLE cond; + +public: + WindowsCond() noexcept { + InitializeConditionVariable(&cond); + } + + WindowsCond(const WindowsCond &other) = delete; + WindowsCond &operator=(const WindowsCond &other) = delete; + + void notify_one() noexcept { + WakeConditionVariable(&cond); + } + + void notify_all() noexcept { + WakeAllConditionVariable(&cond); + } + + void wait(std::unique_lock &lock) noexcept { + SleepConditionVariableCS(&cond, + &lock.mutex()->critical_section, + INFINITE); + } + + template + void wait(std::unique_lock &lock, + P &&predicate) noexcept { + while (!predicate()) + wait(lock); + } + + bool wait_for(std::unique_lock &lock, + std::chrono::steady_clock::duration timeout) noexcept { + auto timeout_ms = std::chrono::duration_cast(timeout).count(); + return SleepConditionVariableCS(&cond, + &lock.mutex()->critical_section, + static_cast(timeout_ms)); + } + + template + bool wait_for(std::unique_lock &lock, + std::chrono::steady_clock::duration timeout, + P &&predicate) noexcept { + while (!predicate()) { + // TODO: without wait_until(), this multiplies the timeout + if (!wait_for(lock, timeout)) + return predicate(); + } + + return true; + } +}; + +#endif diff --git a/src/thread/WindowsFuture.hxx b/src/thread/WindowsFuture.hxx new file mode 100644 index 0000000..1e7cdef --- /dev/null +++ b/src/thread/WindowsFuture.hxx @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef THREAD_WINDOWS_FUTURE_HXX +#define THREAD_WINDOWS_FUTURE_HXX + +#include "CriticalSection.hxx" +#include "WindowsCond.hxx" + +#include +#include // for std::error_category +#include + +enum class WinFutureErrc : int { + future_already_retrieved = 1, + promise_already_satisfied, + no_state, + broken_promise, +}; + +enum class WinFutureStatus { ready, timeout, deferred }; + +static inline const std::error_category &win_future_category() noexcept; +class WinFutureCategory : public std::error_category { +public: + const char *name() const noexcept override { return "win_future"; } + std::string message(int Errcode) const override { + using namespace std::literals; + switch (static_cast(Errcode)) { + case WinFutureErrc::broken_promise: + return "Broken promise"s; + case WinFutureErrc::future_already_retrieved: + return "Future already retrieved"s; + case WinFutureErrc::promise_already_satisfied: + return "Promise already satisfied"s; + case WinFutureErrc::no_state: + return "No associated state"s; + default: + return "Unknown error"s; + } + } + std::error_condition default_error_condition(int code) const noexcept override { + return std::error_condition(code, win_future_category()); + } +}; +static inline const std::error_category &win_future_category() noexcept { + static const WinFutureCategory win_future_category_instance{}; + return win_future_category_instance; +} + +class WinFutureError : public std::logic_error { +public: + WinFutureError(WinFutureErrc errcode) + : WinFutureError( + std::error_code(static_cast(errcode), win_future_category())) {} + +private: + explicit WinFutureError(std::error_code errcode) + : std::logic_error("WinFutureError: " + errcode.message()), code(errcode) {} + std::error_code code; +}; + +template +class WinFutureState { +private: + mutable CriticalSection mutex; + WindowsCond condition; + std::variant result; + bool retrieved = false; + bool ready = false; + +public: + bool is_ready() const noexcept { + const std::lock_guard lock{mutex}; + return ready; + } + + bool already_retrieved() const noexcept { + const std::lock_guard lock{mutex}; + return retrieved; + } + + void wait() { + std::unique_lock lock{mutex}; + condition.wait(lock, [this]() { return ready; }); + } + + template + WinFutureStatus + wait_for(const std::chrono::duration &timeout_duration) const { + std::unique_lock lock{mutex}; + // deferred function not support yet + if (condition.wait_for(lock, timeout_duration, + [this]() { return ready; })) { + return WinFutureStatus::ready; + } + return WinFutureStatus::timeout; + } + + virtual T &get_value() { + std::unique_lock lock{mutex}; + if (retrieved) { + throw WinFutureError(WinFutureErrc::future_already_retrieved); + } + if (auto eptr = std::get_if(&result)) { + std::rethrow_exception(*eptr); + } + retrieved = true; + condition.wait(lock, [this]() { return ready; }); + if (auto eptr = std::get_if(&result)) { + std::rethrow_exception(*eptr); + } + return *std::get_if(&result); + } + + void set_value(const T &value) { + const std::lock_guard lock{mutex}; + if (!std::holds_alternative(result)) { + throw WinFutureError(WinFutureErrc::promise_already_satisfied); + } + result.template emplace(value); + ready = true; + condition.notify_all(); + } + + void set_value(T &&value) { + const std::lock_guard lock{mutex}; + if (!std::holds_alternative(result)) { + throw WinFutureError(WinFutureErrc::promise_already_satisfied); + } + result.template emplace(std::move(value)); + ready = true; + condition.notify_all(); + } + + void set_exception(std::exception_ptr eptr) { + const std::lock_guard lock{mutex}; + if (!std::holds_alternative(result)) { + throw WinFutureError(WinFutureErrc::promise_already_satisfied); + } + result.template emplace(eptr); + ready = true; + condition.notify_all(); + } +}; + +template +class WinFutureStateManager { +public: + WinFutureStateManager() = default; + WinFutureStateManager(std::shared_ptr> new_state) + : state(std::move(new_state)) {} + WinFutureStateManager(const WinFutureStateManager &) = default; + WinFutureStateManager &operator=(const WinFutureStateManager &) = default; + WinFutureStateManager(WinFutureStateManager &&) = default; + WinFutureStateManager &operator=(WinFutureStateManager &&) = default; + + [[nodiscard]] bool valid() const noexcept { return static_cast(state); } + + void wait() const { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + state->wait(); + } + + template + WinFutureStatus + wait_for(const std::chrono::duration &timeout_duration) const { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + return state->wait_for(timeout_duration); + } + + T &get_value() const { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + return state->get_value(); + } + + void set_value(const T &value) { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + state->set_value(value); + } + + void set_value(T &&value) { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + state->set_value(std::move(value)); + } + + void set_exception(std::exception_ptr eptr) { + if (!valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + state->set_exception(eptr); + } + +private: + std::shared_ptr> state; +}; + +template +class WinFuture : public WinFutureStateManager { + using Base = WinFutureStateManager; + static_assert(!std::is_array_v && std::is_object_v && + std::is_destructible_v, + "T in future must meet the Cpp17Destructible requirements " + "(N4878 [futures.unique.future]/4)."); + +public: + WinFuture() noexcept = default; + WinFuture(WinFuture &&) noexcept = default; + WinFuture &operator=(WinFuture &&) noexcept = default; + WinFuture(const WinFuture &) noexcept = delete; + WinFuture &operator=(const WinFuture &) noexcept = delete; + + WinFuture(const Base &base, std::monostate) : Base(base) {} + ~WinFuture() noexcept = default; + T get() { + WinFuture local(std::move(*this)); + return std::move(local.get_value()); + } + +private: + using Base::get_value; + using Base::set_exception; + using Base::set_value; +}; + +template +class WinFuture : public WinFutureStateManager { + using Base = WinFutureStateManager; + +public: + WinFuture() noexcept = default; + WinFuture(WinFuture &&) noexcept = default; + WinFuture &operator=(WinFuture &&) noexcept = default; + WinFuture(const WinFuture &) noexcept = delete; + WinFuture &operator=(const WinFuture &) noexcept = delete; + + WinFuture(const Base &base, std::monostate) : Base(base) {} + ~WinFuture() noexcept = default; + T &get() { + WinFuture local(std::move(*this)); + return *local.get_value(); + } + +private: + using Base::get_value; + using Base::set_exception; + using Base::set_value; +}; + +template <> +class WinFuture : public WinFutureStateManager { + using Base = WinFutureStateManager; + +public: + WinFuture() noexcept = default; + WinFuture(WinFuture &&) noexcept = default; + WinFuture &operator=(WinFuture &&) noexcept = default; + WinFuture(const WinFuture &) noexcept = delete; + WinFuture &operator=(const WinFuture &) noexcept = delete; + + WinFuture(const Base &base, std::monostate) : Base(base) {} + ~WinFuture() noexcept = default; + void get() { + WinFuture local(std::move(*this)); + local.get_value(); + } + +private: + using Base::get_value; + using Base::set_exception; + using Base::set_value; +}; + +template +class WinPromiseBase { +public: + WinPromiseBase(std::shared_ptr> new_state) + : state(std::move(new_state)) {} + WinPromiseBase(WinPromiseBase &&) = default; + WinPromiseBase &operator=(WinPromiseBase &&) = default; + WinPromiseBase(const WinPromiseBase &) = delete; + WinPromiseBase &operator=(const WinPromiseBase &) = delete; + + WinFutureStateManager &get_state_for_set() { + if (!state.valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + return state; + } + + WinFutureStateManager &get_state_for_future() { + if (!state.valid()) { + throw WinFutureError(WinFutureErrc::no_state); + } + if (future_retrieved) { + throw WinFutureError(WinFutureErrc::future_already_retrieved); + } + future_retrieved = true; + return state; + } + +private: + WinFutureStateManager state; + bool future_retrieved = false; +}; + +template +class WinPromise { +public: + WinPromise() : base(std::make_shared>()) {} + WinPromise(WinPromise &&) = default; + WinPromise(const WinPromise &) = delete; + ~WinPromise() noexcept {} + [[nodiscard]] WinFuture get_future() { + return WinFuture(base.get_state_for_future(), std::monostate()); + } + void set_value(const T &value) { base.get_state_for_set().set_value(value); } + void set_value(T &&value) { + base.get_state_for_set().set_value(std::forward(value)); + } + void set_exception(std::exception_ptr eptr) { + base.get_state_for_set().set_exception(eptr); + } + +private: + WinPromiseBase base; +}; + +template +class WinPromise { +public: + WinPromise() : base(std::make_shared>()) {} + WinPromise(WinPromise &&) = default; + WinPromise(const WinPromise &) = delete; + ~WinPromise() noexcept {} + [[nodiscard]] WinFuture get_future() { + return WinFuture(base.get_state_for_future(), std::monostate()); + } + void set_value(T &value) { + base.get_state_for_set().set_value(std::addressof(value)); + } + void set_exception(std::exception_ptr eptr) { + base.get_state_for_set().set_exception(eptr); + } + +private: + WinPromiseBase base; +}; + +template <> +class WinPromise { +public: + WinPromise() : base(std::make_shared>()) {} + WinPromise(WinPromise &&) = default; + WinPromise(const WinPromise &) = delete; + ~WinPromise() noexcept {} + [[nodiscard]] WinFuture get_future() { + return WinFuture(base.get_state_for_future(), std::monostate()); + } + void set_value() { base.get_state_for_set().set_value(0); } + void set_exception(std::exception_ptr eptr) { + base.get_state_for_set().set_exception(eptr); + } + +private: + WinPromiseBase base; +}; + +#endif diff --git a/src/thread/meson.build b/src/thread/meson.build new file mode 100644 index 0000000..ec4aa0f --- /dev/null +++ b/src/thread/meson.build @@ -0,0 +1,27 @@ +if is_windows + # avoid the unused libwinpthread-1.dll dependency on Windows; MPD + # doesn't use the pthread API on Windows, but this is what Meson + # unhelpfully detects for us + threads_dep = [] +else + threads_dep = dependency('threads') +endif + +conf.set('HAVE_PTHREAD_SETNAME_NP', compiler.has_function('pthread_setname_np', dependencies: threads_dep)) + +thread = static_library( + 'thread', + 'Util.cxx', + 'Thread.cxx', + include_directories: inc, + dependencies: [ + threads_dep, + ], +) + +thread_dep = declare_dependency( + link_with: thread, + dependencies: [ + fmt_dep, + ], +) diff --git a/src/time/Calendar.hxx b/src/time/Calendar.hxx new file mode 100644 index 0000000..003db0c --- /dev/null +++ b/src/time/Calendar.hxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +constexpr bool +IsLeapYear(unsigned y) noexcept +{ + return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0); +} + +constexpr unsigned +DaysInFebruary(unsigned year) noexcept +{ + return IsLeapYear(year) ? 29 : 28; +} + +constexpr unsigned +DaysInMonth(unsigned month, unsigned year) noexcept +{ + if (month == 4 || month == 6 || month == 9 || month == 11) + return 30; + else if (month != 2) + return 31; + else + return DaysInFebruary(year); +} + +constexpr unsigned +DaysInYear(unsigned year) noexcept +{ + return IsLeapYear(year) ? 366 : 365; +} diff --git a/src/time/ChronoUtil.hxx b/src/time/ChronoUtil.hxx new file mode 100644 index 0000000..c3e7b88 --- /dev/null +++ b/src/time/ChronoUtil.hxx @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef CHRONO_UTIL_HXX +#define CHRONO_UTIL_HXX + +#include + +template +constexpr bool +IsNegative(const std::chrono::time_point p) +{ + return p < std::chrono::time_point(); +} + +#endif diff --git a/src/time/ClockCache.hxx b/src/time/ClockCache.hxx new file mode 100644 index 0000000..9bb0ccc --- /dev/null +++ b/src/time/ClockCache.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include + +/** + * Cache the now() method of a clock. + */ +template +class ClockCache { + using value_type = typename Clock::time_point; + mutable value_type value; + +public: + ClockCache() = default; + ClockCache(const ClockCache &) = delete; + ClockCache &operator=(const ClockCache &) = delete; + + [[gnu::pure]] + const auto &now() const noexcept { + if (value <= value_type()) + value = Clock::now(); + return value; + } + + void flush() noexcept { + value = {}; + } + + /** + * Inject a fake value. This can be helpful for unit tests. + */ + void Mock(value_type _value) noexcept { + value = _value; + } +}; diff --git a/src/time/Convert.cxx b/src/time/Convert.cxx new file mode 100644 index 0000000..10938e0 --- /dev/null +++ b/src/time/Convert.cxx @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "Convert.hxx" +#include "Zone.hxx" + +#include + +#include + +#ifdef _WIN32 +#include /* for struct timeval */ +#else +#include /* for struct timeval */ +#endif + +struct tm +GmTime(std::chrono::system_clock::time_point tp) +{ + const time_t t = std::chrono::system_clock::to_time_t(tp); +#ifdef _WIN32 + const struct tm *tm = gmtime(&t); +#else + struct tm buffer, *tm = gmtime_r(&t, &buffer); +#endif + if (tm == nullptr) + throw std::runtime_error("gmtime_r() failed"); + + return *tm; +} + +struct tm +LocalTime(std::chrono::system_clock::time_point tp) +{ + const time_t t = std::chrono::system_clock::to_time_t(tp); +#ifdef _WIN32 + const struct tm *tm = localtime(&t); +#else + struct tm buffer, *tm = localtime_r(&t, &buffer); +#endif + if (tm == nullptr) + throw std::runtime_error("localtime_r() failed"); + + return *tm; +} + +std::chrono::system_clock::time_point +TimeGm(struct tm &tm) noexcept +{ +#ifdef __GLIBC__ + /* timegm() is a GNU extension */ + const auto t = timegm(&tm); +#else + tm.tm_isdst = 0; + const auto t = mktime(&tm) + GetTimeZoneOffset(); +#endif /* !__GLIBC__ */ + + return std::chrono::system_clock::from_time_t(t); +} + +std::chrono::system_clock::time_point +MakeTime(struct tm &tm) noexcept +{ + return std::chrono::system_clock::from_time_t(mktime(&tm)); +} + +std::chrono::steady_clock::duration +ToSteadyClockDuration(const struct timeval &tv) noexcept +{ + return std::chrono::steady_clock::duration(std::chrono::seconds(tv.tv_sec)) + + std::chrono::steady_clock::duration(std::chrono::microseconds(tv.tv_usec)); +} diff --git a/src/time/Convert.hxx b/src/time/Convert.hxx new file mode 100644 index 0000000..597cccf --- /dev/null +++ b/src/time/Convert.hxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include + +struct tm; + +/** + * Convert a UTC-based time point to a UTC-based "struct tm". + * + * Throws on error. + */ +struct tm +GmTime(std::chrono::system_clock::time_point tp); + +/** + * Convert a UTC-based time point to a local "struct tm". + * + * Throws on error. + */ +struct tm +LocalTime(std::chrono::system_clock::time_point tp); + +/** + * Convert a UTC-based "struct tm" to a UTC-based time point. + */ +[[gnu::pure]] +std::chrono::system_clock::time_point +TimeGm(struct tm &tm) noexcept; + +/** + * Convert a local "struct tm" to a UTC-based time point. + */ +[[gnu::pure]] +std::chrono::system_clock::time_point +MakeTime(struct tm &tm) noexcept; + +[[gnu::pure]] +std::chrono::steady_clock::duration +ToSteadyClockDuration(const struct timeval &tv) noexcept; diff --git a/src/time/FileTime.hxx b/src/time/FileTime.hxx new file mode 100644 index 0000000..a7405c8 --- /dev/null +++ b/src/time/FileTime.hxx @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef FILE_TIME_HXX +#define FILE_TIME_HXX + +#include "SystemClock.hxx" + +#include + +#include +#include + +constexpr uint_least64_t +ConstructUint64(DWORD lo, DWORD hi) noexcept +{ + return uint_least64_t(lo) | (uint_least64_t(hi) << 32); +} + +constexpr uint_least64_t +ToUint64(FILETIME ft) noexcept +{ + return ConstructUint64(ft.dwLowDateTime, ft.dwHighDateTime); +} + +constexpr int_least64_t +ToInt64(FILETIME ft) noexcept +{ + return ToUint64(ft); +} + +constexpr FILETIME +ToFileTime(uint_least64_t t) noexcept +{ + FILETIME ft{}; + ft.dwLowDateTime = DWORD(t); + ft.dwHighDateTime = DWORD(t >> 32); + return ft; +} + +constexpr FILETIME +ToFileTime(int_least64_t t) noexcept +{ + return ToFileTime(uint_least64_t(t)); +} + +/* "A file time is a 64-bit value that represents the number of + 100-nanosecond intervals" + https://docs.microsoft.com/en-us/windows/win32/sysinfo/file-times */ +using FileTimeResolution = std::ratio<1, 10000000>; + +using FileTimeDuration = std::chrono::duration; + +/** + * Calculate a std::chrono::duration specifying the duration of the + * FILETIME since its epoch (1601-01-01T00:00). + */ +constexpr auto +FileTimeToChronoDuration(FILETIME ft) noexcept +{ + return FileTimeDuration(ToInt64(ft)); +} + +/** + * Calculate a std::chrono::duration specifying the duration between + * the unix epoch and the given FILETIME. + */ +constexpr auto +FileTimeToUnixEpochDuration(FILETIME ft) noexcept +{ + /** + * The number of days between the Windows FILETIME epoch + * (1601-01-01T00:00) and the Unix epoch (1970-01-01T00:00). + */ + constexpr int_least64_t windows_unix_days = 134774; + constexpr int_least64_t windows_unix_hours = windows_unix_days * 24; + + constexpr FileTimeDuration windows_unix_delta{std::chrono::hours{windows_unix_hours}}; + + return FileTimeToChronoDuration(ft) - windows_unix_delta; +} + +inline std::chrono::system_clock::time_point +FileTimeToChrono(FILETIME ft) noexcept +{ + return TimePointAfterUnixEpoch(FileTimeToUnixEpochDuration(ft)); +} + +constexpr FILETIME +ToFileTime(FileTimeDuration d) noexcept +{ + return ToFileTime(d.count()); +} + +constexpr FILETIME +UnixEpochDurationToFileTime(FileTimeDuration d) noexcept +{ + /** + * The number of days between the Windows FILETIME epoch + * (1601-01-01T00:00) and the Unix epoch (1970-01-01T00:00). + */ + constexpr int_least64_t windows_unix_days = 134774; + constexpr int_least64_t windows_unix_hours = windows_unix_days * 24; + + constexpr FileTimeDuration windows_unix_delta{std::chrono::hours{windows_unix_hours}}; + + return ToFileTime(d + windows_unix_delta); +} + +inline FILETIME +ChronoToFileTime(std::chrono::system_clock::time_point tp) noexcept +{ + const auto since_unix_epoch = DurationSinceUnixEpoch(tp); + const auto ft_since_unix_epoch = + std::chrono::duration_cast(since_unix_epoch); + + return UnixEpochDurationToFileTime(ft_since_unix_epoch); +} + +constexpr std::chrono::seconds +DeltaFileTimeS(FILETIME a, FILETIME b) noexcept +{ + return std::chrono::duration_cast + (FileTimeToChronoDuration(a) - FileTimeToChronoDuration(b)); +} + +#endif diff --git a/src/time/ISO8601.cxx b/src/time/ISO8601.cxx new file mode 100644 index 0000000..c9f791d --- /dev/null +++ b/src/time/ISO8601.cxx @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "ISO8601.hxx" +#include "Convert.hxx" +#include "Math.hxx" +#include "util/StringBuffer.hxx" + +#include +#include +#include + +StringBuffer<64> +FormatISO8601(const struct tm &tm) noexcept +{ + StringBuffer<64> buffer; + strftime(buffer.data(), buffer.capacity(), +#ifdef _WIN32 + "%Y-%m-%dT%H:%M:%SZ", +#else + "%FT%TZ", +#endif + &tm); + return buffer; +} + +StringBuffer<64> +FormatISO8601(std::chrono::system_clock::time_point tp) +{ + return FormatISO8601(GmTime(tp)); +} + +#ifndef _WIN32 + +static std::pair +ParseTimeZoneOffsetRaw(const char *&s) +{ + char *endptr; + unsigned long value = std::strtoul(s, &endptr, 10); + if (endptr == s + 4) { + s = endptr; + return {value / 100, value % 100}; + } else if (endptr == s + 2) { + s = endptr; + + unsigned hours = value, minutes = 0; + if (*s == ':') { + ++s; + minutes = std::strtoul(s, &endptr, 10); + if (endptr != s + 2) + throw std::invalid_argument("Failed to parse time zone offset"); + + s = endptr; + } + + return {hours, minutes}; + } else + throw std::invalid_argument("Failed to parse time zone offset"); +} + +static std::chrono::system_clock::duration +ParseTimeZoneOffset(const char *&s) +{ + assert(*s == '+' || *s == '-'); + + bool negative = *s == '-'; + ++s; + + auto raw = ParseTimeZoneOffsetRaw(s); + if (raw.first > 13) + throw std::invalid_argument("Time offset hours out of range"); + + if (raw.second >= 60) + throw std::invalid_argument("Time offset minutes out of range"); + + std::chrono::system_clock::duration d = std::chrono::hours(raw.first); + d += std::chrono::minutes(raw.second); + + if (negative) + d = -d; + + return d; +} + +static const char * +ParseTimeOfDay(const char *s, struct tm &tm, + std::chrono::system_clock::duration &precision) noexcept +{ + /* this function always checks "end==s" to work around a + strptime() bug on OS X: if nothing could be parsed, + strptime() returns the input string (indicating success) + instead of nullptr (indicating error) */ + + const char *end = strptime(s, "%H", &tm); + if (end == nullptr || end == s) + return end; + + s = end; + precision = std::chrono::hours(1); + + if (*s == ':') { + /* with field separators: now a minute must follow */ + + ++s; + + end = strptime(s, "%M", &tm); + if (end == nullptr || end == s) + return nullptr; + + s = end; + precision = std::chrono::minutes(1); + + /* the "seconds" field is optional */ + if (*s != ':') + return s; + + ++s; + + end = strptime(s, "%S", &tm); + if (end == nullptr || end == s) + return nullptr; + + precision = std::chrono::seconds(1); + return end; + } + + /* without field separators */ + + end = strptime(s, "%M", &tm); + if (end == nullptr || end == s) + return s; + + s = end; + precision = std::chrono::minutes(1); + + end = strptime(s, "%S", &tm); + if (end == nullptr || end == s) + return s; + + precision = std::chrono::seconds(1); + return end; +} + +static bool +StrptimeFull(const char *s, const char *fmt, struct tm *tm) noexcept +{ + const char *end = strptime(s, fmt, tm); + return end != nullptr && *end == 0; +} + +#endif + +std::pair +ParseISO8601(const char *s) +{ + assert(s != nullptr); + +#ifdef _WIN32 + /* TODO: emulate strptime()? */ + (void)s; + throw std::runtime_error("Time parsing not implemented on Windows"); +#else + struct tm tm{}; + + if (StrptimeFull(s, "%Y-%m", &tm)) { + /* full month */ + tm.tm_mday = 1; + const auto start = TimeGm(tm); + EndOfMonth(tm); + const auto end = TimeGm(tm); + return {start, end - start}; + } + + /* parse the date */ + const char *end = strptime(s, "%Y-%m-%d", &tm); + if (end == nullptr) { + /* try without field separators */ + end = strptime(s, "%Y%m%d", &tm); + if (end == nullptr) + throw std::invalid_argument("Failed to parse date"); + } + + s = end; + + std::chrono::system_clock::duration precision = std::chrono::hours(24); + + /* parse the time of day */ + if (*s == 'T') { + ++s; + + s = ParseTimeOfDay(s, tm, precision); + if (s == nullptr) + throw std::invalid_argument("Failed to parse time of day"); + } + + auto tp = TimeGm(tm); + + /* time zone */ + if (*s == 'Z') + ++s; + else if (*s == '+' || *s == '-') + tp -= ParseTimeZoneOffset(s); + + if (*s != 0) + throw std::invalid_argument("Garbage at end of time stamp"); + + return {tp, precision}; +#endif /* !_WIN32 */ +} diff --git a/src/time/ISO8601.hxx b/src/time/ISO8601.hxx new file mode 100644 index 0000000..a77d31b --- /dev/null +++ b/src/time/ISO8601.hxx @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#ifndef TIME_ISO8601_HXX +#define TIME_ISO8601_HXX + +#include +#include +#include + +struct tm; +template class StringBuffer; + +[[gnu::pure]] +StringBuffer<64> +FormatISO8601(const struct tm &tm) noexcept; + +[[gnu::pure]] +StringBuffer<64> +FormatISO8601(std::chrono::system_clock::time_point tp); + +/** + * Parse a time stamp in ISO8601 format. + * + * Throws on error. + * + * @return a pair consisting of the time point and the specified + * precision; e.g. for a date, the second value is "one day" + */ +std::pair +ParseISO8601(const char *s); + +#endif diff --git a/src/time/Math.cxx b/src/time/Math.cxx new file mode 100644 index 0000000..d5fb9e5 --- /dev/null +++ b/src/time/Math.cxx @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "Math.hxx" +#include "Calendar.hxx" +#include "Convert.hxx" + +#include + +std::chrono::system_clock::time_point +PrecedingMidnightLocal(std::chrono::system_clock::time_point t) noexcept +try { + auto tm = LocalTime(t); + tm.tm_sec = 0; + tm.tm_min = 0; + tm.tm_hour = 0; + return MakeTime(tm); +} catch (...) { + /* best-effort fallback for this exotic error condition */ + return t; + } + +static void +IncrementMonth(struct tm &tm) noexcept +{ + ++tm.tm_mon; + + if (tm.tm_mon >= 12) { + /* roll over to next year */ + tm.tm_mon = 0; + ++tm.tm_year; + } +} + +void +EndOfMonth(struct tm &tm) noexcept +{ + tm.tm_sec = 0; + tm.tm_min = 0; + tm.tm_hour = 0; + tm.tm_mday = 1; + IncrementMonth(tm); +} + +void +IncrementDay(struct tm &tm) noexcept +{ + const unsigned max_day = DaysInMonth(tm.tm_mon + 1, tm.tm_year + 1900); + + ++tm.tm_mday; + + if ((unsigned)tm.tm_mday > max_day) { + /* roll over to next month */ + tm.tm_mday = 1; + IncrementMonth(tm); + } + + ++tm.tm_wday; + if (tm.tm_wday >= 7) + tm.tm_wday = 0; +} + +void +DecrementDay(struct tm &tm) noexcept +{ + --tm.tm_mday; + + if (tm.tm_mday < 1) { + /* roll over to previous month */ + + --tm.tm_mon; + if (tm.tm_mon < 0) { + /* roll over to previous eyar */ + tm.tm_mon = 11; + --tm.tm_year; + } + + const unsigned max_day = DaysInMonth(tm.tm_mon + 1, + tm.tm_year + 1900); + tm.tm_mday = max_day; + } + + --tm.tm_wday; + if (tm.tm_wday < 0) + tm.tm_wday = 6; +} diff --git a/src/time/Math.hxx b/src/time/Math.hxx new file mode 100644 index 0000000..703223f --- /dev/null +++ b/src/time/Math.hxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include + +struct tm; + +/** + * Calculates the preceding midnight time point in the current time + * zone. + */ +[[gnu::const]] +std::chrono::system_clock::time_point +PrecedingMidnightLocal(std::chrono::system_clock::time_point t) noexcept; + +/** + * Calculate the end of the current month (i.e. midnight on the 1st of + * the following month). Does NOT keeps the tm_wday and tm_yday + * attributes updated, and ignores day light saving transitions. + */ +void +EndOfMonth(struct tm &tm) noexcept; + +/** + * Calculate the next day, keeping month/year wraparounds and leap + * days in mind. Keeps the tm_wday attribute updated, but not other + * derived attributes such as tm_yday, and ignores day light saving + * transitions. + */ +void +IncrementDay(struct tm &tm) noexcept; + +/** + * Calculate the previous day, keeping month/year wraparounds and leap + * days in mind. Keeps the tm_wday attribute updated, but not other + * derived attributes such as tm_yday, and ignores day light saving + * transitions. + */ +void +DecrementDay(struct tm &tm) noexcept; diff --git a/src/time/PeriodClock.hxx b/src/time/PeriodClock.hxx new file mode 100644 index 0000000..9a6c2ef --- /dev/null +++ b/src/time/PeriodClock.hxx @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PERIOD_CLOCK_HXX +#define MPD_PERIOD_CLOCK_HXX + +#include + +/** + * This is a stopwatch which saves the timestamp of an event, and can + * check whether a specified time span has passed since then. + */ +class PeriodClock { +public: + typedef std::chrono::steady_clock::duration Duration; + typedef Duration Delta; + typedef std::chrono::steady_clock::time_point Stamp; + +private: + Stamp last; + +public: + /** + * Initializes the object, setting the last time stamp to "0", + * i.e. a Check() will always succeed. If you do not want this + * default behaviour, call Update() immediately after creating the + * object. + */ + constexpr + PeriodClock():last() {} + +protected: + static Stamp GetNow() { + return std::chrono::steady_clock::now(); + } + + constexpr Delta Elapsed(Stamp now) const { + return last == Stamp() + ? Delta(-1) + : Delta(now - last); + } + + constexpr bool Check(Stamp now, Duration duration) const { + return now >= last + duration; + } + + void Update(Stamp now) { + last = now; + } + +public: + constexpr bool IsDefined() const { + return last > Stamp(); + } + + /** + * Resets the clock. + */ + void Reset() { + last = Stamp(); + } + + /** + * Returns the time elapsed since the last update(). Returns + * a negative value if update() was never called. + */ + Delta Elapsed() const { + return Elapsed(GetNow()); + } + + /** + * Combines a call to Elapsed() and Update(). + */ + Delta ElapsedUpdate() { + const auto now = GetNow(); + const auto result = Elapsed(now); + Update(now); + return result; + } + + /** + * Checks whether the specified duration has passed since the last + * update. + * + * @param duration the duration + */ + bool Check(Duration duration) const { + return Check(GetNow(), duration); + } + + /** + * Updates the time stamp, setting it to the current clock. + */ + void Update() { + Update(GetNow()); + } + + /** + * Updates the time stamp, setting it to the current clock plus the + * specified offset. + */ + void UpdateWithOffset(Delta offset) { + Update(GetNow() + offset); + } + + /** + * Checks whether the specified duration has passed since the last + * update. If yes, it updates the time stamp. + * + * @param duration the duration in milliseconds + */ + bool CheckUpdate(Duration duration) { + Stamp now = GetNow(); + if (Check(now, duration)) { + Update(now); + return true; + } else + return false; + } + + /** + * Checks whether the specified duration has passed since the last + * update. After that, it updates the time stamp. + * + * @param duration the duration in milliseconds + */ + bool CheckAlwaysUpdate(Duration duration) { + Stamp now = GetNow(); + bool ret = Check(now, duration); + Update(now); + return ret; + } +}; + +#endif diff --git a/src/time/SystemClock.hxx b/src/time/SystemClock.hxx new file mode 100644 index 0000000..2c5a12f --- /dev/null +++ b/src/time/SystemClock.hxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Calculate a std::chrono::system_clock::time_point from a duration + * relative to the UNIX epoch (1970-01-01T00:00Z). + */ +template +[[gnu::const]] +std::chrono::system_clock::time_point +TimePointAfterUnixEpoch(const std::chrono::duration d) noexcept +{ + /* this is guaranteed to be 0 in C++20 */ + const auto unix_epoch = std::chrono::system_clock::from_time_t(0); + + return unix_epoch + + std::chrono::duration_cast(d); +} + +/** + * Calculate the duration that has passed since the UNIX epoch + * (1970-01-01T00:00Z). + */ +[[gnu::const]] +inline std::chrono::system_clock::duration +DurationSinceUnixEpoch(const std::chrono::system_clock::time_point tp) noexcept +{ + /* this is guaranteed to be 0 in C++20 */ + const auto unix_epoch = std::chrono::system_clock::from_time_t(0); + + return tp - unix_epoch; +} diff --git a/src/time/Zone.cxx b/src/time/Zone.cxx new file mode 100644 index 0000000..fa5583a --- /dev/null +++ b/src/time/Zone.cxx @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "Zone.hxx" + +#ifdef _WIN32 +#include +#include +#include +#else +#include +#endif + +int +GetTimeZoneOffset() noexcept +{ +#ifdef _WIN32 + TIME_ZONE_INFORMATION TimeZoneInformation; + DWORD tzi = GetTimeZoneInformation(&TimeZoneInformation); + + int offset = -TimeZoneInformation.Bias * 60; + if (tzi == TIME_ZONE_ID_STANDARD) + offset -= TimeZoneInformation.StandardBias * 60; + + if (tzi == TIME_ZONE_ID_DAYLIGHT) + offset -= TimeZoneInformation.DaylightBias * 60; + + return offset; +#else + time_t t = 1234567890; + struct tm tm; + tm.tm_isdst = 0; + struct tm *p = &tm; + gmtime_r(&t, p); + return t - mktime(p); +#endif +} diff --git a/src/time/Zone.hxx b/src/time/Zone.hxx new file mode 100644 index 0000000..8440fe4 --- /dev/null +++ b/src/time/Zone.hxx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +/** + * Determine the time zone offset in a portable way. + */ +[[gnu::const]] +int +GetTimeZoneOffset() noexcept; diff --git a/src/time/meson.build b/src/time/meson.build new file mode 100644 index 0000000..c80cd88 --- /dev/null +++ b/src/time/meson.build @@ -0,0 +1,12 @@ +time = static_library( + 'time', + 'Convert.cxx', + 'ISO8601.cxx', + 'Math.cxx', + 'Zone.cxx', + include_directories: inc, +) + +time_dep = declare_dependency( + link_with: time, +) diff --git a/src/unix/Daemon.cxx b/src/unix/Daemon.cxx new file mode 100644 index 0000000..7b0988e --- /dev/null +++ b/src/unix/Daemon.cxx @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "Daemon.hxx" +#include "PidFile.hxx" +#include "lib/fmt/PathFormatter.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "lib/fmt/SystemError.hxx" +#include "fs/AllocatedPath.hxx" +#include "io/FileDescriptor.hxx" +#include "util/SpanCast.hxx" + +#include +#include // for std::exit() + +#include +#include +#include +#include + +#ifndef WCOREDUMP +#define WCOREDUMP(v) 0 +#endif + +/** the Unix user name which MPD runs as */ +static char *user_name; + +/** the Unix user id which MPD runs as */ +static uid_t user_uid = (uid_t)-1; + +/** the Unix group id which MPD runs as */ +static gid_t user_gid = (gid_t)-1; + +/** the absolute path of the pidfile */ +static AllocatedPath pidfile = nullptr; + +/* whether "group" conf. option was given */ +static bool had_group = false; + +/** + * The write end of a pipe that is used to notify the parent process + * that initialization has finished and that it should detach. + */ +static FileDescriptor detach_fd = FileDescriptor::Undefined(); + +void +daemonize_kill() +{ + if (pidfile.IsNull()) + throw std::runtime_error("no pid_file specified in the config file"); + + const pid_t pid = ReadPidFile(pidfile); + if (pid < 0) + throw FmtErrno("unable to read the pid from file {:?}", + pidfile); + + if (kill(pid, SIGTERM) < 0) + throw FmtErrno("unable to kill process {}", pid); + + std::exit(EXIT_SUCCESS); +} + +void +daemonize_close_stdin() noexcept +{ + close(STDIN_FILENO); + open("/dev/null", O_RDONLY); +} + +void +daemonize_set_user() +{ + if (user_name == nullptr) + return; + + /* set gid */ + if (user_gid != (gid_t)-1 && user_gid != getgid() && + setgid(user_gid) == -1) { + throw FmtErrno("Failed to set group {}", user_gid); + } + +#ifdef HAVE_INITGROUPS + /* init supplementary groups + * (must be done before we change our uid) + */ + if (!had_group && + /* no need to set the new user's supplementary groups if + we are already this user */ + user_uid != getuid() && + initgroups(user_name, user_gid) == -1) { + throw FmtErrno("Failed to set supplementary groups " + "of user {:?}", + user_name); + } +#endif + + /* set uid */ + if (user_uid != (uid_t)-1 && user_uid != getuid() && + setuid(user_uid) == -1) { + throw FmtErrno("Failed to set user {:?}", user_name); + } +} + +void +daemonize_begin(bool detach) +{ + /* release the current working directory */ + if (chdir("/") < 0) + throw MakeErrno("problems changing to root directory"); + + if (!detach) + /* the rest of this function deals with detaching the + process */ + return; + + /* do this before daemonizing so we can fail gracefully if we + can't write to the pid file */ + PidFile pidfile2(pidfile); + + /* flush all file handles before duplicating the buffers */ + + fflush(nullptr); + + /* create a pipe to synchronize the parent and the child */ + + FileDescriptor p; + + if (!FileDescriptor::CreatePipe(p, detach_fd)) + throw MakeErrno("pipe() failed"); + + /* move to a child process */ + +#ifndef __APPLE__ + + pid_t pid = fork(); + if (pid < 0) + throw MakeErrno("fork() failed"); + + if (pid == 0) { + /* in the child process */ + + pidfile2.Close(); + p.Close(); + + /* detach from the current session */ + setsid(); + + /* continue starting MPD */ + return; + } + + /* in the parent process */ + + detach_fd.Close(); + + int result; + ssize_t nbytes = p.Read(ReferenceAsWritableBytes(result)); + if (nbytes == (ssize_t)sizeof(result)) { + /* the child process was successful */ + pidfile2.Write(pid); + std::exit(EXIT_SUCCESS); + } + + /* something bad happened in the child process */ + + pidfile2.Delete(pidfile); + + int status; + pid_t pid2 = waitpid(pid, &status, 0); + if (pid2 < 0) + throw MakeErrno("waitpid() failed"); + + if (WIFSIGNALED(status)) + throw FmtErrno("MPD died from signal {}{}", WTERMSIG(status), + WCOREDUMP(status) ? " (core dumped)" : ""); + + std::exit(WEXITSTATUS(status)); + +#endif +} + +void +daemonize_commit() +{ + if (detach_fd.IsDefined()) { + /* tell the parent process to let go of us and exit + indicating success */ + static constexpr int result = 0; + (void)detach_fd.Write(ReferenceAsBytes(result)); + detach_fd.Close(); + } else + /* the pidfile was not written by the parent because + there is no parent - do it now */ + PidFile(pidfile).Write(); +} + +void +daemonize_init(const char *user, const char *group, AllocatedPath &&_pidfile) +{ + if (user) { + struct passwd *pwd = getpwnam(user); + if (pwd == nullptr) + throw FmtRuntimeError("no such user {:?}", user); + + user_uid = pwd->pw_uid; + user_gid = pwd->pw_gid; + + user_name = strdup(user); + + /* this is needed by libs such as arts */ + setenv("HOME", pwd->pw_dir, true); + } + + if (group) { + struct group *grp = getgrnam(group); + if (grp == nullptr) + throw FmtRuntimeError("no such group {:?}", group); + user_gid = grp->gr_gid; + had_group = true; + } + + + pidfile = std::move(_pidfile); +} + +void +daemonize_finish() noexcept +{ + if (!pidfile.IsNull()) { + unlink(pidfile.c_str()); + pidfile = nullptr; + } + + free(user_name); +} diff --git a/src/unix/Daemon.hxx b/src/unix/Daemon.hxx new file mode 100644 index 0000000..1fd2ea7 --- /dev/null +++ b/src/unix/Daemon.hxx @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_DAEMON_HXX +#define MPD_DAEMON_HXX + +class AllocatedPath; + +/** + * Throws on error. + */ +#ifndef _WIN32 +void +daemonize_init(const char *user, const char *group, AllocatedPath &&pidfile); +#else +static inline void +daemonize_init(const char *user, const char *group, AllocatedPath &&pidfile) +{ (void)user; (void)group; (void)pidfile; } +#endif + +#ifndef _WIN32 +void +daemonize_finish() noexcept; +#else +static inline void +daemonize_finish() noexcept +{ /* nop */ } +#endif + +/** + * Kill the MPD which is currently running, pid determined from the + * pid file. + * + * Throws on error. + */ +#ifndef _WIN32 +[[noreturn]] +void +daemonize_kill(); +#else +#include +[[noreturn]] +static inline void +daemonize_kill() +{ + throw std::runtime_error("--kill is not available on WIN32"); +} +#endif + +/** + * Close stdin (fd 0) and re-open it as /dev/null. + */ +#ifndef _WIN32 +void +daemonize_close_stdin() noexcept; +#else +static inline void +daemonize_close_stdin() noexcept {} +#endif + +/** + * Change to the configured Unix user. + * + * Throws on error. + */ +#ifndef _WIN32 +void +daemonize_set_user(); +#else +static inline void +daemonize_set_user() +{ /* nop */ } +#endif + +/** + * Throws on error. + */ +#ifndef _WIN32 +void +daemonize_begin(bool detach); +#else +static inline void +daemonize_begin(bool detach) +{ (void)detach; } +#endif + +/** + * Throws on error. + */ +#ifndef _WIN32 +void +daemonize_commit(); +#else +static inline void +daemonize_commit() {} +#endif + +#endif diff --git a/src/unix/PidFile.hxx b/src/unix/PidFile.hxx new file mode 100644 index 0000000..5a41e78 --- /dev/null +++ b/src/unix/PidFile.hxx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "lib/fmt/PathFormatter.hxx" +#include "fs/FileSystem.hxx" +#include "fs/AllocatedPath.hxx" +#include "lib/fmt/SystemError.hxx" +#include "lib/fmt/Unsafe.hxx" +#include "io/FileDescriptor.hxx" +#include "util/SpanCast.hxx" + +#include + +#include + +class PidFile { + FileDescriptor fd; + +public: + PidFile(const AllocatedPath &path):fd(-1) { + if (path.IsNull()) + return; + + fd = OpenFile(path, O_WRONLY|O_CREAT|O_TRUNC, 0666).Release(); + if (!fd.IsDefined()) + throw FmtErrno("Failed to create pid file {:?}", + path); + } + + PidFile(const PidFile &) = delete; + + void Close() noexcept { + if (!fd.IsDefined()) + return; + + fd.Close(); + } + + void Delete(const AllocatedPath &path) noexcept { + if (!fd.IsDefined()) { + assert(path.IsNull()); + return; + } + + assert(!path.IsNull()); + + fd.Close(); + unlink(path.c_str()); + } + + void Write(pid_t pid) noexcept { + if (!fd.IsDefined()) + return; + + char buffer[32]; + (void)fd.Write(AsBytes(FmtUnsafeSV(buffer, "{}\n", pid))); + fd.Close(); + } + + void Write() noexcept { + if (!fd.IsDefined()) + return; + + Write(getpid()); + } +}; + +[[gnu::pure]] +static inline pid_t +ReadPidFile(Path path) noexcept +{ + auto fd = OpenFile(path, O_RDONLY, 0); + if (!fd.IsDefined()) + return -1; + + pid_t pid = -1; + + char buffer[32]; + auto nbytes = fd.Read(std::as_writable_bytes(std::span{buffer, sizeof(buffer) - 1})); + if (nbytes > 0) { + buffer[nbytes] = 0; + + char *endptr; + auto value = strtoul(buffer, &endptr, 10); + if (endptr > buffer) + pid = value; + } + + return pid; +} diff --git a/src/unix/SignalHandlers.cxx b/src/unix/SignalHandlers.cxx new file mode 100644 index 0000000..dece45a --- /dev/null +++ b/src/unix/SignalHandlers.cxx @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "SignalHandlers.hxx" +#include "Instance.hxx" +#include "event/SignalMonitor.hxx" + +#ifndef _WIN32 + +#include "Log.hxx" +#include "LogInit.hxx" +#include "system/Error.hxx" +#include "util/Domain.hxx" + +#include + +#ifdef __linux__ +#include +#endif + +static constexpr Domain signal_handlers_domain("signal_handlers"); + +static void +HandleShutdownSignal(void *ctx) noexcept +{ + auto &loop = *(EventLoop *)ctx; + loop.Break(); +} + +static void +x_sigaction(int signum, const struct sigaction *act) +{ + if (sigaction(signum, act, nullptr) < 0) + throw MakeErrno("sigaction() failed"); +} + +static void +handle_reload_event(void *ctx) noexcept +{ + auto &instance = *(Instance *)ctx; + + LogDebug(signal_handlers_domain, "got SIGHUP, reopening log files and flushing caches"); + cycle_log_files(); + + instance.FlushCaches(); +} + +#endif + +void +SignalHandlersInit(Instance &instance, bool daemon) +{ + auto &loop = instance.event_loop; + + SignalMonitorInit(loop); + +#ifndef _WIN32 + struct sigaction sa; + + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sa.sa_handler = SIG_IGN; + x_sigaction(SIGPIPE, &sa); + + SignalMonitorRegister(SIGINT, {&loop, HandleShutdownSignal}); + SignalMonitorRegister(SIGTERM, {&loop, HandleShutdownSignal}); + + SignalMonitorRegister(SIGHUP, {&instance, handle_reload_event}); +#endif + + if (!daemon) { +#ifdef __linux__ + /* if MPD was not daemonized, shut it down when the + parent process dies */ + prctl(PR_SET_PDEATHSIG, SIGTERM); +#endif + } +} + +void +SignalHandlersFinish() noexcept +{ + SignalMonitorFinish(); +} diff --git a/src/unix/SignalHandlers.hxx b/src/unix/SignalHandlers.hxx new file mode 100644 index 0000000..e1a7a35 --- /dev/null +++ b/src/unix/SignalHandlers.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SIGNAL_HANDLERS_HXX +#define MPD_SIGNAL_HANDLERS_HXX + +struct Instance; + +void +SignalHandlersInit(Instance &instance, bool daemon); + +void +SignalHandlersFinish() noexcept; + +class ScopeSignalHandlersInit { +public: + ScopeSignalHandlersInit(Instance &instance, bool daemon) { + SignalHandlersInit(instance, daemon); + } + + ~ScopeSignalHandlersInit() noexcept { + SignalHandlersFinish(); + } +}; + +#endif diff --git a/src/util/ASCII.hxx b/src/util/ASCII.hxx new file mode 100644 index 0000000..d23d950 --- /dev/null +++ b/src/util/ASCII.hxx @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef ASCII_HXX +#define ASCII_HXX + +#include "Compiler.h" + +#include +#include + +#include + +/** + * Determine whether two strings are equal, ignoring case for ASCII + * letters. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringEqualsCaseASCII(const char *a, const char *b) noexcept +{ +#if !CLANG_CHECK_VERSION(3,6) + /* disabled on clang due to -Wtautological-pointer-compare */ + assert(a != nullptr); + assert(b != nullptr); +#endif + + /* note: strcasecmp() depends on the locale, but for ASCII-only + strings, it's safe to use */ + return strcasecmp(a, b) == 0; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringEqualsCaseASCII(const char *a, const char *b, size_t n) noexcept +{ +#if !CLANG_CHECK_VERSION(3,6) + /* disabled on clang due to -Wtautological-pointer-compare */ + assert(a != nullptr); + assert(b != nullptr); +#endif + + /* note: strcasecmp() depends on the locale, but for ASCII-only + strings, it's safe to use */ + return strncasecmp(a, b, n) == 0; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringStartsWithCaseASCII(const char *haystack, + std::string_view needle) noexcept +{ + return StringEqualsCaseASCII(haystack, needle.data(), needle.length()); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringAfterPrefixCaseASCII(const char *haystack, + std::string_view needle) noexcept +{ + return StringStartsWithCaseASCII(haystack, needle) + ? haystack + needle.length() + : nullptr; +} + +#endif diff --git a/src/util/AllocatedArray.hxx b/src/util/AllocatedArray.hxx new file mode 100644 index 0000000..d7c1ef8 --- /dev/null +++ b/src/util/AllocatedArray.hxx @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include + +/** + * An array allocated on the heap with a length determined at runtime. + */ +template +class AllocatedArray { + using Buffer = std::span; + +public: + using value_type = T; + using size_type = typename Buffer::size_type; + using reference = typename Buffer::reference; + using const_reference = typename Buffer::const_reference; + using pointer = typename Buffer::pointer; + using const_pointer = typename Buffer::const_pointer; + using iterator = typename Buffer::iterator; + using const_iterator = typename Buffer::iterator; + +protected: + Buffer buffer{}; + +public: + constexpr AllocatedArray() = default; + + explicit AllocatedArray(size_type _size) noexcept + :buffer{new T[_size], _size} {} + + explicit AllocatedArray(std::span src) noexcept { + if (src.data() == nullptr) + return; + + buffer = {new T[src.size()], src.size()}; + std::copy(src.begin(), src.end(), buffer.begin()); + } + + AllocatedArray(std::nullptr_t) noexcept {} + + explicit AllocatedArray(const AllocatedArray &other) noexcept + :AllocatedArray(other.buffer) {} + + AllocatedArray(AllocatedArray &&other) noexcept + :buffer(other.release()) {} + + ~AllocatedArray() noexcept { + delete[] buffer.data(); + } + + AllocatedArray &operator=(std::span src) noexcept { + assert(empty() || buffer.data() != nullptr); + assert(src.empty() || src.data() != nullptr); + + ResizeDiscard(src.size()); + std::copy(src.begin(), src.end(), buffer.begin()); + return *this; + } + + AllocatedArray &operator=(const AllocatedArray &other) noexcept { + assert(empty() || buffer.data() != nullptr); + assert(other.empty() || other.buffer.data() != nullptr); + + if (&other == this) + return *this; + + ResizeDiscard(other.size()); + std::copy_n(other.buffer.begin(), other.buffer.end(), + buffer.begin()); + return *this; + } + + AllocatedArray &operator=(AllocatedArray &&other) noexcept { + using std::swap; + swap(buffer, other.buffer); + return *this; + } + + AllocatedArray &operator=(std::nullptr_t) noexcept { + delete[] buffer.data(); + buffer = {}; + return *this; + } + + operator std::span() const noexcept { + return buffer; + } + + operator std::span() noexcept { + return buffer; + } + + constexpr bool operator==(std::nullptr_t) const noexcept { + return buffer.data() == nullptr; + } + + /** + * Returns true if no memory was allocated so far. + */ + constexpr bool empty() const noexcept { + return buffer.empty(); + } + + /** + * Returns the number of allocated elements. + */ + constexpr size_type size() const noexcept { + return buffer.size(); + } + + /** + * Returns the number of allocated elements. + */ + constexpr size_type capacity() const noexcept { + return buffer.size(); + } + + pointer data() noexcept { + return buffer.data(); + } + + const_pointer data() const noexcept { + return buffer.data(); + } + + reference front() noexcept { + return buffer.front(); + } + + const_reference front() const noexcept { + return buffer.front(); + } + + reference back() noexcept { + return buffer.back(); + } + + const_reference back() const noexcept { + return buffer.back(); + } + + /** + * Returns one element. No bounds checking. + */ + reference operator[](size_type i) noexcept { + return buffer[i]; + } + + /** + * Returns one constant element. No bounds checking. + */ + const_reference operator[](size_type i) const noexcept { + return buffer[i]; + } + + iterator begin() noexcept { + return buffer.begin(); + } + + constexpr const_iterator begin() const noexcept { + return buffer.begin(); + } + + iterator end() noexcept { + return buffer.end(); + } + + constexpr const_iterator end() const noexcept { + return buffer.end(); + } + + /** + * Resizes the array, discarding old data. + */ + void ResizeDiscard(size_type _size) noexcept { + if (_size == buffer.size()) + return; + + delete[] buffer.data(); + buffer = {new T[_size], _size}; + } + + /** + * Grows the array to the specified size, discarding old data. + * Similar to ResizeDiscard(), but will never shrink the array to + * avoid expensive heap operations. + */ + void GrowDiscard(size_type _size) noexcept { + if (_size > buffer.size()) + ResizeDiscard(_size); + } + + /** + * Grows the array to the specified size, preserving the value of a + * range of elements, starting from the beginning. + */ + void GrowPreserve(size_type _size, size_type preserve) noexcept { + if (_size <= buffer.size()) + return; + + T *new_data = new T[_size]; + + std::move(buffer.begin(), std::next(buffer.begin(), preserve), + new_data); + + delete[] buffer.data(); + buffer = {new_data, _size}; + } + + /** + * Declare that the buffer has the specified size. Must not be + * larger than the current size. Excess elements are not used (but + * they are still allocated). + */ + void SetSize(size_type _size) noexcept { + assert(_size <= buffer.size()); + + buffer = buffer.first(_size); + } + + /** + * Give up ownership of the allocated buffer and return it. + */ + Buffer release() noexcept { + return std::exchange(buffer, std::span{}); + } +}; diff --git a/src/util/AllocatedString.hxx b/src/util/AllocatedString.hxx new file mode 100644 index 0000000..1e1f21b --- /dev/null +++ b/src/util/AllocatedString.hxx @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "StringPointer.hxx" + +#include +#include +#include +#include +#include + +/** + * A string pointer whose memory is managed by this class. + * + * Unlike std::string, this object can hold a "nullptr" special value. + */ +template +class BasicAllocatedString { +public: + using value_type = typename StringPointer::value_type; + using reference = typename StringPointer::reference; + using const_reference = typename StringPointer::const_reference; + using pointer = typename StringPointer::pointer; + using const_pointer = typename StringPointer::const_pointer; + using string_view = std::basic_string_view; + using size_type = std::size_t; + + static constexpr value_type SENTINEL = '\0'; + +private: + pointer value = nullptr; + + explicit BasicAllocatedString(pointer _value) noexcept + :value(_value) {} + +public: + BasicAllocatedString() noexcept = default; + BasicAllocatedString(std::nullptr_t n) noexcept + :value(n) {} + + explicit BasicAllocatedString(string_view src) + :value(Duplicate(src)) {} + + explicit BasicAllocatedString(const_pointer src) + :value(Duplicate(src)) {} + + /** + * Concatenate several strings. + */ + BasicAllocatedString(std::initializer_list src) + :value(new value_type[TotalSize(src) + 1]) + { + auto *p = value; + for (const auto i : src) + p = std::copy(i.begin(), i.end(), p); + *p = SENTINEL; + } + + BasicAllocatedString(const BasicAllocatedString &src) noexcept + :BasicAllocatedString(Duplicate(src.value)) {} + + BasicAllocatedString(BasicAllocatedString &&src) noexcept + :value(src.Steal()) {} + + ~BasicAllocatedString() noexcept { + delete[] value; + } + + static BasicAllocatedString Donate(pointer value) noexcept { + return BasicAllocatedString(value); + } + + static BasicAllocatedString Empty() { + auto p = new value_type[1]; + p[0] = SENTINEL; + return Donate(p); + } + + BasicAllocatedString &operator=(BasicAllocatedString &&src) noexcept { + std::swap(value, src.value); + return *this; + } + + BasicAllocatedString &operator=(string_view src) noexcept { + delete[] std::exchange(value, nullptr); + value = Duplicate(src); + return *this; + } + + BasicAllocatedString &operator=(const_pointer src) noexcept { + delete[] std::exchange(value, nullptr); + value = src != nullptr ? Duplicate(src) : nullptr; + return *this; + } + + constexpr bool operator==(std::nullptr_t) const noexcept { + return value == nullptr; + } + + operator string_view() const noexcept { + return value != nullptr + ? string_view(value) + : string_view(); + } + + constexpr const_pointer c_str() const noexcept { + return value; + } + + bool empty() const noexcept { + return *value == SENTINEL; + } + + constexpr pointer data() const noexcept { + return value; + } + + reference operator[](size_type i) noexcept { + return value[i]; + } + + const reference operator[](size_type i) const noexcept { + return value[i]; + } + + pointer Steal() noexcept { + return std::exchange(value, nullptr); + } + +private: + static pointer Duplicate(string_view src) { + auto p = new value_type[src.size() + 1]; + *std::copy_n(src.data(), src.size(), p) = SENTINEL; + return p; + } + + static pointer Duplicate(const_pointer src) { + return src != nullptr + ? Duplicate(string_view(src)) + : nullptr; + } + + static constexpr std::size_t TotalSize(std::initializer_list src) noexcept { + std::size_t size = 0; + for (const string_view i : src) + size += i.size(); + return size; + } +}; + +class AllocatedString : public BasicAllocatedString { +public: + using BasicAllocatedString::BasicAllocatedString; + + AllocatedString() noexcept = default; + AllocatedString(BasicAllocatedString &&src) noexcept + :BasicAllocatedString(std::move(src)) {} + + using BasicAllocatedString::operator=; +}; diff --git a/src/util/BindMethod.hxx b/src/util/BindMethod.hxx new file mode 100644 index 0000000..3899603 --- /dev/null +++ b/src/util/BindMethod.hxx @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include + +/** + * This object stores a function pointer wrapping a method, and a + * reference to an instance of the method's class. It can be used to + * wrap instance methods as callback functions. + * + * @param S the plain function signature type + */ +template +class BoundMethod; + +template +class BoundMethod { + using function_pointer = R (*)(void *, Args...) noexcept(NoExcept); + + void *instance_; + function_pointer function; + +public: + /** + * Non-initializing trivial constructor + */ + constexpr BoundMethod() = default; + + constexpr + BoundMethod(void *_instance, function_pointer _function) noexcept + :instance_(_instance), function(_function) {} + + /** + * Construct an "undefined" object. It must not be called, + * and its "bool" operator returns false. + */ + constexpr BoundMethod(std::nullptr_t) noexcept:function(nullptr) {} + + /** + * Was this object initialized with a valid function pointer? + */ + constexpr operator bool() const noexcept { + return function != nullptr; + } + + R operator()(Args... args) const noexcept(NoExcept) { + return function(instance_, std::forward(args)...); + } +}; + +namespace BindMethodDetail { + +/** + * Helper class which introspects a method/function pointer type. + * + * @param M the method/function pointer type + */ +template +struct SignatureHelper; + +template +struct SignatureHelper { + /** + * The class which contains the given method (signature). + */ + using class_type = T; + + /** + * A function type which describes the "plain" function + * signature. + */ + using plain_signature = R (Args...) noexcept(NoExcept); + + using function_pointer = R (*)(void *, Args...) noexcept(NoExcept); +}; + +template +struct SignatureHelper { + using plain_signature = R (Args...) noexcept(NoExcept); + + using function_pointer = R (*)(void *, Args...) noexcept(NoExcept); +}; + +/** + * Generate a wrapper function. + * + * @param method the method/function pointer + */ +template +struct WrapperGenerator; + +template +struct WrapperGenerator { + static R Invoke(void *_instance, Args... args) noexcept(NoExcept) { + auto &t = *(T *)_instance; + return (t.*method)(std::forward(args)...); + } +}; + +template +struct WrapperGenerator { + static R Invoke(void *, Args... args) noexcept(NoExcept) { + return function(std::forward(args)...); + } +}; + +template +typename SignatureHelper::function_pointer +MakeWrapperFunction() noexcept +{ + return WrapperGenerator::Invoke; +} + +} /* namespace BindMethodDetail */ + +/** + * Construct a #BoundMethod instance. + * + * @param method the method pointer + * @param instance the instance of #T to be bound + */ +template +constexpr BoundMethod::plain_signature> +BindMethod(typename BindMethodDetail::SignatureHelper::class_type &instance) noexcept +{ + return { + &instance, + BindMethodDetail::MakeWrapperFunction(), + }; +} + +/** + * Shortcut macro which takes an instance and a method pointer and + * constructs a #BoundMethod instance. + */ +#define BIND_METHOD(instance, method) \ + BindMethod(instance) + +/** + * Shortcut wrapper for BIND_METHOD() which assumes "*this" is the + * instance to be bound. + */ +#define BIND_THIS_METHOD(method) BIND_METHOD(*this, &std::remove_reference_t::method) + +/** + * Construct a #BoundMethod instance for a plain function. + * + * @param function the function pointer + */ +template +constexpr BoundMethod::plain_signature> +BindFunction() noexcept +{ + return { + nullptr, + BindMethodDetail::MakeWrapperFunction(), + }; +} + +/** + * Shortcut macro which takes a function pointer and constructs a + * #BoundMethod instance. + */ +#define BIND_FUNCTION(function) \ + BindFunction<&function>() diff --git a/src/util/BitReverse.cxx b/src/util/BitReverse.cxx new file mode 100644 index 0000000..ddc8e08 --- /dev/null +++ b/src/util/BitReverse.cxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "BitReverse.hxx" + +static constexpr BitReverseTable +GenerateBitReverseTable() noexcept +{ + BitReverseTable table{}; + for (unsigned i = 0; i < 256; ++i) + table.data[i] = BitReverseMultiplyModulus(static_cast(i)); + return table; +} + +const BitReverseTable bit_reverse_table = GenerateBitReverseTable(); diff --git a/src/util/BitReverse.hxx b/src/util/BitReverse.hxx new file mode 100644 index 0000000..88389c4 --- /dev/null +++ b/src/util/BitReverse.hxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include +#include + +/** + * @see http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv + */ +constexpr std::byte +BitReverseMultiplyModulus(std::byte _in) noexcept +{ + uint64_t in = static_cast(_in); + return static_cast((in * 0x0202020202ULL & 0x010884422010ULL) % 1023); +} + +/* in order to avoid including in this header, this `struct` + is a workaround for GenerateBitReverseTable() being able to return + the plain array */ +struct BitReverseTable { + std::byte data[256]; +}; + +extern const BitReverseTable bit_reverse_table; + +[[gnu::const]] +static inline std::byte +BitReverse(std::byte x) noexcept +{ + return bit_reverse_table.data[static_cast(x)]; +} diff --git a/src/util/ByteOrder.hxx b/src/util/ByteOrder.hxx new file mode 100644 index 0000000..78bcc21 --- /dev/null +++ b/src/util/ByteOrder.hxx @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +#if defined(__i386__) || defined(__x86_64__) || defined(__ARMEL__) +/* well-known little-endian */ +# define IS_LITTLE_ENDIAN true +# define IS_BIG_ENDIAN false +#elif defined(__MIPSEB__) +/* well-known big-endian */ +# define IS_LITTLE_ENDIAN false +# define IS_BIG_ENDIAN true +#elif defined(__APPLE__) || defined(__NetBSD__) +/* compile-time check for MacOS */ +# include +# if BYTE_ORDER == LITTLE_ENDIAN +# define IS_LITTLE_ENDIAN true +# define IS_BIG_ENDIAN false +# else +# define IS_LITTLE_ENDIAN false +# define IS_BIG_ENDIAN true +# endif +#elif defined(__BYTE_ORDER__) +/* GCC-specific macros */ +# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define IS_LITTLE_ENDIAN true +# define IS_BIG_ENDIAN false +# else +# define IS_LITTLE_ENDIAN false +# define IS_BIG_ENDIAN true +# endif +#else +/* generic compile-time check */ +# include +# if __BYTE_ORDER == __LITTLE_ENDIAN +# define IS_LITTLE_ENDIAN true +# define IS_BIG_ENDIAN false +# else +# define IS_LITTLE_ENDIAN false +# define IS_BIG_ENDIAN true +# endif +#endif + +constexpr bool +IsLittleEndian() noexcept +{ + return IS_LITTLE_ENDIAN; +} + +constexpr bool +IsBigEndian() noexcept +{ + return IS_BIG_ENDIAN; +} + +constexpr uint16_t +GenericByteSwap16(uint16_t value) noexcept +{ + return (value >> 8) | (value << 8); +} + +constexpr uint32_t +GenericByteSwap32(uint32_t value) noexcept +{ + return (value >> 24) | ((value >> 8) & 0x0000ff00) | + ((value << 8) & 0x00ff0000) | (value << 24); +} + +constexpr uint64_t +GenericByteSwap64(uint64_t value) noexcept +{ + return uint64_t(GenericByteSwap32(uint32_t(value >> 32))) + | (uint64_t(GenericByteSwap32(value)) << 32); +} + +constexpr uint16_t +ByteSwap16(uint16_t value) noexcept +{ +#ifdef __GNUC__ + return __builtin_bswap16(value); +#else + return GenericByteSwap16(value); +#endif +} + +constexpr uint32_t +ByteSwap32(uint32_t value) noexcept +{ +#ifdef __GNUC__ + return __builtin_bswap32(value); +#else + return GenericByteSwap32(value); +#endif +} + +constexpr uint64_t +ByteSwap64(uint64_t value) noexcept +{ +#ifdef __GNUC__ + return __builtin_bswap64(value); +#else + return GenericByteSwap64(value); +#endif +} + +/** + * Converts a 16bit value from big endian to the system's byte order + */ +constexpr uint16_t +FromBE16(uint16_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap16(value); +} + +/** + * Converts a 32bit value from big endian to the system's byte order + */ +constexpr uint32_t +FromBE32(uint32_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap32(value); +} + +/** + * Converts a 64bit value from big endian to the system's byte order + */ +constexpr uint64_t +FromBE64(uint64_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap64(value); +} + +/** + * Converts a 16bit value from little endian to the system's byte order + */ +constexpr uint16_t +FromLE16(uint16_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap16(value); +} + +/** + * Converts a 32bit value from little endian to the system's byte order + */ +constexpr uint32_t +FromLE32(uint32_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap32(value); +} + +/** + * Converts a 64bit value from little endian to the system's byte order + */ +constexpr uint64_t +FromLE64(uint64_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap64(value); +} + +/** + * Converts a 16bit value from the system's byte order to big endian + */ +constexpr uint16_t +ToBE16(uint16_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap16(value); +} + +/** + * Converts a 32bit value from the system's byte order to big endian + */ +constexpr uint32_t +ToBE32(uint32_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap32(value); +} + +/** + * Converts a 64bit value from the system's byte order to big endian + */ +constexpr uint64_t +ToBE64(uint64_t value) noexcept +{ + return IsBigEndian() ? value : ByteSwap64(value); +} + +/** + * Converts a 16bit value from the system's byte order to little endian + */ +constexpr uint16_t +ToLE16(uint16_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap16(value); +} + +/** + * Converts a 32bit value from the system's byte order to little endian + */ +constexpr uint32_t +ToLE32(uint32_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap32(value); +} + +/** + * Converts a 64bit value from the system's byte order to little endian + */ +constexpr uint64_t +ToLE64(uint64_t value) noexcept +{ + return IsLittleEndian() ? value : ByteSwap64(value); +} + +/** + * Converts a 16 bit integer from little endian to the host byte order + * and returns it as a signed integer. + */ +constexpr int16_t +FromLE16S(uint16_t value) noexcept +{ + /* assuming two's complement representation */ + return static_cast(FromLE16(value)); +} diff --git a/src/util/ByteReverse.cxx b/src/util/ByteReverse.cxx new file mode 100644 index 0000000..fa07d40 --- /dev/null +++ b/src/util/ByteReverse.cxx @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ByteReverse.hxx" +#include "util/ByteOrder.hxx" +#include "Compiler.h" + +#include + +void +reverse_bytes_16(uint16_t *gcc_restrict dest, + const uint16_t *gcc_restrict src, + const uint16_t *src_end) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(src_end >= src); + + while (src < src_end) { + const uint16_t x = *src++; + *dest++ = ByteSwap16(x); + } +} + +void +reverse_bytes_32(uint32_t *gcc_restrict dest, + const uint32_t *gcc_restrict src, + const uint32_t *src_end) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(src_end >= src); + + while (src < src_end) { + const uint32_t x = *src++; + *dest++ = ByteSwap32(x); + } +} + +void +reverse_bytes_64(uint64_t *gcc_restrict dest, + const uint64_t *gcc_restrict src, + const uint64_t *src_end) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(src_end >= src); + + while (src < src_end) { + const uint64_t x = *src++; + *dest++ = ByteSwap64(x); + } +} + +static void +reverse_bytes_linear(uint8_t *gcc_restrict dest, + const uint8_t *gcc_restrict src, size_t n) noexcept +{ + src += n; + + while (n-- > 0) + *dest++ = *--src; +} + +static void +reverse_bytes_generic(uint8_t *gcc_restrict dest, + const uint8_t *gcc_restrict src, const uint8_t *src_end, + size_t frame_size) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(src_end >= src); + assert(frame_size > 0); + assert((src_end - src) % frame_size == 0); + + while (src < src_end) { + reverse_bytes_linear(dest, src, frame_size); + dest += frame_size; + src += frame_size; + } +} + +void +reverse_bytes(uint8_t *gcc_restrict dest, + const uint8_t *gcc_restrict src, const uint8_t *src_end, + size_t frame_size) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(src_end >= src); + assert(frame_size > 0); + assert((src_end - src) % frame_size == 0); + + switch (frame_size) { + case 2: + reverse_bytes_16((uint16_t *)dest, + (const uint16_t *)src, + (const uint16_t *)src_end); + break; + + case 4: + reverse_bytes_32((uint32_t *)dest, + (const uint32_t *)src, + (const uint32_t *)src_end); + break; + + case 8: + reverse_bytes_64((uint64_t *)dest, + (const uint64_t *)src, + (const uint64_t *)src_end); + break; + + default: + reverse_bytes_generic(dest, src, src_end, frame_size); + } +} diff --git a/src/util/ByteReverse.hxx b/src/util/ByteReverse.hxx new file mode 100644 index 0000000..1bcc66a --- /dev/null +++ b/src/util/ByteReverse.hxx @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_BYTE_REVERSE_HXX +#define MPD_BYTE_REVERSE_HXX + +#include +#include + +/** + * Reverse the bytes in each 16 bit "frame". This function can be + * used for in-place operation. + */ +void +reverse_bytes_16(uint16_t *dest, + const uint16_t *src, const uint16_t *src_end) noexcept; + +/** + * Reverse the bytes in each 32 bit "frame". This function can be + * used for in-place operation. + */ +void +reverse_bytes_32(uint32_t *dest, + const uint32_t *src, const uint32_t *src_end) noexcept; + +/** + * Reverse the bytes in each 64 bit "frame". This function can be + * used for in-place operation. + */ +void +reverse_bytes_64(uint64_t *dest, + const uint64_t *src, const uint64_t *src_end) noexcept; + +/** + * Reverse the bytes in each "frame". This function cannot be used + * for in-place operation. + */ +void +reverse_bytes(uint8_t *dest, const uint8_t *src, const uint8_t *src_end, + size_t frame_size) noexcept; + +#endif diff --git a/src/util/CNumberParser.hxx b/src/util/CNumberParser.hxx new file mode 100644 index 0000000..96264c9 --- /dev/null +++ b/src/util/CNumberParser.hxx @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include + +#include + +static inline unsigned +ParseUnsigned(const char *p, char **endptr=nullptr, int base=10) noexcept +{ + assert(p != nullptr); + + return (unsigned)strtoul(p, endptr, base); +} + +static inline int +ParseInt(const char *p, char **endptr=nullptr, int base=10) noexcept +{ + assert(p != nullptr); + + return (int)strtol(p, endptr, base); +} + +static inline uint64_t +ParseUint64(const char *p, char **endptr=nullptr, int base=10) noexcept +{ + assert(p != nullptr); + + return strtoull(p, endptr, base); +} + +static inline double +ParseDouble(const char *p, char **endptr=nullptr) noexcept +{ + assert(p != nullptr); + + return (double)strtod(p, endptr); +} + +static inline float +ParseFloat(const char *p, char **endptr=nullptr) noexcept +{ + return strtof(p, endptr); +} diff --git a/src/util/Cast.hxx b/src/util/Cast.hxx new file mode 100644 index 0000000..1a2a2d0 --- /dev/null +++ b/src/util/Cast.hxx @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "OffsetPointer.hxx" + +#include + +template +constexpr T * +OffsetCast(U *p, std::ptrdiff_t offset) +{ + return reinterpret_cast(OffsetPointer(p, offset)); +} + +template +constexpr T * +OffsetCast(const U *p, std::ptrdiff_t offset) +{ + return reinterpret_cast(OffsetPointer(p, offset)); +} + +template +constexpr std::ptrdiff_t +ContainerAttributeOffset(const C *null_c, const A C::*p) +{ + return std::ptrdiff_t((const char *)&(null_c->*p) - (const char *)null_c); +} + +template +constexpr std::ptrdiff_t +ContainerAttributeOffset(const A C::*p) +{ + return ContainerAttributeOffset(nullptr, p); +} + +/** + * Cast the given pointer to a struct member to its parent structure. + */ +template +constexpr C & +ContainerCast(A &a, const A C::*member) +{ + return *OffsetCast(&a, -ContainerAttributeOffset(member)); +} + +/** + * Cast the given pointer to a struct member to its parent structure. + */ +template +constexpr const C & +ContainerCast(const A &a, const A C::*member) +{ + return *OffsetCast(&a, -ContainerAttributeOffset(member)); +} diff --git a/src/util/CharUtil.hxx b/src/util/CharUtil.hxx new file mode 100644 index 0000000..3f111b3 --- /dev/null +++ b/src/util/CharUtil.hxx @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#ifdef _UNICODE +#include "WCharUtil.hxx" +#endif + +constexpr bool +IsASCII(const unsigned char ch) noexcept +{ + return ch < 0x80; +} + +constexpr bool +IsASCII(const char ch) noexcept +{ + return IsASCII((unsigned char)ch); +} + +constexpr bool +IsWhitespaceOrNull(const char ch) noexcept +{ + return (unsigned char)ch <= 0x20; +} + +constexpr bool +IsWhitespaceNotNull(const char ch) noexcept +{ + return ch > 0 && ch <= 0x20; +} + +/** + * Is the given character whitespace? This calls the faster one of + * IsWhitespaceOrNull() or IsWhitespaceNotNull(). Use this if you + * want the fastest implementation, and you don't care if a null byte + * matches. + */ +constexpr bool +IsWhitespaceFast(const char ch) noexcept +{ + return IsWhitespaceOrNull(ch); +} + +/** + * Is this a non-printable ASCII character? Returns false for + * non-ASCII characters. + * + * Note that this is not the opposite of IsNonPrintableASCII(). + */ +constexpr bool +IsPrintableASCII(char ch) noexcept +{ + return (signed char)ch >= 0x20; +} + +/** + * Is this a non-printable character? Returns false for non-ASCII characters. + * + * Note that this is not the opposite of IsPrintableASCII() + */ +constexpr bool +IsNonPrintableASCII(char ch) noexcept +{ + return (unsigned char)ch < 0x20; +} + +constexpr bool +IsDigitASCII(char ch) noexcept +{ + return ch >= '0' && ch <= '9'; +} + +constexpr bool +IsUpperAlphaASCII(char ch) noexcept +{ + return ch >= 'A' && ch <= 'Z'; +} + +constexpr bool +IsLowerAlphaASCII(char ch) noexcept +{ + return ch >= 'a' && ch <= 'z'; +} + +constexpr bool +IsAlphaASCII(char ch) noexcept +{ + return IsUpperAlphaASCII(ch) || IsLowerAlphaASCII(ch); +} + +constexpr bool +IsAlphaNumericASCII(char ch) noexcept +{ + return IsAlphaASCII(ch) || IsDigitASCII(ch); +} + +constexpr bool +IsUpperAlphaNumericASCII(char ch) noexcept +{ + return IsUpperAlphaASCII(ch) || IsDigitASCII(ch); +} + +constexpr bool +IsLowerAlphaNumericASCII(char ch) noexcept +{ + return IsLowerAlphaASCII(ch) || IsDigitASCII(ch); +} + +/** + * Convert the specified ASCII character (0x00..0x7f) to upper case. + * Unlike toupper(), it ignores the system locale. + */ +constexpr char +ToUpperASCII(char ch) noexcept +{ + return ch >= 'a' && ch <= 'z' + ? (ch - ('a' - 'A')) + : ch; +} + +/** + * Convert the specified ASCII character (0x00..0x7f) to lower case. + * Unlike tolower(), it ignores the system locale. + */ +constexpr char +ToLowerASCII(char ch) noexcept +{ + return ch >= 'A' && ch <= 'Z' + ? (ch + ('a' - 'A')) + : ch; +} + +constexpr bool +IsLowerHexDigit(char ch) noexcept +{ + return IsDigitASCII(ch) || + (ch >= 'a' && ch <= 'f'); +} + +constexpr bool +IsHexDigit(char ch) noexcept +{ + return IsLowerHexDigit(ch) || + (ch >= 'A' && ch <= 'F'); +} diff --git a/src/util/CircularBuffer.hxx b/src/util/CircularBuffer.hxx new file mode 100644 index 0000000..2d549c0 --- /dev/null +++ b/src/util/CircularBuffer.hxx @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include // for std::move() +#include +#include +#include + +/** + * A circular buffer. + * + * This class does not manage buffer memory. It will not allocate or + * free any memory, it only manages the contents of an existing + * buffer given to the constructor. + * + * Everything between #head and #tail is valid data (may wrap around). + * If both are equal, then the buffer is empty. Due to this + * implementation detail, the buffer is empty when #size-1 items are + * stored; the last buffer cell cannot be used. + */ +template +class CircularBuffer { +public: + using Range = std::span; + using pointer = typename Range::pointer; + using size_type = typename Range::size_type; + +protected: + /** + * The next index to be read. + */ + size_type head = 0; + + /** + * The next index to be written to. + */ + size_type tail = 0; + + const std::span buffer; + +public: + explicit constexpr CircularBuffer(Range _buffer) noexcept + :buffer(_buffer) {} + + CircularBuffer(const CircularBuffer &other) = delete; + CircularBuffer &operator=(const CircularBuffer &other) = delete; + +protected: + constexpr size_type Next(size_type i) const noexcept { + return i + 1 == buffer.size() + ? 0 + : i + 1; + } + +public: + constexpr void Clear() noexcept { + head = tail = 0; + } + + constexpr size_type GetCapacity() const noexcept { + return buffer.size(); + } + + constexpr bool empty() const noexcept { + return head == tail; + } + + constexpr bool IsFull() const noexcept { + return Next(tail) == head; + } + + /** + * Returns the number of elements stored in this buffer. + */ + constexpr size_type GetSize() const noexcept { + return head <= tail + ? tail - head + : buffer.size() - head + tail; + } + + /** + * Returns the number of elements that can be added to this + * buffer. + */ + constexpr size_type GetSpace() const noexcept { + /* space = capacity - size - 1 */ + return (head <= tail + ? buffer.size() - tail + head + : head - tail) + - 1; + } + + /** + * Prepares writing. Returns a buffer range which may be written. + * When you are finished, call Append(). + */ + constexpr Range Write() noexcept { + assert(head < buffer.size()); + assert(tail < buffer.size()); + + size_type end = tail < head + ? head - 1 + /* the "head==0" is there so we don't write + the last cell, as this situation cannot be + represented by head/tail */ + : buffer.size() - (head == 0); + + return buffer.subspan(tail, end - tail); + } + + /** + * Expands the tail of the buffer, after data has been written + * to the buffer returned by Write(). + */ + constexpr void Append(size_type n) noexcept { + assert(head < buffer.size()); + assert(tail < buffer.size()); + assert(n < buffer.size()); + assert(tail + n <= buffer.size()); + assert(head <= tail || tail + n < head); + + tail += n; + + if (tail == buffer.size()) { + assert(head > 0); + tail = 0; + } + } + + /** + * Return a buffer range which may be read. The buffer pointer is + * writable, to allow modifications while parsing. + */ + constexpr Range Read() noexcept { + assert(head < buffer.size()); + assert(tail < buffer.size()); + + return buffer.subspan(head, (tail < head ? buffer.size() : tail) - head); + } + + /** + * Marks a chunk as consumed. + */ + constexpr void Consume(size_type n) noexcept { + assert(head < buffer.size()); + assert(tail < buffer.size()); + assert(n < buffer.size()); + assert(head + n <= buffer.size()); + assert(tail < head || head + n <= tail); + + head += n; + if (head == buffer.size()) + head = 0; + } + + /** + * Move data from the buffer to the destination. This method + * considers ring buffer wraparound. + * + * @return the number of items moved + */ + constexpr size_type MoveTo(Range dest) noexcept { + size_type n = 0; + + auto a = Read(); + if (a.size() > dest.size()) + a = a.first(dest.size()); + + if (!a.empty()) { + dest = {std::move(a.begin(), a.end(), dest.begin()), dest.end()}; + Consume(a.size()); + n += a.size(); + + if (dest.empty()) + return n; + + if (auto b = Read(); !b.empty()) { + if (b.size() > dest.size()) + b = b.first(dest.size()); + + std::move(b.begin(), b.end(), dest.begin()); + Consume(b.size()); + n += b.size(); + } + } + + return n; + } +}; diff --git a/src/util/Clamp.hxx b/src/util/Clamp.hxx new file mode 100644 index 0000000..e64bd2b --- /dev/null +++ b/src/util/Clamp.hxx @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef CLAMP_HPP +#define CLAMP_HPP + +/** + * Clamps the specified value in a range. Returns #min or #max if the + * value is outside. + */ +template +constexpr const T & +Clamp(const T &value, const T &min, const T &max) noexcept +{ + if (value < min) [[unlikely]] + return min; + + if (value > max) [[unlikely]] + return max; + + return value; +} + +#endif diff --git a/src/util/Compiler.h b/src/util/Compiler.h new file mode 100644 index 0000000..a7c7811 --- /dev/null +++ b/src/util/Compiler.h @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef COMPILER_H +#define COMPILER_H + +#define GCC_MAKE_VERSION(major, minor, patchlevel) ((major) * 10000 + (minor) * 100 + patchlevel) + +#ifdef __GNUC__ +#define GCC_VERSION GCC_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#else +#define GCC_VERSION 0 +#endif + +#ifdef __clang__ +# define CLANG_VERSION GCC_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) +#elif defined(__GNUC__) +# define CLANG_VERSION 0 +#endif + +/** + * Are we building with the specified version of gcc (not clang or any + * other compiler) or newer? + */ +#define GCC_CHECK_VERSION(major, minor) \ + (CLANG_VERSION == 0 && \ + GCC_VERSION >= GCC_MAKE_VERSION(major, minor, 0)) + +/** + * Are we building with the specified version of clang or newer? + */ +#define CLANG_CHECK_VERSION(major, minor) \ + (CLANG_VERSION >= GCC_MAKE_VERSION(major, minor, 0)) + +#ifdef __GNUC__ + +/* GCC 4.x */ + +#define gcc_malloc __attribute__((malloc)) +#define gcc_pure __attribute__((pure)) + +#define gcc_visibility_default __attribute__((visibility("default"))) + +#else + +/* generic C compiler */ + +#define gcc_malloc +#define gcc_pure + +#define gcc_visibility_default + +#endif + +#ifdef __GNUC__ +#define gcc_fallthrough __attribute__((fallthrough)) +#else +#define gcc_fallthrough +#endif + +#ifndef __cplusplus +/* plain C99 has "restrict" */ +#define gcc_restrict restrict +#elif defined(__GNUC__) +/* "__restrict__" is a GCC extension for C++ */ +#define gcc_restrict __restrict__ +#else +/* disable it on other compilers */ +#define gcc_restrict +#endif + +#endif diff --git a/src/util/Concepts.hxx b/src/util/Concepts.hxx new file mode 100644 index 0000000..a741d69 --- /dev/null +++ b/src/util/Concepts.hxx @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +template +concept Disposer = std::invocable; diff --git a/src/util/CopyConst.hxx b/src/util/CopyConst.hxx new file mode 100644 index 0000000..f30443d --- /dev/null +++ b/src/util/CopyConst.hxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Generate a type based on #To with the same const-ness as #From. + */ +template +using CopyConst = std::conditional_t, + std::add_const_t, + std::remove_const_t>; diff --git a/src/util/DeleteDisposer.hxx b/src/util/DeleteDisposer.hxx new file mode 100644 index 0000000..7be76d0 --- /dev/null +++ b/src/util/DeleteDisposer.hxx @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +/** + * A disposer for boost::intrusive that invokes the "delete" operator + * on the given pointer. + */ +class DeleteDisposer { +public: + template + void operator()(T *t) const noexcept { + delete t; + } +}; diff --git a/src/util/DereferenceIterator.hxx b/src/util/DereferenceIterator.hxx new file mode 100644 index 0000000..c40ea55 --- /dev/null +++ b/src/util/DereferenceIterator.hxx @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include + +/** + * An iterator wrapper that dereferences the values returned by the + * original iterator. + */ +template::value_type>())>> +class DereferenceIterator { + /* this friend declaration allows the template operator==() to + compare arbitrary specializations */ + template + friend class DereferenceIterator; + + using Traits = std::iterator_traits; + + IT original; + +public: + using iterator_category = typename Traits::iterator_category; + using difference_type = typename Traits::difference_type; + using value_type = VT; + using pointer = VT *; + using reference = VT &; + + constexpr DereferenceIterator() = default; + + constexpr DereferenceIterator(const IT _original) noexcept + :original(_original) {} + + constexpr reference operator*() const noexcept { + return static_cast(**original); + } + + constexpr pointer operator->() const noexcept { + return static_cast(&**original); + } + + constexpr auto &operator++() noexcept { + ++original; + return *this; + } + + constexpr auto operator++(int) noexcept { + auto old = *this; + ++original; + return old; + } + + constexpr auto &operator+=(difference_type n) noexcept { + original += n; + return *this; + } + + constexpr auto operator+(difference_type n) const noexcept { + return DereferenceIterator{original + n}; + } + + constexpr auto &operator--() noexcept { + --original; + return *this; + } + + constexpr auto operator--(int) noexcept { + auto old = *this; + --original; + return old; + } + + constexpr auto &operator-=(difference_type n) noexcept { + original -= n; + return *this; + } + + constexpr auto operator-(difference_type n) const noexcept { + return DereferenceIterator{original - n}; + } + + constexpr auto operator-(const DereferenceIterator& other) const noexcept { + return std::distance(other.original, original); + } + + /* this is a template to allow comparisons with sentinel end + iterators */ + template + constexpr bool operator==(const DereferenceIterator &other) const noexcept { + return original == other.original; + } +}; + +/** + * A container wrapper that wraps the iterators in a + * DereferenceIterator. + */ +template::value_type>> +class DereferenceContainerAdapter { + CT original; + + /* these aliases allow the underlying container to return a + different type for begin() and end() */ + using const_end_iterator = DereferenceIterator().cend()), const VT>; + using end_iterator = DereferenceIterator().end()), VT>; + +public: + using value_type = VT; + using pointer = VT *; + using reference = VT &; + + using const_iterator = DereferenceIterator().cbegin()), const VT>; + using iterator = DereferenceIterator().begin()), VT>; + + explicit constexpr DereferenceContainerAdapter(CT &&_original) noexcept + :original(std::move(_original)) {} + + constexpr iterator begin() noexcept { + return original.begin(); + } + + constexpr const_iterator begin() const noexcept { + return original.cbegin(); + } + + constexpr const_iterator cbegin() const noexcept { + return original.cbegin(); + } + + constexpr end_iterator end() noexcept { + return original.end(); + } + + constexpr const_end_iterator end() const noexcept { + return original.cend(); + } + + constexpr const_end_iterator cend() const noexcept { + return original.cend(); + } +}; diff --git a/src/util/DisposablePointer.hxx b/src/util/DisposablePointer.hxx new file mode 100644 index 0000000..6682d69 --- /dev/null +++ b/src/util/DisposablePointer.hxx @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include // for std::nullptr_t +#include + +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic push +/* suppress -Wuninitialized; GCC is right, the "dispose" field is + sometimes not initialized (if ptr==nullptr), but it's only swapped + in the move operator/constructor, and that's okay, we're not going + to use it in that case anyway */ +#pragma GCC diagnostic ignored "-Wuninitialized" +#endif + +/** + * A generic object which is owned by somebody who doesn't know how to + * dispose of it; to do this, a function pointer for disposing it is + * provided. Some implementations may do "delete this", but others + * may be allocated from a custom allocator and may need different + * ways to dispose of it. + * + * Unlike std::any, this class does not require the contained object + * to be copyable; quite contrary, it is designed to adopt ownership + * of the contained value. + */ +class DisposablePointer { +public: + using DisposeFunction = void(*)(void *ptr) noexcept; + +private: + void *ptr = nullptr; + + DisposeFunction dispose; + +public: + DisposablePointer() = default; + DisposablePointer(std::nullptr_t) noexcept {} + + DisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept + :ptr(_ptr), dispose(_dispose) {} + + DisposablePointer(DisposablePointer &&src) noexcept + :ptr(std::exchange(src.ptr, nullptr)), dispose(src.dispose) {} + + ~DisposablePointer() noexcept { + if (ptr != nullptr) + dispose(ptr); + } + + DisposablePointer &operator=(DisposablePointer &&other) noexcept { + using std::swap; + swap(ptr, other.ptr); + swap(dispose, other.dispose); + return *this; + } + + operator bool() const noexcept { + return ptr != nullptr; + } + + void *get() const noexcept { + return ptr; + } + + void reset() noexcept { + if (ptr != nullptr) + dispose(std::exchange(ptr, nullptr)); + } +}; + +#if defined(__GNUC__) && __GNUC__ >= 13 +#pragma GCC diagnostic pop +#endif + +template +class TypedDisposablePointer : public DisposablePointer { +public: + template + TypedDisposablePointer(Args&&... args) noexcept + :DisposablePointer(std::forward(args)...) {} + + TypedDisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept; + + TypedDisposablePointer(T *_ptr, DisposeFunction _dispose) noexcept + :DisposablePointer(_ptr, _dispose) {} + + T *get() const noexcept { + return (T *)DisposablePointer::get(); + } + + T *operator->() const noexcept { + return get(); + } + + T &operator*() const noexcept { + return *get(); + } +}; + +inline DisposablePointer +ToNopPointer(const void *ptr) noexcept +{ + /* since the disposer is a no-op, we allow passing a const + pointer here; the const_cast is necessary because + DisposablePointer wants a non-const pointer */ + return {const_cast(ptr), [](void *) noexcept {}}; +} + +template +TypedDisposablePointer +ToDeletePointer(T *ptr) noexcept +{ + return {ptr, [](void *p) noexcept { + T *t = (T *)p; + delete t; + }}; +} + +template +TypedDisposablePointer +ToDeleteArray(T *ptr) noexcept +{ + return {ptr, [](void *p) noexcept { + T *t = (T *)p; + delete[] t; + }}; +} + +template +TypedDisposablePointer +ToDestructPointer(T *ptr) noexcept +{ + return {ptr, [](void *p) noexcept { + T *t = (T *)p; + t->~T(); + }}; +} diff --git a/src/util/Domain.hxx b/src/util/Domain.hxx new file mode 100644 index 0000000..fb71a21 --- /dev/null +++ b/src/util/Domain.hxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef DOMAIN_HXX +#define DOMAIN_HXX + +class Domain { + const char *const name; + +public: + constexpr explicit Domain(const char *_name) noexcept + :name(_name) {} + + Domain(const Domain &) = delete; + Domain &operator=(const Domain &) = delete; + + constexpr const char *GetName() const noexcept { + return name; + } + + bool operator==(const Domain &other) const noexcept { + return this == &other; + } + + bool operator!=(const Domain &other) const noexcept { + return !(*this == other); + } +}; + +#endif diff --git a/src/util/DynamicFifoBuffer.hxx b/src/util/DynamicFifoBuffer.hxx new file mode 100644 index 0000000..e26f53a --- /dev/null +++ b/src/util/DynamicFifoBuffer.hxx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "ForeignFifoBuffer.hxx" + +/** + * A first-in-first-out buffer: you can append data at the end, and + * read data from the beginning. This class automatically shifts the + * buffer as needed. It is not thread safe. + */ +template +class DynamicFifoBuffer : protected ForeignFifoBuffer { +public: + using typename ForeignFifoBuffer::size_type; + using typename ForeignFifoBuffer::pointer; + using typename ForeignFifoBuffer::const_pointer; + using typename ForeignFifoBuffer::Range; + + /** + * Construct without allocating a buffer. + */ + explicit constexpr DynamicFifoBuffer(std::nullptr_t n) noexcept + :ForeignFifoBuffer(n) {} + + /** + * Allocate a buffer with the given capacity. + */ + explicit DynamicFifoBuffer(size_type _capacity) noexcept + :ForeignFifoBuffer(std::span{new T[_capacity], _capacity}) {} + + ~DynamicFifoBuffer() noexcept { + delete[] GetBuffer(); + } + + DynamicFifoBuffer(const DynamicFifoBuffer &) = delete; + + using ForeignFifoBuffer::GetCapacity; + using ForeignFifoBuffer::Clear; + using ForeignFifoBuffer::empty; + using ForeignFifoBuffer::IsFull; + using ForeignFifoBuffer::GetAvailable; + using ForeignFifoBuffer::Read; + using ForeignFifoBuffer::Consume; + using ForeignFifoBuffer::Write; + using ForeignFifoBuffer::Append; + + void Grow(size_type new_capacity) noexcept { + assert(new_capacity > GetCapacity()); + + T *old_data = GetBuffer(); + T *new_data = new T[new_capacity]; + ForeignFifoBuffer::MoveBuffer({new_data, new_capacity}); + delete[] old_data; + } + + void WantWrite(size_type n) noexcept { + if (ForeignFifoBuffer::WantWrite(n)) + /* we already have enough space */ + return; + + const size_type in_use = GetAvailable(); + const size_type required_capacity = in_use + n; + size_type new_capacity = GetCapacity(); + do { + new_capacity <<= 1; + } while (new_capacity < required_capacity); + + Grow(new_capacity); + } + + /** + * Write data to the buffer, growing it as needed. Returns a + * writable pointer. + */ + pointer Write(size_type n) noexcept { + WantWrite(n); + return Write().data(); + } + + /** + * Append data to the buffer, growing it as needed. + */ + void Append(std::span src) noexcept { + std::copy(src.begin(), src.end(), Write(src.size())); + Append(src.size()); + } + +protected: + using ForeignFifoBuffer::GetBuffer; +}; diff --git a/src/util/Exception.cxx b/src/util/Exception.cxx new file mode 100644 index 0000000..17eff34 --- /dev/null +++ b/src/util/Exception.cxx @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "Exception.hxx" +#include "CharUtil.hxx" +#include "StringStrip.hxx" + +#include + +/** + * Append the given C string to a std::string, with some + * sanitizations: strip whitespace at the beginning and the end and + * combine multiple whitespace to a single space. + * + * This shall compress strangely formatted multi-line messages (which + * may come from third-party libraries) to a single line. + */ +static void +AppendSanitize(std::string &dest, const char *src) noexcept +{ + src = StripLeft(src); + + bool space = false; + while (char ch = *src++) { + if (IsWhitespaceFast(ch)) { + space = true; + continue; + } + + if (space) { + space = false; + dest.push_back(' '); + } + + dest.push_back(ch); + } +} + +template +static void +AppendNestedMessage(std::string &result, T &&e, + const char *fallback, const char *separator) noexcept +{ + try { + std::rethrow_if_nested(std::forward(e)); + } catch (const std::exception &nested) { + result += separator; + AppendSanitize(result, nested.what()); + AppendNestedMessage(result, nested, fallback, separator); + } catch (const std::nested_exception &ne) { + AppendNestedMessage(result, ne, fallback, separator); + } catch (const char *s) { + result += separator; + AppendSanitize(result, s); + } catch (...) { + result += separator; + result += fallback; + } +} + +std::string +GetFullMessage(const std::exception &e, + const char *fallback, const char *separator) noexcept +{ + std::string result; + AppendSanitize(result, e.what()); + AppendNestedMessage(result, e, fallback, separator); + return result; +} + +std::string +GetFullMessage(std::exception_ptr ep, + const char *fallback, const char *separator) noexcept +{ + try { + std::rethrow_exception(std::move(ep)); + } catch (const std::exception &e) { + return GetFullMessage(e, fallback, separator); + } catch (const std::nested_exception &ne) { + return GetFullMessage(ne.nested_ptr(), fallback, separator); + } catch (const char *s) { + return s; + } catch (...) { + return fallback; + } +} diff --git a/src/util/Exception.hxx b/src/util/Exception.hxx new file mode 100644 index 0000000..44f3234 --- /dev/null +++ b/src/util/Exception.hxx @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include + +/** + * Throws the specified exception. There is an overload for + * std::exception_ptr which throws the contained exception instead of + * the std::exception_ptr itself. + */ +template +[[noreturn]] +inline void +ThrowException(T &&t) +{ + throw std::forward(t); +} + +[[noreturn]] +inline void +ThrowException(std::exception_ptr ep) +{ + std::rethrow_exception(ep); +} + +/** + * Create a nested exception, wrapping #ep inside the + * std::current_exception(). + */ +template +inline std::exception_ptr +NestCurrentException(T &&t) noexcept +{ + try { + std::throw_with_nested(std::forward(t)); + } catch (...) { + return std::current_exception(); + } +} + +/** + * Create a nested exception, wrapping #ep inside (a copy of) #t. + */ +template +inline std::exception_ptr +NestException(std::exception_ptr ep, T &&t) noexcept +{ + try { + std::rethrow_exception(ep); + } catch (...) { + return NestCurrentException(std::forward(t)); + } +} + +/** + * Find an instance of #T in the nested exception chain, and return a + * pointer. Returns nullptr if no such instance was found. + */ +template +[[gnu::pure]] +inline const T * +FindNested(std::exception_ptr ep) noexcept +{ + try { + std::rethrow_exception(ep); + } catch (const T &t) { + return &t; + } catch (const std::nested_exception &ne) { + return FindNested(ne.nested_ptr()); + } catch (...) { + } + + return nullptr; +} + +/** + * Find an instance of #T in the nested exception chain, and rethrow + * it. Does nothing if no such instance was found. + */ +template +inline void +FindRetrowNested(std::exception_ptr ep) +{ + try { + std::rethrow_exception(ep); + } catch (const T &t) { + throw; + } catch (const std::nested_exception &ne) { + FindRetrowNested(ne.nested_ptr()); + } catch (...) { + } +} + +/** + * Obtain the full concatenated message of an exception and its nested + * chain. + */ +std::string +GetFullMessage(const std::exception &e, + const char *fallback="Unknown exception", + const char *separator="; ") noexcept; + +/** + * Obtain the full concatenated message of an exception and its nested + * chain. + */ +std::string +GetFullMessage(std::exception_ptr ep, + const char *fallback="Unknown exception", + const char *separator="; ") noexcept; diff --git a/src/util/FilteredContainer.hxx b/src/util/FilteredContainer.hxx new file mode 100644 index 0000000..6e2d8ab --- /dev/null +++ b/src/util/FilteredContainer.hxx @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include // for std::iterator_traits + +/** + * A container wrapper which returns only elements for which a second + * container returns true. + */ +template +class FilteredContainer { + [[no_unique_address]] + AB a_begin; + + [[no_unique_address]] + AE a_end; + + [[no_unique_address]] + BB b_begin; + + struct end_iterator { + using Traits = std::iterator_traits; + + using iterator_category = typename Traits::iterator_category; + using difference_type = typename Traits::difference_type; + using value_type = typename Traits::value_type; + using pointer = typename Traits::pointer; + using reference = typename Traits::reference; + + AE a; + }; + +public: + explicit constexpr FilteredContainer(AB _a_begin, AE _a_end, BB _b_begin) noexcept + :a_begin(_a_begin), a_end(_a_end), b_begin(_b_begin) {} + + class iterator { + using Traits = std::iterator_traits; + + [[no_unique_address]] + AB a; + + [[no_unique_address]] + AE a_end; + + [[no_unique_address]] + BB b; + + public: + using iterator_category = typename std::forward_iterator_tag; + using difference_type = typename Traits::difference_type; + using value_type = typename Traits::value_type; + using pointer = typename Traits::pointer; + using reference = typename Traits::reference; + + explicit constexpr iterator(AB _a, AE _a_end, BB _b) noexcept + :a(_a), a_end(_a_end), b(_b) {} + + constexpr void FindEnabled() noexcept { + while (a != a_end && !*b) { + ++a; + ++b; + } + } + + constexpr bool operator==(const iterator &other) const noexcept { + return a == other.a; + } + + constexpr bool operator==(const end_iterator &other) const noexcept { + return a == other.a; + } + + constexpr auto &operator++() noexcept { + ++a; + ++b; + FindEnabled(); + return *this; + } + + constexpr auto operator++(int) noexcept { + auto old = *this; + ++*this; + return old; + } + + reference operator*() const noexcept { + return a.operator*(); + } + + pointer operator->() const noexcept { + return a.operator->(); + } + }; + + constexpr iterator begin() const noexcept { + iterator it{a_begin, a_end, b_begin}; + it.FindEnabled(); + return it; + } + + constexpr end_iterator end() const noexcept { + return {a_end}; + } + + constexpr iterator cbegin() const noexcept { + return begin(); + } + + constexpr end_iterator cend() const noexcept { + return end(); + } +}; diff --git a/src/util/ForeignFifoBuffer.hxx b/src/util/ForeignFifoBuffer.hxx new file mode 100644 index 0000000..691a679 --- /dev/null +++ b/src/util/ForeignFifoBuffer.hxx @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include +#include + +/** + * A first-in-first-out buffer: you can append data at the end, and + * read data from the beginning. This class automatically shifts the + * buffer as needed. It is not thread safe. + * + * This class does not manage buffer memory. It will not allocate or + * free any memory, it only manages the contents of an existing buffer + * given to the constructor. + */ +template +class ForeignFifoBuffer { +public: + using size_type = std::size_t; + using Range = std::span; + using pointer = typename Range::pointer; + using const_pointer = typename Range::const_pointer; + +protected: + Range buffer; + size_type head = 0, tail = 0; + +public: + explicit constexpr ForeignFifoBuffer(std::nullptr_t) noexcept + :buffer() {} + + explicit constexpr ForeignFifoBuffer(Range _buffer) noexcept + :buffer(_buffer) {} + + constexpr ForeignFifoBuffer(ForeignFifoBuffer &&src) noexcept + :buffer(src.buffer), head(src.head), tail(src.tail) { + src.SetNull(); + } + + constexpr ForeignFifoBuffer &operator=(ForeignFifoBuffer &&src) noexcept { + buffer = src.buffer; + head = src.head; + tail = src.tail; + src.SetNull(); + return *this; + } + + constexpr void swap(ForeignFifoBuffer &other) noexcept { + using std::swap; + swap(buffer, other.buffer); + swap(head, other.head); + swap(tail, other.tail); + } + + friend constexpr void swap(ForeignFifoBuffer &a, + ForeignFifoBuffer &b) noexcept { + a.swap(b); + } + + constexpr bool IsNull() const noexcept { + return buffer.data() == nullptr; + } + + constexpr bool IsDefined() const noexcept { + return !IsNull(); + } + + T *GetBuffer() noexcept { + return buffer.data(); + } + + constexpr size_type GetCapacity() const noexcept { + return buffer.size(); + } + + void SetNull() noexcept { + buffer = {}; + head = tail = 0; + } + + void SetBuffer(Range _buffer) noexcept { + assert(_buffer.data() != nullptr); + assert(!_buffer.empty()); + + buffer = _buffer; + head = tail = 0; + } + + void MoveBuffer(Range _buffer) noexcept { + const auto r = Read(); + assert(_buffer.size() >= r.size()); + std::move(r.begin(), r.end(), _buffer.begin()); + + buffer = _buffer; + tail -= head; + head = 0; + } + + constexpr void Clear() noexcept { + head = tail = 0; + } + + constexpr bool empty() const noexcept { + return head == tail; + } + + constexpr bool IsFull() const noexcept { + return head == 0 && tail == buffer.size(); + } + + /** + * Prepares writing. Returns a buffer range which may be written. + * When you are finished, call Append(). + */ + constexpr Range Write() noexcept { + if (empty()) + Clear(); + else if (tail == buffer.size()) + Shift(); + + return buffer.subspan(tail); + } + + constexpr bool WantWrite(size_type n) noexcept { + if (tail + n <= buffer.size()) + /* enough space after the tail */ + return true; + + const size_type in_use = tail - head; + const size_type required_capacity = in_use + n; + if (required_capacity > buffer.size()) + return false; + + Shift(); + assert(tail + n <= buffer.size()); + return true; + } + + /** + * Expands the tail of the buffer, after data has been written to + * the buffer returned by Write(). + */ + constexpr void Append(size_type n) noexcept { + assert(tail <= buffer.size()); + assert(n <= buffer.size()); + assert(tail + n <= buffer.size()); + + 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. + */ + constexpr Range Read() const noexcept { + return buffer.subspan(head, tail - head); + } + + /** + * Marks a chunk as consumed. + */ + constexpr void Consume(size_type n) noexcept { + assert(tail <= buffer.size()); + assert(head <= tail); + assert(n <= tail); + assert(head + n <= tail); + + head += n; + } + + constexpr size_type Read(pointer p, size_type n) noexcept { + auto range = Read(); + if (n > range.size()) + n = range.size(); + std::copy_n(range.data(), n, p); + Consume(n); + return n; + } + + /** + * Move as much data as possible from the specified buffer. + * + * @return the number of items moved + */ + template + constexpr size_type MoveFrom(std::span src) noexcept { + auto w = Write(); + + if (src.size() > w.size() && head > 0) { + /* if the source contains more data than we + can append at the tail, try to make more + room by shifting the head to 0 */ + Shift(); + w = Write(); + } + + if (src.size() > w.size()) + src = src.first(w.size()); + + std::move(src.begin(), src.end(), w.begin()); + Append(src.size()); + return src.size(); + } + + constexpr size_type MoveFrom(ForeignFifoBuffer &src) noexcept { + auto n = MoveFrom(src.Read()); + src.Consume(n); + return n; + } + +protected: + constexpr void Shift() noexcept { + if (head == 0) + return; + + assert(head <= buffer.size()); + assert(tail <= buffer.size()); + assert(tail >= head); + + const auto r = Read(); + std::move(r.begin(), r.end(), buffer.begin()); + + tail -= head; + head = 0; + } +}; diff --git a/src/util/GenerateArray.hxx b/src/util/GenerateArray.hxx new file mode 100644 index 0000000..bad1b1f --- /dev/null +++ b/src/util/GenerateArray.hxx @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef GENERATE_ARRAY_HXX +#define GENERATE_ARRAY_HXX + +#include +#include + +template +constexpr auto +_GenerateArray(F &&f, std::index_sequence) noexcept +{ + using T = decltype(f(0)); + + /* double curly braces for compatibility with older compilers + which are not 100% C++17 compliant (e.g. Apple xcode + 9.4) */ + return std::array{{f(I)...}}; +} + +/** + * Generate a `constexpr` std::array at compile time by calling the + * given function for each index. + * + * @param N the number of elements in the array + * @param F the function (called N times with the index as only parameter) + */ +template +constexpr auto +GenerateArray(F &&f) noexcept +{ + return _GenerateArray(std::forward(f), + std::make_index_sequence()); +} + +#endif + diff --git a/src/util/HexFormat.hxx b/src/util/HexFormat.hxx new file mode 100644 index 0000000..8d5eef7 --- /dev/null +++ b/src/util/HexFormat.hxx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include +#include +#include + +constexpr char hex_digits[] = "0123456789abcdef"; + +[[gnu::always_inline]] +static constexpr char * +HexFormatUint8Fixed(char dest[2], uint8_t number) noexcept +{ + dest[0] = hex_digits[(number >> 4) & 0xf]; + dest[1] = hex_digits[number & 0xf]; + return dest + 2; +} + +[[gnu::always_inline]] +static constexpr char * +HexFormatUint16Fixed(char dest[4], uint16_t number) noexcept +{ + dest[0] = hex_digits[(number >> 12) & 0xf]; + dest[1] = hex_digits[(number >> 8) & 0xf]; + dest[2] = hex_digits[(number >> 4) & 0xf]; + dest[3] = hex_digits[number & 0xf]; + return dest + 4; +} + +[[gnu::always_inline]] +static constexpr char * +HexFormatUint32Fixed(char dest[8], uint32_t number) noexcept +{ + dest[0] = hex_digits[(number >> 28) & 0xf]; + dest[1] = hex_digits[(number >> 24) & 0xf]; + dest[2] = hex_digits[(number >> 20) & 0xf]; + dest[3] = hex_digits[(number >> 16) & 0xf]; + dest[4] = hex_digits[(number >> 12) & 0xf]; + dest[5] = hex_digits[(number >> 8) & 0xf]; + dest[6] = hex_digits[(number >> 4) & 0xf]; + dest[7] = hex_digits[number & 0xf]; + return dest + 8; +} + +[[gnu::always_inline]] +static constexpr char * +HexFormatUint64Fixed(char dest[16], uint64_t number) noexcept +{ + dest = HexFormatUint32Fixed(dest, number >> 32); + dest = HexFormatUint32Fixed(dest, number); + return dest; +} + +/** + * Format the given input buffer of bytes to hex. The caller ensures + * that the output buffer is at least twice as large as the input. + * Does not null-terminate the output buffer. + * + * @return a pointer to one after the last written character + */ +constexpr char * +HexFormat(char *output, std::span input) noexcept +{ + for (const auto &i : input) + output = HexFormatUint8Fixed(output, (uint8_t)i); + + return output; +} + +/** + * Return a std::array (not null-terminated) containing a hex + * dump of the given fixed-size input. + */ +template +constexpr auto +HexFormat(std::span input) noexcept +{ + std::array output; + HexFormat(output.data(), input); + return output; +} + +template +constexpr auto +HexFormat(std::span input) noexcept +{ + std::span const_input{input}; + return HexFormat(const_input); +} diff --git a/src/util/HugeAllocator.cxx b/src/util/HugeAllocator.cxx new file mode 100644 index 0000000..bc5aeff --- /dev/null +++ b/src/util/HugeAllocator.cxx @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "HugeAllocator.hxx" +#include "system/VmaName.hxx" +#include "util/RoundPowerOfTwo.hxx" + +#include + +#ifdef __linux__ +#include +#include +#else +#include +#endif + +#ifdef __linux__ + +/** + * Round up the parameter, make it page-aligned. + */ +[[gnu::const]] +static size_t +AlignToPageSize(size_t size) noexcept +{ + static const long page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0) + return size; + + return RoundUpToPowerOfTwo(size, static_cast(page_size)); +} + +std::span +HugeAllocate(size_t size) +{ + size = AlignToPageSize(size); + + constexpr int flags = MAP_ANONYMOUS|MAP_PRIVATE|MAP_NORESERVE; + void *p = mmap(nullptr, size, + PROT_READ|PROT_WRITE, flags, + -1, 0); + if (p == (void *)-1) + throw std::bad_alloc(); + +#ifdef MADV_HUGEPAGE + /* allow the Linux kernel to use "Huge Pages", which reduces page + table overhead for this big chunk of data */ + madvise(p, size, MADV_HUGEPAGE); +#endif + + return {(std::byte *)p, size}; +} + +void +HugeFree(void *p, size_t size) noexcept +{ + munmap(p, AlignToPageSize(size)); +} + +void +HugeSetName(void *p, size_t size, const char *name) noexcept +{ + SetVmaName(p, size, name); +} + +void +HugeForkCow(void *p, size_t size, bool enable) noexcept +{ +#ifdef MADV_DONTFORK + madvise(p, AlignToPageSize(size), + enable ? MADV_DOFORK : MADV_DONTFORK); +#endif +} + +void +HugeDiscard(void *p, size_t size) noexcept +{ +#ifdef MADV_DONTNEED + madvise(p, AlignToPageSize(size), MADV_DONTNEED); +#endif +} + +#elif defined(_WIN32) + +std::span +HugeAllocate(size_t size) +{ + // TODO: use MEM_LARGE_PAGES + void *p = VirtualAlloc(nullptr, size, + MEM_COMMIT|MEM_RESERVE, + PAGE_READWRITE); + if (p == nullptr) + throw std::bad_alloc(); + + // TODO: round size up to the page size + return {(std::byte *)p, size}; +} + +#endif diff --git a/src/util/HugeAllocator.hxx b/src/util/HugeAllocator.hxx new file mode 100644 index 0000000..69d7e7a --- /dev/null +++ b/src/util/HugeAllocator.hxx @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "SpanCast.hxx" + +#include +#include +#include + +#ifdef __linux__ + +/** + * Allocate a huge amount of memory. This will be done in a way that + * allows giving the memory back to the kernel as soon as we don't + * need it anymore. On the downside, this call is expensive. + * + * Throws std::bad_alloc on error + * + * @returns the allocated buffer with a size which may be rounded up + * (to the next page size), so callers can take advantage of this + * allocation overhead + */ +std::span +HugeAllocate(size_t size); + +/** + * @param p an allocation returned by HugeAllocate() + * @param size the allocation's size as passed to HugeAllocate() + */ +void +HugeFree(void *p, size_t size) noexcept; + +/** + * Set a name for the specified virtual memory area. + * + * This feature requires Linux 5.17. + */ +void +HugeSetName(void *p, size_t size, const char *name) noexcept; + +/** + * Control whether this allocation is copied to newly forked child + * processes. Disabling that makes forking a little bit cheaper. + */ +void +HugeForkCow(void *p, size_t size, bool enable) noexcept; + +/** + * Discard any data stored in the allocation and give the memory back + * to the kernel. After returning, the allocation still exists and + * can be reused at any time, but its contents are undefined. + * + * @param p an allocation returned by HugeAllocate() + * @param size the allocation's size as passed to HugeAllocate() + */ +void +HugeDiscard(void *p, size_t size) noexcept; + +#elif defined(_WIN32) +#include + +std::span +HugeAllocate(size_t size); + +static inline void +HugeFree(void *p, size_t) noexcept +{ + VirtualFree(p, 0, MEM_RELEASE); +} + +static inline void +HugeSetName(void *, size_t, const char *) noexcept +{ +} + +static inline void +HugeForkCow(void *, size_t, bool) noexcept +{ +} + +static inline void +HugeDiscard(void *p, size_t size) noexcept +{ + VirtualAlloc(p, size, MEM_RESET, PAGE_NOACCESS); +} + +#else + +/* not Linux: fall back to standard C calls */ + +#include + +static inline std::span +HugeAllocate(size_t size) +{ + return {new std::byte[size], size}; +} + +static inline void +HugeFree(void *_p, size_t) noexcept +{ + auto *p = (std::byte *)_p; + delete[] p; +} + +static inline void +HugeSetName(void *, size_t, const char *) noexcept +{ +} + +static inline void +HugeForkCow(void *, size_t, bool) noexcept +{ +} + +static inline void +HugeDiscard(void *, size_t) noexcept +{ +} + +#endif + +/** + * Automatic memory management for a dynamic array in "huge" memory. + */ +template +class HugeArray { + using Buffer = std::span; + Buffer buffer{nullptr}; + +public: + typedef typename Buffer::size_type size_type; + typedef typename Buffer::value_type value_type; + typedef typename Buffer::reference reference; + typedef typename Buffer::const_reference const_reference; + typedef typename Buffer::iterator iterator; + + constexpr HugeArray() noexcept = default; + + explicit HugeArray(size_type _size) + :buffer(FromBytesFloor(HugeAllocate(sizeof(value_type) * _size))) {} + + constexpr HugeArray(HugeArray &&other) noexcept + :buffer(std::exchange(other.buffer, nullptr)) {} + + ~HugeArray() noexcept { + if (!buffer.empty()) { + auto v = std::as_writable_bytes(buffer); + HugeFree(v.data(), v.size()); + } + } + + constexpr HugeArray &operator=(HugeArray &&other) noexcept { + using std::swap; + swap(buffer, other.buffer); + return *this; + } + + void SetName(const char *name) noexcept { + const auto v = std::as_writable_bytes(buffer); + HugeSetName(v.data(), v.size(), name); + } + + void ForkCow(bool enable) noexcept { + const auto v = std::as_writable_bytes(buffer); + HugeForkCow(v.data(), v.size(), enable); + } + + void Discard() noexcept { + const auto v = std::as_writable_bytes(buffer); + HugeDiscard(v.data(), v.size()); + } + + constexpr bool operator==(std::nullptr_t) const noexcept { + return buffer == nullptr; + } + + constexpr bool operator!=(std::nullptr_t) const noexcept { + return buffer != nullptr; + } + + constexpr operator std::span() noexcept { + return buffer; + } + + constexpr operator std::span() noexcept { + return buffer; + } + + /** + * Returns the number of allocated elements. + */ + constexpr size_type size() const noexcept { + return buffer.size(); + } + + constexpr reference front() noexcept { + return buffer.front(); + } + + constexpr const_reference front() const noexcept { + return buffer.front(); + } + + constexpr reference back() noexcept { + return buffer.back(); + } + + constexpr const_reference back() const noexcept { + return buffer.back(); + } + + /** + * Returns one element. No bounds checking. + */ + constexpr reference operator[](size_type i) noexcept { + return buffer[i]; + } + + /** + * Returns one constant element. No bounds checking. + */ + constexpr const_reference operator[](size_type i) const noexcept { + return buffer[i]; + } + + constexpr iterator begin() noexcept { + return buffer.begin(); + } + + constexpr auto begin() const noexcept { + return buffer.begin(); + } + + constexpr iterator end() noexcept { + return buffer.end(); + } + + constexpr auto end() const noexcept { + return buffer.end(); + } +}; diff --git a/src/util/IntrusiveForwardList.hxx b/src/util/IntrusiveForwardList.hxx new file mode 100644 index 0000000..b3eb443 --- /dev/null +++ b/src/util/IntrusiveForwardList.hxx @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include "Cast.hxx" +#include "Concepts.hxx" +#include "MemberPointer.hxx" +#include "OptionalCounter.hxx" +#include "OptionalField.hxx" +#include "TagStructs.hxx" + +#include +#include +#include + +struct IntrusiveForwardListOptions { + bool constant_time_size = false; + + /** + * Cache a pointer to the last item? This makes back() and + * push_back() run in constant time. + */ + bool cache_last = false; +}; + +struct IntrusiveForwardListNode { + IntrusiveForwardListNode *next; +}; + +struct IntrusiveForwardListHook { + IntrusiveForwardListNode siblings; + + static constexpr auto &Cast(IntrusiveForwardListNode &node) noexcept { + return ContainerCast(node, &IntrusiveForwardListHook::siblings); + } + + static constexpr const auto &Cast(const IntrusiveForwardListNode &node) noexcept { + return ContainerCast(node, &IntrusiveForwardListHook::siblings); + } +}; + +/** + * For classes which embed #IntrusiveForwardListHook as base class. + */ +template +struct IntrusiveForwardListBaseHookTraits { + static constexpr T *Cast(IntrusiveForwardListNode *node) noexcept { + static_assert(std::is_base_of_v); + auto *hook = &IntrusiveForwardListHook::Cast(*node); + return static_cast(hook); + } + + static constexpr const T *Cast(const IntrusiveForwardListNode *node) noexcept { + static_assert(std::is_base_of_v); + const auto *hook = &IntrusiveForwardListHook::Cast(*node); + return static_cast(hook); + } + + static constexpr IntrusiveForwardListHook &ToHook(T &t) noexcept { + static_assert(std::is_base_of_v); + return t; + } + + static constexpr const IntrusiveForwardListHook &ToHook(const T &t) noexcept { + static_assert(std::is_base_of_v); + return t; + } +}; + +/** + * For classes which embed #IntrusiveForwardListHook as member. + */ +template +struct IntrusiveForwardListMemberHookTraits { + using T = MemberPointerContainerType; + using Hook = IntrusiveForwardListHook; + + static_assert(std::is_same_v, Hook>); + + static constexpr T *Cast(IntrusiveForwardListNode *node) noexcept { + auto &hook = Hook::Cast(*node); + return &ContainerCast(hook, member); + } + + static constexpr const T *Cast(const IntrusiveForwardListNode *node) noexcept { + const auto &hook = Hook::Cast(*node); + return &ContainerCast(hook, member); + } + + static constexpr auto &ToHook(T &t) noexcept { + return t.*member; + } + + static constexpr const auto &ToHook(const T &t) noexcept { + return t.*member; + } +}; + +/** + * @param constant_time_size make size() constant-time by caching the + * number of items in a field? + */ +template, + IntrusiveForwardListOptions options=IntrusiveForwardListOptions{}> +class IntrusiveForwardList { + static constexpr bool constant_time_size = options.constant_time_size; + + IntrusiveForwardListNode head{nullptr}; + + [[no_unique_address]] + OptionalField last_cache{&head}; + + [[no_unique_address]] + OptionalCounter counter; + + static constexpr T *Cast(IntrusiveForwardListNode *node) noexcept { + return HookTraits::Cast(node); + } + + static constexpr const T *Cast(const IntrusiveForwardListNode *node) noexcept { + return HookTraits::Cast(node); + } + + static constexpr IntrusiveForwardListHook &ToHook(T &t) noexcept { + return HookTraits::ToHook(t); + } + + static constexpr const IntrusiveForwardListHook &ToHook(const T &t) noexcept { + return HookTraits::ToHook(t); + } + + static constexpr IntrusiveForwardListNode &ToNode(T &t) noexcept { + return ToHook(t).siblings; + } + + static constexpr const IntrusiveForwardListNode &ToNode(const T &t) noexcept { + return ToHook(t).siblings; + } + +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + using size_type = std::size_t; + + IntrusiveForwardList() = default; + + IntrusiveForwardList(IntrusiveForwardList &&src) noexcept + :head{std::exchange(src.head.next, nullptr)} + { + using std::swap; + swap(last_cache, src.last_cache); + swap(counter, src.counter); + } + + constexpr IntrusiveForwardList(ShallowCopy, const IntrusiveForwardList &src) noexcept + :head(src.head) + { + // shallow copies mess with the counter + static_assert(!options.constant_time_size); + static_assert(!options.cache_last); + } + + IntrusiveForwardList &operator=(IntrusiveForwardList &&src) noexcept { + using std::swap; + swap(head, src.head); + swap(last_cache, src.last_cache); + swap(counter, src.counter); + return *this; + } + + constexpr bool empty() const noexcept { + return head.next == nullptr; + } + + constexpr size_type size() const noexcept + requires(constant_time_size) { + return counter; + } + + void clear() noexcept { + head = {}; + last_cache = {&head}; + counter.reset(); + } + + void clear_and_dispose(Disposer auto disposer) noexcept { + while (!empty()) { + auto *item = &front(); + pop_front(); + disposer(item); + } + + last_cache = {&head}; + } + + /** + * @return the number of removed items + */ + std::size_t remove_and_dispose_if(std::predicate auto pred, + Disposer auto dispose) noexcept { + std::size_t result = 0; + + for (auto prev = before_begin(), current = std::next(prev); + current != end();) { + auto &item = *current; + + if (pred(item)) { + ++result; + ++current; + erase_after(prev); + dispose(&item); + } else { + prev = current++; + } + } + + return result; + } + + const_reference front() const noexcept { + return *Cast(head.next); + } + + reference front() noexcept { + return *Cast(head.next); + } + + reference pop_front() noexcept { + auto &i = front(); + head.next = head.next->next; + + if constexpr (options.cache_last) + if (head.next == nullptr) + last_cache.value = &head; + + --counter; + return i; + } + + void pop_front_and_dispose(Disposer auto disposer) noexcept { + auto &i = pop_front(); + disposer(&i); + } + + const_reference back() const noexcept + requires(options.cache_last) { + return *Cast(last_cache.value); + } + + reference back() noexcept + requires(options.cache_last) { + return *Cast(last_cache.value); + } + + class const_iterator; + + class iterator final { + friend IntrusiveForwardList; + friend const_iterator; + + IntrusiveForwardListNode *cursor; + + constexpr iterator(IntrusiveForwardListNode *_cursor) noexcept + :cursor(_cursor) {} + + public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + iterator() = default; + + constexpr bool operator==(const iterator &other) const noexcept { + return cursor == other.cursor; + } + + constexpr bool operator!=(const iterator &other) const noexcept { + return !(*this == other); + } + + constexpr reference operator*() const noexcept { + return *Cast(cursor); + } + + constexpr pointer operator->() const noexcept { + return Cast(cursor); + } + + iterator &operator++() noexcept { + cursor = cursor->next; + return *this; + } + + iterator operator++(int) noexcept { + auto old = *this; + cursor = cursor->next; + return old; + } + }; + + constexpr iterator before_begin() noexcept { + return {&head}; + } + + constexpr iterator begin() noexcept { + return {head.next}; + } + + constexpr iterator end() noexcept { + return {nullptr}; + } + + constexpr iterator last() noexcept + requires(options.cache_last) { + return {last_cache.value}; + } + + static constexpr iterator iterator_to(reference t) noexcept { + return {&ToNode(t)}; + } + + class const_iterator final { + friend IntrusiveForwardList; + + const IntrusiveForwardListNode *cursor; + + constexpr const_iterator(const IntrusiveForwardListNode *_cursor) noexcept + :cursor(_cursor) {} + + public: + using iterator_category = std::forward_iterator_tag; + using value_type = const T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + const_iterator() = default; + + const_iterator(iterator src) noexcept + :cursor(src.cursor) {} + + constexpr bool operator==(const const_iterator &other) const noexcept { + return cursor == other.cursor; + } + + constexpr bool operator!=(const const_iterator &other) const noexcept { + return !(*this == other); + } + + constexpr reference operator*() const noexcept { + return *Cast(cursor); + } + + constexpr pointer operator->() const noexcept { + return Cast(cursor); + } + + const_iterator &operator++() noexcept { + cursor = cursor->next; + return *this; + } + + const_iterator operator++(int) noexcept { + auto old = *this; + cursor = cursor->next; + return old; + } + }; + + constexpr const_iterator begin() const noexcept { + return {head.next}; + } + + constexpr const_iterator end() const noexcept { + return {nullptr}; + } + + constexpr const_iterator last() const noexcept + requires(options.cache_last) { + return {last_cache.value}; + } + + static constexpr const_iterator iterator_to(const_reference t) noexcept { + return {&ToNode(t)}; + } + + iterator push_front(reference t) noexcept { + auto &new_node = ToNode(t); + + if constexpr (options.cache_last) + if (empty()) + last_cache.value = &new_node; + + new_node.next = head.next; + head.next = &new_node; + ++counter; + + return iterator_to(t); + } + + iterator push_back(reference t) noexcept + requires(options.cache_last) { + auto &new_node = ToNode(t); + new_node.next = nullptr; + last_cache.value->next = &new_node; + last_cache.value = &new_node; + + ++counter; + + return iterator_to(t); + } + + static iterator insert_after(iterator pos, reference t) noexcept + requires(!constant_time_size && !options.cache_last) { + /* if we have no counter, then this method is allowed + to be static */ + + auto &pos_node = *pos.cursor; + auto &new_node = ToNode(t); + new_node.next = pos_node.next; + pos_node.next = &new_node; + return &new_node; + } + + iterator insert_after(iterator pos, reference t) noexcept + requires(constant_time_size || options.cache_last) { + auto &pos_node = *pos.cursor; + auto &new_node = ToNode(t); + + if constexpr (options.cache_last) + if (pos_node.next == nullptr) + last_cache.value = &new_node; + + new_node.next = pos_node.next; + pos_node.next = &new_node; + ++counter; + return &new_node; + } + + void erase_after(iterator pos) noexcept { + pos.cursor->next = pos.cursor->next->next; + + if constexpr (options.cache_last) + if (pos.cursor->next == nullptr) + last_cache.value = pos.cursor; + + --counter; + } + + void reverse() noexcept { + if (empty()) + return; + + /* the first item will be the last, and will stay + there; during the loop, it will divide the list + between "old order" (right of it) and "new + (reversed) order" (left of it) */ + const auto middle = begin(); + + while (std::next(middle) != end()) { + /* remove the item after the "middle", and + move it to the front */ + auto i = std::next(middle); + erase_after(middle); + push_front(*i); + } + } +}; diff --git a/src/util/IntrusiveHashSet.hxx b/src/util/IntrusiveHashSet.hxx new file mode 100644 index 0000000..4ca132a --- /dev/null +++ b/src/util/IntrusiveHashSet.hxx @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "Concepts.hxx" +#include "IntrusiveList.hxx" + +#include // for std::all_of() +#include +#include // for std::regular_invocable +#include // for std::accumulate() + +template +concept IntrusiveHashSetOperatorsConcept = requires(const Operators &ops, + const Item &c, const Item &c2) +{ + { ops.get_key(c) } noexcept; + + /* note: no "noexcept" here because std::hash is not + noexcept */ + { ops.hash(ops.get_key(c)) } -> std::same_as; + + /* note: no "noexcept" here because std::equal_to is not + noexcept */ + { ops.equal(ops.get_key(c), ops.get_key(c2)) } -> std::same_as; +}; + +struct IntrusiveHashSetOptions { + bool constant_time_size = false; + + /** + * @see IntrusiveListOptions::zero_initialized + */ + bool zero_initialized = false; +}; + +/** + * @param Tag an arbitrary tag type to allow using multiple base hooks + */ +template +struct IntrusiveHashSetHook { + using SiblingsHook = IntrusiveListHook; + + SiblingsHook intrusive_hash_set_siblings; + + void unlink() noexcept { + intrusive_hash_set_siblings.unlink(); + } + + bool is_linked() const noexcept { + return intrusive_hash_set_siblings.is_linked(); + } +}; + +/** + * For classes which embed #IntrusiveHashSetHook as base class. + * + * @param Tag selector for which #IntrusiveHashSetHook to use + */ +template +struct IntrusiveHashSetBaseHookTraits { + /* a never-called helper function which is used by _Cast() */ + template + static constexpr IntrusiveHashSetHook _Identity(const IntrusiveHashSetHook &) noexcept; + + /* another never-called helper function which "calls" + _Identity(), implicitly casting the item to the + IntrusiveHashSetHook specialization; we use this to detect + which IntrusiveHashSetHook specialization is used */ + template + static constexpr auto _Cast(const U &u) noexcept { + return decltype(_Identity(u))(); + } + + template + using Hook = decltype(_Cast(std::declval())); + + static constexpr T *Cast(Hook *node) noexcept { + return static_cast(node); + } + + static constexpr auto &ToHook(T &t) noexcept { + return static_cast &>(t); + } +}; + +/** + * For classes which embed #IntrusiveListHook as member. + */ +template +struct IntrusiveHashSetMemberHookTraits { + using T = MemberPointerContainerType; + using _Hook = MemberPointerType; + + template + using Hook = _Hook; + + static constexpr T *Cast(Hook *node) noexcept { + return &ContainerCast(*node, member); + } + + static constexpr auto &ToHook(T &t) noexcept { + return t.*member; + } +}; + +/** + * @param GetKey a function object which extracts the "key" part of an + * item + */ +template GetKey, + std::regular_invocable> Hash, + std::predicate, + std::invoke_result_t> Equal> +struct IntrusiveHashSetOperators { + using hasher = Hash; + using key_equal = Equal; + + [[no_unique_address]] + Hash hash; + + [[no_unique_address]] + Equal equal; + + [[no_unique_address]] + GetKey get_key; +}; + +/** + * A hash table implementation which stores pointers to items which + * have an embedded #IntrusiveHashSetHook. The actual table is + * embedded with a compile-time fixed size in this object. + * + * @param Operators a class which contains functions `hash` and + * `equal` + */ +template Operators, + typename HookTraits=IntrusiveHashSetBaseHookTraits, + IntrusiveHashSetOptions options=IntrusiveHashSetOptions{}> +class IntrusiveHashSet { + static constexpr bool constant_time_size = options.constant_time_size; + + [[no_unique_address]] + OptionalCounter counter; + + [[no_unique_address]] + Operators ops; + + struct BucketHookTraits { + template + using HashSetHook = typename HookTraits::template Hook; + + template + using ListHook = IntrusiveListMemberHookTraits<&HashSetHook::intrusive_hash_set_siblings>; + + template + using Hook = typename HashSetHook::SiblingsHook; + + static constexpr T *Cast(IntrusiveListNode *node) noexcept { + auto *hook = ListHook::Cast(node); + return HookTraits::Cast(hook); + } + + static constexpr auto &ToHook(T &t) noexcept { + auto &hook = HookTraits::ToHook(t); + return hook.intrusive_hash_set_siblings; + } + }; + + using Bucket = IntrusiveList; + std::array table; + + using bucket_iterator = typename Bucket::iterator; + using const_bucket_iterator = typename Bucket::const_iterator; + +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + using size_type = std::size_t; + + using hasher = typename Operators::hasher; + using key_equal = typename Operators::key_equal; + + [[nodiscard]] + IntrusiveHashSet() noexcept = default; + + [[nodiscard]] + constexpr const hasher &hash_function() const noexcept { + return ops.hash; + } + + [[nodiscard]] + constexpr const key_equal &key_eq() const noexcept { + return ops.equal; + } + + [[nodiscard]] + constexpr bool empty() const noexcept { + if constexpr (constant_time_size) + return size() == 0; + else + return std::all_of(table.begin(), table.end(), [](const auto &bucket){ + return bucket.empty(); + }); + } + + [[nodiscard]] + constexpr size_type size() const noexcept { + if constexpr (constant_time_size) + return counter; + else + return std::accumulate(table.begin(), table.end(), size_type{}, [](std::size_t n, const auto &bucket){ + return n + bucket.size(); + }); + } + + constexpr void clear() noexcept { + for (auto &i : table) + i.clear(); + + counter.reset(); + } + + constexpr void clear_and_dispose(Disposer auto disposer) noexcept { + for (auto &i : table) + i.clear_and_dispose(disposer); + + counter.reset(); + } + + /** + * Remove and dispose all items matching the given predicate. + * + * @return the number of removed items + */ + std::size_t remove_and_dispose_if(std::predicate auto pred, + Disposer auto disposer) noexcept { + std::size_t n = 0; + for (auto &bucket : table) + n += bucket.remove_and_dispose_if(pred, disposer); + counter -= n; + return n; + } + + /** + * Remove and dispose all items with the specified key. + * + * @return the number of removed items + */ + constexpr std::size_t remove_and_dispose_key(const auto &key, + Disposer auto disposer) noexcept { + auto &bucket = GetBucket(key); + std::size_t n = bucket.remove_and_dispose_if([this, &key](const auto &item){ + return ops.equal(key, ops.get_key(item)); + }, disposer); + counter -= n; + return n; + } + + constexpr std::size_t remove_and_dispose_key_if(const auto &key, + std::predicate auto pred, + Disposer auto disposer) noexcept { + auto &bucket = GetBucket(key); + std::size_t n = bucket.remove_and_dispose_if([this, &key, &pred](const auto &item){ + return ops.equal(key, ops.get_key(item)) && pred(item); + }, disposer); + counter -= n; + return n; + } + + [[nodiscard]] + static constexpr bucket_iterator iterator_to(reference item) noexcept { + return Bucket::iterator_to(item); + } + + /** + * Prepare insertion of a new item. If the key already + * exists, return an iterator to the existing item and + * `false`. If the key does not exist, return an iterator to + * the bucket where the new item may be inserted using + * insert() and `true`. + */ + [[nodiscard]] [[gnu::pure]] + constexpr std::pair insert_check(const auto &key) noexcept { + auto &bucket = GetBucket(key); + for (auto &i : bucket) + if (ops.equal(key, ops.get_key(i))) + return {bucket.iterator_to(i), false}; + + /* bucket.end() is a pointer to the bucket's list + head, a stable value that is guaranteed to be still + valid when insert_commit() gets called + eventually */ + return {bucket.end(), true}; + } + + /** + * Like insert_check(), but existing items are only considered + * conflicting if they match the given predicate. + */ + [[nodiscard]] [[gnu::pure]] + constexpr std::pair insert_check_if(const auto &key, + std::predicate auto pred) noexcept { + auto &bucket = GetBucket(key); + for (auto &i : bucket) + if (ops.equal(key, ops.get_key(i)) && pred(i)) + return {bucket.iterator_to(i), false}; + + /* bucket.end() is a pointer to the bucket's list + head, a stable value that is guaranteed to be still + valid when insert_commit() gets called + eventually */ + return {bucket.end(), true}; + } + + /** + * Finish the insertion if insert_check() has returned true. + * + * @param bucket the bucket returned by insert_check() + */ + constexpr bucket_iterator insert_commit(bucket_iterator bucket, + reference item) noexcept { + ++counter; + + /* using insert_after() so the new item gets inserted + at the front of the bucket list */ + return GetBucket(ops.get_key(item)).insert_after(bucket, item); + } + + /** + * Insert a new item without checking whether the key already + * exists. + */ + constexpr bucket_iterator insert(reference item) noexcept { + ++counter; + return GetBucket(ops.get_key(item)).push_front(item); + } + + constexpr bucket_iterator erase(bucket_iterator i) noexcept { + --counter; + return GetBucket(ops.get_key(*i)).erase(i); + } + + constexpr bucket_iterator erase_and_dispose(bucket_iterator i, + Disposer auto disposer) noexcept { + auto result = erase(i); + disposer(&*i); + return result; + } + + [[nodiscard]] [[gnu::pure]] + constexpr bucket_iterator find(const auto &key) noexcept { + auto &bucket = GetBucket(key); + for (auto &i : bucket) + if (ops.equal(key, ops.get_key(i))) + return bucket.iterator_to(i); + + return end(); + } + + [[nodiscard]] [[gnu::pure]] + constexpr const_bucket_iterator find(const auto &key) const noexcept { + auto &bucket = GetBucket(key); + for (auto &i : bucket) + if (ops.equal(key, ops.get_key(i))) + return bucket.iterator_to(i); + + return end(); + } + + /** + * Like find(), but returns an item that matches the given + * predicate. This is useful if the container can contain + * multiple items that compare equal (according to #Equal, but + * not according to #pred). + */ + [[nodiscard]] [[gnu::pure]] + constexpr bucket_iterator find_if(const auto &key, + std::predicate auto pred) noexcept { + auto &bucket = GetBucket(key); + for (auto &i : bucket) + if (ops.equal(key, ops.get_key(i)) && pred(i)) + return bucket.iterator_to(i); + + return end(); + } + + /** + * Like find_if(), but while traversing the bucket linked + * list, remove and dispose expired items. + * + * @param expired_pred returns true if an item is expired; it + * will be removed and disposed + * + * @param disposer function which will be called for items + * that were removed (because they are expired) + * + * @param match_pred returns true if the desired item was + * found + */ + [[nodiscard]] [[gnu::pure]] + constexpr bucket_iterator expire_find_if(const auto &key, + std::predicate auto expired_pred, + Disposer auto disposer, + std::predicate auto match_pred) noexcept { + auto &bucket = GetBucket(key); + + for (auto i = bucket.begin(), e = bucket.end(); i != e;) { + if (!ops.equal(key, ops.get_key(*i))) + ++i; + else if (expired_pred(*i)) + i = erase_and_dispose(i, disposer); + else if (match_pred(*i)) + return i; + else + ++i; + } + + return end(); + } + + constexpr bucket_iterator end() noexcept { + return table.front().end(); + } + + constexpr const_bucket_iterator end() const noexcept { + return table.front().end(); + } + + constexpr void for_each(auto &&f) { + for (auto &bucket : table) + for (auto &i : bucket) + f(i); + } + + constexpr void for_each(auto &&f) const { + for (const auto &bucket : table) + for (const auto &i : bucket) + f(i); + } + +private: + template + [[gnu::pure]] + [[nodiscard]] + constexpr auto &GetBucket(K &&key) noexcept { + const auto h = ops.hash(std::forward(key)); + return table[h % table_size]; + } + + template + [[gnu::pure]] + [[nodiscard]] + constexpr const auto &GetBucket(K &&key) const noexcept { + const auto h = ops.hash(std::forward(key)); + return table[h % table_size]; + } +}; diff --git a/src/util/IntrusiveHookMode.hxx b/src/util/IntrusiveHookMode.hxx new file mode 100644 index 0000000..2c70596 --- /dev/null +++ b/src/util/IntrusiveHookMode.hxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +/** + * Specifies the mode in which a hook for intrusive containers + * operates. This is meant to be used as a template argument to the + * hook class (e.g. #IntrusiveListHook). + */ +enum class IntrusiveHookMode { + /** + * No implicit initialization. + */ + NORMAL, + + /** + * Keep track of whether the item is currently linked, allows + * using method is_linked(). This requires implicit + * initialization and requires iterating all items when + * deleting them which adds a considerable amount of overhead. + */ + TRACK, + + /** + * Automatically unlinks the item in the destructor. This + * implies #TRACK and adds code to the destructor. + */ + AUTO_UNLINK, +}; diff --git a/src/util/IntrusiveList.hxx b/src/util/IntrusiveList.hxx new file mode 100644 index 0000000..df4bb16 --- /dev/null +++ b/src/util/IntrusiveList.hxx @@ -0,0 +1,653 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "Cast.hxx" +#include "Concepts.hxx" +#include "IntrusiveHookMode.hxx" // IWYU pragma: export +#include "MemberPointer.hxx" +#include "OptionalCounter.hxx" + +#include +#include +#include + +/** + * Template parameter for #IntrusiveList with compile-time options. + */ +struct IntrusiveListOptions { + /** + * @param constant_time_size make size() constant-time by caching the + * number of items in a field? + */ + bool constant_time_size = false; + + /** + * Initialize the list head with nullptr (all zeroes) which + * adds some code for checking nullptr, but may reduce the + * data section for statically allocated lists. It's a + * trade-off. + */ + bool zero_initialized = false; +}; + +struct IntrusiveListNode { + IntrusiveListNode *next, *prev; + + static constexpr void Connect(IntrusiveListNode &a, + IntrusiveListNode &b) noexcept { + a.next = &b; + b.prev = &a; + } +}; + +/** + * @param Tag an arbitrary tag type to allow using multiple base hooks + */ +template +class IntrusiveListHook { + template friend struct IntrusiveListBaseHookTraits; + template friend struct IntrusiveListMemberHookTraits; + template friend class IntrusiveList; + +protected: + IntrusiveListNode siblings; + +public: + static constexpr IntrusiveHookMode mode = _mode; + + IntrusiveListHook() noexcept { + if constexpr (mode >= IntrusiveHookMode::TRACK) + siblings.next = nullptr; + } + + ~IntrusiveListHook() noexcept { + if constexpr (mode >= IntrusiveHookMode::AUTO_UNLINK) + if (is_linked()) + unlink(); + } + + IntrusiveListHook(const IntrusiveListHook &) = delete; + IntrusiveListHook &operator=(const IntrusiveListHook &) = delete; + + void unlink() noexcept { + IntrusiveListNode::Connect(*siblings.prev, *siblings.next); + + if constexpr (mode >= IntrusiveHookMode::TRACK) + siblings.next = nullptr; + } + + bool is_linked() const noexcept + requires(mode >= IntrusiveHookMode::TRACK) { + return siblings.next != nullptr; + } + +private: + static constexpr auto &Cast(IntrusiveListNode &node) noexcept { + return ContainerCast(node, &IntrusiveListHook::siblings); + } + + static constexpr const auto &Cast(const IntrusiveListNode &node) noexcept { + return ContainerCast(node, &IntrusiveListHook::siblings); + } +}; + +using SafeLinkIntrusiveListHook = + IntrusiveListHook; +using AutoUnlinkIntrusiveListHook = + IntrusiveListHook; + +/** + * For classes which embed #IntrusiveListHook as base class. + * + * @param Tag selector for which #IntrusiveHashSetHook to use + */ +template +struct IntrusiveListBaseHookTraits { + /* a never-called helper function which is used by _Cast() */ + template + static constexpr IntrusiveListHook _Identity(const IntrusiveListHook &) noexcept; + + /* another never-called helper function which "calls" + _Identity(), implicitly casting the item to the + IntrusiveListHook specialization; we use this to detect + which IntrusiveListHook specialization is used */ + template + static constexpr auto _Cast(const U &u) noexcept { + return decltype(_Identity(u))(); + } + + template + using Hook = decltype(_Cast(std::declval())); + + static constexpr T *Cast(IntrusiveListNode *node) noexcept { + auto *hook = &Hook::Cast(*node); + return static_cast(hook); + } + + static constexpr auto &ToHook(T &t) noexcept { + return static_cast &>(t); + } +}; + +/** + * For classes which embed #IntrusiveListHook as member. + */ +template +struct IntrusiveListMemberHookTraits { + using T = MemberPointerContainerType; + using _Hook = MemberPointerType; + + template + using Hook = _Hook; + + static constexpr T *Cast(IntrusiveListNode *node) noexcept { + auto &hook = Hook::Cast(*node); + return &ContainerCast(hook, member); + } + + static constexpr auto &ToHook(T &t) noexcept { + return t.*member; + } +}; + +/** + * An intrusive doubly-linked circular list. + */ +template, + IntrusiveListOptions options=IntrusiveListOptions{}> +class IntrusiveList { + static constexpr bool constant_time_size = options.constant_time_size; + + IntrusiveListNode head = options.zero_initialized + ? IntrusiveListNode{nullptr, nullptr} + : IntrusiveListNode{&head, &head}; + + [[no_unique_address]] + OptionalCounter counter; + + static constexpr auto GetHookMode() noexcept { + return HookTraits::template Hook::mode; + } + + static constexpr T *Cast(IntrusiveListNode *node) noexcept { + return HookTraits::Cast(node); + } + + static constexpr const T *Cast(const IntrusiveListNode *node) noexcept { + return HookTraits::Cast(const_cast(node)); + } + + static constexpr auto &ToHook(T &t) noexcept { + return HookTraits::ToHook(t); + } + + static constexpr const auto &ToHook(const T &t) noexcept { + return HookTraits::ToHook(const_cast(t)); + } + + static constexpr IntrusiveListNode &ToNode(T &t) noexcept { + return ToHook(t).siblings; + } + + static constexpr const IntrusiveListNode &ToNode(const T &t) noexcept { + return ToHook(t).siblings; + } + +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + using size_type = std::size_t; + + constexpr IntrusiveList() noexcept = default; + + IntrusiveList(IntrusiveList &&src) noexcept { + if (src.empty()) + return; + + head = src.head; + head.next->prev = &head; + head.prev->next = &head; + + src.head.next = &src.head; + src.head.prev = &src.head; + + using std::swap; + swap(counter, src.counter); + } + + ~IntrusiveList() noexcept { + if constexpr (GetHookMode() >= IntrusiveHookMode::TRACK) + clear(); + } + + IntrusiveList &operator=(IntrusiveList &&) = delete; + + friend void swap(IntrusiveList &a, IntrusiveList &b) noexcept { + using std::swap; + + if (a.empty()) { + if (b.empty()) + return; + + a.head = b.head; + a.head.next->prev = &a.head; + a.head.prev->next = &a.head; + + b.head = {&b.head, &b.head}; + } else if (b.empty()) { + b.head = a.head; + b.head.next->prev = &b.head; + b.head.prev->next = &b.head; + + a.head = {&a.head, &a.head}; + } else { + swap(a.head, b.head); + + a.head.next->prev = &a.head; + a.head.prev->next = &a.head; + + b.head.next->prev = &b.head; + b.head.prev->next = &b.head; + } + + swap(a.counter, b.counter); + } + + constexpr bool empty() const noexcept { + if constexpr (options.zero_initialized) + if (head.next == nullptr) + return true; + + return head.next == &head; + } + + constexpr size_type size() const noexcept { + if constexpr (constant_time_size) + return counter; + else + return std::distance(begin(), end()); + } + + /** + * Remove all items from the linked list. + */ + void clear() noexcept { + if constexpr (GetHookMode() >= IntrusiveHookMode::TRACK) { + /* for SafeLinkIntrusiveListHook, we need to + remove each item manually, or else its + is_linked() method will not work */ + while (!empty()) + pop_front(); + } else { + head = {&head, &head}; + counter.reset(); + } + } + + /** + * Like clear(), but invoke a disposer function on each item. + * + * The disposer is not allowed to destruct the list. + */ + void clear_and_dispose(Disposer auto disposer) noexcept { + while (!empty()) { + disposer(&pop_front()); + } + } + + /** + * Remove all items matching the given predicate and invoke + * the given disposer on it. + * + * Neither the predicate nor the disposer are allowed to + * modify the list (or destruct it). + * + * @return the number of removed items + */ + std::size_t remove_and_dispose_if(std::predicate auto pred, + Disposer auto dispose) noexcept { + std::size_t result = 0; + + auto *n = head.next; + + while (n != &head) { + auto *i = Cast(n); + n = n->next; + + if (pred(*i)) { + ToHook(*i).unlink(); + --counter; + dispose(i); + ++result; + } + } + + return result; + } + + const_reference front() const noexcept { + return *Cast(head.next); + } + + reference front() noexcept { + return *Cast(head.next); + } + + reference pop_front() noexcept { + auto &i = front(); + ToHook(i).unlink(); + --counter; + return i; + } + + void pop_front_and_dispose(Disposer auto disposer) noexcept { + auto &i = pop_front(); + disposer(&i); + } + + reference back() noexcept { + return *Cast(head.prev); + } + + void pop_back() noexcept { + auto &i = back(); + ToHook(i).unlink(); + --counter; + } + + class const_iterator; + + class iterator final { + friend IntrusiveList; + friend const_iterator; + + IntrusiveListNode *cursor; + + constexpr iterator(IntrusiveListNode *_cursor) noexcept + :cursor(_cursor) {} + + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + iterator() noexcept = default; + + constexpr bool operator==(const iterator &other) const noexcept { + return cursor == other.cursor; + } + + constexpr bool operator!=(const iterator &other) const noexcept { + return !(*this == other); + } + + constexpr reference operator*() const noexcept { + return *Cast(cursor); + } + + constexpr pointer operator->() const noexcept { + return Cast(cursor); + } + + auto &operator++() noexcept { + cursor = cursor->next; + return *this; + } + + auto operator++(int) noexcept { + auto old = *this; + cursor = cursor->next; + return old; + } + + auto &operator--() noexcept { + cursor = cursor->prev; + return *this; + } + + auto operator--(int) noexcept { + auto old = *this; + cursor = cursor->prev; + return old; + } + }; + + constexpr iterator begin() noexcept { + if constexpr (options.zero_initialized) + if (head.next == nullptr) + return end(); + + return {head.next}; + } + + constexpr iterator end() noexcept { + return {&head}; + } + + static constexpr iterator iterator_to(reference t) noexcept { + return {&ToNode(t)}; + } + + using reverse_iterator = std::reverse_iterator; + + constexpr reverse_iterator rbegin() noexcept { + return reverse_iterator{end()}; + } + + constexpr reverse_iterator rend() noexcept { + return reverse_iterator{begin()}; + } + + class const_iterator final { + friend IntrusiveList; + + const IntrusiveListNode *cursor; + + constexpr const_iterator(const IntrusiveListNode *_cursor) noexcept + :cursor(_cursor) {} + + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = const T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + const_iterator() noexcept = default; + + const_iterator(iterator src) noexcept + :cursor(src.cursor) {} + + constexpr bool operator==(const const_iterator &other) const noexcept { + return cursor == other.cursor; + } + + constexpr bool operator!=(const const_iterator &other) const noexcept { + return !(*this == other); + } + + constexpr reference operator*() const noexcept { + return *Cast(cursor); + } + + constexpr pointer operator->() const noexcept { + return Cast(cursor); + } + + auto &operator++() noexcept { + cursor = cursor->next; + return *this; + } + + auto operator++(int) noexcept { + auto old = *this; + cursor = cursor->next; + return old; + } + + auto &operator--() noexcept { + cursor = cursor->prev; + return *this; + } + + auto operator--(int) noexcept { + auto old = *this; + cursor = cursor->prev; + return old; + } + }; + + constexpr const_iterator begin() const noexcept { + if constexpr (options.zero_initialized) + if (head.next == nullptr) + return end(); + + return {head.next}; + } + + constexpr const_iterator end() const noexcept { + return {&head}; + } + + static constexpr const_iterator iterator_to(const_reference t) noexcept { + return {&ToNode(t)}; + } + + using const_reverse_iterator = std::reverse_iterator; + + constexpr const_reverse_iterator rbegin() const noexcept { + return reverse_iterator{end()}; + } + + constexpr const_reverse_iterator rend() const noexcept { + return reverse_iterator{begin()}; + } + + /** + * @return an iterator to the item following the specified one + */ + iterator erase(iterator i) noexcept { + auto result = std::next(i); + ToHook(*i).unlink(); + --counter; + return result; + } + + /** + * @return an iterator to the item following the specified one + */ + iterator erase_and_dispose(iterator i, + Disposer auto disposer) noexcept { + auto result = erase(i); + disposer(&*i); + return result; + } + + iterator push_front(reference t) noexcept { + return insert(begin(), t); + } + + iterator push_back(reference t) noexcept { + return insert(end(), t); + } + + /** + * Insert a new item before the given position. + * + * @param p a valid iterator (end() is allowed)for this list + * describing the position where to insert + * + * @return an iterator to the new item + */ + iterator insert(iterator p, reference t) noexcept { + static_assert(!constant_time_size || + GetHookMode() < IntrusiveHookMode::AUTO_UNLINK, + "Can't use auto-unlink hooks with constant_time_size"); + + if constexpr (options.zero_initialized) + if (head.next == nullptr) + head = {&head, &head}; + + auto &existing_node = *p.cursor; + auto &new_node = ToNode(t); + + IntrusiveListNode::Connect(*existing_node.prev, + new_node); + IntrusiveListNode::Connect(new_node, existing_node); + + ++counter; + + return iterator_to(t); + } + + /** + * Like insert(), but insert after the given position. + */ + iterator insert_after(iterator p, reference t) noexcept { + if constexpr (options.zero_initialized) + if (head.next == nullptr) + head = {&head, &head}; + + return insert(std::next(p), t); + } + + /** + * Move one item of the given list to this one before the + * given position. + */ + void splice(iterator position, + IntrusiveList &from, iterator i) noexcept { + auto &item = *i; + from.erase(i); + insert(position, item); + } + + /** + * Move the given range of items of the given list to this one + * before the given position. + */ + void splice(iterator position, IntrusiveList &from, + iterator _begin, iterator _end, size_type n) noexcept { + if (_begin == _end) + return; + + if constexpr (options.zero_initialized) + if (head.next == nullptr) + head = {&head, &head}; + + auto &next_node = *position.cursor; + auto &prev_node = *std::prev(position).cursor; + + auto &first_node = *_begin.cursor; + auto &before_first_node = *std::prev(_begin).cursor; + auto &last_node = *std::prev(_end).cursor; + auto &after_last_node = *_end.cursor; + + /* remove from the other list */ + IntrusiveListNode::Connect(before_first_node, after_last_node); + from.counter -= n; + + /* insert into this list */ + IntrusiveListNode::Connect(prev_node, first_node); + IntrusiveListNode::Connect(last_node, next_node); + counter += n; + } + + /** + * Move all items of the given list to this one before the + * given position. + */ + void splice(iterator position, IntrusiveList &from) noexcept { + splice(position, from, from.begin(), from.end(), + constant_time_size ? from.size() : 1); + } +}; diff --git a/src/util/IntrusiveTreeSet.hxx b/src/util/IntrusiveTreeSet.hxx new file mode 100644 index 0000000..7298976 --- /dev/null +++ b/src/util/IntrusiveTreeSet.hxx @@ -0,0 +1,511 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include "RedBlackTree.hxx" + +#include "Cast.hxx" +#include "Concepts.hxx" +#include "IntrusiveHookMode.hxx" // IWYU pragma: export +#include "MemberPointer.hxx" +#include "OptionalCounter.hxx" + +#include +#include // for std::weak_ordering +#include // for std::regular_invocable +#include +#include // for std::exchange() + +struct IntrusiveTreeSetOptions { + bool constant_time_size = false; +}; + +template +class IntrusiveTreeSetHook { + template friend struct IntrusiveTreeSetBaseHookTraits; + template friend struct IntrusiveTreeSetMemberHookTraits; + template friend class IntrusiveTreeSet; + +protected: + RedBlackTreeNode node; + +public: + static constexpr IntrusiveHookMode mode = _mode; + + constexpr IntrusiveTreeSetHook() noexcept { + if constexpr (mode >= IntrusiveHookMode::TRACK) + node.parent = nullptr; + } + + constexpr ~IntrusiveTreeSetHook() noexcept { + if constexpr (mode >= IntrusiveHookMode::AUTO_UNLINK) + if (is_linked()) + unlink(); + } + + IntrusiveTreeSetHook(const IntrusiveTreeSetHook &) = delete; + IntrusiveTreeSetHook &operator=(const IntrusiveTreeSetHook &) = delete; + + constexpr void unlink() noexcept { + if constexpr (mode >= IntrusiveHookMode::TRACK) { + assert(is_linked()); + } + + node.Unlink(); + + if constexpr (mode >= IntrusiveHookMode::TRACK) + node.parent = nullptr; + } + + bool is_linked() const noexcept { + static_assert(mode >= IntrusiveHookMode::TRACK); + + return node.parent != nullptr; + } + +private: + static constexpr auto &Cast(RedBlackTreeNode &node) noexcept { + return ContainerCast(node, &IntrusiveTreeSetHook::node); + } + + static constexpr const auto &Cast(const RedBlackTreeNode &node) noexcept { + return ContainerCast(node, &IntrusiveTreeSetHook::node); + } +}; + +/** + * Detect the hook type. + */ +template +struct IntrusiveTreeSetHookDetection { + /* TODO can this be simplified somehow, without checking for + all possible enum values? */ + using type = std::conditional_t, U>, + IntrusiveTreeSetHook, + std::conditional_t, U>, + IntrusiveTreeSetHook, + std::conditional_t, U>, + IntrusiveTreeSetHook, + void>>>; +}; + +/** + * For classes which embed #IntrusiveTreeSetHook as base class. + */ +template +struct IntrusiveTreeSetBaseHookTraits { + template + using Hook = typename IntrusiveTreeSetHookDetection::type; + + static constexpr T *Cast(RedBlackTreeNode *node) noexcept { + auto *hook = &Hook::Cast(*node); + return static_cast(hook); + } + + static constexpr auto &ToHook(T &t) noexcept { + return static_cast &>(t); + } +}; + +/** + * For classes which embed #IntrusiveTreeSetHook as member. + */ +template +struct IntrusiveTreeSetMemberHookTraits { + using T = MemberPointerContainerType; + using _Hook = MemberPointerType; + + template + using Hook = _Hook; + + static constexpr T *Cast(RedBlackTreeNode *node) noexcept { + auto &hook = Hook::Cast(*node); + return &ContainerCast(hook, member); + } + + static constexpr auto &ToHook(T &t) noexcept { + return t.*member; + } +}; + +/** + * @param GetKey a function object which extracts the "key" part of an + * item + */ +template GetKey=std::identity, + std::regular_invocable, + std::invoke_result_t> Compare=std::compare_three_way> +struct IntrusiveTreeSetOperators { + [[no_unique_address]] + GetKey get_key; + + [[no_unique_address]] + Compare compare; +}; + +/** + * A binary tree implementation which stores pointers to items which + * have an embedded #IntrusiveTreeSetHook. + */ +template, + typename HookTraits=IntrusiveTreeSetBaseHookTraits, + IntrusiveTreeSetOptions options=IntrusiveTreeSetOptions{}> +class IntrusiveTreeSet { + static constexpr bool constant_time_size = options.constant_time_size; + + [[no_unique_address]] + OptionalCounter counter; + + [[no_unique_address]] + Operators ops; + + RedBlackTreeNode head{RedBlackTreeNode::Head{}}; + +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + using size_type = std::size_t; + + [[nodiscard]] + IntrusiveTreeSet() noexcept = default; + +#ifndef NDEBUG + /** + * For debugging only: check the integrity of the red-black + * tree. + */ + void Check() noexcept { + RedBlackTreeNode::BlackHeight(GetRoot()); + } +#endif + + [[nodiscard]] + constexpr bool empty() const noexcept { + return GetRoot() == nullptr; + } + + [[nodiscard]] + constexpr size_type size() const noexcept { + if constexpr (constant_time_size) + return counter; + else + return std::distance(begin(), end()); + } + + constexpr void clear() noexcept { + SetRoot(nullptr); + counter.reset(); + } + + constexpr void clear_and_dispose(Disposer auto disposer) noexcept { + dispose_all(GetRoot(), disposer); + clear(); + } + + class iterator { + friend IntrusiveTreeSet; + + RedBlackTreeNode *node; + + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + explicit constexpr iterator(RedBlackTreeNode *_node) noexcept + :node(_node) {} + + constexpr bool operator==(const iterator &) const noexcept = default; + constexpr bool operator!=(const iterator &) const noexcept = default; + + constexpr reference operator*() const noexcept { + return *Cast(node); + } + + constexpr pointer operator->() const noexcept { + return Cast(node); + } + + constexpr auto &operator++() noexcept { + node = RedBlackTreeNode::GetNextNode(node); + return *this; + } + }; + + [[nodiscard]] + constexpr iterator begin() noexcept { + auto *root = GetRoot(); + return root != nullptr + ? iterator{&root->GetLeftMost()} + : end(); + } + + [[nodiscard]] + constexpr iterator end() noexcept { + return iterator{nullptr}; + } + + class const_iterator { + friend IntrusiveTreeSet; + + const RedBlackTreeNode *node; + + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = const T; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + explicit constexpr const_iterator(RedBlackTreeNode *_node) noexcept + :node(_node) {} + + constexpr const_iterator(iterator i) noexcept + :node(i.node) {} + + constexpr bool operator==(const const_iterator &) const noexcept = default; + constexpr bool operator!=(const const_iterator &) const noexcept = default; + + constexpr reference operator*() const noexcept { + return *Cast(node); + } + + constexpr pointer operator->() const noexcept { + return Cast(node); + } + + constexpr auto &operator++() noexcept { + node = RedBlackTreeNode::GetNextNode(const_cast(node)); + return *this; + } + }; + + [[nodiscard]] + constexpr const_iterator begin() const noexcept { + auto *root = GetRoot(); + return root != nullptr + ? const_iterator{&root->GetLeftMost()} + : end(); + } + + [[nodiscard]] + constexpr const_iterator end() const noexcept { + return const_iterator{nullptr}; + } + + const_reference front() const noexcept { + auto i = begin(); + assert(i != end()); + + return *i; + } + + reference front() noexcept { + auto i = begin(); + assert(i != end()); + + return *i; + } + + [[nodiscard]] + static constexpr iterator iterator_to(reference item) noexcept { + return iterator{&ToNode(item)}; + } + + [[nodiscard]] + constexpr iterator find(const auto &key) const noexcept { + auto *node = GetRoot(); + +#ifndef NDEBUG + bool previous_red = false; +#endif + + while (node != nullptr) { +#ifndef NDEBUG + const bool current_red = node->color == RedBlackTreeNode::Color::RED; + assert(!previous_red || !current_red); + previous_red = current_red; +#endif + + const auto &item = *Cast(node); + + const std::weak_ordering compare_result = ops.compare(key, ops.get_key(item)); + if (compare_result == std::weak_ordering::less) + node = node->GetLeft(); + else if (compare_result == std::weak_ordering::greater) + node = node->GetRight(); + else + break; + } + + return iterator{node}; + } + + constexpr iterator insert(reference value) noexcept { + static_assert(!constant_time_size || + GetHookMode() < IntrusiveHookMode::AUTO_UNLINK, + "Can't use auto-unlink hooks with constant_time_size"); + + auto *root = GetRoot(); + if (root == nullptr) { + root = &ToNode(value); + root->Init(RedBlackTreeNode::Color::BLACK); + } else { + root = &insert(root, value); + } + + SetRoot(root); + + ++counter; + + return iterator_to(value); + } + + iterator erase(iterator i) noexcept { + assert(i.node != nullptr); + assert(!empty()); + + auto *next = RedBlackTreeNode::GetNextNode(i.node); + Cast(i.node)->unlink(); + --counter; + return iterator{next}; + } + + void pop_front() noexcept { + erase(begin()); + } + +private: + [[nodiscard]] + static constexpr auto GetHookMode() noexcept { + return HookTraits::template Hook::mode; + } + + [[nodiscard]] + static constexpr pointer Cast(RedBlackTreeNode *node) noexcept { + return HookTraits::Cast(node); + } + + [[nodiscard]] + static constexpr const_pointer Cast(const RedBlackTreeNode *node) noexcept { + return HookTraits::Cast(const_cast(node)); + } + + [[nodiscard]] + static constexpr auto &ToHook(T &t) noexcept { + return HookTraits::ToHook(t); + } + + [[nodiscard]] + static constexpr const auto &ToHook(const T &t) noexcept { + return HookTraits::ToHook(t); + } + + [[nodiscard]] + static constexpr RedBlackTreeNode &ToNode(T &t) noexcept { + return ToHook(t).node; + } + + [[nodiscard]] + static constexpr const RedBlackTreeNode &ToNode(const T &t) noexcept { + return ToHook(t).node; + } + + [[nodiscard]] + constexpr RedBlackTreeNode *GetRoot() const noexcept { + return head.GetLeft(); + } + + [[nodiscard]] + constexpr bool IsRoot(const RedBlackTreeNode &node) const noexcept { + return &node == GetRoot(); + } + + constexpr void SetRoot(RedBlackTreeNode *root) noexcept { + head.SetChild(RedBlackTreeNode::Direction::LEFT, root); + } + + [[gnu::pure]] + constexpr RedBlackTreeNode::Direction GetInsertDirection(RedBlackTreeNode &parent, + const_reference new_value) const noexcept { + const auto &parent_value = *Cast(&parent); + const std::weak_ordering compare_result = ops.compare(ops.get_key(new_value), ops.get_key(parent_value)); + return compare_result == std::weak_ordering::less + ? RedBlackTreeNode::Direction::LEFT + : RedBlackTreeNode::Direction::RIGHT; + } + + std::optional rotate1, rotate2; + + RedBlackTreeNode &insert(RedBlackTreeNode *base, + reference value) noexcept { + if (base == nullptr) { + auto &node = ToNode(value); + node.Init(RedBlackTreeNode::Color::RED); + return node; + } + + /* the actual insert is here */ + const auto insert_direction = GetInsertDirection(*base, value); + auto &new_child = insert(base->GetChild(insert_direction), value); + base->SetChild(insert_direction, &new_child); + const bool red_red_conflict = !IsRoot(*base) && + base->color == RedBlackTreeNode::Color::RED && + new_child.color == RedBlackTreeNode::Color::RED; + + /* rotate */ + if (rotate1) { + base->SetChild(*rotate1, &base->GetChild(*rotate1)->Rotate(*rotate1)); + rotate1.reset(); + } + + if (rotate2) { + base->color = RedBlackTreeNode::Color::RED; + base = &base->Rotate(*rotate2); + base->color = RedBlackTreeNode::Color::BLACK; + rotate2.reset(); + } + + if (red_red_conflict) { + const auto direction = base->GetDirectionInParent(); + const auto other_direction = RedBlackTreeNode::OtherDirection(direction); + + if (auto *sibling = base->parent->GetChild(other_direction); + sibling != nullptr && + sibling->color == RedBlackTreeNode::Color::RED) { + sibling->color = RedBlackTreeNode::Color::BLACK; + base->color = RedBlackTreeNode::Color::BLACK; + if (!IsRoot(*base->parent)) + base->parent->color = RedBlackTreeNode::Color::RED; + } else if (const auto *other_child = base->GetChild(other_direction); + other_child != nullptr && other_child->color == RedBlackTreeNode::Color::RED) { + rotate1 = direction; + rotate2 = other_direction; + } else if (const auto *child = base->GetChild(direction); + child != nullptr && child->color == RedBlackTreeNode::Color::RED) { + rotate2 = other_direction; + } + } + + return *base; + } + + void dispose_all(RedBlackTreeNode *node, Disposer auto disposer) noexcept { + if (node == nullptr) + return; + + for (auto *i : node->children) + dispose_all(i, disposer); + + disposer(Cast(node)); + } +}; diff --git a/src/util/IterableSplitString.hxx b/src/util/IterableSplitString.hxx new file mode 100644 index 0000000..cece281 --- /dev/null +++ b/src/util/IterableSplitString.hxx @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "StringSplit.hxx" + +#include +#include + +/** + * Split a string at a certain separator character into sub strings + * and allow iterating over the segments. + * + * Two consecutive separator characters result in an empty string. + * + * An empty input string returns one empty string. + */ +template +class BasicIterableSplitString { + using string_view = std::basic_string_view; + using value_type = typename string_view::value_type; + + string_view s; + value_type separator; + +public: + constexpr BasicIterableSplitString(string_view _s, + value_type _separator) noexcept + :s(_s), separator(_separator) {} + + class Iterator final { + friend class BasicIterableSplitString; + + string_view current, rest; + + value_type separator; + + constexpr Iterator(string_view _s, + value_type _separator) noexcept + :rest(_s), separator(_separator) + { + Next(); + } + + constexpr Iterator(std::nullptr_t) noexcept + :current(), rest(), separator() {} + + constexpr void Next() noexcept { + if (rest.data() == nullptr) + current = {}; + else { + const auto [a, b] = Split(rest, separator); + current = a; + rest = b; + } + } + + public: + using iterator_category = std::forward_iterator_tag; + + constexpr Iterator &operator++() noexcept{ + Next(); + return *this; + } + + constexpr bool operator==(Iterator other) const noexcept { + return current.data() == other.current.data(); + } + + constexpr string_view operator*() const noexcept { + return current; + } + + constexpr const string_view *operator->() const noexcept { + return ¤t; + } + }; + + using iterator = Iterator; + using const_iterator = Iterator; + + constexpr const_iterator begin() const noexcept { + return {s, separator}; + } + + constexpr const_iterator end() const noexcept { + return nullptr; + } +}; + +using IterableSplitString = BasicIterableSplitString; + +#ifdef _UNICODE +using WIterableSplitString = BasicIterableSplitString; +using TIterableSplitString = WIterableSplitString; +#else +using TIterableSplitString = IterableSplitString; +#endif diff --git a/src/util/LazyRandomEngine.cxx b/src/util/LazyRandomEngine.cxx new file mode 100644 index 0000000..f2d3ee7 --- /dev/null +++ b/src/util/LazyRandomEngine.cxx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "LazyRandomEngine.hxx" + +void LazyRandomEngine::AutoCreate() { + if (engine) + return; + + std::random_device rd; + engine.emplace(rd()); +} diff --git a/src/util/LazyRandomEngine.hxx b/src/util/LazyRandomEngine.hxx new file mode 100644 index 0000000..4450a0f --- /dev/null +++ b/src/util/LazyRandomEngine.hxx @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_LAZY_RANDOM_ENGINE_HXX +#define MPD_LAZY_RANDOM_ENGINE_HXX + +#include +#include +#include + +/** + * A random engine that will be created and seeded on demand. + */ +class LazyRandomEngine { + std::optional engine; + +public: + typedef std::mt19937::result_type result_type; + + LazyRandomEngine() : engine(std::nullopt) {} + + LazyRandomEngine(const LazyRandomEngine &other) = delete; + LazyRandomEngine &operator=(const LazyRandomEngine &other) = delete; + + /** + * Create and seed the real engine. Call this before any + * other method. + */ + void AutoCreate(); + + static constexpr result_type min() { return std::mt19937::min(); } + + static constexpr result_type max() { return std::mt19937::max(); } + + result_type operator()() { + assert(engine); + + return engine->operator()(); + } +}; + +#endif diff --git a/src/util/Manual.hxx b/src/util/Manual.hxx new file mode 100644 index 0000000..67d0837 --- /dev/null +++ b/src/util/Manual.hxx @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include + +/** + * Container for an object that gets constructed and destructed + * manually. The object is constructed in-place, and therefore + * without allocation overhead. It can be constructed and destructed + * repeatedly. + */ +template +class Manual { + alignas(T) std::byte data[sizeof(T)]; + +#ifndef NDEBUG + bool initialized = false; +#endif + +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + +#ifndef NDEBUG + ~Manual() noexcept { + assert(!initialized); + } +#endif + + /** + * Cast a value reference to the containing Manual instance. + */ + static constexpr Manual &Cast(reference value) noexcept { + return reinterpret_cast &>(value); + } + + template + void Construct(Args&&... args) { + assert(!initialized); + + ::new(data) T(std::forward(args)...); + +#ifndef NDEBUG + initialized = true; +#endif + } + + void Destruct() noexcept { + assert(initialized); + + reference t = Get(); + t.T::~T(); + +#ifndef NDEBUG + initialized = false; +#endif + } + + reference Get() noexcept { + assert(initialized); + + return *std::launder(reinterpret_cast(data)); + } + + const_reference Get() const noexcept { + assert(initialized); + + return *std::launder(reinterpret_cast(data)); + } + + operator reference() noexcept { + return Get(); + } + + operator const_reference() const noexcept { + return Get(); + } + + pointer operator->() noexcept { + return &Get(); + } + + const_pointer operator->() const noexcept { + return &Get(); + } +}; diff --git a/src/util/Math.hxx b/src/util/Math.hxx new file mode 100644 index 0000000..8e557d7 --- /dev/null +++ b/src/util/Math.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef MATH_HXX +#define MATH_HXX + +#include + +/* + * C99 math can be optionally omitted with gcc's libstdc++. + * Use boost if unavailable. + */ +#if (defined(__GLIBCPP__) || defined(__GLIBCXX__)) && !defined(_GLIBCXX_USE_C99_MATH_TR1) +#include +using boost::math::lround; +#else +using std::lround; +#endif + +#endif diff --git a/src/util/MemberPointer.hxx b/src/util/MemberPointer.hxx new file mode 100644 index 0000000..a16f792 --- /dev/null +++ b/src/util/MemberPointer.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +template +struct MemberPointerHelper; + +template +struct MemberPointerHelper { + using ContainerType = C; + using MemberType = M; +}; + +/** + * Given a member pointer, this determines the member type. + */ +template +using MemberPointerType = + typename MemberPointerHelper::MemberType; + +/** + * Given a member pointer, this determines the container type. + */ +template +using MemberPointerContainerType = + typename MemberPointerHelper::ContainerType; diff --git a/src/util/MimeType.cxx b/src/util/MimeType.cxx new file mode 100644 index 0000000..d8f3a92 --- /dev/null +++ b/src/util/MimeType.cxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "MimeType.hxx" +#include "IterableSplitString.hxx" +#include "util/StringSplit.hxx" +#include "util/StringStrip.hxx" + +std::string_view +GetMimeTypeBase(std::string_view s) noexcept +{ + return Split(s, ';').first; +} + +std::map> +ParseMimeTypeParameters(std::string_view mime_type) noexcept +{ + /* discard the first segment (the base MIME type) */ + const auto params = Split(mime_type, ';').second; + + std::map> result; + for (const std::string_view i : IterableSplitString(params, ';')) { + const auto s = Split(Strip(i), '='); + if (!s.first.empty() && s.second.data() != nullptr) + result.emplace(s); + } + + return result; +} diff --git a/src/util/MimeType.hxx b/src/util/MimeType.hxx new file mode 100644 index 0000000..4b7e4fe --- /dev/null +++ b/src/util/MimeType.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include // for std::less +#include +#include +#include + +/** + * Extract the part of the MIME type before the parameters, i.e. the + * part before the semicolon. If there is no semicolon, it returns + * the string as-is. + */ +[[gnu::pure]] +std::string_view +GetMimeTypeBase(std::string_view s) noexcept; + +/** + * Parse the parameters from a MIME type string. Parameters are + * separated by semicolon. Example: + * + * "foo/bar; param1=value1; param2=value2" + */ +std::map> +ParseMimeTypeParameters(std::string_view mime_type) noexcept; diff --git a/src/util/NumberParser.hxx b/src/util/NumberParser.hxx new file mode 100644 index 0000000..8239466 --- /dev/null +++ b/src/util/NumberParser.hxx @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include + +/** + * A std::from_chars() wrapper taking a std::string_view. How + * annoying that the C++ standard library doesn't allow this! + */ +inline std::from_chars_result +FromChars(std::string_view s, std::integral auto &value, int base=10) noexcept +{ + return std::from_chars(s.data(), s.data() + s.size(), value, base); +} + +/** + * A wrapper for FromChars() which translates the #from_chars_result + * to a boolean (true on success, false on error). + */ +inline bool +ParseIntegerTo(std::string_view s, std::integral auto &value, int base=10) noexcept +{ + auto [ptr, ec] = FromChars(s, value, base); + return ptr == s.data() + s.size() && ec == std::errc{}; +} + +template +[[gnu::pure]] +std::optional +ParseInteger(const char *first, const char *last, int base=10) noexcept +{ + T value; + auto [ptr, ec] = std::from_chars(first, last, value, base); + if (ptr == last && ec == std::errc{}) + return value; + else + return std::nullopt; +} + +template +[[gnu::pure]] +std::optional +ParseInteger(std::string_view src, int base=10) noexcept +{ + return ParseInteger(src.data(), src.data() + src.size(), base); +} diff --git a/src/util/OffsetPointer.hxx b/src/util/OffsetPointer.hxx new file mode 100644 index 0000000..b628a8f --- /dev/null +++ b/src/util/OffsetPointer.hxx @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Offset the given pointer by the specified number of bytes. + */ +constexpr void * +OffsetPointer(void *p, std::ptrdiff_t offset) noexcept +{ + return static_cast(p) + offset; +} + +/** + * Offset the given pointer by the specified number of bytes. + */ +constexpr const void * +OffsetPointer(const void *p, std::ptrdiff_t offset) noexcept +{ + return static_cast(p) + offset; +} diff --git a/src/util/OptionalCounter.hxx b/src/util/OptionalCounter.hxx new file mode 100644 index 0000000..1ca6cac --- /dev/null +++ b/src/util/OptionalCounter.hxx @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include +#include + +template class OptionalCounter; + +template<> +class OptionalCounter +{ +public: + constexpr void reset() noexcept {} + constexpr auto &operator++() noexcept { return *this; } + constexpr auto &operator--() noexcept { return *this; } + constexpr auto &operator+=(std::size_t) noexcept { return *this; } + constexpr auto &operator-=(std::size_t) noexcept { return *this; } +}; + +template<> +class OptionalCounter +{ + std::size_t value = 0; + +public: + constexpr operator std::size_t() const noexcept { + return value; + } + + constexpr void reset() noexcept { + value = 0; + } + + constexpr auto &operator++() noexcept { + ++value; + return *this; + } + + constexpr auto &operator--() noexcept { + assert(value > 0); + + --value; + return *this; + } + + constexpr auto &operator+=(std::size_t n) noexcept { + value += n; + return *this; + } + + constexpr auto &operator-=(std::size_t n) noexcept { + assert(value >= n); + + value -= n; + return *this; + } +}; diff --git a/src/util/OptionalField.hxx b/src/util/OptionalField.hxx new file mode 100644 index 0000000..ec32807 --- /dev/null +++ b/src/util/OptionalField.hxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include // for std::forward() + +/** + * Helps with declaring a field that is present only under a certain + * (compile-time) condition. If `enable` is true, this struct + * contains a field named `value` of the specified type. To avoid + * memory overhead when disabled, add the attribute + * [[no_unique_address]]. + */ +template struct OptionalField; + +template +struct OptionalField +{ + template + constexpr OptionalField(Args&&...) {} +}; + +template +struct OptionalField +{ + T value; + + template + constexpr OptionalField(Args&&... args) + :value(std::forward(args)...) {} +}; diff --git a/src/util/PackedBigEndian.hxx b/src/util/PackedBigEndian.hxx new file mode 100644 index 0000000..12b7949 --- /dev/null +++ b/src/util/PackedBigEndian.hxx @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "ByteOrder.hxx" + +#include + +/** + * A packed big-endian 16 bit integer. + */ +class PackedBE16 { + uint8_t hi, lo; + +public: + PackedBE16() = default; + + constexpr PackedBE16(uint16_t src) noexcept + :hi(uint8_t(src >> 8)), + lo(uint8_t(src)) {} + + /** + * Construct an instance from an integer which is already + * big-endian. + */ + static constexpr auto FromBE(uint16_t src) noexcept { + union { + uint16_t in; + PackedBE16 out; + } u{src}; + return u.out; + } + + constexpr operator uint16_t() const noexcept { + return (uint16_t(hi) << 8) | uint16_t(lo); + } + + /** + * Reads the raw, big-endian value. + */ + constexpr uint16_t raw() const noexcept { + uint16_t x = *this; + if (IsLittleEndian()) + x = ByteSwap16(x); + return x; + } +}; + +static_assert(sizeof(PackedBE16) == sizeof(uint16_t), "Wrong size"); +static_assert(alignof(PackedBE16) == 1, "Wrong alignment"); + +/** + * A packed big-endian signed 16 bit integer. + */ +class PackedSignedBE16 { + PackedBE16 u; + +public: + PackedSignedBE16() = default; + + constexpr PackedSignedBE16(int16_t src) noexcept + :u(uint16_t(src)) {} + + constexpr operator int16_t() const noexcept { + return (int16_t)(uint16_t)u; + } +}; + +static_assert(sizeof(PackedSignedBE16) == sizeof(int16_t), "Wrong size"); +static_assert(alignof(PackedSignedBE16) == 1, "Wrong alignment"); + +/** + * A packed big-endian 32 bit integer. + */ +class PackedBE32 { + uint8_t a, b, c, d; + +public: + PackedBE32() = default; + + constexpr PackedBE32(uint32_t src) noexcept + :a(uint8_t(src >> 24)), + b(uint8_t(src >> 16)), + c(uint8_t(src >> 8)), + d(uint8_t(src)) {} + + /** + * Construct an instance from an integer which is already + * big-endian. + */ + static constexpr auto FromBE(uint32_t src) noexcept { + union { + uint32_t in; + PackedBE32 out; + } u{src}; + return u.out; + } + + constexpr operator uint32_t() const noexcept { + return (uint32_t(a) << 24) | (uint32_t(b) << 16) | + (uint32_t(c) << 8) | uint32_t(d); + } + + /** + * Reads the raw, big-endian value. + */ + constexpr uint32_t raw() const noexcept { + uint32_t x = *this; + if (IsLittleEndian()) + x = ByteSwap32(x); + return x; + } + + constexpr auto operator|(PackedBE32 other) noexcept { + PackedBE32 result{}; + result.a = a|other.a; + result.b = b|other.b; + result.c = c|other.c; + result.d = d|other.d; + return result; + } + + constexpr auto &operator|=(PackedBE32 x) noexcept { + return *this = *this | x; + } +}; + +static_assert(sizeof(PackedBE32) == sizeof(uint32_t), "Wrong size"); +static_assert(alignof(PackedBE32) == 1, "Wrong alignment"); + +/** + * A packed big-endian 64 bit integer. + */ +class PackedBE64 { + uint8_t a, b, c, d, e, f, g, h; + +public: + PackedBE64() = default; + + constexpr PackedBE64(uint64_t src) noexcept + :a(uint8_t(src >> 56)), + b(uint8_t(src >> 48)), + c(uint8_t(src >> 40)), + d(uint8_t(src >> 32)), + e(uint8_t(src >> 24)), + f(uint8_t(src >> 16)), + g(uint8_t(src >> 8)), + h(uint8_t(src)) {} + + /** + * Construct an instance from an integer which is already + * big-endian. + */ + static constexpr auto FromBE(uint64_t src) noexcept { + union { + uint64_t in; + PackedBE64 out; + } u{src}; + return u.out; + } + + constexpr operator uint64_t() const noexcept { + return (uint64_t(a) << 56) | (uint64_t(b) << 48) | + (uint64_t(c) << 40) | (uint64_t(d) << 32) | + (uint64_t(e) << 24) | (uint64_t(f) << 16) | + (uint64_t(g) << 8) | uint64_t(h); + } + + /** + * Reads the raw, big-endian value. + */ + constexpr uint64_t raw() const noexcept { + uint64_t x = *this; + if (IsLittleEndian()) + x = ByteSwap64(x); + return x; + } +}; + +static_assert(sizeof(PackedBE64) == sizeof(uint64_t), "Wrong size"); +static_assert(alignof(PackedBE64) == 1, "Wrong alignment"); diff --git a/src/util/PackedLittleEndian.hxx b/src/util/PackedLittleEndian.hxx new file mode 100644 index 0000000..8242a45 --- /dev/null +++ b/src/util/PackedLittleEndian.hxx @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "ByteOrder.hxx" + +#include + +/** + * A packed little-endian 16 bit integer. + */ +class PackedLE16 { + uint8_t lo, hi; + +public: + PackedLE16() = default; + + constexpr PackedLE16(uint16_t src) noexcept + :lo(uint8_t(src)), + hi(uint8_t(src >> 8)) {} + + /** + * Construct an instance from an integer which is already + * little-endian. + */ + static constexpr auto FromLE(uint16_t src) noexcept { + union { + uint16_t in; + PackedLE16 out; + } u{src}; + return u.out; + } + + constexpr operator uint16_t() const noexcept { + return (uint16_t(hi) << 8) | uint16_t(lo); + } + + PackedLE16 &operator=(uint16_t new_value) noexcept { + lo = uint8_t(new_value); + hi = uint8_t(new_value >> 8); + return *this; + } + + /** + * Reads the raw, little-endian value. + */ + constexpr uint16_t raw() const noexcept { + uint16_t x = *this; + if (IsBigEndian()) + x = ByteSwap16(x); + return x; + } +}; + +static_assert(sizeof(PackedLE16) == sizeof(uint16_t), "Wrong size"); +static_assert(alignof(PackedLE16) == 1, "Wrong alignment"); + +/** + * A packed little-endian 32 bit integer. + */ +class PackedLE32 { + uint8_t a, b, c, d; + +public: + PackedLE32() = default; + + constexpr PackedLE32(uint32_t src) noexcept + :a(uint8_t(src)), + b(uint8_t(src >> 8)), + c(uint8_t(src >> 16)), + d(uint8_t(src >> 24)) {} + + /** + * Construct an instance from an integer which is already + * little-endian. + */ + static constexpr auto FromLE(uint32_t src) noexcept { + union { + uint32_t in; + PackedLE32 out; + } u{src}; + return u.out; + } + + constexpr operator uint32_t() const noexcept { + return uint32_t(a) | (uint32_t(b) << 8) | + (uint32_t(c) << 16) | (uint32_t(d) << 24); + } + + PackedLE32 &operator=(uint32_t new_value) noexcept { + a = uint8_t(new_value); + b = uint8_t(new_value >> 8); + c = uint8_t(new_value >> 16); + d = uint8_t(new_value >> 24); + return *this; + } + + /** + * Reads the raw, little-endian value. + */ + constexpr uint32_t raw() const noexcept { + uint32_t x = *this; + if (IsBigEndian()) + x = ByteSwap32(x); + return x; + } +}; + +static_assert(sizeof(PackedLE32) == sizeof(uint32_t), "Wrong size"); +static_assert(alignof(PackedLE32) == 1, "Wrong alignment"); + +/** + * A packed little-endian 64 bit integer. + */ +class PackedLE64 { + uint8_t a, b, c, d, e, f, g, h; + +public: + PackedLE64() = default; + + constexpr PackedLE64(uint64_t src) noexcept + :a(uint8_t(src)), + b(uint8_t(src >> 8)), + c(uint8_t(src >> 16)), + d(uint8_t(src >> 24)), + e(uint8_t(src >> 32)), + f(uint8_t(src >> 40)), + g(uint8_t(src >> 48)), + h(uint8_t(src >> 56)) {} + + /** + * Construct an instance from an integer which is already + * little-endian. + */ + static constexpr auto FromLE(uint64_t src) noexcept { + union { + uint64_t in; + PackedLE64 out; + } u{src}; + return u.out; + } + + constexpr operator uint64_t() const noexcept { + return uint64_t(a) | (uint64_t(b) << 8) | + (uint64_t(c) << 16) | (uint64_t(d) << 24) | + (uint64_t(e) << 32) | (uint64_t(f) << 40) | + (uint64_t(g) << 48) | (uint64_t(h) << 56); + } + + /** + * Reads the raw, big-endian value. + */ + constexpr uint64_t raw() const noexcept { + uint64_t x = *this; + if (IsBigEndian()) + x = ByteSwap64(x); + return x; + } +}; + +static_assert(sizeof(PackedLE64) == sizeof(uint64_t), "Wrong size"); +static_assert(alignof(PackedLE64) == 1, "Wrong alignment"); diff --git a/src/util/PeakBuffer.cxx b/src/util/PeakBuffer.cxx new file mode 100644 index 0000000..be66729 --- /dev/null +++ b/src/util/PeakBuffer.cxx @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PeakBuffer.hxx" +#include "DynamicFifoBuffer.hxx" + +#include +#include + +PeakBuffer::~PeakBuffer() noexcept +{ + delete normal_buffer; + delete peak_buffer; +} + +bool +PeakBuffer::empty() const noexcept +{ + return (normal_buffer == nullptr || normal_buffer->empty()) && + (peak_buffer == nullptr || peak_buffer->empty()); +} + +std::span +PeakBuffer::Read() const noexcept +{ + if (normal_buffer != nullptr) { + const auto p = normal_buffer->Read(); + if (!p.empty()) + return p; + } + + if (peak_buffer != nullptr) { + const auto p = peak_buffer->Read(); + if (!p.empty()) + return p; + } + + return {}; +} + +void +PeakBuffer::Consume(std::size_t length) noexcept +{ + if (normal_buffer != nullptr && !normal_buffer->empty()) { + normal_buffer->Consume(length); + return; + } + + if (peak_buffer != nullptr && !peak_buffer->empty()) { + peak_buffer->Consume(length); + if (peak_buffer->empty()) { + delete peak_buffer; + peak_buffer = nullptr; + } + + return; + } +} + +static std::size_t +AppendTo(DynamicFifoBuffer &buffer, + std::span src) noexcept +{ + assert(!src.empty()); + + std::size_t total = 0; + + do { + const auto p = buffer.Write(); + if (p.empty()) + break; + + const std::size_t nbytes = std::min(src.size(), p.size()); + std::copy_n(src.begin(), nbytes, p.begin()); + buffer.Append(nbytes); + + src = src.subspan(nbytes); + total += nbytes; + } while (!src.empty()); + + return total; +} + +bool +PeakBuffer::Append(std::span src) +{ + if (src.empty()) + return true; + + if (peak_buffer != nullptr && !peak_buffer->empty()) { + std::size_t nbytes = AppendTo(*peak_buffer, src); + return nbytes == src.size(); + } + + if (normal_buffer == nullptr) + normal_buffer = new DynamicFifoBuffer(normal_size); + + std::size_t nbytes = AppendTo(*normal_buffer, src); + if (nbytes > 0) { + src = src.subspan(nbytes); + if (src.empty()) + return true; + } + + if (peak_buffer == nullptr) { + if (peak_size > 0) + peak_buffer = new DynamicFifoBuffer(peak_size); + if (peak_buffer == nullptr) + return false; + } + + nbytes = AppendTo(*peak_buffer, src); + return nbytes == src.size(); +} diff --git a/src/util/PeakBuffer.hxx b/src/util/PeakBuffer.hxx new file mode 100644 index 0000000..73a5fac --- /dev/null +++ b/src/util/PeakBuffer.hxx @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_PEAK_BUFFER_HXX +#define MPD_PEAK_BUFFER_HXX + +#include +#include + +template class DynamicFifoBuffer; + +/** + * A FIFO-like buffer that will allocate more memory on demand to + * allow large peaks. This second buffer will be given back to the + * kernel when it has been consumed. + */ +class PeakBuffer { + std::size_t normal_size, peak_size; + + DynamicFifoBuffer *normal_buffer, *peak_buffer; + +public: + PeakBuffer(std::size_t _normal_size, std::size_t _peak_size) noexcept + :normal_size(_normal_size), peak_size(_peak_size), + normal_buffer(nullptr), peak_buffer(nullptr) {} + + PeakBuffer(PeakBuffer &&other) noexcept + :normal_size(other.normal_size), peak_size(other.peak_size), + normal_buffer(other.normal_buffer), + peak_buffer(other.peak_buffer) { + other.normal_buffer = nullptr; + other.peak_buffer = nullptr; + } + + ~PeakBuffer() noexcept; + + PeakBuffer(const PeakBuffer &) = delete; + PeakBuffer &operator=(const PeakBuffer &) = delete; + + std::size_t max_size() const noexcept { + return normal_size + peak_size; + } + + [[gnu::pure]] + bool empty() const noexcept; + + [[gnu::pure]] + std::span Read() const noexcept; + + void Consume(std::size_t length) noexcept; + + bool Append(std::span src); +}; + +#endif diff --git a/src/util/PrintException.cxx b/src/util/PrintException.cxx new file mode 100644 index 0000000..42b46b1 --- /dev/null +++ b/src/util/PrintException.cxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#include "PrintException.hxx" + +#include + +void +PrintException(const std::exception &e) noexcept +{ + fprintf(stderr, "%s\n", e.what()); + try { + std::rethrow_if_nested(e); + } catch (const std::exception &nested) { + PrintException(nested); + } catch (const char *s) { + fprintf(stderr, "%s\n", s); + } catch (...) { + fprintf(stderr, "Unrecognized nested exception\n"); + } +} + +void +PrintException(const std::exception_ptr &ep) noexcept +{ + try { + std::rethrow_exception(ep); + } catch (const std::exception &e) { + PrintException(e); + } catch (const char *s) { + fprintf(stderr, "%s\n", s); + } catch (...) { + fprintf(stderr, "Unrecognized exception\n"); + } +} diff --git a/src/util/PrintException.hxx b/src/util/PrintException.hxx new file mode 100644 index 0000000..6947041 --- /dev/null +++ b/src/util/PrintException.hxx @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include + +/** + * Print this exception (and its nested exceptions, if any) to stderr. + */ +void +PrintException(const std::exception &e) noexcept; + +void +PrintException(const std::exception_ptr &ep) noexcept; diff --git a/src/util/RecursiveMap.hxx b/src/util/RecursiveMap.hxx new file mode 100644 index 0000000..5f5f848 --- /dev/null +++ b/src/util/RecursiveMap.hxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef RECURSIVE_MAP_HXX +#define RECURSIVE_MAP_HXX + +#include + +/** + * A #std::map which contains instances of itself. + */ +template +class RecursiveMap : public std::map> {}; + +#endif diff --git a/src/util/RedBlackTree.hxx b/src/util/RedBlackTree.hxx new file mode 100644 index 0000000..73d1c35 --- /dev/null +++ b/src/util/RedBlackTree.hxx @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include // for std::any_of() +#include +#include +#include // for std::exchange() + +struct RedBlackTreeNode { + RedBlackTreeNode *parent; + + enum class Direction : std::size_t { LEFT, RIGHT }; + + std::array children; + + enum class Color { HEAD, BLACK, RED }; + + Color color; + + constexpr RedBlackTreeNode() noexcept = default; + + struct Head {}; + explicit constexpr RedBlackTreeNode(Head) noexcept + :children({}), + color(Color::HEAD) {} + + RedBlackTreeNode(const RedBlackTreeNode &) = delete; + RedBlackTreeNode &operator=(const RedBlackTreeNode &) = delete; + + constexpr void Init(Color _color) noexcept { + children = {}; + color = _color; + } + + [[nodiscard]] + constexpr bool IsHead() const noexcept { + return color == Color::HEAD; + } + + [[nodiscard]] + constexpr bool IsRoot() const noexcept { + assert(!IsHead()); + + return parent->IsHead(); + } + + [[nodiscard]] + static constexpr Direction OtherDirection(Direction direction) noexcept { + return static_cast(static_cast(direction) ^ 1); + } + + [[nodiscard]] + constexpr RedBlackTreeNode *GetChild(Direction direction) const noexcept { + return children[static_cast(direction)]; + } + + [[nodiscard]] + constexpr RedBlackTreeNode *GetLeft() const noexcept { + return GetChild(Direction::LEFT); + } + + [[nodiscard]] + constexpr RedBlackTreeNode *GetRight() const noexcept { + return GetChild(Direction::RIGHT); + } + + [[nodiscard]] + constexpr RedBlackTreeNode *GetOtherChild(Direction direction) const noexcept { + return GetChild(OtherDirection(direction)); + } + + /** + * Set a new child and return the old one. + */ + constexpr auto *SetChild(Direction direction, + RedBlackTreeNode *child) noexcept { + auto *old = std::exchange(children[static_cast(direction)], + child); + if (child != nullptr) + child->parent = this; + + return old; + } + + constexpr auto *SetChild(Direction direction, + RedBlackTreeNode &child) noexcept { + auto *old = std::exchange(children[static_cast(direction)], + &child); + child.parent = this; + + return old; + } + + constexpr auto *SetOtherChild(Direction direction, + RedBlackTreeNode *child) noexcept { + return SetChild(OtherDirection(direction), child); + } + + [[nodiscard]] + constexpr Direction GetChildDirection(const RedBlackTreeNode &child) const noexcept { + assert(child.parent == this); + assert(&child == GetChild(Direction::LEFT) || + &child == GetChild(Direction::RIGHT)); + + return &child == GetChild(Direction::LEFT) + ? Direction::LEFT + : Direction::RIGHT; + } + + constexpr void ReplaceChild(RedBlackTreeNode &old_child, + RedBlackTreeNode *new_child) noexcept { + SetChild(GetChildDirection(old_child), new_child); + } + + constexpr void ReplaceChild(RedBlackTreeNode &old_child, + RedBlackTreeNode &new_child) noexcept { + SetChild(GetChildDirection(old_child), new_child); + } + + [[nodiscard]] + constexpr Direction GetDirectionInParent() const noexcept { + assert(parent != nullptr); + assert(!IsHead()); + + return parent->GetChildDirection(*this); + } + + [[nodiscard]] + auto &Rotate(RedBlackTreeNode::Direction direction) noexcept { + assert(!IsHead()); + + auto *x = GetOtherChild(direction); + assert(x != nullptr); + + auto *y = x->SetChild(direction, this); + SetOtherChild(direction, y); + + return *x; + } + + void RotateInParent(RedBlackTreeNode::Direction direction) noexcept { + assert(parent != nullptr); + assert(!IsHead()); + + auto &p = *parent; + const auto direction_in_parent = p.GetChildDirection(*this); + + auto &new_node = Rotate(direction); + assert(new_node.parent == this); + + assert(p.GetChild(direction_in_parent) == this); + p.SetChild(direction_in_parent, new_node); + } + + [[nodiscard]] + constexpr static RedBlackTreeNode &GetLeftMost(RedBlackTreeNode *node) noexcept { + assert(node != nullptr); + assert(!node->IsHead()); + + while (auto *left = node->GetChild(Direction::LEFT)) { + assert(left->parent == node); + node = left; + } + + return *node; + } + + [[nodiscard]] + constexpr RedBlackTreeNode &GetLeftMost() noexcept { + return GetLeftMost(this); + } + +#ifndef NDEBUG + /** + * Determine the "black height" (the number of black nodes in + * any path from the root to the leaves). This is for + * debugging only. It walks the whole tree and aborts if the + * black height is not consistent. + */ + static unsigned BlackHeight(const RedBlackTreeNode *node) noexcept { + if (node == nullptr) + /* leaf nodes (NIL / nullptr) count as + black */ + return 1; + + assert(node->parent != nullptr); + assert(node->color != Color::HEAD); + assert(node->color != Color::RED || node->parent->color != Color::RED); + + assert(node->children[0] == nullptr || node->children[0]->parent == node); + assert(node->children[1] == nullptr || node->children[1]->parent == node); + + const unsigned left_height = BlackHeight(node->children[0]); + const unsigned right_height = BlackHeight(node->children[1]); + + /* the black height must be equal in all paths */ + assert(left_height == right_height); + + return left_height + (node->color == Color::BLACK); + } +#endif + +private: + [[nodiscard]] + constexpr static RedBlackTreeNode *GetLeftHandedParent(RedBlackTreeNode *node) noexcept { + assert(node != nullptr); + assert(!node->IsHead()); + + while (true) { + assert(node->parent != nullptr); + auto &p = *node->parent; + if (p.IsHead()) + return nullptr; + + assert(node->color != RedBlackTreeNode::Color::RED || + p.color != RedBlackTreeNode::Color::RED); + + if (p.GetChildDirection(*node) == Direction::LEFT) + return &p; + + node = &p; + } + } + +public: + [[nodiscard]] + constexpr static RedBlackTreeNode *GetNextNode(RedBlackTreeNode *node) noexcept { + assert(node != nullptr); + assert(!node->IsHead()); + + if (auto *right = node->GetChild(Direction::RIGHT)) { + assert(node->color != RedBlackTreeNode::Color::RED || + right->color != RedBlackTreeNode::Color::RED); + return &right->GetLeftMost(); + } + + assert(node->parent != nullptr); + auto &p = *node->parent; + if (p.IsHead()) + return nullptr; + + if (p.GetChildDirection(*node) == Direction::LEFT) + return &p; + + return GetLeftHandedParent(&p); + } + +private: + [[nodiscard]] + constexpr bool HasTwoChildren() const noexcept { + return children[0] != nullptr && children[1] != nullptr; + } + + constexpr RedBlackTreeNode *GetAnyChild() const noexcept { + return children[children[1] != nullptr]; + } + +public: + constexpr void Unlink() noexcept { + assert(parent != nullptr); + assert(!IsHead()); + + if (HasTwoChildren()) { + /* swap with successor, because it, by + definition, doesn't have two children; the + rest of this method assumes we have exactly + one child or none */ + + auto &right = *GetRight(); + auto &successor = right.GetLeftMost(); + + auto &p = *parent; + const auto direction_in_parent = p.GetChildDirection(*this); + + std::swap(color, successor.color); + + successor.SetChild(Direction::LEFT, GetLeft()); + SetChild(Direction::LEFT, nullptr); + SetChild(Direction::RIGHT, successor.GetRight()); + + if (&successor == &right) { + assert(successor.parent == this); + + successor.SetChild(Direction::RIGHT, *this); + } else { + assert(successor.parent != this); + + successor.parent->SetChild(Direction::LEFT, *this); + successor.SetChild(Direction::RIGHT, &right); + } + + p.SetChild(direction_in_parent, successor); + } else { + /* if there is exactly one child, it must be red */ + assert(GetAnyChild() == nullptr || GetAnyChild()->color == Color::RED); + } + + assert(!HasTwoChildren()); + + auto &p = *parent; + + if (auto *child = GetAnyChild()) { + p.ReplaceChild(*this, *child); + child->color = Color::BLACK; + } else if (IsRoot()) { + p.SetChild(Direction::LEFT, nullptr); + } else { + if (color == Color::BLACK) + FixDoubleBlack(); + + p.ReplaceChild(*this, nullptr); + } + } + +private: + constexpr std::pair GetRedChild() const noexcept { + if (auto *left = GetLeft(); left != nullptr && left->color == Color::RED) + return {Direction::LEFT, left}; + + if (auto *right = GetRight(); right != nullptr && right->color == Color::RED) + return {Direction::RIGHT, right}; + + return {}; + } + + constexpr void FixDoubleBlack() noexcept { + assert(parent != nullptr); + assert(!IsHead()); + assert(color == Color::BLACK); + + if (IsRoot()) + return; + + auto &p = *parent; + const auto direction = p.GetChildDirection(*this); + const auto other_direction = OtherDirection(direction); + auto *const sibling = p.GetChild(other_direction); + + if (sibling == nullptr) { + p.FixDoubleBlack(); + return; + } + + switch (sibling->color) { + case Color::RED: + p.color = Color::RED; + sibling->color = Color::BLACK; + + p.RotateInParent(direction); + FixDoubleBlack(); + break; + + case Color::BLACK: + if (const auto [red_direction, red] = sibling->GetRedChild(); red != nullptr) { + /* at least one red child */ + + if (direction == red_direction) { + red->color = p.color; + sibling->RotateInParent(other_direction); + } else { + red->color = sibling->color; + sibling->color = p.color; + } + + p.RotateInParent(direction); + p.color = Color::BLACK; + } else { + /* no red child (both children are + either black or nullptr) */ + + sibling->color = Color::RED; + if (p.color == Color::BLACK) + p.FixDoubleBlack(); + else + p.color = Color::BLACK; + } + + break; + + case Color::HEAD: + // unreachable + assert(false); + break; + } + } +}; diff --git a/src/util/ReusableArray.hxx b/src/util/ReusableArray.hxx new file mode 100644 index 0000000..de67c8b --- /dev/null +++ b/src/util/ReusableArray.hxx @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef REUSABLE_ARRAY_HXX +#define REUSABLE_ARRAY_HXX + +#include +#include + +/** + * Manager for a temporary array which grows as needed. This attempts + * to reduce the number of consecutive heap allocations and + * deallocations. + * + * @param T the array element type + * @param M always allocate multiples of this number; must be a power of 2 + */ +template +class ReusableArray { + T *buffer = nullptr; + size_t capacity = 0; + +public: + ReusableArray() = default; + + ReusableArray(ReusableArray &&src) + :buffer(std::exchange(src.buffer, nullptr)), + capacity(std::exchange(src.capacity, 0)) {} + + ReusableArray &operator=(ReusableArray &&src) { + std::swap(buffer, src.buffer); + std::swap(capacity, src.capacity); + return *this; + } + + ~ReusableArray() { + delete[] buffer; + } + + size_t GetCapacity() const { + return capacity; + } + + /** + * Free resources allocated by this object. This invalidates + * the buffer returned by Get(). + */ + void Clear() { + delete[] buffer; + buffer = nullptr; + capacity = 0; + } + + /** + * Get the buffer, and guarantee a minimum size. This buffer + * becomes invalid with the next Get() call. + */ + [[gnu::malloc]] [[gnu::returns_nonnull]] + T *Get(size_t size) { + if (size > capacity) [[unlikely]] { + /* too small: grow */ + delete[] buffer; + + capacity = ((size - 1) | (M - 1)) + 1; + buffer = new T[capacity]; + } + + return buffer; + } +}; + +#endif diff --git a/src/util/RingBuffer.hxx b/src/util/RingBuffer.hxx new file mode 100644 index 0000000..e0bd399 --- /dev/null +++ b/src/util/RingBuffer.hxx @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "AllocatedArray.hxx" + +#include +#include +#include + +/** + * A thread-safe (single-producer, single-consumer; lock-free and + * wait-free) circular buffer. + * + * This implementation is optimized for bulk read/write + * (i.e. producing and consuming more than one item at a time). + */ +template +requires std::is_trivial_v +class RingBuffer { +protected: + AllocatedArray buffer; + + std::atomic_size_t write_position{0}, read_position{0}; + +public: + /** + * This default constructor will not allocate a buffer. + * IsDefined() will return false; it is not usable. To + * allocate a buffer later, create a new instance and use the + * move operator. + */ + RingBuffer() noexcept = default; + + /** + * Allocate a buffer of the specified size. + * + * The actual allocation will be the specified #capacity plus + * one, because for internal management, one slot needs to + * stay empty. + */ + explicit RingBuffer(std::size_t capacity) noexcept + :buffer(capacity + 1) {} + + /** + * Move the allocated buffer from another instance. + * + * This operation is not thread-safe. + */ + RingBuffer(RingBuffer &&src) noexcept + :buffer(std::move(src.buffer)), + write_position(src.write_position.load(std::memory_order_relaxed)), + read_position(src.read_position.load(std::memory_order_relaxed)) + { + } + + /** + * Move the allocated buffer from another instance. + * + * This operation is not thread-safe. + */ + RingBuffer &operator=(RingBuffer &&src) noexcept { + buffer = std::move(src.buffer); + write_position = src.write_position.load(std::memory_order_relaxed); + read_position = src.read_position.load(std::memory_order_relaxed); + return *this; + } + + /** + * Was a buffer allocated? + */ + bool IsDefined() const noexcept { + return buffer.capacity() > 0; + } + + /** + * Discard the contents of this buffer. + * + * This method is not thread-safe. For a thread-safe version, + * use Discard(). + */ + void Clear() noexcept { + assert(!IsDefined() || read_position.load() < buffer.capacity()); + assert(!IsDefined() || write_position.load() < buffer.capacity()); + + write_position.store(0, std::memory_order_relaxed); + read_position.store(0, std::memory_order_relaxed); + } + + bool IsFull() const noexcept { + const auto rp = GetPreviousIndex(read_position.load(std::memory_order_relaxed)); + const auto wp = write_position.load(std::memory_order_relaxed); + return rp == wp; + } + + /** + * Prepare a contiguous write directly into the buffer. The + * returned span (which, of course, cannot wrap around the end + * of the ring) may be written to; after that, call Append() + * to commit the write. + */ + [[gnu::pure]] + std::span Write() noexcept { + assert(IsDefined()); + + const auto wp = write_position.load(std::memory_order_acquire); + assert(wp < buffer.capacity()); + + const auto rp = GetPreviousIndex(read_position.load(std::memory_order_relaxed)); + assert(rp < buffer.capacity()); + + std::size_t n = (wp <= rp ? rp : buffer.capacity()) - wp; + return {&buffer[wp], n}; + } + + /** + * Commit the write prepared by Write(). + */ + void Append(std::size_t n) noexcept { + Add(write_position, n); + } + + /** + * Determine how many items may be written. This considers + * wraparound. + */ + [[gnu::pure]] + std::size_t WriteAvailable() const noexcept { + assert(IsDefined()); + + const auto wp = write_position.load(std::memory_order_relaxed); + const auto rp = GetPreviousIndex(read_position.load(std::memory_order_relaxed)); + + return wp <= rp + ? rp - wp + : buffer.capacity() - wp + rp; + } + + /** + * Append data from the given span to this buffer, handling + * wraparound. + * + * @return the number of items appended + */ + std::size_t WriteFrom(std::span src) noexcept { + auto wp = write_position.load(std::memory_order_acquire); + const auto rp = GetPreviousIndex(read_position.load(std::memory_order_relaxed)); + + std::size_t n = std::min((wp <= rp ? rp : buffer.capacity()) - wp, + src.size()); + CopyFrom(wp, src.first(n)); + + wp += n; + if (wp >= buffer.capacity()) { + // wraparound + src = src.subspan(n); + wp = std::min(rp, src.size()); + CopyFrom(0, src.first(wp)); + n += wp; + } + + write_position.store(wp, std::memory_order_release); + + return n; + } + + /** + * Like WriteFrom(), but ensure to never copy partial + * "frames"; a frame being a fixed-size group of items. + * + * @param frame_size the number of items which form one frame; + * the return value of this function is always a multiple of + * this value + */ + std::size_t WriteFramesFrom(std::span src, std::size_t frame_size) noexcept { + // TODO optimize, eliminate duplicate atomic reads + + std::size_t available = WriteAvailable(); + std::size_t frames_available = available / frame_size; + std::size_t rounded_available = frames_available * frame_size; + + if (rounded_available < src.size()) + src = src.first(rounded_available); + + return WriteFrom(src); + } + + /** + * Prepare a contiguous read directly from the buffer. The + * returned span (which, of course, cannot wrap around the end + * of the ring) may be read from; after that, call Consume() + * to commit the read. + */ + [[gnu::pure]] + std::span Read() const noexcept { + const auto rp = read_position.load(std::memory_order_acquire); + const auto wp = write_position.load(std::memory_order_relaxed); + + std::size_t n = (rp <= wp ? wp : buffer.capacity()) - rp; + return {&buffer[rp], n}; + } + + /** + * Commit the read prepared by Read(). + */ + void Consume(std::size_t n) noexcept { + Add(read_position, n); + } + + /** + * Determine how many items may be read. This considers + * wraparound. + */ + [[gnu::pure]] + std::size_t ReadAvailable() const noexcept { + assert(IsDefined()); + + const auto rp = read_position.load(std::memory_order_relaxed); + const auto wp = write_position.load(std::memory_order_relaxed); + + return rp <= wp + ? wp - rp + : buffer.capacity() - rp + wp; + } + + /** + * Pop data from this buffer to the given span, handling + * wraparound. + * + * @return the number of items move to the span + */ + std::size_t ReadTo(std::span dest) noexcept { + auto rp = read_position.load(std::memory_order_acquire); + const auto wp = write_position.load(std::memory_order_relaxed); + + std::size_t n = std::min((rp <= wp ? wp : buffer.capacity()) - rp, + dest.size()); + CopyTo(rp, dest.first(n)); + + rp += n; + if (rp >= buffer.capacity()) { + // wraparound + dest = dest.subspan(n); + rp = std::min(wp, dest.size()); + CopyTo(0, dest.first(rp)); + n += rp; + } + + read_position.store(rp, std::memory_order_release); + + return n; + } + + /** + * Like WriteFrom(), but ensure to never copy partial + * "frames"; a frame being a fixed-size group of items. + * + * @param frame_size the number of items which form one frame; + * the return value of this function is always a multiple of + * this value + */ + std::size_t ReadFramesTo(std::span dest, std::size_t frame_size) noexcept { + // TODO optimize, eliminate duplicate atomic reads + + std::size_t available = ReadAvailable(); + std::size_t frames_available = available / frame_size; + std::size_t rounded_available = frames_available * frame_size; + + if (rounded_available < dest.size()) + dest = dest.first(rounded_available); + + return ReadTo(dest); + } + + /** + * Discard the contents of this buffer. + * + * This method is thread-safe, but it may only be called from + * the consumer thread. + */ + void Discard() noexcept { + const auto wp = write_position.load(std::memory_order_relaxed); + read_position.store(wp, std::memory_order_release); + } + +private: + [[gnu::const]] + std::size_t GetPreviousIndex(std::size_t i) const noexcept { + assert(IsDefined()); + + if (i == 0) + i = buffer.capacity(); + return --i; + } + + void Add(std::atomic_size_t &dest, std::size_t n) const noexcept { + assert(IsDefined()); + + const std::size_t old_value = dest.load(std::memory_order_acquire); + assert(old_value < buffer.capacity()); + + std::size_t new_value = old_value + n; + assert(new_value <= buffer.capacity()); + if (new_value >= buffer.capacity()) + new_value = 0; + dest.store(new_value, std::memory_order_release); + } + + void CopyFrom(std::size_t dest_position, std::span src) noexcept { + std::copy(src.begin(), src.end(), &buffer[dest_position]); + } + + void CopyTo(std::size_t src_position, std::span dest) noexcept { + std::copy_n(&buffer[src_position], dest.size(), dest.begin()); + } +}; diff --git a/src/util/RoundPowerOfTwo.hxx b/src/util/RoundPowerOfTwo.hxx new file mode 100644 index 0000000..1a9aafb --- /dev/null +++ b/src/util/RoundPowerOfTwo.hxx @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include + +template +constexpr T +RoundUpToPowerOfTwo(T value) noexcept +{ + if (value <= 0) + return 1; + + --value; + + for (unsigned bits = 1; bits < sizeof(T) * 8; bits <<= 1) + value |= value >> bits; + + ++value; + + return value; +} + +static_assert(RoundUpToPowerOfTwo(0U) == 1U); +static_assert(RoundUpToPowerOfTwo(2U) == 2U); +static_assert(RoundUpToPowerOfTwo(3U) == 4U); +static_assert(RoundUpToPowerOfTwo(4U) == 4U); +static_assert(RoundUpToPowerOfTwo(5U) == 8U); +static_assert(RoundUpToPowerOfTwo(0x7fffU) == 0x8000U); +static_assert(RoundUpToPowerOfTwo(0x7ffffU) == 0x80000U); +static_assert(RoundUpToPowerOfTwo(0x1000000000000000ULL) == 0x1000000000000000ULL); +static_assert(RoundUpToPowerOfTwo(0x1fffffffffffffffULL) == 0x2000000000000000ULL); +static_assert(RoundUpToPowerOfTwo(0x7fffffffffffffffULL) == 0x8000000000000000ULL); +static_assert(RoundUpToPowerOfTwo(0x8000000000000000ULL) == 0x8000000000000000ULL); + +template +constexpr T +RoundUpToPowerOfTwo(T value, T power_of_two) noexcept +{ + return ((value - 1) | (power_of_two - 1)) + 1; +} + +template +constexpr T +RoundDownToPowerOfTwo(T value, T power_of_two) noexcept +{ + return value & ~(power_of_two - 1); +} diff --git a/src/util/ScopeExit.hxx b/src/util/ScopeExit.hxx new file mode 100644 index 0000000..2c2c992 --- /dev/null +++ b/src/util/ScopeExit.hxx @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Internal class. Do not use directly. + */ +template +class ScopeExitGuard { + [[no_unique_address]] + F function; + + bool enabled = true; + +public: + explicit ScopeExitGuard(F &&f) noexcept + :function(std::forward(f)) {} + + ScopeExitGuard(ScopeExitGuard &&src) noexcept + :function(std::move(src.function)), + enabled(std::exchange(src.enabled, false)) {} + + /* destructors are "noexcept" by default; this explicit + "noexcept" declaration allows the destructor to throw if + the function can throw; without this, a throwing function + would std::terminate() */ + ~ScopeExitGuard() noexcept(noexcept(std::declval()())) { + if (enabled) + function(); + } + + ScopeExitGuard(const ScopeExitGuard &) = delete; + ScopeExitGuard &operator=(const ScopeExitGuard &) = delete; +}; + +/** + * Internal class. Do not use directly. + */ +struct ScopeExitTag { + /* this operator is a trick so we don't need to close + parantheses at the end of the expression AtScopeExit() + call */ + template + ScopeExitGuard operator+(F &&f) noexcept { + return ScopeExitGuard(std::forward(f)); + } +}; + +#define ScopeExitCat(a, b) a ## b +#define ScopeExitName(line) ScopeExitCat(at_scope_exit_, line) + +/** + * Call the block after this macro at the end of the current scope. + * Parameters are lambda captures. + * + * This is exception-safe, however the given code block must not throw + * exceptions. + * + * This attempts to be a better boost/scope_exit.hpp, without all of + * Boost's compile-time and runtime bloat. + */ +#define AtScopeExit(...) auto ScopeExitName(__LINE__) = ScopeExitTag() + [__VA_ARGS__]() diff --git a/src/util/Serial.cxx b/src/util/Serial.cxx new file mode 100644 index 0000000..fb9b91b --- /dev/null +++ b/src/util/Serial.cxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Serial.hxx" + +#include +#include + +static std::atomic_uint next_serial; + +int +GenerateSerial() noexcept +{ + unsigned serial = ++next_serial; + if (serial < 16) [[unlikely]] { + /* first-time initialization: seed with a clock value, + which is random enough for our use */ + + /* this code is not race-free, but good enough */ + using namespace std::chrono; + const auto now = steady_clock::now().time_since_epoch(); + const auto now_ms = duration_cast(now); + const unsigned seed = now_ms.count(); + next_serial = serial = seed; + } + + return serial; +} + diff --git a/src/util/Serial.hxx b/src/util/Serial.hxx new file mode 100644 index 0000000..d91ea3a --- /dev/null +++ b/src/util/Serial.hxx @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SERIAL_HXX +#define MPD_SERIAL_HXX + +/** + * Generate the next pseudo-random serial. + */ +int +GenerateSerial() noexcept; + +#endif diff --git a/src/util/SliceBuffer.hxx b/src/util/SliceBuffer.hxx new file mode 100644 index 0000000..c7d593b --- /dev/null +++ b/src/util/SliceBuffer.hxx @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_SLICE_BUFFER_HXX +#define MPD_SLICE_BUFFER_HXX + +#include "HugeAllocator.hxx" + +#include +#include +#include +#include + +/** + * This class pre-allocates a certain number of objects, and allows + * callers to allocate and free these objects ("slices"). + */ +template +class SliceBuffer { + union Slice { + Slice *next; + + T value; + }; + + HugeArray buffer; + + /** + * The number of slices that are initialized. This is used to + * avoid page faulting on the new allocation, so the kernel + * does not need to reserve physical memory pages. + */ + unsigned n_initialized = 0; + + /** + * The number of slices currently allocated. + */ + unsigned n_allocated = 0; + + /** + * Pointer to the first free element in the chain. + */ + Slice *available = nullptr; + +public: + SliceBuffer(unsigned _count) + :buffer(_count) { + buffer.ForkCow(false); + } + + ~SliceBuffer() noexcept { + /* all slices must be freed explicitly, and this + assertion checks for leaks */ + assert(n_allocated == 0); + } + + SliceBuffer(const SliceBuffer &other) = delete; + SliceBuffer &operator=(const SliceBuffer &other) = delete; + + unsigned GetCapacity() const noexcept { + return buffer.size(); + } + + bool empty() const noexcept { + return n_allocated == 0; + } + + bool IsFull() const noexcept { + return n_allocated == buffer.size(); + } + + void SetName(const char *name) noexcept { + buffer.SetName(name); + } + + void DiscardMemory() noexcept { + assert(empty()); + + n_initialized = 0; + buffer.Discard(); + available = nullptr; + } + + template + T *Allocate(Args&&... args) { + assert(n_initialized <= buffer.size()); + assert(n_allocated <= n_initialized); + + if (available == nullptr) { + if (n_initialized == buffer.size()) { + /* out of (internal) memory, buffer is full */ + assert(n_allocated == buffer.size()); + return nullptr; + } + + available = &buffer[n_initialized++]; + available->next = nullptr; + } + + /* allocate a slice */ + T *value = &available->value; + available = available->next; + ++n_allocated; + + /* construct the object */ + return ::new((void *)value) T(std::forward(args)...); + } + + void Free(T *value) noexcept { + assert(n_initialized <= buffer.size()); + assert(n_allocated > 0); + assert(n_allocated <= n_initialized); + + Slice *slice = reinterpret_cast(value); + assert(slice >= &buffer.front() && slice <= &buffer.back()); + + /* destruct the object */ + value->~T(); + + /* insert the slice in the "available" linked list */ + slice->next = available; + available = slice; + --n_allocated; + + /* give memory back to the kernel when the last slice + was freed */ + if (n_allocated == 0) { + DiscardMemory(); + } + } +}; + +#endif diff --git a/src/util/SortList.hxx b/src/util/SortList.hxx new file mode 100644 index 0000000..54a4374 --- /dev/null +++ b/src/util/SortList.hxx @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "StaticVector.hxx" + +#include // for std::find_if() +#include + +/** + * Move all items from #src to #dest, keeping both sorted. + * + * @param p the predicate by which both lists are already + * sorted + */ +template +constexpr void +MergeList(List &dest, List &src, + std::predicate auto p) noexcept +{ + const auto dest_end = dest.end(), src_end = src.end(); + + auto dest_at = dest.begin(); + + while (!src.empty()) { + const auto src_begin = src.begin(); + + /* find the first item of "dest" that is larger than + the front of "src"; this is the next insertion + position */ + dest_at = std::find_if(dest_at, dest_end, [&p, &src_front = *src_begin](const auto &i){ + return p(src_front, i); + }); + + if (dest_at == dest_end) { + /* all items in "src" are larger than + "this": splice the whole list at + the end of "this" */ + dest.splice(dest_end, src); + break; + } + + /* find the first item of "src" that is not smaller + than the "dest" insertion anchor; this is the end + of the range of items to be spliced */ + const auto &dest_anchor = *dest_at; + typename List::size_type n = 1; + auto src_until = std::next(src_begin); + while (src_until != src_end && p(*src_until, dest_anchor)) { + ++src_until; + ++n; + } + + dest.splice(dest_at, src, src_begin, src_until, n); + } +} + +template +constexpr void +SortList(List &list, + std::predicate auto p) noexcept +{ + using std::swap; + + if (list.empty()) + return; + + /* bottom-up merge sort */ + + List carry; + StaticVector array; + + while (!list.empty()) { + carry.splice(carry.begin(), list, list.begin()); + + std::size_t i = 0; + while (i < array.size() && !array[i].empty()) { + auto &c = array[i++]; + MergeList(c, carry, p); + swap(carry, c); + } + + if (i == array.size()) + array.emplace_back(); + swap(carry, array[i]); + } + + assert(!array.empty()); + + for (std::size_t i = 1; i < array.size(); ++i) + MergeList(array[i], array[i - 1], p); + + swap(list, array.back()); +} diff --git a/src/util/SpanCast.hxx b/src/util/SpanCast.hxx new file mode 100644 index 0000000..59ea8bc --- /dev/null +++ b/src/util/SpanCast.hxx @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "CopyConst.hxx" + +#include +#include +#include +#include +#include + +/** + * Cast a std::span to a std::span, rounding down to the + * next multiple of T's size. + */ +template +constexpr std::span +FromBytesFloor(std::span> other) noexcept +{ + static_assert(sizeof(T) > 0, "Empty base type"); + + /* TODO: the "void *" cast suppresses alignment + warnings, but should we really suppress them? */ + + return { + reinterpret_cast(reinterpret_cast *>(other.data())), + other.size() / sizeof(T), + }; +} + +/** + * Like FromBytesFloor(), but assert that rounding is not necessary. + */ +template +constexpr std::span +FromBytesStrict(std::span> other) noexcept +{ + assert(other.size() % sizeof(T) == 0); + + return FromBytesFloor(other); +} + +constexpr std::span +ToSpan(std::string_view sv) noexcept +{ +#if defined(__clang__) && __clang_major__ < 15 + /* workaround for old clang/libc++ versions which can't cast + std::string_view to std::span */ + return {sv.data(), sv.size()}; +#else + return std::span{sv}; +#endif +} + +inline std::span +AsBytes(std::string_view sv) noexcept +{ + return std::as_bytes(ToSpan(sv)); +} + +/** + * Cast a reference to a fixed-size std::span. + */ +template +requires std::has_unique_object_representations_v +constexpr auto +ReferenceAsBytes(const T &value) noexcept +{ + return std::as_bytes(std::span{&value, 1}); +} + +template +requires std::has_unique_object_representations_v +constexpr auto +ReferenceAsWritableBytes(T &value) noexcept +{ + return std::as_writable_bytes(std::span{&value, 1}); +} + +constexpr std::string_view +ToStringView(std::span s) noexcept +{ + return {s.data(), s.size()}; +} + +constexpr std::string_view +ToStringView(std::span s) noexcept +{ + return ToStringView(FromBytesStrict(s)); +} + +template +requires std::is_integral_v +constexpr std::basic_string_view> +ToStringView(std::span s) noexcept +{ + return {s.data(), s.size()}; +} + +/* this overload matches std::span (without "const") and is + written that way to avoid ambiguities when passing an object that + has cast operators for both std::span and + std::span */ +template +constexpr std::string_view +ToStringView(std::span s) noexcept + requires(std::is_same_v, std::byte>) +{ + return ToStringView(FromBytesStrict(s)); +} diff --git a/src/util/SparseBuffer.cxx b/src/util/SparseBuffer.cxx new file mode 100644 index 0000000..2f88e58 --- /dev/null +++ b/src/util/SparseBuffer.cxx @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "SparseBuffer.hxx" + +SparseMap::CheckResult +SparseMap::Check(size_type offset) const noexcept +{ + assert(!map.empty()); + assert(offset < GetEndOffset()); + + auto i = map.lower_bound(offset); + if (i == map.end()) + /* from here up until the end of the file is + defined */ + return {0, std::prev(i)->second - offset}; + + assert(i->first >= offset); + + if (offset == i->first) + /* at the beginning of this chunk: the whole chunk can + be read */ + return {0, i->second - offset}; + + if (i == map.begin()) + /* before the very first chunk: there's a hole, and + after the hole, the whole chunk can be read */ + return {i->first - offset, i->second - i->first}; + + auto p = std::prev(i); + assert(p->first < offset); + + if (offset >= p->second) + /* between two chunks */ + return {i->first - offset, i->second - i->first}; + + /* inside a chunk: the rest of the chunk can be read */ + return {0, p->second - offset}; +} + +void +SparseMap::Commit(size_type start_offset, size_type end_offset) noexcept +{ + assert(start_offset < end_offset); + + auto e = map.emplace(start_offset, end_offset); + if (!e.second && end_offset > e.first->second) + e.first->second = end_offset; + + CheckCollapseNext(CheckCollapsePrevious(e.first)); +} + +inline SparseMap::Iterator +SparseMap::CheckCollapsePrevious(Iterator i) noexcept +{ + assert(i != map.end()); + + while (i != map.begin()) { + auto previous = std::prev(i); + if (previous->second < i->first) + break; + + if (i->second > previous->second) + previous->second = i->second; + + map.erase(i); + i = previous; + } + + return i; +} + +inline SparseMap::Iterator +SparseMap::CheckCollapseNext(Iterator i) noexcept +{ + assert(i != map.end()); + + for (auto next = std::next(i); + next != map.end() && i->second >= next->first;) { + if (next->second > i->second) + i->second = next->second; + + next = map.erase(next); + } + + return i; +} diff --git a/src/util/SparseBuffer.hxx b/src/util/SparseBuffer.hxx new file mode 100644 index 0000000..095d066 --- /dev/null +++ b/src/util/SparseBuffer.hxx @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "HugeAllocator.hxx" + +#include +#include + +/** + * Helper class for #SparseBuffer which describes which portions of + * the buffer have "known" data. + */ +class SparseMap { + using size_type = std::size_t; + + /** + * Key is start offset, value is end offset. + */ + using Map = std::map; + using Iterator = typename Map::iterator; + + Map map; + +public: + explicit SparseMap(size_type size) noexcept + :map{{size, size}} { + assert(size > 0); + } + + size_type size() const noexcept { + return GetEndOffset(); + } + + struct CheckResult { + size_type undefined_size; + size_type defined_size; + }; + + /** + * Check and classify the given offset. Returns a structure + * which tells you how much data is undefined, and how much + * data follows which is defined. + */ + CheckResult Check(size_type offset) const noexcept; + + /** + * Commit a write: mark the given range in the buffer as + * "defined". + */ + void Commit(size_type start_offset, size_type end_offset) noexcept; + +private: + size_type GetEndOffset() const noexcept { + return std::prev(map.end())->second; + } + + Iterator CheckCollapsePrevious(Iterator i) noexcept; + Iterator CheckCollapseNext(Iterator i) noexcept; +}; + +/** + * A buffer which caches the contents of a "huge" array, and remembers + * which chunks are available. + */ +template +class SparseBuffer { + using Buffer = HugeArray; + using size_type = typename Buffer::size_type; + + Buffer buffer; + + SparseMap map; + +public: + explicit SparseBuffer(size_type size) + :buffer(size), map(size) { + buffer.ForkCow(false); + } + + size_type size() const noexcept { + return map.size(); + } + + void SetName(const char *name) noexcept { + buffer.SetName(name); + } + + struct ReadResult { + size_type undefined_size; + std::span defined_buffer; + + constexpr bool HasData() const noexcept { + return undefined_size == 0 && + !defined_buffer.empty(); + } + }; + + ReadResult Read(size_type offset) const noexcept { + auto c = map.Check(offset); + return {c.undefined_size, {&buffer.front() + offset + c.undefined_size, c.defined_size}}; + } + + std::span Write(size_type offset) noexcept { + auto c = map.Check(offset); + return {&buffer.front() + offset, c.undefined_size}; + } + + void Commit(size_type start_offset, size_type end_offset) noexcept { + map.Commit(start_offset, end_offset); + } +}; diff --git a/src/util/SplitString.cxx b/src/util/SplitString.cxx new file mode 100644 index 0000000..7b66222 --- /dev/null +++ b/src/util/SplitString.cxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "SplitString.hxx" +#include "IterableSplitString.hxx" +#include "StringStrip.hxx" + +std::forward_list +SplitString(std::string_view s, char separator, bool strip) noexcept +{ + if (strip) + s = StripLeft(s); + + std::forward_list list; + if (s.empty()) + return list; + + auto i = list.before_begin(); + + for (auto value : IterableSplitString(s, separator)) { + if (strip) + value = Strip(value); + + i = list.emplace_after(i, value); + } + + return list; +} diff --git a/src/util/SplitString.hxx b/src/util/SplitString.hxx new file mode 100644 index 0000000..0732607 --- /dev/null +++ b/src/util/SplitString.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include + +/** + * Split a string at a certain separator character into sub strings + * and returns a list of these. + * + * Two consecutive separator characters result in an empty string in + * the list. + * + * An empty input string, as a special case, results in an empty list + * (and not a list with an empty string). + */ +std::forward_list +SplitString(std::string_view s, char separator, bool strip=true) noexcept; diff --git a/src/util/StaticFifoBuffer.hxx b/src/util/StaticFifoBuffer.hxx new file mode 100644 index 0000000..5e38598 --- /dev/null +++ b/src/util/StaticFifoBuffer.hxx @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include +#include + +/** + * A first-in-first-out buffer: you can append data at the end, and + * read data from the beginning. This class automatically shifts the + * buffer as needed. It is not thread safe. + */ +template +class StaticFifoBuffer { +public: + using size_type = std::size_t; + using Range = std::span; + +protected: + size_type head = 0, tail = 0; + T data[size]; + +public: + constexpr size_type GetCapacity() const noexcept { + return size; + } + + void Shift() noexcept { + if (head == 0) + return; + + assert(head <= size); + assert(tail <= size); + assert(tail >= head); + + std::move(data + head, data + tail, data); + + tail -= head; + head = 0; + } + + void Clear() noexcept { + head = tail = 0; + } + + constexpr bool empty() const noexcept { + return head == tail; + } + + constexpr bool IsFull() const noexcept { + return head == 0 && tail == size; + } + + /** + * Prepares writing. Returns a buffer range which may be written. + * When you are finished, call Append(). + */ + Range Write() noexcept { + if (empty()) + Clear(); + else if (tail == size) + Shift(); + + return Range(data + tail, size - tail); + } + + /** + * Expands the tail of the buffer, after data has been written to + * the buffer returned by Write(). + */ + void Append(size_type n) noexcept { + assert(tail <= size); + assert(n <= size); + assert(tail + n <= size); + + tail += n; + } + + /** + * Move as much data as possible from the specified buffer. + * + * @return the number of items moved + */ + template + constexpr size_type MoveFrom(std::span src) noexcept { + auto w = Write(); + + if (src.size() > w.size() && head > 0) { + /* if the source contains more data than we + can append at the tail, try to make more + room by shifting the head to 0 */ + Shift(); + w = Write(); + } + + if (src.size() > w.size()) + src = src.first(w.size()); + + std::move(src.begin(), src.end(), w.begin()); + Append(src.size()); + return src.size(); + } + + 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. + */ + constexpr Range Read() noexcept { + return Range(data + head, tail - head); + } + + /** + * Marks a chunk as consumed. + */ + void Consume(size_type n) noexcept { + assert(tail <= size); + assert(head <= tail); + assert(n <= tail); + assert(head + n <= tail); + + head += n; + } +}; diff --git a/src/util/StaticVector.hxx b/src/util/StaticVector.hxx new file mode 100644 index 0000000..5151b69 --- /dev/null +++ b/src/util/StaticVector.hxx @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * An array with a maximum size known at compile time. It keeps track + * of the actual length at runtime. + */ +template +class StaticVector { + struct alignas(T) Storage { + std::byte data[sizeof(T)]; + }; + + using Array = std::array; + +public: + using size_type = typename Array::size_type; + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + using iterator = pointer; + using const_iterator = const_pointer; + +private: + size_type the_size = 0; + Array array; + + static constexpr pointer Launder(Storage *storage) noexcept { + return std::launder(reinterpret_cast(storage->data)); + } + + static constexpr const_pointer Launder(const Storage *storage) noexcept { + return std::launder(reinterpret_cast(storage->data)); + } + +public: + constexpr StaticVector() noexcept = default; + + constexpr StaticVector(size_type _size, const_reference value) + { + if (_size > max) + throw std::bad_alloc{}; + + while (_size-- > 0) + push_back(value); + } + + /** + * Initialise the array with values from the iterator range. + */ + template + constexpr StaticVector(I _begin, I _end) + :the_size(0) + { + for (I i = _begin; i != _end; ++i) + push_back(*i); + } + + template + constexpr StaticVector(std::initializer_list init) noexcept + :the_size(init.size()) + { + static_assert(init.size() <= max); + + for (auto &i : init) + emplace_back(std::move(i)); + } + + constexpr ~StaticVector() noexcept { + clear(); + } + + constexpr operator std::span() const noexcept { + return { + Launder(array.data()), + the_size, + }; + } + + constexpr operator std::span() noexcept { + return { + Launder(array.data()), + the_size, + }; + } + + constexpr size_type max_size() const noexcept { + return max; + } + + constexpr size_type size() const noexcept { + return the_size; + } + + constexpr bool empty() const noexcept { + return the_size == 0; + } + + constexpr bool full() const noexcept { + return the_size == max; + } + + constexpr void clear() noexcept { + if constexpr (std::is_trivially_destructible_v) { + /* we don't need to call any destructor */ + the_size = 0; + } else { + while (!empty()) + pop_back(); + } + } + + /** + * Returns one element. No bounds checking. + */ + constexpr reference operator[](size_type i) noexcept { + assert(i < size()); + + return *Launder(&array[i]); + } + + /** + * Returns one constant element. No bounds checking. + */ + constexpr const_reference operator[](size_type i) const noexcept { + assert(i < size()); + + return *Launder(&array[i]); + } + + constexpr reference front() noexcept { + assert(!empty()); + + return *Launder(&array.front()); + } + + constexpr const_reference front() const noexcept { + assert(!empty()); + + return *Launder(&array.front()); + } + + constexpr reference back() noexcept { + assert(!empty()); + + return *Launder(&array[the_size - 1]); + } + + constexpr const_reference back() const noexcept { + assert(!empty()); + + return *Launder(&array[the_size - 1]); + } + + constexpr iterator begin() noexcept { + return Launder(&array.front()); + } + + constexpr const_iterator begin() const noexcept { + return Launder(&array.front()); + } + + constexpr iterator end() noexcept { + return std::next(begin(), the_size); + } + + constexpr const_iterator end() const noexcept { + return std::next(begin(), the_size); + } + + /** + * Return address of start of data segment. + */ + constexpr pointer data() noexcept { + return Launder(array.data()); + } + + constexpr const_pointer data() const noexcept { + return Launder(array.data()); + } + + constexpr reference push_back(const_reference value) { + return emplace_back(value); + } + + constexpr reference push_back(T &&value) { + return emplace_back(std::move(value)); + } + + template + constexpr reference emplace_back(Args&&... args) { + if (full()) + throw std::bad_alloc{}; + + ::new(&array[the_size]) T(std::forward(args)...); + return *Launder(&array[the_size++]); + } + + constexpr void pop_front() noexcept { + assert(!empty()); + + erase(begin()); + } + + constexpr void pop_back() noexcept { + assert(!empty()); + + back().~T(); + --the_size; + } + + constexpr iterator erase(iterator first, iterator last) noexcept { + std::size_t n = std::distance(first, last); + std::move(last, end(), first); + the_size -= n; + return first; + } + + constexpr iterator erase(iterator pos) noexcept { + return erase(pos, std::next(pos)); + } +}; diff --git a/src/util/StringAPI.hxx b/src/util/StringAPI.hxx new file mode 100644 index 0000000..95d2ae9 --- /dev/null +++ b/src/util/StringAPI.hxx @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +#ifdef _UNICODE +#include "WStringAPI.hxx" +#endif + +[[gnu::pure]] [[gnu::nonnull]] +static inline size_t +StringLength(const char *p) noexcept +{ + return strlen(p); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFind(const char *haystack, const char *needle) noexcept +{ + return strstr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline char * +StringFind(char *haystack, char needle, size_t size) noexcept +{ + return (char *)std::memchr(haystack, needle, size); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFind(const char *haystack, char needle, size_t size) noexcept +{ + return (const char *)std::memchr(haystack, needle, size); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFind(const char *haystack, char needle) noexcept +{ + return std::strchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline char * +StringFind(char *haystack, char needle) noexcept +{ + return std::strchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFindLast(const char *haystack, char needle) noexcept +{ + return std::strrchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline char * +StringFindLast(char *haystack, char needle) noexcept +{ + return std::strrchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFindLast(const char *haystack, char needle, size_t size) noexcept +{ +#if defined(__GLIBC__) || defined(__BIONIC__) + /* memrchr() is a GNU extension (and also available on + Android) */ + return (const char *)memrchr(haystack, needle, size); +#else + /* emulate for everybody else */ + const auto *p = haystack + size; + while (p > haystack) { + --p; + if (*p == needle) + return p; + } + + return nullptr; +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringFindAny(const char *haystack, const char *accept) noexcept +{ + return strpbrk(haystack, accept); +} + +[[gnu::nonnull]] +static inline void +UnsafeCopyString(char *dest, const char *src) noexcept +{ + strcpy(dest, src); +} + +[[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline char * +UnsafeCopyStringP(char *dest, const char *src) noexcept +{ +#if defined(_WIN32) + /* emulate stpcpy() */ + UnsafeCopyString(dest, src); + return dest + StringLength(dest); +#else + return stpcpy(dest, src); +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCompare(const char *a, const char *b) noexcept +{ + return strcmp(a, b); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCompare(const char *a, const char *b, size_t n) noexcept +{ + return strncmp(a, b, n); +} + +/** + * Checks whether #a and #b are equal. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqual(const char *a, const char *b) noexcept +{ + return StringCompare(a, b) == 0; +} + +/** + * Checks whether #a and #b are equal. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqual(const char *a, const char *b, size_t length) noexcept +{ + return strncmp(a, b, length) == 0; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqualIgnoreCase(const char *a, const char *b) noexcept +{ +#ifdef _MSC_VER + return _stricmp(a, b) == 0; +#else + return strcasecmp(a, b) == 0; +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqualIgnoreCase(const char *a, const char *b, size_t size) noexcept +{ +#ifdef _MSC_VER + return _strnicmp(a, b, size) == 0; +#else + return strncasecmp(a, b, size) == 0; +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCollate(const char *a, const char *b) noexcept +{ + return strcoll(a, b); +} + +/** + * Copy the string to a new allocation. The return value must be + * freed with free(). + */ +[[gnu::malloc]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline char * +DuplicateString(const char *p) noexcept +{ + return strdup(p); +} diff --git a/src/util/StringBuffer.hxx b/src/util/StringBuffer.hxx new file mode 100644 index 0000000..e25d42c --- /dev/null +++ b/src/util/StringBuffer.hxx @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * A statically allocated string buffer. + */ +template +class BasicStringBuffer { +public: + using value_type = T; + using reference = T &; + using pointer = T *; + using const_pointer = const T *; + using size_type = std::size_t; + + static constexpr value_type SENTINEL = '\0'; + +protected: + using Array = std::array; + Array the_data; + +public: + using iterator = typename Array::iterator; + using const_iterator = typename Array::const_iterator; + + static constexpr size_type capacity() noexcept { + return CAPACITY; + } + + constexpr bool empty() const noexcept { + return front() == SENTINEL; + } + + constexpr void clear() noexcept { + the_data[0] = SENTINEL; + } + + constexpr const_pointer c_str() const noexcept { + return the_data.data(); + } + + constexpr pointer data() noexcept { + return the_data.data(); + } + + constexpr value_type front() const noexcept { + return the_data.front(); + } + + /** + * Returns one character. No bounds checking. + */ + constexpr value_type operator[](size_type i) const noexcept { + return the_data[i]; + } + + /** + * Returns one writable character. No bounds checking. + */ + constexpr reference operator[](size_type i) noexcept { + return the_data[i]; + } + + constexpr iterator begin() noexcept { + return the_data.begin(); + } + + constexpr iterator end() noexcept { + return the_data.end(); + } + + constexpr const_iterator begin() const noexcept { + return the_data.begin(); + } + + constexpr const_iterator end() const noexcept { + return the_data.end(); + } + + constexpr operator const_pointer() const noexcept { + return c_str(); + } +}; + +template +class StringBuffer : public BasicStringBuffer {}; diff --git a/src/util/StringCompare.cxx b/src/util/StringCompare.cxx new file mode 100644 index 0000000..372d385 --- /dev/null +++ b/src/util/StringCompare.cxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "StringCompare.hxx" + +#include + +bool +StringEndsWith(const char *haystack, const char *needle) noexcept +{ + const size_t haystack_length = StringLength(haystack); + const size_t needle_length = StringLength(needle); + + return haystack_length >= needle_length && + std::memcmp(haystack + haystack_length - needle_length, + needle, needle_length) == 0; +} + +bool +StringEndsWithIgnoreCase(const char *haystack, const char *needle) noexcept +{ + const size_t haystack_length = StringLength(haystack); + const size_t needle_length = StringLength(needle); + + return haystack_length >= needle_length && + StringIsEqualIgnoreCase(haystack + haystack_length - needle_length, + needle); +} + +const char * +FindStringSuffix(const char *p, const char *suffix) noexcept +{ + const size_t p_length = StringLength(p); + const size_t suffix_length = StringLength(suffix); + + if (p_length < suffix_length) + return nullptr; + + const char *q = p + p_length - suffix_length; + return std::memcmp(q, suffix, suffix_length) == 0 + ? q + : nullptr; +} diff --git a/src/util/StringCompare.hxx b/src/util/StringCompare.hxx new file mode 100644 index 0000000..b4163cc --- /dev/null +++ b/src/util/StringCompare.hxx @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include "StringAPI.hxx" + +#ifdef _UNICODE +#include "WStringCompare.hxx" +#endif + +#include + +[[gnu::pure]] [[gnu::nonnull]] +static constexpr bool +StringIsEmpty(const char *string) noexcept +{ + return *string == 0; +} + +[[gnu::pure]] +static constexpr bool +StringIsEqual(std::string_view a, std::string_view b) noexcept +{ + return a == b; +} + +[[gnu::pure]] +static inline bool +StringIsEqualIgnoreCase(std::string_view a, std::string_view b) noexcept +{ + return a.size() == b.size() && + StringIsEqualIgnoreCase(a.data(), b.data(), b.size()); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringStartsWith(const char *haystack, std::string_view needle) noexcept +{ + return StringIsEqual(haystack, needle.data(), needle.size()); +} + +[[gnu::pure]] [[gnu::nonnull]] +bool +StringEndsWith(const char *haystack, const char *needle) noexcept; + +[[gnu::pure]] [[gnu::nonnull]] +bool +StringEndsWithIgnoreCase(const char *haystack, const char *needle) noexcept; + +/** + * Returns the portion of the string after a prefix. If the string + * does not begin with the specified prefix, this function returns + * nullptr. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringAfterPrefix(const char *haystack, std::string_view needle) noexcept +{ + return StringStartsWith(haystack, needle) + ? haystack + needle.size() + : nullptr; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringStartsWithIgnoreCase(const char *haystack, std::string_view needle) noexcept +{ + return StringIsEqualIgnoreCase(haystack, needle.data(), needle.size()); +} + +[[gnu::pure]] +static inline bool +StringStartsWithIgnoreCase(std::string_view haystack, std::string_view needle) noexcept +{ + return haystack.size() >= needle.size() && + StringIsEqualIgnoreCase(haystack.data(), + needle.data(), needle.size()); +} + +/** + * Returns the portion of the string after a prefix. If the string + * does not begin with the specified prefix, this function returns + * nullptr. + * This function is case-independent. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline const char * +StringAfterPrefixIgnoreCase(const char *haystack, std::string_view needle) noexcept +{ + return StringStartsWithIgnoreCase(haystack, needle) + ? haystack + needle.size() + : nullptr; +} + +[[gnu::pure]] +static inline std::string_view +StringAfterPrefixIgnoreCase(std::string_view haystack, + std::string_view needle) noexcept +{ + return StringStartsWithIgnoreCase(haystack, needle) + ? haystack.substr(needle.size()) + : std::string_view{}; +} + +/** + * Check if the given string ends with the specified suffix. If yes, + * returns the position of the suffix, and nullptr otherwise. + */ +[[gnu::pure]] [[gnu::nonnull]] +const char * +FindStringSuffix(const char *p, const char *suffix) noexcept; + +template +constexpr bool +SkipPrefix(std::basic_string_view &haystack, + std::basic_string_view needle) noexcept +{ + bool match = haystack.starts_with(needle); + if (match) + haystack.remove_prefix(needle.size()); + return match; +} + +template +constexpr bool +RemoveSuffix(std::basic_string_view &haystack, + std::basic_string_view needle) noexcept +{ + bool match = haystack.ends_with(needle); + if (match) + haystack.remove_suffix(needle.size()); + return match; +} + +template +constexpr bool +SkipPrefixIgnoreCase(std::basic_string_view &haystack, + std::basic_string_view needle) noexcept +{ + bool match = StringStartsWithIgnoreCase(haystack, needle); + if (match) + haystack.remove_prefix(needle.size()); + return match; +} + +template +constexpr bool +RemoveSuffixIgnoreCase(std::basic_string_view &haystack, + std::basic_string_view needle) noexcept +{ + bool match = StringEndsWithIgnoreCase(haystack, needle); + if (match) + haystack.remove_suffix(needle.size()); + return match; +} diff --git a/src/util/StringPointer.hxx b/src/util/StringPointer.hxx new file mode 100644 index 0000000..a3e1c53 --- /dev/null +++ b/src/util/StringPointer.hxx @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Simple OO wrapper for a const string pointer. + */ +template +class StringPointer { +public: + using value_type = T; + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + + static constexpr value_type SENTINEL = '\0'; + +private: + const_pointer value; + +public: + StringPointer() = default; + constexpr StringPointer(const_pointer _value) noexcept + :value(_value) {} + + constexpr bool operator==(std::nullptr_t) const noexcept { + return value == nullptr; + } + + /** + * Check if this is a "nulled" instance. A "nulled" instance + * must not be used. + */ + constexpr bool IsNull() const noexcept { + return value == nullptr; + } + + constexpr const_pointer c_str() const noexcept { + return value; + } + + bool empty() const noexcept { + return *value == SENTINEL; + } +}; diff --git a/src/util/StringSplit.hxx b/src/util/StringSplit.hxx new file mode 100644 index 0000000..0642293 --- /dev/null +++ b/src/util/StringSplit.hxx @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include + +/** + * Partition the string_view at the specified position, returning one + * string_view until the given position and one beginning at the given + * position. + */ +template +constexpr std::pair, std::basic_string_view> +Partition(const std::basic_string_view haystack, + const typename std::basic_string_view::size_type position) noexcept +{ + return { + haystack.substr(0, position), + haystack.substr(position), + }; +} + +template +constexpr std::pair, std::basic_string_view> +Partition(const std::basic_string_view haystack, + const typename std::basic_string_view::const_pointer position) noexcept +{ + return Partition(haystack, position - haystack.data()); +} + +template +requires(!std::is_same_v::const_pointer, + typename std::basic_string_view::const_iterator>) +constexpr std::pair, std::basic_string_view> +Partition(const std::basic_string_view haystack, + const typename std::basic_string_view::const_iterator i) noexcept +{ + return Partition(haystack, i - haystack.begin()); +} + +/** + * Like Partition(), but exclude the given position from the second + * string_view. + */ +template +constexpr std::pair, std::basic_string_view> +PartitionWithout(const std::basic_string_view haystack, + const typename std::basic_string_view::size_type separator) noexcept +{ + return { + haystack.substr(0, separator), + haystack.substr(separator + 1), + }; +} + +template +constexpr std::pair, std::basic_string_view> +PartitionWithout(const std::basic_string_view haystack, + const typename std::basic_string_view::const_pointer separator) noexcept +{ + return PartitionWithout(haystack, separator - haystack.data()); +} + +template +requires(!std::is_same_v::const_pointer, + typename std::basic_string_view::const_iterator>) +constexpr std::pair, std::basic_string_view> +PartitionWithout(const std::basic_string_view haystack, + const typename std::basic_string_view::const_iterator separator) noexcept +{ + return PartitionWithout(haystack, separator - haystack.begin()); +} + +/** + * Split the string at the first occurrence of the given character. + * If the character is not found, then the first value is the whole + * string and the second value is nullptr. + */ +template +constexpr std::pair, std::basic_string_view> +Split(const std::basic_string_view haystack, const T ch) noexcept +{ + const auto i = haystack.find(ch); + if (i == haystack.npos) + return {haystack, {}}; + + return PartitionWithout(haystack, i); +} + +/** + * Split the string at the last occurrence of the given + * character. If the character is not found, then the first + * value is the whole string and the second value is nullptr. + */ +template +constexpr std::pair, std::basic_string_view> +SplitLast(const std::basic_string_view haystack, const T ch) noexcept +{ + const auto i = haystack.rfind(ch); + if (i == haystack.npos) + return {haystack, {}}; + + return PartitionWithout(haystack, i); +} + +/** + * Find the first character that does not match the given predicate + * and split at this boundary. + */ +template +constexpr std::pair, std::basic_string_view> +SplitWhile(const std::basic_string_view haystack, P &&predicate) noexcept +{ + const auto i = std::find_if_not(haystack.begin(), haystack.end(), + std::forward

(predicate)); + return Partition(haystack, i); +} diff --git a/src/util/StringStrip.cxx b/src/util/StringStrip.cxx new file mode 100644 index 0000000..fdecf9d --- /dev/null +++ b/src/util/StringStrip.cxx @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "StringStrip.hxx" +#include "CharUtil.hxx" + +#include +#include + +const char * +StripLeft(const char *p) noexcept +{ + while (IsWhitespaceNotNull(*p)) + ++p; + + return p; +} + +const char * +StripLeft(const char *p, const char *end) noexcept +{ + while (p < end && IsWhitespaceOrNull(*p)) + ++p; + + return p; +} + +std::string_view +StripLeft(const std::string_view s) noexcept +{ + auto i = std::find_if_not(s.begin(), s.end(), + [](auto ch){ return IsWhitespaceOrNull(ch); }); + +#ifdef __clang__ + // libc++ doesn't yet support the C++20 constructor + return s.substr(std::distance(s.begin(), i)); +#else + return { + i, + s.end(), + }; +#endif +} + +const char * +StripRight(const char *p, const char *end) noexcept +{ + while (end > p && IsWhitespaceOrNull(end[-1])) + --end; + + return end; +} + +std::size_t +StripRight(const char *p, std::size_t length) noexcept +{ + while (length > 0 && IsWhitespaceOrNull(p[length - 1])) + --length; + + return length; +} + +void +StripRight(char *p) noexcept +{ + std::size_t old_length = std::strlen(p); + std::size_t new_length = StripRight(p, old_length); + p[new_length] = 0; +} + +std::string_view +StripRight(std::string_view s) noexcept +{ + auto i = std::find_if_not(s.rbegin(), s.rend(), + [](auto ch){ return IsWhitespaceOrNull(ch); }); + + return s.substr(0, std::distance(i, s.rend())); +} + +char * +Strip(char *p) noexcept +{ + p = StripLeft(p); + StripRight(p); + return p; +} + +std::string_view +Strip(std::string_view s) noexcept +{ + return StripRight(StripLeft(s)); +} diff --git a/src/util/StringStrip.hxx b/src/util/StringStrip.hxx new file mode 100644 index 0000000..11c2298 --- /dev/null +++ b/src/util/StringStrip.hxx @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include + +/** + * Skips whitespace at the beginning of the string, and returns the + * first non-whitespace character. If the string has no + * non-whitespace characters, then a pointer to the NULL terminator is + * returned. + */ +[[gnu::pure]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +const char * +StripLeft(const char *p) noexcept; + +[[gnu::pure]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline char * +StripLeft(char *p) noexcept +{ + return const_cast(StripLeft((const char *)p)); +} + +/** + * Skips whitespace at the beginning of the string, and returns the + * first non-whitespace character or the end pointer. + */ +[[gnu::pure]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +const char * +StripLeft(const char *p, const char *end) noexcept; + +[[gnu::pure]] +std::string_view +StripLeft(std::string_view s) noexcept; + +/** + * Determine the string's end as if it was stripped on the right side. + */ +[[gnu::pure]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +const char * +StripRight(const char *p, const char *end) noexcept; + +/** + * Determine the string's end as if it was stripped on the right side. + */ +[[gnu::pure]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline char * +StripRight(char *p, char *end) noexcept +{ + return const_cast(StripRight((const char *)p, + (const char *)end)); +} + +/** + * Determine the string's length as if it was stripped on the right + * side. + */ +[[gnu::pure]] [[gnu::nonnull]] +std::size_t +StripRight(const char *p, std::size_t length) noexcept; + +/** + * Strip trailing whitespace by null-terminating the string. + */ +[[gnu::nonnull]] +void +StripRight(char *p) noexcept; + +[[gnu::pure]] +std::string_view +StripRight(std::string_view s) noexcept; + +/** + * Skip whitespace at the beginning and terminate the string after the + * last non-whitespace character. + */ +[[gnu::returns_nonnull]] [[gnu::nonnull]] +char * +Strip(char *p) noexcept; + +[[gnu::pure]] +std::string_view +Strip(std::string_view s) noexcept; diff --git a/src/util/StringUtil.cxx b/src/util/StringUtil.cxx new file mode 100644 index 0000000..31db1ee --- /dev/null +++ b/src/util/StringUtil.cxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "StringUtil.hxx" +#include "StringCompare.hxx" +#include "CharUtil.hxx" + +#include + +bool +StringArrayContainsCase(const char *const*haystack, + std::string_view needle) noexcept +{ + assert(haystack != nullptr); + + for (; *haystack != nullptr; ++haystack) + if (StringIsEqualIgnoreCase(*haystack, needle)) + return true; + + return false; +} + +void +ToUpperASCII(char *dest, const char *src, size_t size) noexcept +{ + assert(dest != nullptr); + assert(src != nullptr); + assert(size > 1); + + char *const end = dest + size - 1; + + do { + char ch = *src++; + if (ch == 0) + break; + + *dest++ = ToUpperASCII(ch); + } while (dest < end); + + *dest = 0; +} diff --git a/src/util/StringUtil.hxx b/src/util/StringUtil.hxx new file mode 100644 index 0000000..6752c77 --- /dev/null +++ b/src/util/StringUtil.hxx @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef STRING_UTIL_HXX +#define STRING_UTIL_HXX + +#include +#include + +/** + * Checks whether a string array contains the specified string. + * + * @param haystack a NULL terminated list of strings + * @param needle the string to search for; the comparison is + * case-insensitive for ASCII characters + * @return true if found + */ +[[gnu::pure]] +bool +StringArrayContainsCase(const char *const*haystack, + std::string_view needle) noexcept; + +/** + * Convert the specified ASCII string (0x00..0x7f) to upper case. + * + * @param size the destination buffer size + */ +void +ToUpperASCII(char *dest, const char *src, size_t size) noexcept; + +#endif diff --git a/src/util/StringVerify.hxx b/src/util/StringVerify.hxx new file mode 100644 index 0000000..e177f4a --- /dev/null +++ b/src/util/StringVerify.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +#include +#include +#include + +/** + * Does the given string consist only of characters allowed by the + * given function? + */ +constexpr bool +CheckChars(std::string_view s, std::predicate auto f) noexcept +{ + return std::all_of(s.begin(), s.end(), f); +} + +/** + * Is the given string non-empty and consists only of characters + * allowed by the given function? + */ +constexpr bool +CheckCharsNonEmpty(std::string_view s, std::predicate auto f) noexcept +{ + return !s.empty() && CheckChars(s, f); +} + +constexpr bool +CheckCharsNonEmpty(const char *s, std::predicate auto f) noexcept +{ + do { + if (!f(*s)) + return false; + } while (*++s); + return true; +} diff --git a/src/util/TagStructs.hxx b/src/util/TagStructs.hxx new file mode 100644 index 0000000..aa49db4 --- /dev/null +++ b/src/util/TagStructs.hxx @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +#pragma once + +/* + * This header contains empty struct definitiosn that are supposed to + * select special overloads of functions/methods/constructors. + */ + +/** + * A tag for overloading copying constructors, telling them to make + * shallow copies of source data (e.g. copy pointers instead of + * duplicating the referenced objects). + */ +struct ShallowCopy {}; + +/** + * A tag that signals that the callee shall take ownership of the + * object that is being passed to it. Usually, that owned is an + * unmanaged reference and rvalues do not make sense. + */ +struct AdoptTag {}; diff --git a/src/util/TemplateString.hxx b/src/util/TemplateString.hxx new file mode 100644 index 0000000..19f669d --- /dev/null +++ b/src/util/TemplateString.hxx @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef TEMPLATE_STRING_HXX +#define TEMPLATE_STRING_HXX + +#include // for std::size() +#include +#include + +namespace TemplateString { + +template +struct Buffer { + static constexpr std::size_t size = _size; + char value[size + 1]; + + constexpr operator const char *() const noexcept { + return value; + } + + constexpr operator std::string_view() const noexcept { + return {value, size}; + } +}; + +/** + * An empty string. + */ +constexpr auto +Empty() noexcept +{ + return Buffer<0>{}; +} + +/** + * A string consisting of a single character. + */ +constexpr auto +FromChar(char ch) noexcept +{ + Buffer<1> result{}; + result.value[0] = ch; + return result; +} + +namespace detail { + +constexpr auto +size(const char &) noexcept +{ + return 1; +} + +constexpr const char * +data(const char &ch) noexcept +{ + return &ch; +} + +template +constexpr auto +size(const Buffer &b) noexcept +{ + return b.size; +} + +template +constexpr const char * +data(const Buffer &b) noexcept +{ + return b.value; +} + +constexpr char * +copy_n(const char *src, std::size_t n, char *dest) noexcept +{ + for (std::size_t i = 0; i < n; ++i) + dest[i] = src[i]; + return dest + n; +} + +} + +/** + * A string consisting of a single character. + */ +template +constexpr auto +FromLiteral(const char (&src)[size]) noexcept +{ + Buffer result{}; + detail::copy_n(src, result.size, result.value); + return result; +} + +template +constexpr auto +Concat(Args... args) noexcept +{ + using std::size; + using std::data; + using detail::size; + using detail::data; + using detail::copy_n; + + constexpr std::size_t total_size = (std::size_t(0) + ... + size(args)); + Buffer result{}; + + char *p = result.value; + ((p = copy_n(data(args), size(args), p)), ...); + + return result; +} + +} // namespace TemplateString + +#endif diff --git a/src/util/TerminatedArray.hxx b/src/util/TerminatedArray.hxx new file mode 100644 index 0000000..38d40c9 --- /dev/null +++ b/src/util/TerminatedArray.hxx @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include // for std::iterator_traits + +/** + * A container-like class which allows iterating over an array + * terminated by sentinel value. Most commonly, this is an array of + * pointers terminated by nullptr, but null-terminated C strings can + * also be used. + * + * @param T the type of an item in the aray + * @param Sentinel the sentinel value + */ +template +class TerminatedArray { + T *head; + + /** + * A special type for the end iterator which is always equal + * the iterator that points to the #Sentinel value. + */ + struct sentinel { + using Traits = std::iterator_traits; + + using iterator_category = typename Traits::iterator_category; + using difference_type = typename Traits::difference_type; + using value_type = typename Traits::value_type; + using pointer = typename Traits::pointer; + using reference = typename Traits::reference; + }; + +public: + using value_type = T; + + explicit constexpr TerminatedArray(T *_head) noexcept + :head(_head) {} + + class iterator { + using Traits = std::iterator_traits; + + T *cursor; + + public: + using iterator_category = typename Traits::iterator_category; + using difference_type = typename Traits::difference_type; + using value_type = typename Traits::value_type; + using pointer = typename Traits::pointer; + using reference = typename Traits::reference; + + explicit constexpr iterator(T *_cursor) noexcept + :cursor(_cursor) {} + + constexpr bool operator==(const iterator &other) const noexcept { + return cursor == other.cursor; + } + + constexpr bool operator==(const sentinel &) const noexcept { + return *cursor == Sentinel; + } + + constexpr auto &operator++() noexcept { + ++cursor; + return *this; + } + + constexpr auto operator++(int) noexcept { + auto old = *this; + ++cursor; + return old; + } + + constexpr auto &operator+=(difference_type n) noexcept { + cursor += n; + return *this; + } + + constexpr auto operator+(difference_type n) const noexcept { + return iterator{cursor + n}; + } + + constexpr auto &operator--() noexcept { + --cursor; + return *this; + } + + constexpr auto operator--(int) noexcept { + auto old = *this; + --cursor; + return old; + } + + constexpr auto &operator-=(difference_type n) noexcept { + cursor -= n; + return *this; + } + + constexpr auto operator-(difference_type n) const noexcept { + return iterator{cursor - n}; + } + + constexpr auto operator-(const iterator& other) const noexcept { + return std::distance(other.cursor, cursor); + } + + reference operator*() const noexcept { + return *cursor; + } + + pointer operator->() const noexcept { + return cursor; + } + }; + + constexpr iterator begin() const noexcept { + return iterator{head}; + } + + constexpr sentinel end() const noexcept { + return {}; + } + + constexpr iterator cbegin() const noexcept { + return begin(); + } + + constexpr sentinel cend() const noexcept { + return end(); + } +}; diff --git a/src/util/TextFile.hxx b/src/util/TextFile.hxx new file mode 100644 index 0000000..c7a8492 --- /dev/null +++ b/src/util/TextFile.hxx @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef TEXT_FILE_HXX +#define TEXT_FILE_HXX + +#include + +template +char * +ReadBufferedLine(B &buffer) +{ + auto r = buffer.Read(); + char *data = reinterpret_cast(r.data()); + char *newline = reinterpret_cast(std::memchr(data, '\n', r.size())); + if (newline == nullptr) + return nullptr; + + buffer.Consume(newline + 1 - data); + + if (newline > data && newline[-1] == '\r') + --newline; + *newline = 0; + return data; +} + +#endif diff --git a/src/util/Tokenizer.cxx b/src/util/Tokenizer.cxx new file mode 100644 index 0000000..5e31fdb --- /dev/null +++ b/src/util/Tokenizer.cxx @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "Tokenizer.hxx" +#include "CharUtil.hxx" +#include "StringStrip.hxx" + +#include + +static inline bool +valid_word_first_char(char ch) +{ + return IsAlphaASCII(ch); +} + +static inline bool +valid_word_char(char ch) +{ + return IsAlphaNumericASCII(ch) || ch == '_'; +} + +char * +Tokenizer::NextWord() +{ + char *const word = input; + + if (*input == 0) + return nullptr; + + /* check the first character */ + + if (!valid_word_first_char(*input)) + throw std::runtime_error("Letter expected"); + + /* now iterate over the other characters until we find a + whitespace or end-of-string */ + + while (*++input != 0) { + if (IsWhitespaceFast(*input)) { + /* a whitespace: the word ends here */ + *input = 0; + /* skip all following spaces, too */ + input = StripLeft(input + 1); + break; + } + + if (!valid_word_char(*input)) + throw std::runtime_error("Invalid word character"); + } + + /* end of string: the string is already null-terminated + here */ + + return word; +} + +static inline bool +valid_unquoted_char(char ch) +{ + return (unsigned char)ch > 0x20 && ch != '"' && ch != '\''; +} + +char * +Tokenizer::NextUnquoted() +{ + char *const word = input; + + if (*input == 0) + return nullptr; + + /* check the first character */ + + if (!valid_unquoted_char(*input)) + throw std::runtime_error("Invalid unquoted character"); + + /* now iterate over the other characters until we find a + whitespace or end-of-string */ + + while (*++input != 0) { + if (IsWhitespaceFast(*input)) { + /* a whitespace: the word ends here */ + *input = 0; + /* skip all following spaces, too */ + input = StripLeft(input + 1); + break; + } + + if (!valid_unquoted_char(*input)) + throw std::runtime_error("Invalid unquoted character"); + } + + /* end of string: the string is already null-terminated + here */ + + return word; +} + +char * +Tokenizer::NextString() +{ + char *const word = input, *dest = input; + + if (*input == 0) + /* end of line */ + return nullptr; + + /* check for the opening " */ + + if (*input != '"') + throw std::runtime_error("'\"' expected"); + + ++input; + + /* copy all characters */ + + while (*input != '"') { + if (*input == '\\') + /* the backslash escapes the following + character */ + ++input; + + if (*input == 0) + throw std::runtime_error("Missing closing '\"'"); + + /* copy one character */ + *dest++ = *input++; + } + + /* the following character must be a whitespace (or end of + line) */ + + ++input; + if (!IsWhitespaceFast(*input)) + throw std::runtime_error("Space expected after closing '\"'"); + + /* finish the string and return it */ + + *dest = 0; + input = StripLeft(input); + return word; +} + +char * +Tokenizer::NextParam() +{ + if (*input == '"') + return NextString(); + else + return NextUnquoted(); +} diff --git a/src/util/Tokenizer.hxx b/src/util/Tokenizer.hxx new file mode 100644 index 0000000..81a0e65 --- /dev/null +++ b/src/util/Tokenizer.hxx @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef TOKENIZER_HXX +#define TOKENIZER_HXX + +class Tokenizer { + char *input; + +public: + /** + * @param _input the input string; the contents will be + * modified by this class + */ + constexpr Tokenizer(char *_input):input(_input) {} + + Tokenizer(const Tokenizer &) = delete; + Tokenizer &operator=(const Tokenizer &) = delete; + + char *Rest() { + return input; + } + + char CurrentChar() const { + return *input; + } + + bool IsEnd() const { + return CurrentChar() == 0; + } + + /** + * Reads the next word. Throws std::runtime_error on error. + * + * @return a pointer to the null-terminated word, or nullptr + * on end of line + */ + char *NextWord(); + + /** + * Reads the next unquoted word from the input string. Throws + * std::runtime_error on error. + * + * @return a pointer to the null-terminated word, or nullptr + * on end of line + */ + char *NextUnquoted(); + + /** + * Reads the next quoted string from the input string. A + * backslash escapes the following character. This function + * modifies the input string. Throws std::runtime_error on + * error. + * + * @return a pointer to the null-terminated string, or nullptr + * end of line + */ + char *NextString(); + + /** + * Reads the next unquoted word or quoted string from the + * input. This is a wrapper for NextUnquoted() and + * NextString(). Throws std::runtime_error on error. + * + * @return a pointer to the null-terminated string, or nullptr + * on end of line + */ + char *NextParam(); +}; + +#endif diff --git a/src/util/TransformN.hxx b/src/util/TransformN.hxx new file mode 100644 index 0000000..1a8c166 --- /dev/null +++ b/src/util/TransformN.hxx @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef TRANSFORM_N_HXX +#define TRANSFORM_N_HXX + +#include + +/** + * The std::transform_n() function that is missing in the C++ standard + * library. + */ +template +OutputIt +transform_n(InputIt input, size_t n, OutputIt output, + UnaryOperation unary_op) +{ + while (n-- > 0) + *output++ = unary_op(*input++); + return output; +} + +/** + * Optimized overload for the above transform_n() implementation for + * the special case that both input and output are regular pointers. + * Turns out that most compilers generate better code this way. + */ +template +OutputType * +transform_n(const InputType *input, size_t n, OutputType *output, + UnaryOperation unary_op) +{ + for (size_t i = 0; i < n; ++i) + output[i] = unary_op(input[i]); + return output + n; +} + +#endif diff --git a/src/util/TruncateString.cxx b/src/util/TruncateString.cxx new file mode 100644 index 0000000..4203295 --- /dev/null +++ b/src/util/TruncateString.cxx @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "TruncateString.hxx" +#include "Compiler.h" + +#include + +#include + +char * +CopyTruncateString(char *gcc_restrict dest, const char *gcc_restrict src, + size_t size) noexcept +{ + size_t length = strlen(src); + if (length >= size) + length = size - 1; + + char *p = std::copy_n(src, length, dest); + *p = '\0'; + return p; +} diff --git a/src/util/TruncateString.hxx b/src/util/TruncateString.hxx new file mode 100644 index 0000000..e7a9e44 --- /dev/null +++ b/src/util/TruncateString.hxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef TRUNCATE_STRING_HXX +#define TRUNCATE_STRING_HXX + +#include + +/** + * Copy a string. If the buffer is too small, then the string is + * truncated. This is a safer version of strncpy(). + * + * @param size the size of the destination buffer (including the null + * terminator) + * @return a pointer to the null terminator + */ +[[gnu::nonnull]] +char * +CopyTruncateString(char *dest, const char *src, size_t size) noexcept; + +#endif diff --git a/src/util/UTF8.cxx b/src/util/UTF8.cxx new file mode 100644 index 0000000..57e478a --- /dev/null +++ b/src/util/UTF8.cxx @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "UTF8.hxx" +#include "CharUtil.hxx" +#include "Compiler.h" + +#include +#include + +/** + * Is this a leading byte that is followed by 1 continuation byte? + */ +static constexpr bool +IsLeading1(uint8_t ch) noexcept +{ + return (ch & 0xe0) == 0xc0; +} + +static constexpr uint8_t +MakeLeading1(uint8_t value) noexcept +{ + return 0xc0 | value; +} + +/** + * Is this a leading byte that is followed by 2 continuation byte? + */ +static constexpr bool +IsLeading2(uint8_t ch) noexcept +{ + return (ch & 0xf0) == 0xe0; +} + +static constexpr uint8_t +MakeLeading2(uint8_t value) noexcept +{ + return 0xe0 | value; +} + +/** + * Is this a leading byte that is followed by 3 continuation byte? + */ +static constexpr bool +IsLeading3(uint8_t ch) noexcept +{ + return (ch & 0xf8) == 0xf0; +} + +static constexpr uint8_t +MakeLeading3(uint8_t value) noexcept +{ + return 0xf0 | value; +} + +/** + * Is this a leading byte that is followed by 4 continuation byte? + */ +static constexpr bool +IsLeading4(uint8_t ch) noexcept +{ + return (ch & 0xfc) == 0xf8; +} + +static constexpr uint8_t +MakeLeading4(uint8_t value) noexcept +{ + return 0xf8 | value; +} + +/** + * Is this a leading byte that is followed by 5 continuation byte? + */ +static constexpr bool +IsLeading5(uint8_t ch) noexcept +{ + return (ch & 0xfe) == 0xfc; +} + +static constexpr uint8_t +MakeLeading5(uint8_t value) noexcept +{ + return 0xfc | value; +} + +static constexpr bool +IsContinuation(uint8_t ch) noexcept +{ + return (ch & 0xc0) == 0x80; +} + +/** + * Generate a continuation byte of the low 6 bit. + */ +static constexpr uint8_t +MakeContinuation(uint8_t value) noexcept +{ + return 0x80 | (value & 0x3f); +} + +bool +ValidateUTF8(const char *p) noexcept +{ + for (; *p != 0; ++p) { + uint8_t ch = *p; + if (IsASCII(ch)) + continue; + + if (IsContinuation(ch)) + /* continuation without a prefix */ + return false; + + if (IsLeading1(ch)) { + /* 1 continuation */ + if (!IsContinuation(*++p)) + return false; + } else if (IsLeading2(ch)) { + /* 2 continuations */ + if (!IsContinuation(*++p) || !IsContinuation(*++p)) + return false; + } else if (IsLeading3(ch)) { + /* 3 continuations */ + if (!IsContinuation(*++p) || !IsContinuation(*++p) || + !IsContinuation(*++p)) + return false; + } else if (IsLeading4(ch)) { + /* 4 continuations */ + if (!IsContinuation(*++p) || !IsContinuation(*++p) || + !IsContinuation(*++p) || !IsContinuation(*++p)) + return false; + } else if (IsLeading5(ch)) { + /* 5 continuations */ + if (!IsContinuation(*++p) || !IsContinuation(*++p) || + !IsContinuation(*++p) || !IsContinuation(*++p) || + !IsContinuation(*++p)) + return false; + } else + return false; + } + + return true; +} + +std::size_t +SequenceLengthUTF8(char ch) noexcept +{ + if (IsASCII(ch)) + return 1; + else if (IsLeading1(ch)) + /* 1 continuation */ + return 2; + else if (IsLeading2(ch)) + /* 2 continuations */ + return 3; + else if (IsLeading3(ch)) + /* 3 continuations */ + return 4; + else if (IsLeading4(ch)) + /* 4 continuations */ + return 5; + else if (IsLeading5(ch)) + /* 5 continuations */ + return 6; + else + /* continuation without a prefix or some other illegal + start byte */ + return 0; + +} + +template +struct CheckSequenceUTF8 { + [[gnu::pure]] + bool operator()(const char *p) const noexcept { + return IsContinuation(*p) && CheckSequenceUTF8()(p + 1); + } +}; + +template<> +struct CheckSequenceUTF8<0U> { + constexpr bool operator()([[maybe_unused]] const char *p) const noexcept { + return true; + } +}; + +template +[[gnu::pure]] +static std::size_t +InnerSequenceLengthUTF8(const char *p) noexcept +{ + return CheckSequenceUTF8()(p) + ? L + 1 + : 0U; +} + +std::size_t +SequenceLengthUTF8(const char *p) noexcept +{ + const uint8_t ch = *p++; + + if (IsASCII(ch)) + return 1; + else if (IsLeading1(ch)) + /* 1 continuation */ + return InnerSequenceLengthUTF8<1>(p); + else if (IsLeading2(ch)) + /* 2 continuations */ + return InnerSequenceLengthUTF8<2>(p); + else if (IsLeading3(ch)) + /* 3 continuations */ + return InnerSequenceLengthUTF8<3>(p); + else if (IsLeading4(ch)) + /* 4 continuations */ + return InnerSequenceLengthUTF8<4>(p); + else if (IsLeading5(ch)) + /* 5 continuations */ + return InnerSequenceLengthUTF8<5>(p); + else + /* continuation without a prefix or some other illegal + start byte */ + return 0; +} + +[[gnu::pure]] +static const char * +FindNonASCIIOrZero(const char *p) noexcept +{ + while (*p != 0 && IsASCII(*p)) + ++p; + return p; +} + +const char * +Latin1ToUTF8(const char *gcc_restrict src, char *gcc_restrict buffer, + std::size_t buffer_size) noexcept +{ + const char *p = FindNonASCIIOrZero(src); + if (*p == 0) + /* everything is plain ASCII, we don't need to convert anything */ + return src; + + if ((std::size_t)(p - src) >= buffer_size) + /* buffer too small */ + return nullptr; + + const char *const end = buffer + buffer_size; + char *q = std::copy(src, p, buffer); + + while (*p != 0) { + uint8_t ch = *p++; + + if (IsASCII(ch)) { + *q++ = ch; + + if (q >= end) + /* buffer too small */ + return nullptr; + } else { + if (q + 2 >= end) + /* buffer too small */ + return nullptr; + + *q++ = MakeLeading1(ch >> 6); + *q++ = MakeContinuation(ch); + } + } + + *q = 0; + return buffer; +} + +char * +UnicodeToUTF8(unsigned ch, char *q) noexcept +{ + if (ch < 0x80) [[likely]] { + *q++ = (char)ch; + } else if (ch < 0x800) [[likely]] { + *q++ = MakeLeading1(ch >> 6); + *q++ = MakeContinuation(ch); + } else if (ch < 0x10000) { + *q++ = MakeLeading2(ch >> 12); + *q++ = MakeContinuation(ch >> 6); + *q++ = MakeContinuation(ch); + } else if (ch < 0x200000) { + *q++ = MakeLeading3(ch >> 18); + *q++ = MakeContinuation(ch >> 12); + *q++ = MakeContinuation(ch >> 6); + *q++ = MakeContinuation(ch); + } else if (ch < 0x4000000) { + *q++ = MakeLeading4(ch >> 24); + *q++ = MakeContinuation(ch >> 18); + *q++ = MakeContinuation(ch >> 12); + *q++ = MakeContinuation(ch >> 6); + *q++ = MakeContinuation(ch); + } else if (ch < 0x80000000) { + *q++ = MakeLeading5(ch >> 30); + *q++ = MakeContinuation(ch >> 24); + *q++ = MakeContinuation(ch >> 18); + *q++ = MakeContinuation(ch >> 12); + *q++ = MakeContinuation(ch >> 6); + *q++ = MakeContinuation(ch); + } else { + // error + } + + return q; +} + +std::size_t +LengthUTF8(const char *p) noexcept +{ + /* this is a very naive implementation: it does not do any + verification, it just counts the bytes that are not a UTF-8 + continuation */ + + std::size_t n = 0; + for (; *p != 0; ++p) + if (!IsContinuation(*p)) + ++n; + return n; +} diff --git a/src/util/UTF8.hxx b/src/util/UTF8.hxx new file mode 100644 index 0000000..e8a1dd0 --- /dev/null +++ b/src/util/UTF8.hxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef UTF8_HXX +#define UTF8_HXX + +#include + +/** + * Is this a valid UTF-8 string? + */ +[[gnu::pure]] [[gnu::nonnull]] +bool +ValidateUTF8(const char *p) noexcept; + +/** + * @return the number of the sequence beginning with the given + * character, or 0 if the character is not a valid start byte + */ +[[gnu::const]] +std::size_t +SequenceLengthUTF8(char ch) noexcept; + +/** + * @return the number of the first sequence in the given string, or 0 + * if the sequence is malformed + */ +[[gnu::pure]] +std::size_t +SequenceLengthUTF8(const char *p) noexcept; + +/** + * Convert the specified string from ISO-8859-1 to UTF-8. + * + * @return the UTF-8 version of the source string; may return #src if + * there are no non-ASCII characters; returns nullptr if the destination + * buffer is too small + */ +[[gnu::pure]] [[gnu::nonnull]] +const char * +Latin1ToUTF8(const char *src, char *buffer, std::size_t buffer_size) noexcept; + +/** + * Convert the specified Unicode character to UTF-8 and write it to + * the buffer. buffer must have a length of at least 6! + * + * @return a pointer to the buffer plus the added bytes(s) + */ +[[gnu::nonnull]] +char * +UnicodeToUTF8(unsigned ch, char *buffer) noexcept; + +/** + * Returns the number of characters in the string. This is different + * from strlen(), which counts the number of bytes. + */ +[[gnu::pure]] [[gnu::nonnull]] +std::size_t +LengthUTF8(const char *p) noexcept; + +#endif diff --git a/src/util/UriExtract.cxx b/src/util/UriExtract.cxx new file mode 100644 index 0000000..cf1ab64 --- /dev/null +++ b/src/util/UriExtract.cxx @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "UriExtract.hxx" +#include "CharUtil.hxx" +#include "StringSplit.hxx" + +#include + +static constexpr bool +IsValidSchemeStart(char ch) +{ + return IsLowerAlphaASCII(ch); +} + +static constexpr bool +IsValidSchemeChar(char ch) +{ + return IsLowerAlphaASCII(ch) || IsDigitASCII(ch) || + ch == '+' || ch == '.' || ch == '-'; +} + +[[gnu::pure]] +static bool +IsValidScheme(std::string_view p) noexcept +{ + if (p.empty() || !IsValidSchemeStart(p.front())) + return false; + + for (size_t i = 1; i < p.size(); ++i) + if (!IsValidSchemeChar(p[i])) + return false; + + return true; +} + +/** + * Return the URI part after the scheme specification (and after the + * double slash). + */ +[[gnu::pure]] +static std::string_view +uri_after_scheme(std::string_view uri) noexcept +{ + if (uri.length() > 2 && + uri[0] == '/' && uri[1] == '/' && uri[2] != '/') + return uri.substr(2); + + auto colon = uri.find(':'); + if (colon == std::string_view::npos || + !IsValidScheme(uri.substr(0, colon))) + return {}; + + uri = uri.substr(colon + 1); + if (uri[0] != '/' || uri[1] != '/') + return {}; + + return uri.substr(2); +} + +bool +uri_has_scheme(std::string_view uri) noexcept +{ + return !uri_get_scheme(uri).empty(); +} + +std::string_view +uri_get_scheme(std::string_view uri) noexcept +{ + auto end = uri.find("://"); + if (end == std::string_view::npos) + return {}; + + return uri.substr(0, end); +} + +bool +uri_is_relative_path(const char *uri) noexcept +{ + return !uri_has_scheme(uri) && *uri != '/'; +} + +std::string_view +uri_get_path_query_fragment(std::string_view uri) noexcept +{ + auto ap = uri_after_scheme(uri); + if (ap.data() != nullptr) { + auto slash = ap.find('/'); + if (slash == std::string_view::npos) + return {}; + return ap.substr(slash); + } + + return uri; +} + +[[gnu::pure]] +static std::string_view +UriWithoutQueryString(std::string_view uri) noexcept +{ + return Split(uri, '?').first; +} + +std::string_view +uri_get_path(std::string_view uri) noexcept +{ + auto path = uri_get_path_query_fragment(uri); + if (path.data() == nullptr || path.data() == uri.data()) + /* preserve query and fragment if this URI doesn't + have a scheme; the question mark may be part of the + file name, after all */ + return path; + + auto end = path.find('?'); + if (end == std::string_view::npos) + end = path.find('#'); + + return path.substr(0, end); +} + +/* suffixes should be ascii only characters */ +std::string_view +uri_get_suffix(std::string_view _uri) noexcept +{ + const auto uri = UriWithoutQueryString(_uri); + + const auto dot = uri.rfind('.'); + if (dot == uri.npos || dot == 0 || + uri[dot - 1] == '/' || uri[dot - 1] == '\\') + return {}; + + auto suffix = uri.substr(dot + 1); + if (suffix.find('/') != suffix.npos || + suffix.find('\\') != suffix.npos) + /* this was not the last path segment */ + return {}; + + return suffix; +} + +const char * +uri_get_fragment(const char *uri) noexcept +{ + const char *fragment = std::strchr(uri, '#'); + if (fragment == nullptr) + return nullptr; + + return fragment + 1; +} diff --git a/src/util/UriExtract.hxx b/src/util/UriExtract.hxx new file mode 100644 index 0000000..e4bb90f --- /dev/null +++ b/src/util/UriExtract.hxx @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Checks whether the specified URI has a scheme in the form + * "scheme://". + */ +[[gnu::pure]] +bool +uri_has_scheme(std::string_view uri) noexcept; + +/** + * Returns the scheme name of the specified URI, or an empty string. + */ +[[gnu::pure]] +std::string_view +uri_get_scheme(std::string_view uri) noexcept; + +[[gnu::pure]] +bool +uri_is_relative_path(const char *uri) noexcept; + +/** + * Returns the URI path (including query and fragment) or nullptr if + * the given URI has no path. + */ +[[gnu::pure]] +std::string_view +uri_get_path_query_fragment(std::string_view uri) noexcept; + +/** + * Returns the URI path (excluding query and fragment) or nullptr if + * the given URI has no path. + */ +[[gnu::pure]] +std::string_view +uri_get_path(std::string_view uri) noexcept; + +[[gnu::pure]] +std::string_view +uri_get_suffix(std::string_view uri) noexcept; + +/** + * Returns the URI fragment, i.e. the portion after the '#', but + * without the '#'. If there is no '#', this function returns + * nullptr; if there is a '#' but no fragment text, it returns an + * empty std::string_view. + */ +[[gnu::pure]] [[gnu::nonnull]] +const char * +uri_get_fragment(const char *uri) noexcept; diff --git a/src/util/UriQueryParser.cxx b/src/util/UriQueryParser.cxx new file mode 100644 index 0000000..bd0db49 --- /dev/null +++ b/src/util/UriQueryParser.cxx @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "UriQueryParser.hxx" +#include "IterableSplitString.hxx" + +using std::string_view_literals::operator""sv; + +std::string_view +UriFindRawQueryParameter(std::string_view query_string, std::string_view name) noexcept +{ + for (const std::string_view i : IterableSplitString(query_string, '&')) { + if (i.starts_with(name)) { + if (i.size() == name.size()) + return ""sv; + + if (i[name.size()] == '=') + return i.substr(name.size() + 1); + } + } + + return {}; +} diff --git a/src/util/UriQueryParser.hxx b/src/util/UriQueryParser.hxx new file mode 100644 index 0000000..eeedd4b --- /dev/null +++ b/src/util/UriQueryParser.hxx @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include + +/** + * Find the first query parameter with the given name and return its + * raw value (without unescaping). + * + * @return the raw value (pointing into the #query_string parameter) + * or nullptr if the parameter does not exist + */ +[[gnu::pure]] +std::string_view +UriFindRawQueryParameter(std::string_view query_string, std::string_view name) noexcept; diff --git a/src/util/UriRelative.cxx b/src/util/UriRelative.cxx new file mode 100644 index 0000000..9c6d3d4 --- /dev/null +++ b/src/util/UriRelative.cxx @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "UriRelative.hxx" +#include "UriExtract.hxx" +#include "StringAPI.hxx" +#include "StringCompare.hxx" +#include "Compiler.h" + +#include + +#include + +using std::string_view_literals::operator""sv; + +bool +uri_is_child(const char *parent, const char *child) noexcept +{ +#if !CLANG_CHECK_VERSION(3,6) + /* disabled on clang due to -Wtautological-pointer-compare */ + assert(parent != nullptr); + assert(child != nullptr); +#endif + + const char *suffix = StringAfterPrefix(child, parent); + return suffix != nullptr && *suffix != 0 && + (suffix == child || suffix[-1] == '/' || *suffix == '/'); +} + + +bool +uri_is_child_or_same(const char *parent, const char *child) noexcept +{ + return StringIsEqual(parent, child) || uri_is_child(parent, child); +} + +std::string +uri_apply_base(std::string_view uri, std::string_view base) noexcept +{ + if (uri.front() == '/') { + /* absolute path: replace the whole URI path in base */ + + auto i = base.find("://"); + if (i == base.npos) + /* no scheme: override base completely */ + return std::string(uri); + + /* find the first slash after the host part */ + i = base.find('/', i + 3); + if (i == base.npos) + /* there's no URI path - simply append uri */ + i = base.length(); + + std::string out(base.substr(0, i)); + out += uri; + return out; + } + + std::string out(base); + if (out.back() != '/') + out.push_back('/'); + + out += uri; + return out; +} + +static void +ClearFilename(std::string_view &path) noexcept +{ + const auto slash = path.rfind('/'); + if (slash != path.npos) + path = path.substr(0, slash + 1); + else + path = path.substr(0, 0); +} + +static void +StripLeadingSlashes(std::string_view &s) noexcept +{ + while (s.starts_with('/')) + s.remove_prefix(1); +} + +static bool +ConsumeLastSegment(std::string_view &path) noexcept +{ + assert(!path.empty()); + assert(path.back() == '/'); + + path.remove_suffix(1); + + const auto slash = path.rfind('/'); + if (slash == path.npos) + return false; + + path = path.substr(0, slash + 1); + return true; +} + +static bool +ConsumeSpecial(std::string_view &relative_path, std::string_view &base_path) noexcept +{ + while (true) { + if (SkipPrefix(relative_path, "./"sv)) { + StripLeadingSlashes(relative_path); + } else if (SkipPrefix(relative_path, "../"sv)) { + StripLeadingSlashes(relative_path); + + if (!ConsumeLastSegment(base_path)) + return false; + } else if (relative_path == "."sv) { + relative_path.remove_prefix(1); + return true; + } else + return true; + } +} + +std::string +uri_apply_relative(std::string_view relative_uri, + std::string_view base_uri) noexcept +{ + if (relative_uri.empty()) + return std::string(base_uri); + + if (uri_has_scheme(relative_uri)) + return std::string(relative_uri); + + // TODO: support double slash at beginning of relative_uri + if (relative_uri.front() == '/') { + /* absolute path: replace the whole URI path in base */ + + auto i = base_uri.find("://"); + if (i == base_uri.npos) + /* no scheme: override base completely */ + return std::string{relative_uri}; + + /* find the first slash after the host part */ + i = base_uri.find('/', i + 3); + if (i == base_uri.npos) + /* there's no URI path - simply append uri */ + i = base_uri.length(); + + std::string result{base_uri.substr(0, i)}; + result.append(relative_uri); + return result; + } + + std::string_view relative_path{relative_uri}; + + const auto _base_path = uri_get_path(base_uri); + if (_base_path.data() == nullptr) { + std::string result(base_uri); + if (relative_path.front() != '/') + result.push_back('/'); + while (SkipPrefix(relative_path, "./"sv)) {} + if (relative_path.starts_with("../"sv)) + return {}; + if (relative_path != "."sv) + result += relative_path; + return result; + } + + std::string_view base_path(_base_path); + ClearFilename(base_path); + + if (!ConsumeSpecial(relative_path, base_path)) + return {}; + + std::string result(base_uri.data(), _base_path.data()); + result.append(base_path); + result.append(relative_path); + return result; +} diff --git a/src/util/UriRelative.hxx b/src/util/UriRelative.hxx new file mode 100644 index 0000000..f01e3d1 --- /dev/null +++ b/src/util/UriRelative.hxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include + +/** + * Check whether #child specifies a resource "inside" the directory + * specified by #parent. If the strings are equal, the function + * returns false. + */ +[[gnu::pure]] [[gnu::nonnull]] +bool +uri_is_child(const char *parent, const char *child) noexcept; + +[[gnu::pure]] [[gnu::nonnull]] +bool +uri_is_child_or_same(const char *parent, const char *child) noexcept; + +/** + * Translate the given URI in the context of #base. For example, + * uri_apply_base("foo", "http://bar/a/")=="http://bar/a/foo". + */ +[[gnu::pure]] +std::string +uri_apply_base(std::string_view uri, std::string_view base) noexcept; + +[[gnu::pure]] +std::string +uri_apply_relative(std::string_view relative_uri, + std::string_view base_uri) noexcept; diff --git a/src/util/UriUtil.cxx b/src/util/UriUtil.cxx new file mode 100644 index 0000000..3ad74cd --- /dev/null +++ b/src/util/UriUtil.cxx @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "UriUtil.hxx" +#include "ASCII.hxx" +#include "SplitString.hxx" + +#include +#include +#include + +#include + +static const char * +verify_uri_segment(const char *p) noexcept +{ + unsigned dots = 0; + while (*p == '.') { + ++p; + ++dots; + } + + if (dots <= 2 && (*p == 0 || *p == '/')) + return nullptr; + + const char *q = std::strchr(p + 1, '/'); + return q != nullptr ? q : ""; +} + +bool +uri_safe_local(const char *uri) noexcept +{ + while (true) { + uri = verify_uri_segment(uri); + if (uri == nullptr) + return false; + + if (*uri == 0) + return true; + + assert(*uri == '/'); + + ++uri; + } +} + +[[gnu::pure]] +static const char * +SkipUriScheme(const char *uri) noexcept +{ + static constexpr auto schemes = std::array { + "http://", "https://", + "ftp://", + "smb://", + }; + + for (auto scheme : schemes) { + auto result = StringAfterPrefixCaseASCII(uri, scheme); + if (result != nullptr) + return result; + } + + return nullptr; +} + +std::string +uri_remove_auth(const char *uri) noexcept +{ + const char *auth = SkipUriScheme(uri); + if (auth == nullptr) + /* unrecognized URI */ + return {}; + + const char *slash = std::strchr(auth, '/'); + if (slash == nullptr) + slash = auth + strlen(auth); + + auto at = (const char *)std::memchr(auth, '@', slash - auth); + if (at == nullptr) + /* no auth info present, do nothing */ + return {}; + + /* duplicate the full URI and then delete the auth + information */ + std::string result(uri); + result.erase(auth - uri, at + 1 - auth); + return result; +} + +std::string +uri_squash_dot_segments(const char *uri) noexcept +{ + std::forward_list path = SplitString(std::string_view(uri), '/', false); + path.remove_if([](const std::string_view &seg) { return seg == "."; }); + path.reverse(); + + std::string result; + + int segskips = 0; + auto it = path.begin(); + while (it != path.end()) { + if (*it == "..") { + segskips++; + it++; + continue; + } else if (segskips != 0) { + segskips--; + it++; + continue; + } + + result.insert(0, *it); + + if (it != path.begin()) { + result.insert(it->length(), "/"); + } + + it++; + } + + return result; +} diff --git a/src/util/UriUtil.hxx b/src/util/UriUtil.hxx new file mode 100644 index 0000000..c1c458c --- /dev/null +++ b/src/util/UriUtil.hxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef URI_UTIL_HXX +#define URI_UTIL_HXX + +#include + +/** + * Returns true if this is a safe "local" URI: + * + * - non-empty + * - does not begin or end with a slash + * - no double slashes + * - no path component begins with a dot + */ +[[gnu::pure]] +bool +uri_safe_local(const char *uri) noexcept; + +/** + * Removes HTTP username and password from the URI. This may be + * useful for displaying an URI without disclosing secrets. Returns + * an empty string if nothing needs to be removed, or if the URI is + * not recognized. + */ +[[gnu::pure]] +std::string +uri_remove_auth(const char *uri) noexcept; + +/** + * Remove dot segments in the URI. For example, uri_squash_dot_segments + * ("foo/bar/.././")=="foo/". + */ +[[gnu::pure]] +std::string +uri_squash_dot_segments(const char *uri) noexcept; + +#endif diff --git a/src/util/VarSize.hxx b/src/util/VarSize.hxx new file mode 100644 index 0000000..bc55077 --- /dev/null +++ b/src/util/VarSize.hxx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include + +/** + * Allocate and construct a variable-size object. That is useful for + * example when you want to store a variable-length string as the last + * attribute without the overhead of a second allocation. + * + * @tparam T a struct/class with a variable-size last attribute + * @param declared_tail_size the declared size of the last element in + * #T + * @param real_tail_size the real required size of the last element in + * #T + */ +template +requires std::is_standard_layout_v +[[gnu::malloc]] [[gnu::returns_nonnull]] +T * +NewVarSize(size_t declared_tail_size, size_t real_tail_size, Args&&... args) +{ + /* determine the total size of this instance */ + size_t size = sizeof(T) - declared_tail_size + real_tail_size; + + /* allocate memory */ + T *instance = (T *)malloc(size); + if (instance == nullptr) + throw std::bad_alloc{}; + + /* call the constructor */ + new(instance) T(std::forward(args)...); + + return instance; +} + +template +[[gnu::nonnull]] +void +DeleteVarSize(T *instance) +{ + /* call the destructor */ + instance->T::~T(); + + /* free memory */ + free(instance); +} diff --git a/src/util/WCharUtil.hxx b/src/util/WCharUtil.hxx new file mode 100644 index 0000000..e764af7 --- /dev/null +++ b/src/util/WCharUtil.hxx @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef WCHAR_UTIL_HXX +#define WCHAR_UTIL_HXX + +#include + +constexpr bool +IsASCII(const wchar_t ch) noexcept +{ + return (ch & ~0x7f) == 0; +} + +constexpr bool +IsWhitespaceOrNull(const wchar_t ch) noexcept +{ + return (unsigned)ch <= 0x20; +} + +constexpr bool +IsWhitespaceNotNull(const wchar_t ch) noexcept +{ + return ch > 0 && ch <= 0x20; +} + +/** + * Is the given character whitespace? This calls the faster one of + * IsWhitespaceOrNull() or IsWhitespaceNotNull(). Use this if you + * want the fastest implementation, and you don't care if a null byte + * matches. + */ +constexpr bool +IsWhitespaceFast(const wchar_t ch) noexcept +{ + return IsWhitespaceOrNull(ch); +} + +/** + * Is this a non-printable ASCII character? Returns false for + * non-ASCII characters. + * + * Note that this is not the opposide of IsNonPrintableASCII(). + */ +constexpr bool +IsPrintableASCII(wchar_t ch) noexcept +{ + return IsASCII(ch) && ch >= 0x20; +} + +/** + * Is this a non-printable character? Returns false for non-ASCII + * characters. + * + * Note that this is not the opposide of IsPrintableASCII() + */ +constexpr bool +IsNonPrintableASCII(wchar_t ch) noexcept +{ + return (unsigned)ch < 0x20; +} + +constexpr bool +IsDigitASCII(wchar_t ch) noexcept +{ + return ch >= '0' && ch <= '9'; +} + +constexpr bool +IsUpperAlphaASCII(wchar_t ch) noexcept +{ + return ch >= 'A' && ch <= 'Z'; +} + +constexpr bool +IsLowerAlphaASCII(wchar_t ch) noexcept +{ + return ch >= 'a' && ch <= 'z'; +} + +constexpr bool +IsAlphaASCII(wchar_t ch) noexcept +{ + return IsUpperAlphaASCII(ch) || IsLowerAlphaASCII(ch); +} + +constexpr bool +IsAlphaNumericASCII(wchar_t ch) noexcept +{ + return IsAlphaASCII(ch) || IsDigitASCII(ch); +} + +constexpr bool +IsLowerAlphaNumericASCII(wchar_t ch) noexcept +{ + return IsLowerAlphaASCII(ch) || IsDigitASCII(ch); +} + +/** + * Convert the specified ASCII character (0x00..0x7f) to upper case. + * Unlike toupper(), it ignores the system locale. + */ +constexpr wchar_t +ToUpperASCII(wchar_t ch) noexcept +{ + return ch >= 'a' && ch <= 'z' + ? (ch - ('a' - 'A')) + : ch; +} + +/** + * Convert the specified ASCII character (0x00..0x7f) to lower case. + * Unlike tolower(), it ignores the system locale. + */ +constexpr wchar_t +ToLowerASCII(wchar_t ch) noexcept +{ + return ch >= 'A' && ch <= 'Z' + ? (ch + ('a' - 'A')) + : ch; +} + +#endif diff --git a/src/util/WStringAPI.hxx b/src/util/WStringAPI.hxx new file mode 100644 index 0000000..47c294a --- /dev/null +++ b/src/util/WStringAPI.hxx @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef WSTRING_API_HXX +#define WSTRING_API_HXX + +#include + +[[gnu::pure]] [[gnu::nonnull]] +static inline size_t +StringLength(const wchar_t *p) noexcept +{ + return wcslen(p); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFind(const wchar_t *haystack, const wchar_t *needle) noexcept +{ + return wcsstr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFind(const wchar_t *haystack, wchar_t needle, size_t size) noexcept +{ + return std::wmemchr(haystack, needle, size); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline wchar_t * +StringFind(wchar_t *haystack, wchar_t needle, size_t size) noexcept +{ + return std::wmemchr(haystack, needle, size); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFind(const wchar_t *haystack, wchar_t needle) noexcept +{ + return wcschr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline wchar_t * +StringFind(wchar_t *haystack, wchar_t needle) noexcept +{ + return wcschr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFindLast(const wchar_t *haystack, wchar_t needle) noexcept +{ + return wcsrchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline wchar_t * +StringFindLast(wchar_t *haystack, wchar_t needle) noexcept +{ + return wcsrchr(haystack, needle); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFindLast(const wchar_t *haystack, wchar_t needle, size_t size) noexcept +{ + /* there's no wmemrchr() unfortunately */ + const auto *p = haystack + size; + while (p > haystack) { + --p; + if (*p == needle) + return p; + } + + return nullptr; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringFindAny(const wchar_t *haystack, const wchar_t *accept) noexcept +{ + return wcspbrk(haystack, accept); +} + +[[gnu::nonnull]] +static inline void +UnsafeCopyString(wchar_t *dest, const wchar_t *src) noexcept +{ + wcscpy(dest, src); +} + +[[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline wchar_t * +UnsafeCopyStringP(wchar_t *dest, const wchar_t *src) noexcept +{ +#if defined(_WIN32) || defined(__OpenBSD__) || defined(__NetBSD__) + /* emulate wcpcpy() */ + UnsafeCopyString(dest, src); + return dest + StringLength(dest); +#elif defined(__sun) && defined (__SVR4) + return std::wcpcpy(dest, src); +#else + return wcpcpy(dest, src); +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCompare(const wchar_t *a, const wchar_t *b) noexcept +{ + return wcscmp(a, b); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCompare(const wchar_t *a, const wchar_t *b, size_t n) noexcept +{ + return wcsncmp(a, b, n); +} + +/** + * Checks whether str1 and str2 are equal. + * @param str1 String 1 + * @param str2 String 2 + * @return True if equal, False otherwise + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqual(const wchar_t *str1, const wchar_t *str2) noexcept +{ + return StringCompare(str1, str2) == 0; +} + +/** + * Checks whether #a and #b are equal. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqual(const wchar_t *a, const wchar_t *b, size_t length) noexcept +{ + return wcsncmp(a, b, length) == 0; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqualIgnoreCase(const wchar_t *a, const wchar_t *b) noexcept +{ +#ifdef _WIN32 + return _wcsicmp(a, b) == 0; +#else + return wcscasecmp(a, b) == 0; +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringIsEqualIgnoreCase(const wchar_t *a, const wchar_t *b, + size_t size) noexcept +{ +#ifdef _WIN32 + return _wcsnicmp(a, b, size) == 0; +#else + return wcsncasecmp(a, b, size) == 0; +#endif +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline int +StringCollate(const wchar_t *a, const wchar_t *b) noexcept +{ + return wcscoll(a, b); +} + +[[gnu::malloc]] [[gnu::returns_nonnull]] [[gnu::nonnull]] +static inline wchar_t * +DuplicateString(const wchar_t *p) noexcept +{ +#if defined(__sun) && defined (__SVR4) + return std::wcsdup(p); +#else + return wcsdup(p); +#endif +} + +#endif diff --git a/src/util/WStringCompare.cxx b/src/util/WStringCompare.cxx new file mode 100644 index 0000000..4d715d8 --- /dev/null +++ b/src/util/WStringCompare.cxx @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "WStringCompare.hxx" + +#include + +bool +StringEndsWith(const wchar_t *haystack, const wchar_t *needle) noexcept +{ + const size_t haystack_length = StringLength(haystack); + const size_t needle_length = StringLength(needle); + + return haystack_length >= needle_length && + StringIsEqual(haystack + haystack_length - needle_length, needle); +} + +bool +StringEndsWithIgnoreCase(const wchar_t *haystack, + const wchar_t *needle) noexcept +{ + const size_t haystack_length = StringLength(haystack); + const size_t needle_length = StringLength(needle); + + return haystack_length >= needle_length && + StringIsEqualIgnoreCase(haystack + haystack_length - needle_length, + needle); +} + +const wchar_t * +FindStringSuffix(const wchar_t *p, const wchar_t *suffix) noexcept +{ + const size_t p_length = StringLength(p); + const size_t suffix_length = StringLength(suffix); + + if (p_length < suffix_length) + return nullptr; + + const auto *q = p + p_length - suffix_length; + return memcmp(q, suffix, suffix_length * sizeof(*suffix)) == 0 + ? q + : nullptr; +} diff --git a/src/util/WStringCompare.hxx b/src/util/WStringCompare.hxx new file mode 100644 index 0000000..ceb5d59 --- /dev/null +++ b/src/util/WStringCompare.hxx @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#ifndef WSTRING_COMPARE_HXX +#define WSTRING_COMPARE_HXX + +#include "WStringAPI.hxx" + +#include + +#include + +[[gnu::pure]] [[gnu::nonnull]] +static constexpr bool +StringIsEmpty(const wchar_t *string) noexcept +{ + return *string == 0; +} + +[[gnu::pure]] +static constexpr bool +StringIsEqual(std::wstring_view a, std::wstring_view b) noexcept +{ + return a == b; +} + +[[gnu::pure]] +static inline bool +StringIsEqualIgnoreCase(std::wstring_view a, std::wstring_view b) noexcept +{ + return a.size() == b.size() && + StringIsEqualIgnoreCase(a.data(), b.data(), b.size()); +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringStartsWith(const wchar_t *haystack, std::wstring_view needle) noexcept +{ + return StringIsEqual(haystack, needle.data(), needle.size()); +} + +[[gnu::pure]] [[gnu::nonnull]] +bool +StringEndsWith(const wchar_t *haystack, const wchar_t *needle) noexcept; + +[[gnu::pure]] [[gnu::nonnull]] +bool +StringEndsWithIgnoreCase(const wchar_t *haystack, + const wchar_t *needle) noexcept; + +/** + * Returns the portion of the string after a prefix. If the string + * does not begin with the specified prefix, this function returns + * nullptr. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringAfterPrefix(const wchar_t *haystack, std::wstring_view needle) noexcept +{ + return StringStartsWith(haystack, needle) + ? haystack + needle.size() + : nullptr; +} + +[[gnu::pure]] [[gnu::nonnull]] +static inline bool +StringStartsWithIgnoreCase(const wchar_t *haystack, + std::wstring_view needle) noexcept +{ + return StringIsEqualIgnoreCase(haystack, needle.data(), needle.size()); +} + +/** + * Returns the portion of the string after a prefix. If the string + * does not begin with the specified prefix, this function returns + * nullptr. + * This function is case-independent. + */ +[[gnu::pure]] [[gnu::nonnull]] +static inline const wchar_t * +StringAfterPrefixIgnoreCase(const wchar_t *haystack, + std::wstring_view needle) noexcept +{ + return StringStartsWithIgnoreCase(haystack, needle) + ? haystack + needle.size() + : nullptr; +} + +/** + * Check if the given string ends with the specified suffix. If yes, + * returns the position of the suffix, and nullptr otherwise. + */ +[[gnu::pure]] [[gnu::nonnull]] +const wchar_t * +FindStringSuffix(const wchar_t *p, const wchar_t *suffix) noexcept; + +#endif diff --git a/src/util/djb_hash.hxx b/src/util/djb_hash.hxx new file mode 100644 index 0000000..bbf732a --- /dev/null +++ b/src/util/djb_hash.hxx @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: BSD-2-Clause +// Copyright CM4all GmbH +// author: Max Kellermann + +/* + * Implementation of D. J. Bernstein's cdb hash function. + * http://cr.yp.to/cdb/cdb.txt + */ + +#pragma once + +#include +#include + +static constexpr std::size_t DJB_HASH_INIT = 5381; + +[[nodiscard]] [[gnu::always_inline]] [[gnu::hot]] +constexpr std::size_t +djb_hash_update(std::size_t hash, std::byte b) noexcept +{ + return (hash * 33) ^ static_cast(b); +} + +[[nodiscard]] [[gnu::hot]] +constexpr std::size_t +djb_hash(std::span src, + std::size_t init=DJB_HASH_INIT) noexcept +{ + std::size_t hash = init; + + for (const auto i : src) + hash = djb_hash_update(hash, i); + + return hash; +} + +[[nodiscard]] [[gnu::hot]] +constexpr std::size_t +djb_hash_string(const char *p, + std::size_t init=DJB_HASH_INIT) noexcept +{ + std::size_t hash = init; + + while (*p != 0) + hash = djb_hash_update(hash, static_cast(*p++)); + + return hash; +} diff --git a/src/util/format.c b/src/util/format.c new file mode 100644 index 0000000..7e29869 --- /dev/null +++ b/src/util/format.c @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "format.h" +#include "util/Compiler.h" + +#include +#include +#include +#include + +/** + * Reallocate the given string and append the source string. + */ +gcc_malloc +static char * +string_append(char *dest, const char *src, size_t len) +{ + size_t destlen = dest != NULL + ? strlen(dest) + : 0; + + dest = realloc(dest, destlen + len + 1); + memcpy(dest + destlen, src, len); + dest[destlen + len] = '\0'; + + return dest; +} + +/** + * Skip the format string until the current group is closed by either + * '&', '|' or ']' (supports nesting). + */ +gcc_pure +static const char * +skip_format(const char *p) +{ + unsigned stack = 0; + + while (*p != '\0') { + if (*p == '[') + stack++; + else if (*p == '#' && p[1] != '\0') + /* skip escaped stuff */ + ++p; + else if (stack > 0) { + if (*p == ']') + --stack; + } else if (*p == '&' || *p == '|' || *p == ']') + break; + + ++p; + } + + return p; +} + +static bool +is_name_char(char ch) +{ + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || ch == '_'; +} + +static char * +format_object2(const char *format, const char **last, const void *object, + const char *(*getter)(const void *object, const char *name)) +{ + char *ret = NULL; + const char *p; + bool found = false; + + for (p = format; *p != '\0';) { + switch (p[0]) { + case '|': + ++p; + if (!found) { + /* nothing found yet: try the next + section */ + free(ret); + ret = NULL; + } else + /* already found a value: skip the + next section */ + p = skip_format(p); + break; + + case '&': + ++p; + if (!found) + /* nothing found yet, so skip this + section */ + p = skip_format(p); + else + /* we found something yet, but it will + only be used if the next section + also found something, so reset the + flag */ + found = false; + break; + + case '[': { + char *t = format_object2(p + 1, &p, object, getter); + if (t != NULL) { + ret = string_append(ret, t, strlen(t)); + free(t); + found = true; + } + } + break; + + case ']': + if (last != NULL) + *last = p + 1; + if (!found) { + free(ret); + ret = NULL; + } + return ret; + + case '\\': { + /* take care of escape sequences */ + char ltemp; + switch (p[1]) { + case 'a': + ltemp = '\a'; + break; + + case 'b': + ltemp = '\b'; + break; + + case 't': + ltemp = '\t'; + break; + + case 'n': + ltemp = '\n'; + break; + + case 'v': + ltemp = '\v'; + break; + + case 'f': + ltemp = '\f'; + break; + + case 'r': + ltemp = '\r'; + break; + + case '[': + case ']': + ltemp = p[1]; + break; + + default: + /* unknown escape: copy the + backslash */ + ltemp = p[0]; + --p; + break; + } + + ret = string_append(ret, <emp, 1); + p += 2; + } + break; + + case '%': { + /* find the extent of this format specifier + (stop at \0, ' ', or esc) */ + const char *end = p + 1; + while (is_name_char(*end)) + ++end; + + const size_t length = end - p + 1; + + if (*end != '%') { + ret = string_append(ret, p, length - 1); + p = end; + continue; + } + + char name[32]; + if (length > (int)sizeof(name)) { + ret = string_append(ret, p, length); + p = end + 1; + continue; + } + + memcpy(name, p + 1, length - 2); + name[length - 2] = 0; + + const char *value = getter(object, name); + size_t value_length; + if (value != NULL) { + if (*value != 0) + found = true; + value_length = strlen(value); + } else { + /* unknown variable: copy verbatim + from format string */ + value = p; + value_length = length; + } + + ret = string_append(ret, value, value_length); + + /* advance past the specifier */ + p = end + 1; + } + break; + + case '#': + /* let the escape character escape itself */ + if (p[1] != '\0') { + ret = string_append(ret, p + 1, 1); + p += 2; + break; + } + + /* fall through */ + gcc_fallthrough; + + default: + /* pass-through non-escaped portions of the format string */ + ret = string_append(ret, p, 1); + ++p; + } + } + + if (last != NULL) + *last = p; + return ret; +} + +char * +format_object(const char *format, const void *object, + const char *(*getter)(const void *object, const char *name)) +{ + return format_object2(format, NULL, object, getter); +} diff --git a/src/util/format.h b/src/util/format.h new file mode 100644 index 0000000..e7aefeb --- /dev/null +++ b/src/util/format.h @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPC_FORMAT_H +#define MPC_FORMAT_H + +#include "Compiler.h" + +struct mpd_song; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Pretty-print an object into a string using the given format + * specification. + * + * @param format the format string + * @param object the object + * @param getter a getter function that extracts a value from the object + * @return the resulting string to be freed by free(); NULL if + * no format string group produced any output + */ +gcc_malloc +char * +format_object(const char *format, const void *object, + const char *(*getter)(const void *object, const char *name)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/util/meson.build b/src/util/meson.build new file mode 100644 index 0000000..144f5db --- /dev/null +++ b/src/util/meson.build @@ -0,0 +1,31 @@ +util = static_library( + 'util', + 'Exception.cxx', + 'UTF8.cxx', + 'MimeType.cxx', + 'TruncateString.cxx', + 'StringStrip.cxx', + 'StringUtil.cxx', + 'StringCompare.cxx', + 'WStringCompare.cxx', + 'SplitString.cxx', + 'Tokenizer.cxx', + 'UriExtract.cxx', + 'UriQueryParser.cxx', + 'UriRelative.cxx', + 'UriUtil.cxx', + 'LazyRandomEngine.cxx', + 'HugeAllocator.cxx', + 'PeakBuffer.cxx', + 'PrintException.cxx', + 'SparseBuffer.cxx', + 'ByteReverse.cxx', + 'format.c', + 'BitReverse.cxx', + 'Serial.cxx', + include_directories: inc, +) + +util_dep = declare_dependency( + link_with: util, +) diff --git a/src/win32/Com.hxx b/src/win32/Com.hxx new file mode 100644 index 0000000..bd924c8 --- /dev/null +++ b/src/win32/Com.hxx @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_COM_HXX +#define MPD_WIN32_COM_HXX + +#include "HResult.hxx" + +#include +#include // for COINIT_APARTMENTTHREADED + +// RAII for Microsoft Component Object Model(COM) +// https://docs.microsoft.com/en-us/windows/win32/api/_com/ +class COM { +public: + COM() { + if (HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED|COINIT_DISABLE_OLE1DDE); + FAILED(result)) { + throw MakeHResultError( + result, + "Unable to initialize COM with COINIT_APARTMENTTHREADED"); + } + } + ~COM() noexcept { CoUninitialize(); } + + COM(const COM &) = delete; + COM(COM &&) = delete; + COM &operator=(const COM &) = delete; + COM &operator=(COM &&) = delete; +}; + +#endif diff --git a/src/win32/ComHeapPtr.hxx b/src/win32/ComHeapPtr.hxx new file mode 100644 index 0000000..9513e11 --- /dev/null +++ b/src/win32/ComHeapPtr.hxx @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_COMHEAPPTR_HXX +#define MPD_WIN32_COMHEAPPTR_HXX + +#include +#include +#include + +#include + +// RAII for CoTaskMemAlloc and CoTaskMemFree +// https://docs.microsoft.com/zh-tw/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemalloc +// https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemfree +template +class ComHeapPtr { +public: + using pointer = T *; + using element_type = T; + + constexpr ComHeapPtr() noexcept : ptr(nullptr) {} + constexpr ComHeapPtr(std::nullptr_t) noexcept : ptr(nullptr) {} + explicit constexpr ComHeapPtr(pointer p) noexcept : ptr(p) {} + + ComHeapPtr(const ComHeapPtr &u) = delete; + constexpr ComHeapPtr(ComHeapPtr &&u) noexcept : ptr(std::exchange(u.ptr, nullptr)) {} + + ComHeapPtr &operator=(const ComHeapPtr &r) = delete; + constexpr ComHeapPtr &operator=(ComHeapPtr &&r) noexcept { + std::swap(ptr, r.ptr); + return *this; + } + ComHeapPtr &operator=(std::nullptr_t) noexcept { + reset(); + return *this; + } + + ~ComHeapPtr() noexcept { reset(); } + + pointer release() noexcept { return std::exchange(ptr, nullptr); } + void reset() noexcept { + if (ptr) { + CoTaskMemFree(release()); + } + } + void swap(ComHeapPtr &other) noexcept { std::swap(ptr, other.ptr); } + + pointer get() const noexcept { return ptr; } + explicit operator bool() const noexcept { return ptr; } + + auto operator*() const { return *ptr; } + pointer operator->() const noexcept { return ptr; } + + T **Address() noexcept { + reset(); + return &ptr; + } + template + U **AddressCast() noexcept { + reset(); + return reinterpret_cast(&ptr); + } + + template + U *Cast() noexcept { + return reinterpret_cast(ptr); + } + +private: + pointer ptr; +}; + +namespace std { +template +void swap(ComHeapPtr &lhs, ComHeapPtr &rhs) noexcept { + lhs.swap(rhs); +} +} + +#endif diff --git a/src/win32/ComPtr.hxx b/src/win32/ComPtr.hxx new file mode 100644 index 0000000..bc52a50 --- /dev/null +++ b/src/win32/ComPtr.hxx @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_COMPTR_HXX +#define MPD_WIN32_COMPTR_HXX + +#include "win32/HResult.hxx" + +#include +#include +#include + +#include + +// RAII for Object in Microsoft Component Object Model(COM) +// https://docs.microsoft.com/zh-tw/windows/win32/api/_com/ +template +class ComPtr { +public: + using pointer = T *; + using reference = T &; + using element_type = T; + + constexpr ComPtr() noexcept : ptr(nullptr) {} + constexpr ComPtr(std::nullptr_t) noexcept : ptr(nullptr) {} + explicit constexpr ComPtr(pointer p) noexcept : ptr(p) {} + + ComPtr(const ComPtr &u) noexcept : ptr(u.ptr) { + if (ptr) { + ptr->AddRef(); + } + } + constexpr ComPtr(ComPtr &&u) noexcept : ptr(std::exchange(u.ptr, nullptr)) {} + + ComPtr &operator=(const ComPtr &r) noexcept { + reset(); + ptr = r.ptr; + if (ptr) { + ptr->AddRef(); + } + return *this; + } + constexpr ComPtr &operator=(ComPtr &&r) noexcept { + std::swap(ptr, r.ptr); + return *this; + } + ComPtr &operator=(std::nullptr_t) noexcept { + reset(); + return *this; + } + + ~ComPtr() noexcept { reset(); } + + pointer release() noexcept { return std::exchange(ptr, nullptr); } + void reset() noexcept { + if (ptr) { + release()->Release(); + } + } + void swap(ComPtr &other) noexcept { std::swap(ptr, other.ptr); } + + pointer get() const noexcept { return ptr; } + explicit operator bool() const noexcept { return ptr; } + + reference operator*() const noexcept { return *ptr; } + pointer operator->() const noexcept { return ptr; } + + void CoCreateInstance(REFCLSID class_id, LPUNKNOWN unknown_outer = nullptr, + DWORD class_context = CLSCTX_ALL) { + HRESULT result = + ::CoCreateInstance(class_id, unknown_outer, class_context, + __uuidof(T), reinterpret_cast(&ptr)); + if (FAILED(result)) { + throw MakeHResultError(result, "Unable to create instance"); + } + } + + T **Address() noexcept { + reset(); + return &ptr; + } + template + U **AddressCast() noexcept { + reset(); + return reinterpret_cast(&ptr); + } + + template + U *Cast() noexcept { + return reinterpret_cast(ptr); + } + +private: + pointer ptr; +}; + +namespace std { +template +void swap(ComPtr &lhs, ComPtr &rhs) noexcept { + lhs.swap(rhs); +} +} // namespace std + +#endif diff --git a/src/win32/ComWorker.cxx b/src/win32/ComWorker.cxx new file mode 100644 index 0000000..f1ae8e4 --- /dev/null +++ b/src/win32/ComWorker.cxx @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#undef NOUSER // COM needs the "MSG" typedef + +#include "ComWorker.hxx" +#include "Com.hxx" +#include "thread/Name.hxx" + +void +COMWorker::Work() noexcept +{ + SetThreadName("COM Worker"); + COM com; + + std::unique_lock lock{mutex}; + while (running_flag) { + while (!queue.empty()) { + auto function = std::move(queue.front()); + queue.pop(); + + lock.unlock(); + function(); + lock.lock(); + } + + cond.wait(lock); + } +} diff --git a/src/win32/ComWorker.hxx b/src/win32/ComWorker.hxx new file mode 100644 index 0000000..a51710b --- /dev/null +++ b/src/win32/ComWorker.hxx @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_COM_WORKER_HXX +#define MPD_WIN32_COM_WORKER_HXX + +#include "thread/Cond.hxx" +#include "thread/Future.hxx" +#include "thread/Mutex.hxx" +#include "thread/Thread.hxx" + +#include +#include + +// Worker thread for all COM operation +class COMWorker { + Mutex mutex; + Cond cond; + + std::queue> queue; + bool running_flag = true; + + Thread thread{BIND_THIS_METHOD(Work)}; + +public: + COMWorker() { + thread.Start(); + } + + ~COMWorker() noexcept { + Finish(); + thread.Join(); + } + + COMWorker(const COMWorker &) = delete; + COMWorker &operator=(const COMWorker &) = delete; + + template + auto Async(Function &&function) { + using R = std::invoke_result_t>; + auto promise = std::make_shared>(); + auto future = promise->get_future(); + Push([func = std::forward(function), + prom = std::move(promise)]() mutable { + try { + if constexpr (std::is_void_v) { + std::invoke(std::forward(func)); + prom->set_value(); + } else { + prom->set_value(std::invoke(std::forward(func))); + } + } catch (...) { + prom->set_exception(std::current_exception()); + } + }); + return future; + } + +private: + void Finish() noexcept { + const std::scoped_lock lock{mutex}; + running_flag = false; + cond.notify_one(); + } + + void Push(const std::function &function) { + const std::scoped_lock lock{mutex}; + queue.push(function); + cond.notify_one(); + } + + void Work() noexcept; +}; + +#endif diff --git a/src/win32/HResult.cxx b/src/win32/HResult.cxx new file mode 100644 index 0000000..6d792e6 --- /dev/null +++ b/src/win32/HResult.cxx @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifdef _WIN32 +// COM needs the "MSG" typedef, and audiopolicy.h includes COM headers +#undef NOUSER +#endif + +#include "HResult.hxx" + +#include + +#include + +#include // needed by audiopolicy.h if COM_NO_WINDOWS_H is defined +#include + +std::string_view +HRESULTToString(HRESULT result) noexcept +{ + using namespace std::literals; + switch (result) { +#define C(x) \ +case x: \ + return #x##sv + C(AUDCLNT_E_ALREADY_INITIALIZED); + C(AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL); + C(AUDCLNT_E_BUFFER_ERROR); + C(AUDCLNT_E_BUFFER_OPERATION_PENDING); + C(AUDCLNT_E_BUFFER_SIZE_ERROR); + C(AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED); + C(AUDCLNT_E_BUFFER_TOO_LARGE); + C(AUDCLNT_E_CPUUSAGE_EXCEEDED); + C(AUDCLNT_E_DEVICE_INVALIDATED); + C(AUDCLNT_E_DEVICE_IN_USE); + C(AUDCLNT_E_ENDPOINT_CREATE_FAILED); + C(AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED); + C(AUDCLNT_E_INVALID_DEVICE_PERIOD); + C(AUDCLNT_E_OUT_OF_ORDER); + C(AUDCLNT_E_SERVICE_NOT_RUNNING); + C(AUDCLNT_E_UNSUPPORTED_FORMAT); + C(AUDCLNT_E_WRONG_ENDPOINT_TYPE); + C(AUDCLNT_E_NOT_INITIALIZED); + C(AUDCLNT_E_NOT_STOPPED); + C(CO_E_NOTINITIALIZED); + C(E_INVALIDARG); + C(E_OUTOFMEMORY); + C(E_POINTER); + C(NO_ERROR); +#undef C + } + return std::string_view(); +} + +std::string +HResultCategory::message(int Errcode) const +{ + char buffer[256]; + + /* FormatMessage() supports some HRESULT values (depending on + the Windows version) */ + if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, Errcode, 0, + buffer, sizeof(buffer), + nullptr)) + return buffer; + + const auto msg = HRESULTToString(Errcode); + if (!msg.empty()) + return std::string(msg); + + return fmt::format("{:#x}", Errcode); +} diff --git a/src/win32/HResult.hxx b/src/win32/HResult.hxx new file mode 100644 index 0000000..d4625f2 --- /dev/null +++ b/src/win32/HResult.hxx @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_HRESULT_HXX +#define MPD_WIN32_HRESULT_HXX + +#include +#include + +#include + +[[gnu::const]] +std::string_view +HRESULTToString(HRESULT result) noexcept; + +static inline const std::error_category &hresult_category() noexcept; +class HResultCategory : public std::error_category { +public: + const char *name() const noexcept override { return "HRESULT"; } + std::string message(int Errcode) const override; + std::error_condition default_error_condition(int code) const noexcept override { + return std::error_condition(code, hresult_category()); + } +}; +static inline const std::error_category &hresult_category() noexcept { + static const HResultCategory hresult_category_instance{}; + return hresult_category_instance; +} + +inline std::system_error +MakeHResultError(HRESULT result, const char *msg) noexcept +{ + return std::system_error(std::error_code(result, hresult_category()), + msg); +} + +#endif diff --git a/src/win32/PropVariant.cxx b/src/win32/PropVariant.cxx new file mode 100644 index 0000000..53dd610 --- /dev/null +++ b/src/win32/PropVariant.cxx @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PropVariant.hxx" +#include "lib/icu/Win32.hxx" +#include "util/AllocatedString.hxx" +#include "util/ScopeExit.hxx" + +AllocatedString +ToString(const PROPVARIANT &pv) noexcept +{ + // TODO: VT_BSTR + + switch (pv.vt) { + case VT_LPSTR: + return AllocatedString{static_cast(pv.pszVal)}; + + case VT_LPWSTR: + return WideCharToMultiByte(CP_UTF8, pv.pwszVal); + + default: + return nullptr; + } +} diff --git a/src/win32/PropVariant.hxx b/src/win32/PropVariant.hxx new file mode 100644 index 0000000..894923a --- /dev/null +++ b/src/win32/PropVariant.hxx @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_PROPVARIANT_HXX +#define MPD_WIN32_PROPVARIANT_HXX + +#include // needed by propidl.h if COM_NO_WINDOWS_H is defined +#include + +class AllocatedString; + +[[gnu::pure]] +AllocatedString +ToString(const PROPVARIANT &pv) noexcept; + +#endif diff --git a/src/win32/Win32Main.cxx b/src/win32/Win32Main.cxx new file mode 100644 index 0000000..b874761 --- /dev/null +++ b/src/win32/Win32Main.cxx @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Main.hxx" +#include "Instance.hxx" +#include "system/Error.hxx" +#include "Log.hxx" + +#include +#include + +#include +#include + +static int service_argc; +static char **service_argv; +static TCHAR service_name[] = _T(""); +static std::atomic_bool running; +static SERVICE_STATUS_HANDLE service_handle; + +static void WINAPI +service_main(DWORD argc, LPTSTR argv[]); + +static constexpr SERVICE_TABLE_ENTRY service_registry[] = { + {service_name, service_main}, + {nullptr, nullptr} +}; + +static void +service_notify_status(DWORD status_code) +{ + SERVICE_STATUS current_status; + + current_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + current_status.dwControlsAccepted = status_code == SERVICE_START_PENDING + ? 0 + : SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP; + + current_status.dwCurrentState = status_code; + current_status.dwWin32ExitCode = NO_ERROR; + current_status.dwCheckPoint = 0; + current_status.dwWaitHint = 1000; + + SetServiceStatus(service_handle, ¤t_status); +} + +static DWORD WINAPI +service_dispatcher([[maybe_unused]] DWORD control, [[maybe_unused]] DWORD event_type, + [[maybe_unused]] void *event_data, [[maybe_unused]] void *context) +{ + switch (control) { + case SERVICE_CONTROL_SHUTDOWN: + case SERVICE_CONTROL_STOP: + global_instance->Break(); + return NO_ERROR; + default: + return NO_ERROR; + } +} + +static void WINAPI +service_main([[maybe_unused]] DWORD argc, [[maybe_unused]] LPTSTR argv[]) +try { + service_handle = + RegisterServiceCtrlHandlerEx(service_name, + service_dispatcher, nullptr); + + if (service_handle == 0) + throw MakeLastError("RegisterServiceCtrlHandlerEx() failed"); + + service_notify_status(SERVICE_START_PENDING); + mpd_main(service_argc, service_argv); + service_notify_status(SERVICE_STOPPED); +} catch (...) { + LogError(std::current_exception()); +} + +static BOOL WINAPI +console_handler(DWORD event) +{ + switch (event) { + case CTRL_C_EVENT: + case CTRL_CLOSE_EVENT: + if (running.load()) { + // Recent msdn docs that process is terminated + // if this function returns TRUE. + // We initiate correct shutdown sequence (if possible). + // Once main() returns CRT will terminate our process + // regardless our thread is still active. + // If this did not happen within 3 seconds + // let's shutdown anyway. + global_instance->Break(); + // Under debugger it's better to wait indefinitely + // to allow debugging of shutdown code. + Sleep(IsDebuggerPresent() ? INFINITE : 3000); + } + // If we're not running main loop there is no chance for + // clean shutdown. + std::exit(EXIT_FAILURE); + return TRUE; + default: + return FALSE; + } +} + +int win32_main(int argc, char *argv[]) +{ + service_argc = argc; + service_argv = argv; + + if (StartServiceCtrlDispatcher(service_registry)) + return 0; /* run as service successefully */ + + const DWORD error_code = GetLastError(); + if (error_code == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) { + /* running as console app */ + running.store(false); + SetConsoleTitle(_T("Music Player Daemon")); + SetConsoleCtrlHandler(console_handler, TRUE); + return mpd_main(argc, argv); + } + + throw MakeLastError(error_code, "StartServiceCtrlDispatcher() failed"); +} + +void win32_app_started() +{ + if (service_handle != 0) + service_notify_status(SERVICE_RUNNING); + else + running.store(true); +} + +void win32_app_stopping() +{ + if (service_handle != 0) + service_notify_status(SERVICE_STOP_PENDING); + else + running.store(false); +} diff --git a/src/win32/WinEvent.cxx b/src/win32/WinEvent.cxx new file mode 100644 index 0000000..438ac47 --- /dev/null +++ b/src/win32/WinEvent.cxx @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "WinEvent.hxx" +#include "system/Error.hxx" + +WinEvent::WinEvent() + :event(CreateEventW(nullptr, false, false, nullptr)) +{ + if (!event) + throw MakeLastError("Error creating events"); +} diff --git a/src/win32/WinEvent.hxx b/src/win32/WinEvent.hxx new file mode 100644 index 0000000..d79c6a3 --- /dev/null +++ b/src/win32/WinEvent.hxx @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_WIN32_WINEVENT_HXX +#define MPD_WIN32_WINEVENT_HXX + +#include +#include +#include // for HWND (needed by winbase.h) +#include // for INFINITE + +// RAII for Windows unnamed event object +// https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventw + +class WinEvent { +public: + /** + * Throws on error. + */ + WinEvent(); + + ~WinEvent() noexcept { CloseHandle(event); } + WinEvent(WinEvent &&) = delete; + WinEvent(const WinEvent &) = delete; + WinEvent &operator=(WinEvent &&) = delete; + WinEvent &operator=(const WinEvent &) = delete; + + HANDLE handle() noexcept { return event; } + + DWORD Wait(DWORD milliseconds=INFINITE) noexcept { + return WaitForSingleObject(event, milliseconds); + } + + bool Set() noexcept { return SetEvent(event); } + +private: + HANDLE event; +}; + +#endif diff --git a/src/win32/meson.build b/src/win32/meson.build new file mode 100644 index 0000000..ce71c19 --- /dev/null +++ b/src/win32/meson.build @@ -0,0 +1,23 @@ +if not is_windows + win32_dep = dependency('', required: false) + subdir_done() +endif + +win32 = static_library( + 'win32', + 'ComWorker.cxx', + 'HResult.cxx', + 'PropVariant.cxx', + 'WinEvent.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + ], +) + +win32_dep = declare_dependency( + link_with: win32, + dependencies: [ + thread_dep, + ], +) diff --git a/src/zeroconf/Bonjour.cxx b/src/zeroconf/Bonjour.cxx new file mode 100644 index 0000000..bb5403d --- /dev/null +++ b/src/zeroconf/Bonjour.cxx @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Bonjour.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" + +#include + +#include + +#include + +static constexpr Domain bonjour_domain("bonjour"); + +/** + * A wrapper for DNSServiceRegister() which returns the DNSServiceRef + * and throws on error. + */ +static DNSServiceRef +RegisterBonjour(const char *name, const char *type, unsigned port, + DNSServiceRegisterReply callback, void *ctx) +{ + DNSServiceRef ref; + DNSServiceErrorType error = DNSServiceRegister(&ref, + 0, 0, name, type, + nullptr, nullptr, + htons(port), 0, + nullptr, + callback, ctx); + + if (error != kDNSServiceErr_NoError) + throw std::runtime_error("DNSServiceRegister() failed"); + + return ref; +} + +BonjourHelper::BonjourHelper(EventLoop &_loop, const char *name, + const char *service_type, unsigned port) + :service_ref(RegisterBonjour(name, service_type, port, + Callback, this)), + socket_event(_loop, + BIND_THIS_METHOD(OnSocketReady), + SocketDescriptor(DNSServiceRefSockFD(service_ref))) +{ + socket_event.ScheduleRead(); +} + +void +BonjourHelper::Callback([[maybe_unused]] DNSServiceRef sdRef, + [[maybe_unused]] DNSServiceFlags flags, + DNSServiceErrorType errorCode, const char *name, + [[maybe_unused]] const char *regtype, + [[maybe_unused]] const char *domain, + [[maybe_unused]] void *context) noexcept +{ + auto &helper = *(BonjourHelper *)context; + + if (errorCode != kDNSServiceErr_NoError) { + LogError(bonjour_domain, + "Failed to register zeroconf service"); + + helper.Cancel(); + } else { + FmtDebug(bonjour_domain, + "Registered zeroconf service with name {:?}", + name); + } +} + +std::unique_ptr +BonjourInit(EventLoop &loop, const char *name, + const char *service_type, unsigned port) +{ + return std::make_unique(loop, name, service_type, port); +} diff --git a/src/zeroconf/Bonjour.hxx b/src/zeroconf/Bonjour.hxx new file mode 100644 index 0000000..f13f737 --- /dev/null +++ b/src/zeroconf/Bonjour.hxx @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ZEROCONF_BONJOUR_HXX +#define MPD_ZEROCONF_BONJOUR_HXX + +#include "event/SocketEvent.hxx" + +#include + +#include + +class EventLoop; + +class BonjourHelper final { + const DNSServiceRef service_ref; + + SocketEvent socket_event; + +public: + BonjourHelper(EventLoop &_loop, const char *name, + const char *service_name, unsigned port); + + ~BonjourHelper() noexcept { + DNSServiceRefDeallocate(service_ref); + } + + BonjourHelper(const BonjourHelper &) = delete; + BonjourHelper &operator=(const BonjourHelper &) = delete; + +private: + void Cancel() noexcept { + socket_event.Cancel(); + } + + static void Callback(DNSServiceRef sdRef, DNSServiceFlags flags, + DNSServiceErrorType errorCode, const char *name, + const char *regtype, + const char *domain, + void *context) noexcept; + + /* virtual methods from class SocketMonitor */ + void OnSocketReady([[maybe_unused]] unsigned flags) noexcept { + DNSServiceProcessResult(service_ref); + } +}; + +/** + * Throws on error. + */ +std::unique_ptr +BonjourInit(EventLoop &loop, const char *name, + const char *service_type, unsigned port); + +#endif diff --git a/src/zeroconf/Glue.cxx b/src/zeroconf/Glue.cxx new file mode 100644 index 0000000..4db46ab --- /dev/null +++ b/src/zeroconf/Glue.cxx @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Glue.hxx" +#include "Helper.hxx" +#include "config/Data.hxx" +#include "config/Option.hxx" +#include "Listen.hxx" +#include "util/Domain.hxx" +#include "Log.hxx" + +#ifdef HAVE_AVAHI +#include "avahi/Helper.hxx" +#endif + +#ifdef HAVE_BONJOUR +#include "Bonjour.hxx" +#endif + +#include + +#include +#include + +#ifndef HOST_NAME_MAX +/* HOST_NAME_MAX is not a portable macro; it is undefined on some + systems */ +#define HOST_NAME_MAX 255 +#endif + +static constexpr Domain zeroconf_domain("zeroconf"); + +/* The default service name to publish + * (overridden by 'zeroconf_name' config parameter) + */ +#define SERVICE_NAME "Music Player @ %h" + +/* The dns-sd service type qualifier to publish */ +#define SERVICE_TYPE "_mpd._tcp" + +#define DEFAULT_ZEROCONF_ENABLED 1 + +std::unique_ptr +ZeroconfInit(const ConfigData &config, [[maybe_unused]] EventLoop &loop) +{ + const char *serviceName; + + if (!config.GetBool(ConfigOption::ZEROCONF_ENABLED, + DEFAULT_ZEROCONF_ENABLED)) + return nullptr; + + if (listen_port <= 0) { + LogWarning(zeroconf_domain, + "No global port, disabling zeroconf"); + return nullptr; + } + + serviceName = config.GetString(ConfigOption::ZEROCONF_NAME, + SERVICE_NAME); + + /* replace "%h" with the host name */ + const char *h = strstr(serviceName, "%h"); + std::string buffer; + if (h != nullptr) { + char hostname[HOST_NAME_MAX+1]; + if (gethostname(hostname, HOST_NAME_MAX) == 0) { + buffer = serviceName; + buffer.replace(h - serviceName, 2, hostname); + serviceName = buffer.c_str(); + } + } + + return std::make_unique(loop, serviceName, + SERVICE_TYPE, listen_port); +} diff --git a/src/zeroconf/Glue.hxx b/src/zeroconf/Glue.hxx new file mode 100644 index 0000000..c9f4bbe --- /dev/null +++ b/src/zeroconf/Glue.hxx @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ZEROCONF_GLUE_HXX +#define MPD_ZEROCONF_GLUE_HXX + +#include "Helper.hxx" +#include "config.h" + +#include + +struct ConfigData; +class EventLoop; +class ZeroconfHelper; + +#ifdef HAVE_ZEROCONF + +/** + * Throws on error. + */ +std::unique_ptr +ZeroconfInit(const ConfigData &config, EventLoop &loop); + +#endif /* ! HAVE_ZEROCONF */ + +#endif diff --git a/src/zeroconf/Helper.cxx b/src/zeroconf/Helper.cxx new file mode 100644 index 0000000..2001375 --- /dev/null +++ b/src/zeroconf/Helper.cxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Helper.hxx" + +#ifdef HAVE_AVAHI +#include "avahi/Helper.hxx" +#define CreateHelper AvahiInit +#endif + +#ifdef HAVE_BONJOUR +#include "Bonjour.hxx" +#define CreateHelper BonjourInit +#endif + +ZeroconfHelper::ZeroconfHelper(EventLoop &event_loop, const char *name, + const char *service_type, unsigned port) + :helper(CreateHelper(event_loop, name, service_type, port)) {} + +ZeroconfHelper::~ZeroconfHelper() noexcept = default; diff --git a/src/zeroconf/Helper.hxx b/src/zeroconf/Helper.hxx new file mode 100644 index 0000000..ce6bc5d --- /dev/null +++ b/src/zeroconf/Helper.hxx @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_ZEROCONF_HELPER_HXX +#define MPD_ZEROCONF_HELPER_HXX + +#include "config.h" + +#include + +class EventLoop; +class AvahiHelper; +class BonjourHelper; + +class ZeroconfHelper final { +#ifdef HAVE_AVAHI + std::unique_ptr helper; +#endif + +#ifdef HAVE_BONJOUR + std::unique_ptr helper; +#endif + +public: + ZeroconfHelper(EventLoop &event_loop, const char *name, + const char *service_type, unsigned port); + + ~ZeroconfHelper() noexcept; +}; + +#endif diff --git a/src/zeroconf/avahi/Helper.cxx b/src/zeroconf/avahi/Helper.cxx new file mode 100644 index 0000000..881c1c4 --- /dev/null +++ b/src/zeroconf/avahi/Helper.cxx @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "Helper.hxx" +#include "lib/avahi/Client.hxx" +#include "lib/avahi/ErrorHandler.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "Log.hxx" + +#include + +class SharedAvahiClient final : public Avahi::ErrorHandler { +public: + Avahi::Client client; + + SharedAvahiClient(EventLoop &event_loop) + :client(event_loop, *this) {} + + /* virtual methods from class Avahi::ErrorHandler */ + bool OnAvahiError(std::exception_ptr e) noexcept override { + LogError(e); + return true; + } +}; + +static std::weak_ptr shared_avahi_client; + +inline +AvahiHelper::AvahiHelper(std::shared_ptr _client, + const char *service_name, + const char *service_type, unsigned port) + :client(std::move(_client)), + publisher(client->client, service_name, *client), + service(AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, + service_type, port) +{ + publisher.AddService(service); +} + +AvahiHelper::~AvahiHelper() noexcept +{ + publisher.RemoveService(service); +} + +std::unique_ptr +AvahiInit(EventLoop &event_loop, const char *service_name, + const char *service_type, unsigned port) +{ + if (!avahi_is_valid_service_name(service_name)) + throw FmtRuntimeError("Invalid zeroconf_name {:?}", + service_name); + + auto client = shared_avahi_client.lock(); + if (!client) + shared_avahi_client = client = + std::make_shared(event_loop); + + return std::make_unique(std::move(client), service_name, + service_type, port); +} diff --git a/src/zeroconf/avahi/Helper.hxx b/src/zeroconf/avahi/Helper.hxx new file mode 100644 index 0000000..083f0e8 --- /dev/null +++ b/src/zeroconf/avahi/Helper.hxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include "lib/avahi/Publisher.hxx" +#include "lib/avahi/Service.hxx" + +#include + +class EventLoop; +namespace Avahi { class Publisher; } + +class SharedAvahiClient; + +class AvahiHelper final { + std::shared_ptr client; + Avahi::Publisher publisher; + Avahi::Service service; + +public: + AvahiHelper(std::shared_ptr _client, + const char *service_name, + const char *service_type, unsigned port); + ~AvahiHelper() noexcept; +}; + +std::unique_ptr +AvahiInit(EventLoop &event_loop, const char *service_name, + const char *service_type, unsigned port); diff --git a/src/zeroconf/avahi/meson.build b/src/zeroconf/avahi/meson.build new file mode 100644 index 0000000..b366169 --- /dev/null +++ b/src/zeroconf/avahi/meson.build @@ -0,0 +1,26 @@ +libavahi_client = dependency('avahi-client', required: get_option('zeroconf') == 'avahi') +if not libavahi_client.found() + avahi_dep = dependency('', required: false) + subdir_done() +endif + +avahi = static_library( + 'avahi', + 'Helper.cxx', + '../../lib/avahi/Client.cxx', + '../../lib/avahi/Error.cxx', + '../../lib/avahi/Poll.cxx', + '../../lib/avahi/Publisher.cxx', + include_directories: inc, + dependencies: [ + log_dep, + libavahi_client, + ], +) + +avahi_dep = declare_dependency( + link_with: avahi, + dependencies: [ + event_dep, + ], +) diff --git a/src/zeroconf/meson.build b/src/zeroconf/meson.build new file mode 100644 index 0000000..754cf68 --- /dev/null +++ b/src/zeroconf/meson.build @@ -0,0 +1,79 @@ +zeroconf_option = get_option('zeroconf') + +avahi_dep = dependency('', required: false) + +if zeroconf_option == 'auto' + if is_darwin + zeroconf_option = 'bonjour' + elif is_android or is_windows + zeroconf_option = 'disabled' + elif dbus_dep.found() + zeroconf_option = 'avahi' + else + zeroconf_option = 'disabled' + endif +endif + +if zeroconf_option == 'disabled' + zeroconf_dep = dependency('', required: false) + subdir_done() +endif + +if zeroconf_option == 'bonjour' + if not compiler.has_header('dns_sd.h') + error('dns_sd.h not found') + endif + + bonjour_deps = [ + ] + + if not is_darwin + bonjour_deps += declare_dependency(link_args: ['-ldns_sd']) + endif + conf.set('HAVE_BONJOUR', true) + + zeroconf = static_library( + 'zeroconf_bonjour', + 'Glue.cxx', + 'Helper.cxx', + 'Bonjour.cxx', + include_directories: inc, + dependencies: [ + event_dep, + log_dep, + ], + ) + + zeroconf_dep = declare_dependency( + link_with: zeroconf, + dependencies: bonjour_deps, + ) +else + subdir('avahi') + + if not avahi_dep.found() + zeroconf_dep = dependency('', required: false) + subdir_done() + endif + + conf.set('HAVE_AVAHI', true) + + zeroconf = static_library( + 'zeroconf_avahi', + 'Glue.cxx', + 'Helper.cxx', + include_directories: inc, + dependencies: [ + avahi_dep, + dbus_dep, + time_dep, + log_dep, + ], + ) + + zeroconf_dep = declare_dependency( + link_with: zeroconf, + ) +endif + +conf.set('HAVE_ZEROCONF', true) diff --git a/subprojects/.gitignore b/subprojects/.gitignore new file mode 100644 index 0000000..3824e72 --- /dev/null +++ b/subprojects/.gitignore @@ -0,0 +1,20 @@ +/packagecache/ + +/curl-*/ +/expat-*/ +/flac-*/ +/fmt-*/ +/googletest-*/ +/lame-*/ +/libid3tag-*/ +/libmicrohttpd* +/libmpdclient/ +/libnpupnp-*/ +/libogg-*/ +/libsndfile-*/ +/libvorbis-*/ +/liburing-*/ +/nlohmann_json-*/ +/openssl-*/ +/opus-*/ +/sqlite-*/ diff --git a/subprojects/curl.wrap b/subprojects/curl.wrap new file mode 100644 index 0000000..f7e384b --- /dev/null +++ b/subprojects/curl.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = curl-8.10.1 +source_url = https://github.com/curl/curl/releases/download/curl-8_10_1/curl-8.10.1.tar.xz +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/curl_8.10.1-1/curl-8.10.1.tar.xz +source_filename = curl-8.10.1.tar.xz +source_hash = 73a4b0e99596a09fa5924a4fb7e4b995a85fda0d18a2c02ab9cf134bebce04ee +patch_filename = curl_8.10.1-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/curl_8.10.1-1/get_patch +patch_hash = 707c28f35fc9b0e8d68c0c2800712007612f922a31da9637ce706a2159f3ddd8 +wrapdb_version = 8.10.1-1 + +[provide] +dependency_names = libcurl diff --git a/subprojects/expat.wrap b/subprojects/expat.wrap new file mode 100644 index 0000000..0e9292f --- /dev/null +++ b/subprojects/expat.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = expat-2.7.1 +source_url = https://github.com/libexpat/libexpat/releases/download/R_2_7_1/expat-2.7.1.tar.xz +source_filename = expat-2.7.1.tar.bz2 +source_hash = 354552544b8f99012e5062f7d570ec77f14b412a3ff5c7d8d0dae62c0d217c30 +patch_filename = expat_2.7.1-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/expat_2.7.1-1/get_patch +patch_hash = fe28cbbc427a7c9787d08b969ad54d19f59d8dd18294b4a18651cecfc789d4ef +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/expat_2.7.1-1/expat-2.7.1.tar.bz2 +wrapdb_version = 2.7.1-1 + +[provide] +expat = expat_dep diff --git a/subprojects/flac.wrap b/subprojects/flac.wrap new file mode 100644 index 0000000..b3e2741 --- /dev/null +++ b/subprojects/flac.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = flac-1.5.0 +source_url = https://github.com/xiph/flac/releases/download/1.5.0/flac-1.5.0.tar.xz +source_filename = flac-1.5.0.tar.xz +source_hash = f2c1c76592a82ffff8413ba3c4a1299b6c7ab06c734dee03fd88630485c2b920 +patch_filename = flac_1.5.0-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/flac_1.5.0-1/get_patch +patch_hash = c3d7dcb01d6e0a2bc066b12e789661fd9c4356500787004cfc1950d52babd6ca +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/flac_1.5.0-1/flac-1.5.0.tar.xz +wrapdb_version = 1.5.0-1 + +[provide] +flac = flac_dep diff --git a/subprojects/fmt.wrap b/subprojects/fmt.wrap new file mode 100644 index 0000000..07223cd --- /dev/null +++ b/subprojects/fmt.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = fmt-11.2.0 +source_url = https://github.com/fmtlib/fmt/archive/11.2.0.tar.gz +source_filename = fmt-11.2.0.tar.gz +source_hash = bc23066d87ab3168f27cef3e97d545fa63314f5c79df5ea444d41d56f962c6af +patch_filename = fmt_11.2.0-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/fmt_11.2.0-1/get_patch +patch_hash = 645bf1c335a24608b4b34f16ed10b9237bbb0131488668fb86454202239e086c +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/fmt_11.2.0-1/fmt-11.2.0.tar.gz +wrapdb_version = 11.2.0-1 + +[provide] +fmt = fmt_dep diff --git a/subprojects/gtest.wrap b/subprojects/gtest.wrap new file mode 100644 index 0000000..ba73d96 --- /dev/null +++ b/subprojects/gtest.wrap @@ -0,0 +1,16 @@ +[wrap-file] +directory = googletest-1.15.2 +source_url = https://github.com/google/googletest/archive/refs/tags/v1.15.2.tar.gz +source_filename = gtest-1.15.2.tar.gz +source_hash = 7b42b4d6ed48810c5362c265a17faebe90dc2373c885e5216439d37927f02926 +patch_filename = gtest_1.15.2-4_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/gtest_1.15.2-4/get_patch +patch_hash = a5151324b97e6a98fa7a0e8095523e6d5c4bb3431210d6ac4ad9800c345acf40 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/gtest_1.15.2-4/gtest-1.15.2.tar.gz +wrapdb_version = 1.15.2-4 + +[provide] +gtest = gtest_dep +gtest_main = gtest_main_dep +gmock = gmock_dep +gmock_main = gmock_main_dep diff --git a/subprojects/id3tag.wrap b/subprojects/id3tag.wrap new file mode 100644 index 0000000..5723b52 --- /dev/null +++ b/subprojects/id3tag.wrap @@ -0,0 +1,9 @@ +[wrap-file] +directory = libid3tag-0.15.1b +source_url = ftp://ftp.mars.org/pub/mpeg/libid3tag-0.15.1b.tar.gz +source_filename = libid3tag-0.15.1b.tar.gz +source_hash = 63da4f6e7997278f8a3fef4c6a372d342f705051d1eeb6a46a86b03610e26151 +patch_directory = id3tag + +[provide] +id3tag = libid3tag_dep diff --git a/subprojects/lame.wrap b/subprojects/lame.wrap new file mode 100644 index 0000000..9bea635 --- /dev/null +++ b/subprojects/lame.wrap @@ -0,0 +1,14 @@ +[wrap-file] +directory = lame-3.100 +source_url = http://downloads.sourceforge.net/project/lame/lame/3.100/lame-3.100.tar.gz +source_filename = lame-3.100.tar.gz +source_hash = ddfe36cab873794038ae2c1210557ad34857a4b6bdc515785d1da9e175b1da1e +patch_filename = lame_3.100-11_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/lame_3.100-11/get_patch +patch_hash = 2cf0d047bfa5d444d5a13b85816d05895e587f61cdf9ee49a7fc40fe360ded0d +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lame_3.100-11/lame-3.100.tar.gz +wrapdb_version = 3.100-11 + +[provide] +mp3lame = lame_dep +mpglib = mpglib_dep diff --git a/subprojects/libmpdclient.wrap b/subprojects/libmpdclient.wrap new file mode 100644 index 0000000..2610fb5 --- /dev/null +++ b/subprojects/libmpdclient.wrap @@ -0,0 +1,6 @@ +[wrap-git] +url = https://github.com/MusicPlayerDaemon/libmpdclient +revision = v2.22 + +[provide] +libmpdclient = libmpdclient_dep diff --git a/subprojects/libnpupnp.wrap b/subprojects/libnpupnp.wrap new file mode 100644 index 0000000..c91d1ee --- /dev/null +++ b/subprojects/libnpupnp.wrap @@ -0,0 +1,10 @@ +[wrap-file] +directory = libnpupnp-6.2.1 +source_url = https://www.lesbonscomptes.com/upmpdcli/downloads/libnpupnp-6.2.1.tar.gz +source_filename = libnpupnp-6.2.1.tar.gz +source_hash = 1cc1222512d480826d2923cc7b98b7361183a2add8c6b646a7fa32c2f34b32b3 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/libnpupnp_6.2.1-1/libnpupnp-6.2.1.tar.gz +wrapdb_version = 6.2.1-1 + +[provide] +libnpupnp = libnpupnp_dep diff --git a/subprojects/libsndfile.wrap b/subprojects/libsndfile.wrap new file mode 100644 index 0000000..f75feb9 --- /dev/null +++ b/subprojects/libsndfile.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = libsndfile-1.2.2 +source_url = https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2.tar.xz +source_filename = libsndfile-1.2.2.tar.xz +source_hash = 3799ca9924d3125038880367bf1468e53a1b7e3686a934f098b7e1d286cdb80e +patch_filename = libsndfile_1.2.2-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/libsndfile_1.2.2-1/get_patch +patch_hash = 0438f3ea86b2facf4fe05f761c717f3b71e144cb59e60504e49ecd25874d67ad +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/libsndfile_1.2.2-1/libsndfile-1.2.2.tar.xz +wrapdb_version = 1.2.2-1 + +[provide] +sndfile = libsndfile_dep diff --git a/subprojects/liburing.wrap b/subprojects/liburing.wrap new file mode 100644 index 0000000..00de3a7 --- /dev/null +++ b/subprojects/liburing.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = liburing-liburing-2.5 +source_url = https://github.com/axboe/liburing/archive/refs/tags/liburing-2.5.tar.gz +source_filename = liburing-2.5.tar.gz +source_hash = 456f5f882165630f0dc7b75e8fd53bd01a955d5d4720729b4323097e6e9f2a98 +patch_filename = liburing_2.5-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/liburing_2.5-1/get_patch +patch_hash = d72f651e0edd8102535af575d682ce86c3fc2fdabb40b8faa2659d0f7d437f44 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/liburing_2.5-1/liburing-2.5.tar.gz +wrapdb_version = 2.5-1 + +[provide] +dependency_names = liburing diff --git a/subprojects/nlohmann_json.wrap b/subprojects/nlohmann_json.wrap new file mode 100644 index 0000000..f9bb22d --- /dev/null +++ b/subprojects/nlohmann_json.wrap @@ -0,0 +1,11 @@ +[wrap-file] +directory = nlohmann_json-3.12.0 +lead_directory_missing = true +source_url = https://github.com/nlohmann/json/releases/download/v3.12.0/include.zip +source_filename = nlohmann_json-3.12.0.zip +source_hash = b8cb0ef2dd7f57f18933997c9934bb1fa962594f701cd5a8d3c2c80541559372 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/nlohmann_json_3.12.0-1/nlohmann_json-3.12.0.zip +wrapdb_version = 3.12.0-1 + +[provide] +nlohmann_json = nlohmann_json_dep diff --git a/subprojects/ogg.wrap b/subprojects/ogg.wrap new file mode 100644 index 0000000..e7f23eb --- /dev/null +++ b/subprojects/ogg.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = libogg-1.3.5 +source_url = https://downloads.xiph.org/releases/ogg/libogg-1.3.5.tar.xz +source_filename = libogg-1.3.5.tar.xz +source_hash = c4d91be36fc8e54deae7575241e03f4211eb102afb3fc0775fbbc1b740016705 +patch_filename = ogg_1.3.5-6_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/ogg_1.3.5-6/get_patch +patch_hash = 8be6dcd5f93bbf9c0b9c8ec1fa29810226a60f846383074ca05b313a248e78b2 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/ogg_1.3.5-6/libogg-1.3.5.tar.xz +wrapdb_version = 1.3.5-6 + +[provide] +ogg = libogg_dep diff --git a/subprojects/openssl.wrap b/subprojects/openssl.wrap new file mode 100644 index 0000000..873d551 --- /dev/null +++ b/subprojects/openssl.wrap @@ -0,0 +1,15 @@ +[wrap-file] +directory = openssl-3.0.8 +source_url = https://www.openssl.org/source/openssl-3.0.8.tar.gz +source_filename = openssl-3.0.8.tar.gz +source_hash = 6c13d2bf38fdf31eac3ce2a347073673f5d63263398f1f69d0df4a41253e4b3e +patch_filename = openssl_3.0.8-3_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/openssl_3.0.8-3/get_patch +patch_hash = 300da189e106942347d61a4a4295aa2edbcf06184f8d13b4cee0bed9fb936963 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/openssl_3.0.8-3/openssl-3.0.8.tar.gz +wrapdb_version = 3.0.8-3 + +[provide] +libcrypto = libcrypto_dep +libssl = libssl_dep +openssl = openssl_dep diff --git a/subprojects/opus.wrap b/subprojects/opus.wrap new file mode 100644 index 0000000..357643b --- /dev/null +++ b/subprojects/opus.wrap @@ -0,0 +1,10 @@ +[wrap-file] +directory = opus-1.5.2 +source_url = https://downloads.xiph.org/releases/opus/opus-1.5.2.tar.gz +source_filename = opus-1.5.2.tar.gz +source_hash = 65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/opus_1.5.2-1/opus-1.5.2.tar.gz +wrapdb_version = 1.5.2-1 + +[provide] +opus = opus_dep diff --git a/subprojects/packagefiles/id3tag/meson.build b/subprojects/packagefiles/id3tag/meson.build new file mode 100644 index 0000000..409a702 --- /dev/null +++ b/subprojects/packagefiles/id3tag/meson.build @@ -0,0 +1,39 @@ +project( + 'libid3tag', 'c', + version: '0.15.1b', + license: 'GPLv2+', +) + +compiler = meson.get_compiler('c') + +conf = configuration_data() +conf.set('HAVE_ASSERT_H', true) +conf.set('HAVE_FTRUNCATE', compiler.has_function('ftruncate')) +conf.set('HAVE_INTTYPES_H', true) +conf.set('HAVE_LIBZ', false) # TODO +conf.set('HAVE_STDINT_H', true) +conf.set('HAVE_STDIO_H', true) +conf.set('HAVE_STDLIB_H', true) +conf.set('HAVE_STRINGS_H', true) +conf.set('HAVE_STRING_H', true) +conf.set('HAVE_SYS_STAT_H', compiler.has_header('sys/stat.h')) +conf.set('HAVE_SYS_TYPES_H', true) +conf.set('HAVE_UNISTD_H', compiler.has_header('unistd.h')) +configure_file(output: 'config.h', configuration: conf) + +add_project_arguments('-DHAVE_CONFIG_H', language: 'c') + +libid3tag = static_library( + 'id3tag', + 'version.c', 'ucs4.c', 'latin1.c', 'utf16.c', 'utf8.c', + 'parse.c', 'render.c', 'field.c', 'frametype.c', 'compat.c', + 'genre.c', 'frame.c', 'crc.c', 'util.c', 'tag.c', 'file.c', +) + +libid3tag_dep = declare_dependency( + link_with: libid3tag, + dependencies: [ + dependency('zlib'), + ], + include_directories: include_directories('.'), +) diff --git a/subprojects/sqlite3.wrap b/subprojects/sqlite3.wrap new file mode 100644 index 0000000..1d16669 --- /dev/null +++ b/subprojects/sqlite3.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = sqlite-amalgamation-3490200 +source_url = https://www.sqlite.org/2025/sqlite-amalgamation-3490200.zip +source_filename = sqlite-amalgamation-3490200.zip +source_hash = 921fc725517a694df7df38a2a3dfede6684024b5788d9de464187c612afb5918 +patch_filename = sqlite3_3.49.2-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/sqlite3_3.49.2-1/get_patch +patch_hash = e3eef046409329c5c1ca8308255caa2266710fc1b9d8695fdedd04cebe42a690 +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sqlite3_3.49.2-1/sqlite-amalgamation-3490200.zip +wrapdb_version = 3.49.2-1 + +[provide] +sqlite3 = sqlite3_dep diff --git a/subprojects/vorbis.wrap b/subprojects/vorbis.wrap new file mode 100644 index 0000000..7425c11 --- /dev/null +++ b/subprojects/vorbis.wrap @@ -0,0 +1,14 @@ +[wrap-file] +directory = libvorbis-1.3.7 +source_url = https://downloads.xiph.org/releases/vorbis/libvorbis-1.3.7.tar.xz +source_filename = libvorbis-1.3.7.tar.xz +source_hash = b33cc4934322bcbf6efcbacf49e3ca01aadbea4114ec9589d1b1e9d20f72954b +patch_filename = vorbis_1.3.7-4_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/vorbis_1.3.7-4/get_patch +patch_hash = 979e22b24b16c927040700dfd8319cd6ba29bf52a14dbc66b1cb4ea60504f14a +wrapdb_version = 1.3.7-4 + +[provide] +vorbis = vorbis_dep +vorbisfile = vorbisfile_dep +vorbisenc = vorbisenc_dep diff --git a/systemd/meson.build b/systemd/meson.build new file mode 100644 index 0000000..1ae36c0 --- /dev/null +++ b/systemd/meson.build @@ -0,0 +1,22 @@ +systemd_unit_conf = configuration_data() +systemd_unit_conf.set('prefix', get_option('prefix')) + +address_families = ['AF_INET', 'AF_INET6', 'AF_UNIX'] +if get_option('smbclient').enabled() + # AF_NETLINK is required by libsmbclient, or it will exit() .. *sigh* + address_families += 'AF_NETLINK' +endif +systemd_unit_conf.set('address_families', ' '.join(address_families)) + +systemd_socket_conf = configuration_data() +listen_streams = [] +if get_option('local_socket') + listen_streams += 'ListenStream=%t/mpd/socket' +endif +if get_option('tcp') + listen_streams += 'ListenStream=6600' +endif +systemd_socket_conf.set('listen_streams', '\n'.join(listen_streams)) + +subdir('system') +subdir('user') diff --git a/systemd/system/meson.build b/systemd/system/meson.build new file mode 100644 index 0000000..3484982 --- /dev/null +++ b/systemd/system/meson.build @@ -0,0 +1,27 @@ +systemd_system_unit_dir = get_option('systemd_system_unit_dir') +if systemd_system_unit_dir == '' + systemd = dependency('systemd', required: false) + if systemd.found() + systemd_system_unit_dir = systemd.get_variable( + pkgconfig: 'systemdsystemunitdir', + pkgconfig_define: ['rootprefix', get_option('prefix')], + ) + endif +endif +if systemd_system_unit_dir == '' + systemd_system_unit_dir = join_paths(get_option('prefix'), 'lib', 'systemd', 'system') +endif + +configure_file( + input: 'mpd.socket.in', + output: 'mpd.socket', + configuration: systemd_socket_conf, + install_dir: systemd_system_unit_dir, +) + +configure_file( + input: 'mpd.service.in', + output: 'mpd.service', + configuration: systemd_unit_conf, + install_dir: systemd_system_unit_dir, +) diff --git a/systemd/system/mpd.service.in b/systemd/system/mpd.service.in new file mode 100644 index 0000000..fcb4b52 --- /dev/null +++ b/systemd/system/mpd.service.in @@ -0,0 +1,35 @@ +[Unit] +Description=Music Player Daemon +Documentation=man:mpd(1) man:mpd.conf(5) +After=network.target sound.target + +[Service] +Type=notify +ExecStart=@prefix@/bin/mpd --systemd + +# Enable this setting to ask systemd to watch over MPD, see +# systemd.service(5). This is disabled by default because it causes +# periodic wakeups which are unnecessary if MPD is not playing. +#WatchdogSec=120 + +# allow MPD to use real-time priority 40 +LimitRTPRIO=40 +LimitRTTIME=infinity + +# for io_uring +LimitMEMLOCK=64M + +# disallow writing to /usr, /bin, /sbin, ... +ProtectSystem=yes + +# more paranoid security settings +NoNewPrivileges=yes +ProtectKernelTunables=yes +ProtectControlGroups=yes +ProtectKernelModules=yes +RestrictAddressFamilies=@address_families@ +RestrictNamespaces=yes + +[Install] +WantedBy=multi-user.target +Also=mpd.socket diff --git a/systemd/system/mpd.socket.in b/systemd/system/mpd.socket.in new file mode 100644 index 0000000..793581e --- /dev/null +++ b/systemd/system/mpd.socket.in @@ -0,0 +1,8 @@ +[Socket] +@listen_streams@ +Backlog=5 +KeepAlive=true +PassCredentials=true + +[Install] +WantedBy=sockets.target diff --git a/systemd/user/meson.build b/systemd/user/meson.build new file mode 100644 index 0000000..892876d --- /dev/null +++ b/systemd/user/meson.build @@ -0,0 +1,27 @@ +systemd_user_unit_dir = get_option('systemd_user_unit_dir') +if systemd_user_unit_dir == '' + systemd = dependency('systemd', required: false) + if systemd.found() + systemd_user_unit_dir = systemd.get_variable( + pkgconfig: 'systemduserunitdir', + pkgconfig_define: ['prefix', get_option('prefix')], + ) + endif +endif +if systemd_user_unit_dir == '' + systemd_user_unit_dir = join_paths(get_option('prefix'), 'lib', 'systemd', 'user') +endif + +configure_file( + input: join_paths('..', 'system', 'mpd.socket.in'), + output: 'mpd.socket', + configuration: systemd_socket_conf, + install_dir: systemd_user_unit_dir, +) + +configure_file( + input: 'mpd.service.in', + output: 'mpd.service', + configuration: systemd_unit_conf, + install_dir: systemd_user_unit_dir, +) diff --git a/systemd/user/mpd.service.in b/systemd/user/mpd.service.in new file mode 100644 index 0000000..16ad03b --- /dev/null +++ b/systemd/user/mpd.service.in @@ -0,0 +1,40 @@ +[Unit] +Description=Music Player Daemon +Documentation=man:mpd(1) man:mpd.conf(5) +After=network.target sound.target + +[Service] +Type=notify +ExecStart=@prefix@/bin/mpd --systemd + +# Enable this setting to ask systemd to watch over MPD, see +# systemd.service(5). This is disabled by default because it causes +# periodic wakeups which are unnecessary if MPD is not playing. +#WatchdogSec=120 + +# allow MPD to use real-time priority 40 +LimitRTPRIO=40 +LimitRTTIME=infinity + +# for io_uring +LimitMEMLOCK=64M + +# Required in order for ProtectSystem= (and other sandboxing) to work +PrivateUsers=yes +# disallow writing to /usr, /bin, /sbin, ... +ProtectSystem=yes + +# more paranoid security settings +NoNewPrivileges=yes +ProtectKernelTunables=yes +ProtectControlGroups=yes +RestrictAddressFamilies=@address_families@ +RestrictNamespaces=yes + +# Note that "ProtectKernelModules=yes" is missing in the user unit +# because systemd 232 is unable to reduce its own capabilities +# ("Failed at step CAPABILITIES spawning /usr/bin/mpd: Operation not +# permitted") + +[Install] +WantedBy=default.target diff --git a/test/ConfigGlue.hxx b/test/ConfigGlue.hxx new file mode 100644 index 0000000..468d7fd --- /dev/null +++ b/test/ConfigGlue.hxx @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TEST_CONFIG_GLUE_HXX +#define MPD_TEST_CONFIG_GLUE_HXX + +#include "config/File.hxx" +#include "config/Migrate.hxx" +#include "config/Data.hxx" +#include "fs/Path.hxx" + +inline ConfigData +AutoLoadConfigFile(Path path) +{ + ConfigData data; + + if (!path.IsNull()) { + ReadConfigFile(data, path); + Migrate(data); + } + + return data; +} + +#endif diff --git a/test/ContainerScan.cxx b/test/ContainerScan.cxx new file mode 100644 index 0000000..305e6b5 --- /dev/null +++ b/test/ContainerScan.cxx @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "song/DetachedSong.hxx" +#include "SongSave.hxx" +#include "config/Data.hxx" +#include "decoder/DecoderList.hxx" +#include "decoder/DecoderPlugin.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "io/StdioOutputStream.hxx" +#include "io/BufferedOutputStream.hxx" +#include "util/PrintException.hxx" +#include "util/UriExtract.hxx" + +#include +#include + +#include +#include +#include + +static const DecoderPlugin * +FindContainerDecoderPlugin(std::string_view suffix) +{ + return decoder_plugins_find([suffix](const DecoderPlugin &plugin){ + return plugin.container_scan != nullptr && + plugin.SupportsSuffix(suffix); + }); +} + +static const DecoderPlugin * +FindContainerDecoderPlugin(Path path) +{ + const auto path_utf8 = path.ToUTF8Throw(); + const auto suffix = uri_get_suffix(path_utf8); + if (suffix.empty()) + return nullptr; + + return FindContainerDecoderPlugin(suffix); +} + +int main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: ContainerScan PATH\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath path = argv[1]; + + const ScopeDecoderPluginsInit decoder_plugins_init({}); + + const auto *plugin = FindContainerDecoderPlugin(path); + if (plugin == nullptr) { + fprintf(stderr, "No decoder found for this file\n"); + return EXIT_FAILURE; + } + + const auto v = plugin->container_scan(path); + if (v.empty()) { + fprintf(stderr, "File is not a container\n"); + return EXIT_FAILURE; + } + + StdioOutputStream sos(stdout); + BufferedOutputStream bos(sos); + + for (const auto &song : v) + song_save(bos, song); + + bos.Flush(); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/DumpDatabase.cxx b/test/DumpDatabase.cxx new file mode 100644 index 0000000..ec9e57a --- /dev/null +++ b/test/DumpDatabase.cxx @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "db/Registry.hxx" +#include "db/Configured.hxx" +#include "db/Interface.hxx" +#include "db/Selection.hxx" +#include "db/DatabaseListener.hxx" +#include "db/LightDirectory.hxx" +#include "song/LightSong.hxx" +#include "db/PlaylistVector.hxx" +#include "ConfigGlue.hxx" +#include "tag/Config.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "event/Thread.hxx" +#include "util/ScopeExit.hxx" +#include "util/PrintException.hxx" + +#include + +#include + +#include + +class GlobalInit { + EventThread io_thread; + +public: + GlobalInit() { + io_thread.Start(); + } + + ~GlobalInit() = default; + + EventLoop &GetEventLoop() { + return io_thread.GetEventLoop(); + } +}; + +#ifdef ENABLE_UPNP +#include "input/InputStream.hxx" +size_t +InputStream::LockRead(std::span) +{ + return 0; +} +#endif + +class MyDatabaseListener final : public DatabaseListener { +public: + void OnDatabaseModified() noexcept override { + fmt::print("DatabaseModified\n"); + } + + void OnDatabaseSongRemoved(const char *uri) noexcept override { + fmt::print("SongRemoved {:?}\n", uri); + } +}; + +static void +DumpDirectory(const LightDirectory &directory) +{ + fmt::print("D {}\n", directory.GetPath()); +} + +static void +DumpSong(const LightSong &song) +{ + if (song.directory != nullptr) + fmt::print("S {}/{}\n", song.directory, song.uri); + else + fmt::print("S {}\n", song.uri); +} + +static void +DumpPlaylist(const PlaylistInfo &playlist, const LightDirectory &directory) +{ + fmt::print("P {}/{}\n", directory.GetPath(), playlist.name); +} + +int +main(int argc, char **argv) +try { + if (argc < 2 || argc > 3) { + fmt::print(stderr, "Usage: DumpDatabase CONFIG [URI]\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath config_path = argv[1]; + + const char *uri = argc >= 3 ? argv[2] : ""; + + /* initialize MPD */ + + GlobalInit init; + + const auto config = AutoLoadConfigFile(config_path); + + TagLoadConfig(config); + + MyDatabaseListener database_listener; + + /* do it */ + + auto db = CreateConfiguredDatabase(config, + init.GetEventLoop(), + init.GetEventLoop(), + database_listener); + + db->Open(); + + AtScopeExit(&db) { db->Close(); }; + + const DatabaseSelection selection(uri, true); + + db->Visit(selection, DumpDirectory, DumpSong, DumpPlaylist); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/DumpDecoderClient.cxx b/test/DumpDecoderClient.cxx new file mode 100644 index 0000000..67916e1 --- /dev/null +++ b/test/DumpDecoderClient.cxx @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "DumpDecoderClient.hxx" +#include "lib/fmt/AudioFormatFormatter.hxx" +#include "decoder/DecoderAPI.hxx" +#include "input/InputStream.hxx" +#include "tag/Names.hxx" +#include "util/StringBuffer.hxx" + +#include +#include + +void +DumpDecoderClient::Ready(const AudioFormat audio_format, + bool seekable, + SignedSongTime duration) noexcept +{ + assert(!initialized); + assert(audio_format.IsValid()); + + fmt::print(stderr, "audio_format={} duration={} seekable={}\n", + audio_format, duration.ToDoubleS(), seekable); + + initialized = true; +} + +DecoderCommand +DumpDecoderClient::GetCommand() noexcept +{ + return DecoderCommand::NONE; +} + +void +DumpDecoderClient::CommandFinished() noexcept +{ +} + +SongTime +DumpDecoderClient::GetSeekTime() noexcept +{ + return SongTime(); +} + +uint64_t +DumpDecoderClient::GetSeekFrame() noexcept +{ + return 1; +} + +void +DumpDecoderClient::SeekError() noexcept +{ +} + +InputStreamPtr +DumpDecoderClient::OpenUri(std::string_view uri) +{ + return InputStream::OpenReady(uri, mutex); +} + +size_t +DumpDecoderClient::Read(InputStream &is, std::span dest) noexcept +{ + try { + return is.LockRead(dest); + } catch (...) { + return 0; + } +} + +void +DumpDecoderClient::SubmitTimestamp([[maybe_unused]] FloatDuration t) noexcept +{ +} + +DecoderCommand +DumpDecoderClient::SubmitAudio([[maybe_unused]] InputStream *is, + std::span audio, + [[maybe_unused]] uint16_t kbit_rate) noexcept +{ + if (kbit_rate != prev_kbit_rate) { + prev_kbit_rate = kbit_rate; + fmt::print(stderr, "{} kbit/s\n", kbit_rate); + } + + [[maybe_unused]] ssize_t nbytes = write(STDOUT_FILENO, + audio.data(), audio.size()); + return GetCommand(); +} + +DecoderCommand +DumpDecoderClient::SubmitTag([[maybe_unused]] InputStream *is, + Tag &&tag) noexcept +{ + fmt::print(stderr, "TAG: duration={}\n", tag.duration.ToDoubleS()); + + for (const auto &i : tag) + fmt::print(stderr, " {}={:?}\n", tag_item_names[i.type], i.value); + + return GetCommand(); +} + +static void +DumpReplayGainTuple(const char *name, const ReplayGainTuple &tuple) noexcept +{ + if (tuple.IsDefined()) + fmt::print(stderr, "replay_gain[{}]: gain={} peak={}\n", + name, tuple.gain, tuple.peak); +} + +static void +DumpReplayGainInfo(const ReplayGainInfo &info) noexcept +{ + DumpReplayGainTuple("album", info.album); + DumpReplayGainTuple("track", info.track); +} + +void +DumpDecoderClient::SubmitReplayGain(const ReplayGainInfo *rgi) noexcept +{ + if (rgi != nullptr) + DumpReplayGainInfo(*rgi); +} + +void +DumpDecoderClient::SubmitMixRamp([[maybe_unused]] MixRampInfo &&mix_ramp) noexcept +{ + fmt::print(stderr, "MixRamp: start={:?} end={:?}\n", + mix_ramp.GetStart(), mix_ramp.GetEnd()); +} diff --git a/test/DumpDecoderClient.hxx b/test/DumpDecoderClient.hxx new file mode 100644 index 0000000..d35fd60 --- /dev/null +++ b/test/DumpDecoderClient.hxx @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef DUMP_DECODER_CLIENT_HXX +#define DUMP_DECODER_CLIENT_HXX + +#include "decoder/Client.hxx" +#include "thread/Mutex.hxx" + +/** + * A #DecoderClient implementation which dumps metadata to stderr and + * decoded data to stdout. + */ +class DumpDecoderClient : public DecoderClient { + bool initialized = false; + + uint16_t prev_kbit_rate = 0; + +public: + Mutex mutex; + + bool IsInitialized() const noexcept { + return initialized; + } + + /* virtual methods from DecoderClient */ + void Ready(AudioFormat audio_format, + bool seekable, SignedSongTime duration) noexcept override; + DecoderCommand GetCommand() noexcept override; + void CommandFinished() noexcept override; + SongTime GetSeekTime() noexcept override; + uint64_t GetSeekFrame() noexcept override; + void SeekError() noexcept override; + InputStreamPtr OpenUri(std::string_view uri) override; + size_t Read(InputStream &is, + std::span dest) noexcept override; + void SubmitTimestamp(FloatDuration t) noexcept override; + DecoderCommand SubmitAudio(InputStream *is, + std::span audio, + uint16_t kbit_rate) noexcept override; + DecoderCommand SubmitTag(InputStream *is, Tag &&tag) noexcept override; + void SubmitReplayGain(const ReplayGainInfo *replay_gain_info) noexcept override; + void SubmitMixRamp(MixRampInfo &&mix_ramp) noexcept override; +}; + +#endif diff --git a/test/DumpOgg.cxx b/test/DumpOgg.cxx new file mode 100644 index 0000000..12679c6 --- /dev/null +++ b/test/DumpOgg.cxx @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "lib/xiph/OggSyncState.hxx" +#include "lib/xiph/OggStreamState.hxx" +#include "config/Data.hxx" +#include "input/Init.hxx" +#include "input/InputStream.hxx" +#include "input/Reader.hxx" +#include "event/Thread.hxx" +#include "util/PrintException.hxx" + +#include +#include + +int +main(int argc, char **argv) noexcept +try { + if (argc != 2) { + fprintf(stderr, "Usage: DumpOgg FILE\n"); + return EXIT_FAILURE; + } + + const char *path = argv[1]; + + EventThread io_thread; + io_thread.Start(); + + const ScopeInputPluginsInit input_plugins_init(ConfigData(), + io_thread.GetEventLoop()); + + Mutex mutex; + auto is = InputStream::OpenReady(path, mutex); + + InputStreamReader reader{*is}; + + OggSyncState sync{reader}; + + while (true) { + ogg_page page; + if (!sync.ExpectPage(page)) + break; + + printf("page offset=%" PRIu64 " serial=%d\n", + sync.GetStartOffset(), ogg_page_serialno(&page)); + } + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/LoadDatabase.cxx b/test/LoadDatabase.cxx new file mode 100644 index 0000000..7e62890 --- /dev/null +++ b/test/LoadDatabase.cxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "db/plugins/simple/DatabaseSave.hxx" +#include "db/plugins/simple/Directory.hxx" +#include "lib/zlib/AutoGunzipFileLineReader.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "util/PrintException.hxx" + +int +main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: LoadDatabase PATH\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath db_path = argv[1]; + + Directory root{{}, nullptr}; + AutoGunzipFileLineReader line_reader{db_path}; + db_load_internal(line_reader, root, true); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/MakeTag.hxx b/test/MakeTag.hxx new file mode 100644 index 0000000..20317df --- /dev/null +++ b/test/MakeTag.hxx @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "tag/Builder.hxx" +#include "tag/Tag.hxx" + +inline void +BuildTag([[maybe_unused]] TagBuilder &tag) noexcept +{ +} + +template +inline void +BuildTag(TagBuilder &tag, TagType type, const char *value, + Args&&... args) noexcept +{ + tag.AddItem(type, value); + BuildTag(tag, std::forward(args)...); +} + +template +inline Tag +MakeTag(Args&&... args) noexcept +{ + TagBuilder tag; + BuildTag(tag, std::forward(args)...); + return tag.Commit(); +} diff --git a/test/NullMixerListener.hxx b/test/NullMixerListener.hxx new file mode 100644 index 0000000..c28abff --- /dev/null +++ b/test/NullMixerListener.hxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef NULL_MIXER_LISTENER_HXX +#define NULL_MIXER_LISTENER_HXX + +#include "mixer/Listener.hxx" + +class NullMixerListener : public MixerListener { +public: + void OnMixerVolumeChanged(Mixer &, int) noexcept override {} + virtual void OnMixerChanged() noexcept override {} +}; + +#endif diff --git a/test/ParseSongFilter.cxx b/test/ParseSongFilter.cxx new file mode 100644 index 0000000..ff04178 --- /dev/null +++ b/test/ParseSongFilter.cxx @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This program is a command line interface to SongFilter::Parse(). + * + */ + +#include "song/Filter.hxx" +#include "util/PrintException.hxx" + +#include + +#include +#include + +int main(int argc, char **argv) +try { + if (argc < 2) { + fprintf(stderr, "Usage: ParseSongFilter FILTER ...\n"); + return 1; + } + + SongFilter filter; + filter.Parse({argv + 1, std::size_t(argc - 1)}); + filter.Optimize(); + + puts(filter.ToExpression().c_str()); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/ReadApeTags.cxx b/test/ReadApeTags.cxx new file mode 100644 index 0000000..f88ae25 --- /dev/null +++ b/test/ReadApeTags.cxx @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "tag/ApeLoader.hxx" +#include "thread/Mutex.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "util/PrintException.hxx" + +#include +#include + +#ifdef HAVE_LOCALE_H +#include +#endif + +static bool +MyApeTagCallback([[maybe_unused]] unsigned long flags, + const char *key, std::string_view value) +{ + if ((flags & (0x3 << 1)) == 0) + // UTF-8 + printf("\"%s\"=\"%.*s\"\n", key, + (int)value.size(), value.data()); + else + printf("\"%s\"=0x%lx\n", key, flags); + return true; +} + +int +main(int argc, char **argv) +try { +#ifdef HAVE_LOCALE_H + /* initialize locale */ + setlocale(LC_CTYPE,""); +#endif + + if (argc != 2) { + fprintf(stderr, "Usage: ReadApeTags FILE\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath path = argv[1]; + + Mutex mutex; + + auto is = OpenLocalInputStream(path, mutex); + + if (!tag_ape_scan(*is, MyApeTagCallback)) { + fprintf(stderr, "error\n"); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/ReadFrames.cxx b/test/ReadFrames.cxx new file mode 100644 index 0000000..d6fe3f4 --- /dev/null +++ b/test/ReadFrames.cxx @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ReadFrames.hxx" +#include "system/Error.hxx" +#include "io/FileDescriptor.hxx" + +static size_t +ReadOrThrow(FileDescriptor fd, std::span dest) +{ + auto nbytes = fd.Read(dest); + if (nbytes < 0) + throw MakeErrno("Read failed"); + + return nbytes; +} + +std::size_t +ReadFrames(FileDescriptor fd, void *_buffer, std::size_t size, + std::size_t frame_size) +{ + auto buffer = (std::byte *)_buffer; + + size = (size / frame_size) * frame_size; + + size_t nbytes = ReadOrThrow(fd, {buffer, size}); + + const size_t modulo = nbytes % frame_size; + if (modulo > 0) { + size_t rest = frame_size - modulo; + fd.FullRead({(std::byte *)buffer + nbytes, rest}); + nbytes += rest; + } + + return nbytes; +} diff --git a/test/ReadFrames.hxx b/test/ReadFrames.hxx new file mode 100644 index 0000000..4869200 --- /dev/null +++ b/test/ReadFrames.hxx @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include + +class FileDescriptor; + +std::size_t +ReadFrames(FileDescriptor fd, void *buffer, std::size_t size, + std::size_t frame_size); diff --git a/test/RunChromaprint.cxx b/test/RunChromaprint.cxx new file mode 100644 index 0000000..172ed24 --- /dev/null +++ b/test/RunChromaprint.cxx @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ConfigGlue.hxx" +#include "pcm/Convert.hxx" +#include "lib/chromaprint/DecoderClient.hxx" +#include "event/Thread.hxx" +#include "decoder/DecoderList.hxx" +#include "decoder/DecoderPlugin.hxx" +#include "decoder/DecoderAPI.hxx" /* for class StopDecoder */ +#include "input/Init.hxx" +#include "input/InputStream.hxx" +#include "fs/NarrowPath.hxx" +#include "fs/Path.hxx" +#include "pcm/AudioFormat.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "util/PrintException.hxx" +#include "Log.hxx" +#include "LogBackend.hxx" + +#include +#include + +#include +#include +#include + +struct CommandLine { + const char *decoder = nullptr; + const char *uri = nullptr; + + FromNarrowPath config_path = nullptr; + + bool verbose = false; +}; + +enum Option { + OPTION_CONFIG, + OPTION_VERBOSE, +}; + +static constexpr OptionDef option_defs[] = { + {"config", 0, true, "Load a MPD configuration file"}, + {"verbose", 'v', false, "Verbose logging"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_CONFIG: + c.config_path = o.value; + break; + + case OPTION_VERBOSE: + c.verbose = true; + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() != 2) + throw std::runtime_error("Usage: RunChromaprint [--verbose] [--config=FILE] DECODER URI"); + + c.decoder = args[0]; + c.uri = args[1]; + return c; +} + +class GlobalInit { + const ConfigData config; + EventThread io_thread; + const ScopeInputPluginsInit input_plugins_init; + const ScopeDecoderPluginsInit decoder_plugins_init; + +public: + explicit GlobalInit(Path config_path) + :config(AutoLoadConfigFile(config_path)), + input_plugins_init(config, io_thread.GetEventLoop()), + decoder_plugins_init(config) + { + io_thread.Start(); + + pcm_convert_global_init(config); + } +}; + +class MyChromaprintDecoderClient final : public ChromaprintDecoderClient { +public: + InputStreamPtr OpenUri(std::string_view) override { + throw std::runtime_error("Not implemented"); + } +}; + +int main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + const GlobalInit init(c.config_path); + + const DecoderPlugin *plugin = decoder_plugin_from_name(c.decoder); + if (plugin == nullptr) { + fprintf(stderr, "No such decoder: %s\n", c.decoder); + return EXIT_FAILURE; + } + + MyChromaprintDecoderClient client; + if (plugin->file_decode != nullptr) { + try { + plugin->FileDecode(client, FromNarrowPath(c.uri)); + } catch (StopDecoder) { + } + } else if (plugin->stream_decode != nullptr) { + auto is = InputStream::OpenReady(c.uri, client.mutex); + try { + plugin->StreamDecode(client, *is); + } catch (StopDecoder) { + } + } else { + fprintf(stderr, "Decoder plugin is not usable\n"); + return EXIT_FAILURE; + } + + client.Finish(); + printf("%s\n", client.GetFingerprint().c_str()); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/RunCurl.cxx b/test/RunCurl.cxx new file mode 100644 index 0000000..f00c982 --- /dev/null +++ b/test/RunCurl.cxx @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ShutdownHandler.hxx" +#include "lib/curl/Global.hxx" +#include "lib/curl/Request.hxx" +#include "lib/curl/Handler.hxx" +#include "event/Loop.hxx" +#include "util/PrintException.hxx" + +#include + +class MyHandler final : public CurlResponseHandler { + EventLoop &event_loop; + + std::exception_ptr error; + +public: + explicit MyHandler(EventLoop &_event_loop) noexcept + :event_loop(_event_loop) {} + + void Finish() { + if (error) + std::rethrow_exception(error); + } + + /* virtual methods from CurlResponseHandler */ + void OnHeaders(unsigned status, Curl::Headers &&headers) override { + fprintf(stderr, "status: %u\n", status); + for (const auto &i : headers) + fprintf(stderr, "%s: %s\n", + i.first.c_str(), i.second.c_str()); + } + + void OnData(std::span data) override { + try { + if (fwrite(data.data(), data.size(), 1, stdout) != 1) + throw std::runtime_error("Failed to write"); + } catch (...) { + OnError(std::current_exception()); + } + } + + void OnEnd() override { + event_loop.Break(); + } + + void OnError(std::exception_ptr e) noexcept override { + error = std::move(e); + event_loop.Break(); + } +}; + +int +main(int argc, char **argv) noexcept +try { + if (argc != 2) { + fprintf(stderr, "Usage: RunCurl URI\n"); + return EXIT_FAILURE; + } + + const char *const uri = argv[1]; + + EventLoop event_loop; + const ShutdownHandler shutdown_handler(event_loop); + CurlGlobal curl_global(event_loop); + + MyHandler handler(event_loop); + CurlRequest request(curl_global, uri, handler); + request.Start(); + + event_loop.Run(); + + handler.Finish(); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/RunMixRampAnalyzer.cxx b/test/RunMixRampAnalyzer.cxx new file mode 100644 index 0000000..30e52ae --- /dev/null +++ b/test/RunMixRampAnalyzer.cxx @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ReadFrames.hxx" +#include "pcm/MixRampAnalyzer.hxx" +#include "io/FileDescriptor.hxx" +#include "util/PrintException.hxx" + +#include +#include + +#include +#include + +int +main(int, char **) noexcept +try { + constexpr std::size_t frame_size = sizeof(ReplayGainAnalyzer::Frame); + + const FileDescriptor input_fd(STDIN_FILENO); + + MixRampAnalyzer a; + + while (true) { + std::array buffer; + + size_t nbytes = ReadFrames(input_fd, + buffer.data(), sizeof(buffer), + frame_size); + if (nbytes == 0) + break; + + const std::size_t n_frames = nbytes / frame_size; + a.Process({buffer.data(), n_frames}); + } + + const auto data = a.GetResult(); + + const auto total_time = a.GetTime(); + + printf("MIXRAMP_START="); + + MixRampItem last{}; + + for (const auto &i : data.start) { + if (i.time >= FloatDuration{} && i != last) { + printf("%.2f %.2f;", i.volume, i.time.count()); + last = i; + } + } + + printf("\n"); + + printf("MIXRAMP_END="); + last = {}; + for (const auto &i : data.end) { + if (i.time >= FloatDuration{} && i != last) { + printf("%.2f %.2f;", i.volume, (total_time - i.time).count()); + last = i; + } + } + printf("\n"); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/RunReplayGainAnalyzer.cxx b/test/RunReplayGainAnalyzer.cxx new file mode 100644 index 0000000..7432908 --- /dev/null +++ b/test/RunReplayGainAnalyzer.cxx @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ReadFrames.hxx" +#include "pcm/ReplayGainAnalyzer.hxx" +#include "io/FileDescriptor.hxx" +#include "system/Error.hxx" +#include "util/PrintException.hxx" + +#include +#include + +#include + +int +main(int, char **) noexcept +try { + WindowReplayGainAnalyzer a; + + constexpr std::size_t frame_size = ReplayGainAnalyzer::CHANNELS * + sizeof(ReplayGainAnalyzer::sample_type); + + const FileDescriptor input_fd(STDIN_FILENO); + + while (true) { + std::array buffer; + + size_t nbytes = ReadFrames(input_fd, + buffer.data(), sizeof(buffer), + frame_size); + if (nbytes == 0) + break; + + a.Process({buffer.data(), nbytes / frame_size}); + } + + a.Flush(); + + printf("gain = %+.2f dB\n", (double)a.GetGain()); + printf("peak = %.6f\n", (double)a.GetPeak()); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/RunZeroconf.cxx b/test/RunZeroconf.cxx new file mode 100644 index 0000000..60c3939 --- /dev/null +++ b/test/RunZeroconf.cxx @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "event/Loop.hxx" +#include "ShutdownHandler.hxx" +#include "zeroconf/Helper.hxx" + +#include + +int +main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) +{ + EventLoop event_loop; + const ShutdownHandler shutdown_handler(event_loop); + + const ZeroconfHelper helper(event_loop, "test", "_mpd._tcp", 1234); + + event_loop.Run(); + + return EXIT_SUCCESS; +} diff --git a/test/ShutdownHandler.cxx b/test/ShutdownHandler.cxx new file mode 100644 index 0000000..414d6d7 --- /dev/null +++ b/test/ShutdownHandler.cxx @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ShutdownHandler.hxx" + +#ifndef _WIN32 +#include "event/SignalMonitor.hxx" +#include "event/Loop.hxx" + +#include + +static void +HandleShutdownSignal(void *ctx) noexcept +{ + auto &loop = *(EventLoop *)ctx; + loop.Break(); +} + +ShutdownHandler::ShutdownHandler(EventLoop &loop) +{ + SignalMonitorInit(loop); + + SignalMonitorRegister(SIGINT, {&loop, HandleShutdownSignal}); + SignalMonitorRegister(SIGTERM, {&loop, HandleShutdownSignal}); +} + +ShutdownHandler::~ShutdownHandler() +{ + SignalMonitorFinish(); +} + +#endif diff --git a/test/ShutdownHandler.hxx b/test/ShutdownHandler.hxx new file mode 100644 index 0000000..3ee8036 --- /dev/null +++ b/test/ShutdownHandler.hxx @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#ifndef MPD_TEST_SHUTDOWN_HANDLER_HXX +#define MPD_TEST_SHUTDOWN_HANDLER_HXX + +class EventLoop; + +class ShutdownHandler { +public: + explicit ShutdownHandler(EventLoop &loop); + ~ShutdownHandler(); +}; + +#ifdef _WIN32 +inline ShutdownHandler::ShutdownHandler(EventLoop &) {} +inline ShutdownHandler::~ShutdownHandler() {} +#endif + +#endif diff --git a/test/TestAudioFormat.cxx b/test/TestAudioFormat.cxx new file mode 100644 index 0000000..ac4fdd7 --- /dev/null +++ b/test/TestAudioFormat.cxx @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "pcm/AudioFormat.hxx" +#include "pcm/AudioParser.hxx" +#include "util/StringBuffer.hxx" + +#include + +#include + +struct AudioFormatStringTest { + AudioFormat af; + const char *s; +}; + +static constexpr AudioFormatStringTest af_string_tests[] = { + { AudioFormat(44100, SampleFormat::S8, 1), "44100:8:1" }, + { AudioFormat(44100, SampleFormat::S16, 2), "44100:16:2" }, + { AudioFormat(48000, SampleFormat::S24_P32, 6), "48000:24:6" }, + { AudioFormat(192000, SampleFormat::FLOAT, 2), "192000:f:2" }, + { AudioFormat(352801, SampleFormat::DSD, 2), "352801:dsd:2" }, + { AudioFormat(352800, SampleFormat::DSD, 2), "dsd64:2" }, +}; + +static constexpr AudioFormatStringTest af_mask_tests[] = { + { AudioFormat(44100, SampleFormat::UNDEFINED, 1), "44100:*:1" }, + { AudioFormat(44100, SampleFormat::S16, 0), "44100:16:*" }, + { AudioFormat(0, SampleFormat::S24_P32, 6), "*:24:6" }, + { AudioFormat::Undefined(), "*:*:*" }, +}; + +TEST(AudioFormatTest, ToString) +{ + for (const auto &i : af_string_tests) + EXPECT_STREQ(i.s, ToString(i.af).c_str()); +} + +TEST(AudioFormatTest, Parse) +{ + for (const auto &i : af_string_tests) { + EXPECT_EQ(i.af, ParseAudioFormat(i.s, false)); + EXPECT_EQ(i.af, ParseAudioFormat(i.s, true)); + } + + for (const auto &i : af_mask_tests) + EXPECT_EQ(i.af, ParseAudioFormat(i.s, true)); +} diff --git a/test/TestIcu.cxx b/test/TestIcu.cxx new file mode 100644 index 0000000..f9b456f --- /dev/null +++ b/test/TestIcu.cxx @@ -0,0 +1,48 @@ +/* + * Unit tests for src/util/ + */ + +#include "lib/icu/Converter.hxx" +#include "util/AllocatedString.hxx" + +#include + +#ifdef HAVE_ICU_CONVERTER + +static const char *const invalid_utf8[] = { + "\xfc", +}; + +struct StringPair { + const char *utf8, *other; +}; + +static constexpr StringPair latin1_tests[] = { + { "foo", "foo" }, + { "\xc3\xbc", "\xfc" }, +}; + +TEST(IcuConverter, InvalidCharset) +{ + EXPECT_ANY_THROW(IcuConverter::Create("doesntexist")); +} + +TEST(IcuConverter, Latin1) +{ + const auto converter = IcuConverter::Create("iso-8859-1"); + ASSERT_NE(converter, nullptr); + + for (const auto i : invalid_utf8) { + EXPECT_ANY_THROW(converter->FromUTF8(i)); + } + + for (const auto i : latin1_tests) { + auto f = converter->FromUTF8(i.utf8); + EXPECT_STREQ(f.c_str(), i.other); + + auto t = converter->ToUTF8(i.other); + EXPECT_STREQ(t.c_str(), i.utf8); + } +} + +#endif diff --git a/test/TestRewindInputStream.cxx b/test/TestRewindInputStream.cxx new file mode 100644 index 0000000..6cc4cec --- /dev/null +++ b/test/TestRewindInputStream.cxx @@ -0,0 +1,126 @@ +/* + * Unit tests for class RewindInputStream. + */ + +#include "input/RewindInputStream.hxx" +#include "input/InputStream.hxx" +#include "thread/Mutex.hxx" + +#include + +#include + +class StringInputStream final : public InputStream { + const char *data; + size_t remaining; + +public: + StringInputStream(const char *_uri, + Mutex &_mutex, + const char *_data) + :InputStream(_uri, _mutex), + data(_data), remaining(strlen(data)) { + SetReady(); + } + + /* virtual methods from InputStream */ + bool IsEOF() const noexcept override { + return remaining == 0; + } + + size_t Read(std::unique_lock &, + std::span dest) override { + size_t nbytes = std::min(remaining, dest.size()); + memcpy(dest.data(), data, nbytes); + data += nbytes; + remaining -= nbytes; + offset += nbytes; + return nbytes; + } +}; + +TEST(RewindInputStream, Basic) +{ + Mutex mutex; + + auto *sis = + new StringInputStream("foo://", mutex, + "foo bar"); + EXPECT_TRUE(sis->IsReady()); + + auto ris = input_rewind_open(InputStreamPtr(sis)); + EXPECT_TRUE(ris.get() != sis); + EXPECT_TRUE(ris != nullptr); + + std::unique_lock lock{mutex}; + + ris->Update(); + EXPECT_TRUE(ris->IsReady()); + EXPECT_FALSE(ris->KnownSize()); + EXPECT_EQ(offset_type(0), ris->GetOffset()); + + char buffer[16]; + size_t nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer}.first(2))); + EXPECT_EQ(size_t(2), nbytes); + EXPECT_EQ('f', buffer[0]); + EXPECT_EQ('o', buffer[1]); + EXPECT_EQ(offset_type(2), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer}.first(2))); + EXPECT_EQ(size_t(2), nbytes); + EXPECT_EQ('o', buffer[0]); + EXPECT_EQ(' ', buffer[1]); + EXPECT_EQ(offset_type(4), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + ris->Seek(lock, 1); + EXPECT_EQ(offset_type(1), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer}.first(2))); + EXPECT_EQ(size_t(2), nbytes); + EXPECT_EQ('o', buffer[0]); + EXPECT_EQ('o', buffer[1]); + EXPECT_EQ(offset_type(3), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + ris->Seek(lock, 0); + EXPECT_EQ(offset_type(0), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer}.first(2))); + EXPECT_EQ(size_t(2), nbytes); + EXPECT_EQ('f', buffer[0]); + EXPECT_EQ('o', buffer[1]); + EXPECT_EQ(offset_type(2), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer})); + EXPECT_EQ(size_t(2), nbytes); + EXPECT_EQ('o', buffer[0]); + EXPECT_EQ(' ', buffer[1]); + EXPECT_EQ(offset_type(4), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer})); + EXPECT_EQ(size_t(3), nbytes); + EXPECT_EQ('b', buffer[0]); + EXPECT_EQ('a', buffer[1]); + EXPECT_EQ('r', buffer[2]); + EXPECT_EQ(offset_type(7), ris->GetOffset()); + EXPECT_TRUE(ris->IsEOF()); + + ris->Seek(lock, 3); + EXPECT_EQ(offset_type(3), ris->GetOffset()); + EXPECT_FALSE(ris->IsEOF()); + + nbytes = ris->Read(lock, std::as_writable_bytes(std::span{buffer})); + EXPECT_EQ(size_t(4), nbytes); + EXPECT_EQ(' ', buffer[0]); + EXPECT_EQ('b', buffer[1]); + EXPECT_EQ('a', buffer[2]); + EXPECT_EQ('r', buffer[3]); + EXPECT_EQ(offset_type(7), ris->GetOffset()); + EXPECT_TRUE(ris->IsEOF()); +} diff --git a/test/TestStringFilter.cxx b/test/TestStringFilter.cxx new file mode 100644 index 0000000..f7fc8a7 --- /dev/null +++ b/test/TestStringFilter.cxx @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "song/StringFilter.hxx" +#include "lib/icu/Features.h" // for HAVE_ICU +#include "lib/icu/Init.hxx" + +#include + +class StringFilterTest : public ::testing::Test { +protected: + void SetUp() override { + IcuInit(); + } + + void TearDown() override { + IcuFinish(); + } +}; + +TEST_F(StringFilterTest, ASCII) +{ + const StringFilter f{"needle", false, StringFilter::Position::FULL, false}; + + EXPECT_TRUE(f.Match("needle")); + EXPECT_FALSE(f.Match("nëedle")); + EXPECT_FALSE(f.Match("néedle")); + EXPECT_FALSE(f.Match("nèedle")); + EXPECT_FALSE(f.Match("nêedle")); + EXPECT_FALSE(f.Match("Needle")); + EXPECT_FALSE(f.Match("NEEDLE")); + EXPECT_FALSE(f.Match("")); + EXPECT_FALSE(f.Match("foo")); + EXPECT_FALSE(f.Match("needleBAR")); + EXPECT_FALSE(f.Match("FOOneedleBAR")); +} + +TEST_F(StringFilterTest, Negated) +{ + const StringFilter f{"needle", false, StringFilter::Position::FULL, true}; + + EXPECT_FALSE(f.Match("needle")); + EXPECT_TRUE(f.Match("Needle")); + EXPECT_TRUE(f.Match("NEEDLE")); + EXPECT_TRUE(f.Match("")); + EXPECT_TRUE(f.Match("foo")); + EXPECT_TRUE(f.Match("needleBAR")); + EXPECT_TRUE(f.Match("FOOneedleBAR")); +} + +TEST_F(StringFilterTest, StartsWith) +{ + const StringFilter f{"needle", false, StringFilter::Position::PREFIX, false}; + + EXPECT_TRUE(f.Match("needle")); + EXPECT_FALSE(f.Match("Needle")); + EXPECT_FALSE(f.Match("NEEDLE")); + EXPECT_FALSE(f.Match("")); + EXPECT_FALSE(f.Match("foo")); + EXPECT_TRUE(f.Match("needleBAR")); + EXPECT_FALSE(f.Match("NeedleBAR")); + EXPECT_FALSE(f.Match("FOOneedleBAR")); +} + +TEST_F(StringFilterTest, IsIn) +{ + const StringFilter f{"needle", false, StringFilter::Position::ANYWHERE, false}; + + EXPECT_TRUE(f.Match("needle")); + EXPECT_FALSE(f.Match("Needle")); + EXPECT_FALSE(f.Match("NEEDLE")); + EXPECT_FALSE(f.Match("")); + EXPECT_FALSE(f.Match("foo")); + EXPECT_TRUE(f.Match("needleBAR")); + EXPECT_FALSE(f.Match("NeedleBAR")); + EXPECT_TRUE(f.Match("FOOneedleBAR")); +} + +TEST_F(StringFilterTest, Latin) +{ + const StringFilter f{"nëedlé", false, StringFilter::Position::FULL, false}; + + EXPECT_TRUE(f.Match("nëedlé")); +#if defined(HAVE_ICU) || defined(_WIN32) + EXPECT_TRUE(f.Match("nëedl\u00e9")); + // TODO EXPECT_TRUE(f.Match("nëedl\u0065\u0301")); +#endif + EXPECT_FALSE(f.Match("NËEDLÉ")); + EXPECT_FALSE(f.Match("needlé")); + EXPECT_FALSE(f.Match("néedlé")); + EXPECT_FALSE(f.Match("nèedlé")); + EXPECT_FALSE(f.Match("nêedlé")); + EXPECT_FALSE(f.Match("Needlé")); + EXPECT_FALSE(f.Match("NEEDLÉ")); + EXPECT_FALSE(f.Match("")); + EXPECT_FALSE(f.Match("foo")); + EXPECT_FALSE(f.Match("FOOnëedleBAR")); +} + +#if defined(HAVE_ICU) || defined(_WIN32) + +TEST_F(StringFilterTest, Normalize) +{ + const StringFilter f{"1①H", true, StringFilter::Position::FULL, false}; + + EXPECT_TRUE(f.Match("1①H")); + +#ifndef _WIN32 + // fails with Windows CompareStringEx() + EXPECT_TRUE(f.Match("¹₁H")); + EXPECT_TRUE(f.Match("①1ℌ")); + EXPECT_TRUE(f.Match("①1ℍ")); +#endif + + EXPECT_FALSE(f.Match("21H")); + + EXPECT_TRUE(StringFilter("dž", true, StringFilter::Position::FULL, false).Match("dž")); + + EXPECT_TRUE(StringFilter("\u212b", true, StringFilter::Position::FULL, false).Match("\u0041\u030a")); + EXPECT_TRUE(StringFilter("\u212b", true, StringFilter::Position::FULL, false).Match("\u00c5")); + + EXPECT_TRUE(StringFilter("\u1e69", true, StringFilter::Position::FULL, false).Match("\u0073\u0323\u0307")); + + EXPECT_TRUE(StringFilter("\u1e69", true, StringFilter::Position::FULL, false).Match("\u0073\u0307\u0323")); +} + +#endif + +#ifdef HAVE_ICU + +TEST_F(StringFilterTest, Transliterate) +{ + const StringFilter f{"'", true, StringFilter::Position::FULL, false}; + + EXPECT_TRUE(f.Match("’")); + EXPECT_FALSE(f.Match("\"")); +} + +#endif + +TEST_F(StringFilterTest, FoldCase) +{ + const StringFilter f{"nëedlé", true, StringFilter::Position::FULL, false}; + + EXPECT_TRUE(f.Match("nëedlé")); +#if defined(HAVE_ICU) || defined(_WIN32) + EXPECT_TRUE(f.Match("nëedl\u00e9")); + EXPECT_TRUE(f.Match("nëedl\u0065\u0301")); + EXPECT_TRUE(f.Match("NËEDLÉ")); + EXPECT_TRUE(f.Match("NËEDL\u00c9")); + EXPECT_TRUE(f.Match("NËEDL\u0045\u0301")); +#endif + EXPECT_FALSE(f.Match("needlé")); + EXPECT_FALSE(f.Match("néedlé")); + EXPECT_FALSE(f.Match("nèedlé")); + EXPECT_FALSE(f.Match("nêedlé")); + EXPECT_FALSE(f.Match("Needlé")); + EXPECT_FALSE(f.Match("NEEDLÉ")); + EXPECT_FALSE(f.Match("")); + EXPECT_FALSE(f.Match("foo")); + EXPECT_FALSE(f.Match("FOOnëedleBAR")); +} diff --git a/test/TestTagSongFilter.cxx b/test/TestTagSongFilter.cxx new file mode 100644 index 0000000..a7ea689 --- /dev/null +++ b/test/TestTagSongFilter.cxx @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "MakeTag.hxx" +#include "song/TagSongFilter.hxx" +#include "song/LightSong.hxx" +#include "tag/Type.hxx" +#include "lib/icu/Init.hxx" + +#include + +class TagSongFilterTest : public ::testing::Test { +protected: + void SetUp() override { + IcuInit(); + } + + void TearDown() override { + IcuFinish(); + } +}; + +static bool +InvokeFilter(const TagSongFilter &f, const Tag &tag) noexcept +{ + return f.Match(LightSong("dummy", tag)); +} + +TEST_F(TagSongFilterTest, Basic) +{ + const TagSongFilter f{ + TAG_TITLE, + {"needle", false, StringFilter::Position::FULL, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_TITLE, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle", TAG_TITLE, "foo"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ARTIST, "foo", TAG_TITLE, "needle", TAG_ALBUM, "bar"))); + + EXPECT_FALSE(InvokeFilter(f, MakeTag())); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_TITLE, "bar"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_ARTIST, "needle"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "FOOneedleBAR"))); +} + +/** + * Test with empty string. This matches tags where the given tag type + * does not exist. + */ +TEST_F(TagSongFilterTest, Empty) +{ + const TagSongFilter f{ + TAG_TITLE, + {"", false, StringFilter::Position::FULL, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag())); + + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_TITLE, "bar"))); +} + +TEST_F(TagSongFilterTest, Substring) +{ + const TagSongFilter f{ + TAG_TITLE, + {"needle", false, StringFilter::Position::ANYWHERE, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needleBAR"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "FOOneedle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "FOOneedleBAR"))); + + EXPECT_FALSE(InvokeFilter(f, MakeTag())); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "eedle"))); +} + +TEST_F(TagSongFilterTest, Startswith) +{ + const TagSongFilter f{ + TAG_TITLE, + {"needle", false, StringFilter::Position::PREFIX, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "needleBAR"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "FOOneedle"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "FOOneedleBAR"))); + + EXPECT_FALSE(InvokeFilter(f, MakeTag())); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "eedle"))); +} + +TEST_F(TagSongFilterTest, Negated) +{ + const TagSongFilter f{ + TAG_TITLE, + {"needle", false, StringFilter::Position::FULL, true}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag())); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo"))); +} + +/** + * Combine the "Empty" and "Negated" tests. + */ +TEST_F(TagSongFilterTest, EmptyNegated) +{ + const TagSongFilter f{ + TAG_TITLE, + {"", false, StringFilter::Position::FULL, true}, + }; + + EXPECT_FALSE(InvokeFilter(f, MakeTag())); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo"))); +} + +/** + * Negation with multiple tag values. + */ +TEST_F(TagSongFilterTest, MultiNegated) +{ + const TagSongFilter f{ + TAG_TITLE, + {"needle", false, StringFilter::Position::FULL, true}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_TITLE, "bar"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "needle", TAG_TITLE, "bar"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_TITLE, "foo", TAG_TITLE, "needle"))); +} + +/** + * Check whether fallback tags work, e.g. AlbumArtist falls back to + * just Artist if there is no AlbumArtist. + */ +TEST_F(TagSongFilterTest, Fallback) +{ + const TagSongFilter f{ + TAG_ALBUM_ARTIST, + {"needle", false, StringFilter::Position::FULL, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ALBUM_ARTIST, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ARTIST, "needle"))); + + EXPECT_FALSE(InvokeFilter(f, MakeTag())); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ALBUM_ARTIST, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ARTIST, "foo"))); + + /* no fallback, thus the Artist tag isn't used and this must + be a mismatch */ + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ARTIST, "needle", TAG_ALBUM_ARTIST, "foo"))); +} + +/** + * Combine the "Empty" and "Fallback" tests. + */ +TEST_F(TagSongFilterTest, EmptyFallback) +{ + const TagSongFilter f{ + TAG_ALBUM_ARTIST, + {"", false, StringFilter::Position::FULL, false}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag())); + + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ALBUM_ARTIST, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ARTIST, "foo"))); +} + +/** + * Combine the "Negated" and "Fallback" tests. + */ +TEST_F(TagSongFilterTest, NegatedFallback) +{ + const TagSongFilter f{ + TAG_ALBUM_ARTIST, + {"needle", false, StringFilter::Position::FULL, true}, + }; + + EXPECT_TRUE(InvokeFilter(f, MakeTag())); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ALBUM_ARTIST, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ALBUM_ARTIST, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ARTIST, "foo"))); + EXPECT_FALSE(InvokeFilter(f, MakeTag(TAG_ARTIST, "needle"))); + EXPECT_TRUE(InvokeFilter(f, MakeTag(TAG_ARTIST, "needle", TAG_ALBUM_ARTIST, "foo"))); +} diff --git a/test/WriteFile.cxx b/test/WriteFile.cxx new file mode 100644 index 0000000..5f86e1d --- /dev/null +++ b/test/WriteFile.cxx @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "io/FileOutputStream.hxx" +#include "fs/NarrowPath.hxx" +#include "util/PrintException.hxx" + +#include + +#include + +#include +#include +#include + +static bool +Copy(OutputStream &dest, int src) +{ + while (true) { + std::byte buffer[8192]; + ssize_t nbytes = read(src, buffer, sizeof(buffer)); + if (nbytes < 0) { + fprintf(stderr, "Failed to read from stdin: %s\n", + strerror(errno)); + return false; + } + + if (nbytes == 0) + return true; + + dest.Write(std::span{buffer}.first(nbytes)); + } +} + +int +main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: WriteFile PATH\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath path = argv[1]; + + FileOutputStream fos(path); + + if (!Copy(fos, STDIN_FILENO)) + return EXIT_FAILURE; + + fos.Commit(); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/dump_playlist.cxx b/test/dump_playlist.cxx new file mode 100644 index 0000000..883ac28 --- /dev/null +++ b/test/dump_playlist.cxx @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "TagSave.hxx" +#include "song/DetachedSong.hxx" +#include "playlist/SongEnumerator.hxx" +#include "input/InputStream.hxx" +#include "ConfigGlue.hxx" +#include "decoder/DecoderList.hxx" +#include "input/Init.hxx" +#include "event/Thread.hxx" +#include "playlist/PlaylistRegistry.hxx" +#include "playlist/PlaylistPlugin.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "io/BufferedOutputStream.hxx" +#include "io/StdioOutputStream.hxx" +#include "thread/Cond.hxx" +#include "util/PrintException.hxx" + +#include +#include + +static void +tag_save(FILE *file, const Tag &tag) +{ + StdioOutputStream sos(file); + WithBufferedOutputStream(sos, [&](auto &bos){ + tag_save(bos, tag); + }); +} + +int main(int argc, char **argv) +try { + const char *uri; + + if (argc != 3) { + fprintf(stderr, "Usage: dump_playlist CONFIG URI\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath config_path = argv[1]; + uri = argv[2]; + + /* initialize MPD */ + + const auto config = AutoLoadConfigFile(config_path); + + EventThread io_thread; + io_thread.Start(); + + const ScopeInputPluginsInit input_plugins_init(config, io_thread.GetEventLoop()); + const ScopePlaylistPluginsInit playlist_plugins_init(config); + const ScopeDecoderPluginsInit decoder_plugins_init(config); + + /* open the playlist */ + + Mutex mutex; + + InputStreamPtr is; + auto playlist = playlist_list_open_uri(uri, mutex); + if (playlist == nullptr) { + /* open the stream and wait until it becomes ready */ + + is = InputStream::OpenReady(uri, mutex); + + /* open the playlist */ + + playlist = playlist_list_open_stream(std::move(is), uri); + if (playlist == nullptr) { + fprintf(stderr, "Failed to open playlist\n"); + return 2; + } + } + + /* dump the playlist */ + + std::unique_ptr song; + while ((song = playlist->NextSong()) != nullptr) { + printf("%s\n", song->GetURI()); + + const unsigned start_ms = song->GetStartTime().ToMS(); + const unsigned end_ms = song->GetEndTime().ToMS(); + + if (end_ms > 0) + printf("range: %u:%02u..%u:%02u\n", + start_ms / 60000, + (start_ms / 1000) % 60, + end_ms / 60000, + (end_ms / 1000) % 60); + else if (start_ms > 0) + printf("range: %u:%02u..\n", + start_ms / 60000, + (start_ms / 1000) % 60); + + tag_save(stdout, song->GetTag()); + } + + /* deinitialize everything */ + + playlist.reset(); + is.reset(); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/dump_rva2.cxx b/test/dump_rva2.cxx new file mode 100644 index 0000000..83b7837 --- /dev/null +++ b/test/dump_rva2.cxx @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "tag/Id3Load.hxx" +#include "tag/Rva2.hxx" +#include "tag/ReplayGainInfo.hxx" +#include "thread/Mutex.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "input/InputStream.hxx" +#include "input/LocalOpen.hxx" +#include "util/PrintException.hxx" + +#include + +#ifdef HAVE_LOCALE_H +#include +#endif + +#include +#include + +static void +DumpReplayGainTuple(const char *name, const ReplayGainTuple &tuple) +{ + if (tuple.IsDefined()) + fprintf(stderr, "replay_gain[%s]: gain=%f peak=%f\n", + name, (double)tuple.gain, (double)tuple.peak); +} + +static void +DumpReplayGainInfo(const ReplayGainInfo &info) +{ + DumpReplayGainTuple("album", info.album); + DumpReplayGainTuple("track", info.track); +} + +int main(int argc, char **argv) +try { +#ifdef HAVE_LOCALE_H + /* initialize locale */ + setlocale(LC_CTYPE,""); +#endif + + if (argc != 2) { + fprintf(stderr, "Usage: read_rva2 FILE\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath path = argv[1]; + + Mutex mutex; + + auto is = OpenLocalInputStream(path, mutex); + + const auto tag = tag_id3_load(*is); + if (tag == nullptr) { + fprintf(stderr, "No ID3 tag found\n"); + return EXIT_FAILURE; + } + + ReplayGainInfo replay_gain; + replay_gain.Clear(); + + bool success = tag_rva2_parse(tag.get(), replay_gain); + if (!success) { + fprintf(stderr, "No RVA2 tag found\n"); + return EXIT_FAILURE; + } + + DumpReplayGainInfo(replay_gain); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/dump_text_file.cxx b/test/dump_text_file.cxx new file mode 100644 index 0000000..30e6c1f --- /dev/null +++ b/test/dump_text_file.cxx @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ConfigGlue.hxx" +#include "event/Thread.hxx" +#include "input/Init.hxx" +#include "input/InputStream.hxx" +#include "input/TextInputStream.hxx" +#include "util/PrintException.hxx" + +#include "archive/Features.h" // for ENABLE_ARCHIVE +#ifdef ENABLE_ARCHIVE +#include "archive/ArchiveList.hxx" +#endif + +#include + +#include +#include +#include + +class GlobalInit { + const ConfigData config; + + EventThread io_thread; + +#ifdef ENABLE_ARCHIVE + const ScopeArchivePluginsInit archive_plugins_init{config}; +#endif + + const ScopeInputPluginsInit input_plugins_init{config, io_thread.GetEventLoop()}; + +public: + explicit GlobalInit(Path config_path) + :config(AutoLoadConfigFile(config_path)) + { + io_thread.Start(); + } +}; + +static void +dump_text_file(TextInputStream &is) +{ + const char *line; + while ((line = is.ReadLine()) != nullptr) + printf("'%s'\n", line); +} + +static int +dump_input_stream(InputStreamPtr &&is) +{ + { + TextInputStream tis(std::move(is)); + dump_text_file(tis); + } + + const std::scoped_lock protect{is->mutex}; + + is->Check(); + return 0; +} + +int main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: dump_text_file URI\n"); + return EXIT_FAILURE; + } + + /* initialize MPD */ + + const GlobalInit init{nullptr}; + + /* open the stream and dump it */ + + Mutex mutex; + + auto is = InputStream::OpenReady(argv[1], mutex); + return dump_input_stream(std::move(is)); +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/fs/TestGlob.cxx b/test/fs/TestGlob.cxx new file mode 100644 index 0000000..e7ab4cc --- /dev/null +++ b/test/fs/TestGlob.cxx @@ -0,0 +1,79 @@ +/* + * Unit tests for src/fs/ + */ + +#include "config.h" +#include "fs/Glob.hxx" + +#include + +#ifdef HAVE_CLASS_GLOB + +TEST(Glob, Basic) +{ + const Glob glob("foo"); + EXPECT_TRUE(glob.Check("foo")); + EXPECT_FALSE(glob.Check("fooo")); + EXPECT_FALSE(glob.Check("_foo")); + EXPECT_FALSE(glob.Check("a/foo")); + EXPECT_FALSE(glob.Check("")); + EXPECT_FALSE(glob.Check("*")); +} + +TEST(Glob, Asterisk) +{ + const Glob glob("*"); + EXPECT_TRUE(glob.Check("foo")); + EXPECT_TRUE(glob.Check("bar")); + EXPECT_TRUE(glob.Check("*")); + EXPECT_TRUE(glob.Check("?")); +} + +TEST(Glob, QuestionMark) +{ + const Glob glob("foo?bar"); + EXPECT_TRUE(glob.Check("foo_bar")); + EXPECT_TRUE(glob.Check("foo?bar")); + EXPECT_TRUE(glob.Check("foo bar")); + EXPECT_FALSE(glob.Check("foobar")); + EXPECT_FALSE(glob.Check("foo__bar")); +} + +TEST(Glob, Wildcard) +{ + const Glob glob("foo*bar"); + EXPECT_TRUE(glob.Check("foo_bar")); + EXPECT_TRUE(glob.Check("foo?bar")); + EXPECT_TRUE(glob.Check("foo bar")); + EXPECT_TRUE(glob.Check("foobar")); + EXPECT_TRUE(glob.Check("foo__bar")); + EXPECT_FALSE(glob.Check("_foobar")); + EXPECT_FALSE(glob.Check("foobar_")); +} + +TEST(Glob, PrefixWildcard) +{ + const Glob glob("*bar"); + EXPECT_TRUE(glob.Check("foo_bar")); + EXPECT_TRUE(glob.Check("foo?bar")); + EXPECT_TRUE(glob.Check("foo bar")); + EXPECT_TRUE(glob.Check("foobar")); + EXPECT_TRUE(glob.Check("foo__bar")); + EXPECT_TRUE(glob.Check("_foobar")); + EXPECT_TRUE(glob.Check("bar")); + EXPECT_FALSE(glob.Check("foobar_")); +} + +TEST(Glob, SuffixWildcard) +{ + const Glob glob("foo*"); + EXPECT_TRUE(glob.Check("foo_bar")); + EXPECT_TRUE(glob.Check("foo?bar")); + EXPECT_TRUE(glob.Check("foo bar")); + EXPECT_TRUE(glob.Check("foobar")); + EXPECT_TRUE(glob.Check("foo__bar")); + EXPECT_TRUE(glob.Check("foobar_")); + EXPECT_TRUE(glob.Check("foo")); +} + +#endif diff --git a/test/fs/TestLookupFile.cxx b/test/fs/TestLookupFile.cxx new file mode 100644 index 0000000..1efc64a --- /dev/null +++ b/test/fs/TestLookupFile.cxx @@ -0,0 +1,29 @@ +#include "fs/LookupFile.hxx" + +#include + +#include +#include + +TEST(ArchiveTest, Lookup) +{ + EXPECT_THROW(LookupFile(Path::FromFS(PATH_LITERAL(""))), std::system_error); + + EXPECT_FALSE(LookupFile(Path::FromFS(PATH_LITERAL(".")))); + + EXPECT_FALSE(LookupFile(Path::FromFS(PATH_LITERAL("config.h")))); + + EXPECT_THROW(LookupFile(Path::FromFS(PATH_LITERAL("src/foo/bar"))), std::system_error); + + fclose(fopen("dummy", "w")); + + auto result = LookupFile(Path::FromFS(PATH_LITERAL("dummy/foo/bar"))); + EXPECT_TRUE(result); + EXPECT_STREQ(result.archive.c_str(), PATH_LITERAL("dummy")); + EXPECT_STREQ(result.inside.c_str(), PATH_LITERAL("foo/bar")); + + result = LookupFile(Path::FromFS(PATH_LITERAL("config.h/foo/bar"))); + EXPECT_TRUE(result); + EXPECT_STREQ(result.archive.c_str(), PATH_LITERAL("config.h")); + EXPECT_STREQ(result.inside.c_str(), PATH_LITERAL("foo/bar")); +} diff --git a/test/fs/TestParsePath.cxx b/test/fs/TestParsePath.cxx new file mode 100644 index 0000000..294b3e9 --- /dev/null +++ b/test/fs/TestParsePath.cxx @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config/Path.hxx" +#include "config/Data.hxx" +#include "fs/Path.hxx" +#include "fs/AllocatedPath.hxx" +#include "fs/glue/StandardDirectory.hxx" +#include "fs/XDG.hxx" // for USE_XDG + +#include + +#include + +#ifndef _WIN32 + +AllocatedPath +GetHomeDir(const char *user_name) noexcept +{ + return AllocatedPath::FromFS(PATH_LITERAL("/home")) / AllocatedPath::FromUTF8(user_name); +} + +AllocatedPath +GetHomeDir() noexcept +{ + return GetHomeDir("foo"); +} + +#endif + +AllocatedPath +GetUserConfigDir() noexcept +{ +#ifdef _WIN32 + return AllocatedPath::FromFS(PATH_LITERAL("c:\\users\\foo\\config")); +#else + return GetHomeDir() / AllocatedPath::FromFS(PATH_LITERAL(".config")); +#endif +} + +AllocatedPath +GetUserMusicDir() noexcept +{ +#ifdef _WIN32 + return AllocatedPath::FromFS(PATH_LITERAL("c:\\users\\foo\\Music")); +#else + return GetHomeDir() / AllocatedPath::FromFS(PATH_LITERAL("Music")); +#endif +} + +AllocatedPath +GetUserCacheDir() noexcept +{ +#ifdef _WIN32 + return nullptr; +#else + return GetHomeDir() / AllocatedPath::FromFS(PATH_LITERAL(".cache")); +#endif +} + +AllocatedPath +GetAppCacheDir() noexcept +{ +#ifdef _WIN32 + return nullptr; +#else + return GetUserCacheDir() / AllocatedPath::FromFS(PATH_LITERAL("mpd")); +#endif +} + +AllocatedPath +GetUserRuntimeDir() noexcept +{ +#ifdef _WIN32 + return nullptr; +#else + return AllocatedPath::FromFS(PATH_LITERAL("/run/user/foo")); +#endif +} + +AllocatedPath +GetAppRuntimeDir() noexcept +{ +#ifdef _WIN32 + return nullptr; +#else + return GetUserRuntimeDir() / AllocatedPath::FromFS(PATH_LITERAL("mpd")); +#endif +} + +const char * +ConfigData::GetString([[maybe_unused]] ConfigOption option, + const char *default_value) const noexcept +{ + return default_value; +} + +TEST(ParsePath, Basic) +{ + EXPECT_THROW(ParsePath(""), std::runtime_error); + EXPECT_EQ(ParsePath("/"), AllocatedPath::FromFS(PATH_LITERAL("/"))); + EXPECT_EQ(ParsePath("/abc"), AllocatedPath::FromFS(PATH_LITERAL("/abc"))); + +#ifdef _WIN32 + EXPECT_EQ(ParsePath("c:/abc"), AllocatedPath::FromFS(PATH_LITERAL("c:/abc"))); + EXPECT_EQ(ParsePath("c:\\abc"), AllocatedPath::FromFS(PATH_LITERAL("c:\\abc"))); +#endif +} + +#ifndef _WIN32 + +TEST(ParsePath, Tilde) +{ + EXPECT_EQ(ParsePath("~"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo"))); + EXPECT_EQ(ParsePath("~/"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo"))); + EXPECT_EQ(ParsePath("~/abc"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/abc"))); + EXPECT_EQ(ParsePath("~bar"), AllocatedPath::FromFS(PATH_LITERAL("/home/bar"))); + EXPECT_EQ(ParsePath("~bar/"), AllocatedPath::FromFS(PATH_LITERAL("/home/bar"))); + EXPECT_EQ(ParsePath("~bar/abc"), AllocatedPath::FromFS(PATH_LITERAL("/home/bar/abc"))); +} + +TEST(ParsePath, Home) +{ + EXPECT_EQ(ParsePath("$HOME"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo"))); + EXPECT_EQ(ParsePath("$HOME/"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo"))); + EXPECT_EQ(ParsePath("$HOME/abc"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/abc"))); +} + +#endif + +#ifdef USE_XDG + +TEST(ParsePath, XDG) +{ + EXPECT_EQ(ParsePath("$XDG_CONFIG_HOME"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/.config"))); + EXPECT_EQ(ParsePath("$XDG_CONFIG_HOME/abc"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/.config/abc"))); + EXPECT_EQ(ParsePath("$XDG_MUSIC_DIR"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/Music"))); + EXPECT_EQ(ParsePath("$XDG_CACHE_HOME"), AllocatedPath::FromFS(PATH_LITERAL("/home/foo/.cache"))); + EXPECT_EQ(ParsePath("$XDG_RUNTIME_DIR/mpd"), AllocatedPath::FromFS(PATH_LITERAL("/run/user/foo/mpd"))); +} + +#endif diff --git a/test/fs/TestPath.cxx b/test/fs/TestPath.cxx new file mode 100644 index 0000000..b8f280a --- /dev/null +++ b/test/fs/TestPath.cxx @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "fs/Path.hxx" +#include "fs/AllocatedPath.hxx" + +#include + +TEST(Path, Basic) +{ + EXPECT_TRUE(Path{nullptr}.IsNull()); + EXPECT_FALSE(Path::FromFS(PATH_LITERAL("")).IsNull()); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("")).length(), 0U); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).length(), 3U); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).ToUTF8(), "foo"); +} + +TEST(Path, GetBase) +{ + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("")).GetBase().c_str(), + PATH_LITERAL("")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("foo")).GetBase().c_str(), + PATH_LITERAL("foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("./foo")).GetBase().c_str(), + PATH_LITERAL("foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("../foo")).GetBase().c_str(), + PATH_LITERAL("foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("foo/bar")).GetBase().c_str(), + PATH_LITERAL("bar")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/bar")).GetBase().c_str(), + PATH_LITERAL("bar")); +} + +TEST(Path, GetDirectoryName) +{ + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("")).GetDirectoryName().c_str(), + PATH_LITERAL(".")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("foo")).GetDirectoryName().c_str(), + PATH_LITERAL(".")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("./foo")).GetDirectoryName().c_str(), + PATH_LITERAL(".")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("../foo")).GetDirectoryName().c_str(), + PATH_LITERAL("..")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("foo/bar")).GetDirectoryName().c_str(), + PATH_LITERAL("foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/bar")).GetDirectoryName().c_str(), + PATH_LITERAL("/foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/")).GetDirectoryName().c_str(), + PATH_LITERAL("/foo")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/bar/baz")).GetDirectoryName().c_str(), + PATH_LITERAL("/foo/bar")); +} + +TEST(Path, Relative) +{ + EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).Relative(Path::FromFS(PATH_LITERAL(""))), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/bar")).Relative(Path::FromFS(PATH_LITERAL("/foo/bar"))), nullptr); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo")).Relative(Path::FromFS(PATH_LITERAL("/foo/bar"))), + PATH_LITERAL("bar")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/")).Relative(Path::FromFS(PATH_LITERAL("/foo/bar"))), + PATH_LITERAL("bar")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo")).Relative(Path::FromFS(PATH_LITERAL("/foo///bar"))), + PATH_LITERAL("bar")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo")).Relative(Path::FromFS(PATH_LITERAL("/foo///"))), + PATH_LITERAL("")); +} + +TEST(Path, Extension) +{ + EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/bar")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/./bar")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.bar")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/..")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar")).GetExtension(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/")).GetExtension(), nullptr); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def")).GetExtension(), + PATH_LITERAL("def")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.")).GetExtension(), + PATH_LITERAL("")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def.ghi")).GetExtension(), + PATH_LITERAL("ghi")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc")).GetExtension(), + PATH_LITERAL("abc")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc.def")).GetExtension(), + PATH_LITERAL("def")); +} + +TEST(Path, Suffix) +{ + EXPECT_EQ(Path::FromFS(PATH_LITERAL("foo")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/bar")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/./bar")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.bar")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/.")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo/..")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar")).GetSuffix(), nullptr); + EXPECT_EQ(Path::FromFS(PATH_LITERAL("/foo.abc/")).GetSuffix(), nullptr); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def")).GetSuffix(), + PATH_LITERAL(".def")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.")).GetSuffix(), + PATH_LITERAL(".")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def.ghi")).GetSuffix(), + PATH_LITERAL(".ghi")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc")).GetSuffix(), + PATH_LITERAL(".abc")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc.def")).GetSuffix(), + PATH_LITERAL(".def")); +} + +TEST(Path, WithSuffix) +{ + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("foo")).WithSuffix(PATH_LITERAL(".abc")).c_str(), + PATH_LITERAL("foo.abc")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/bar")).WithSuffix(PATH_LITERAL(".abc")).c_str(), + PATH_LITERAL("/foo/bar.abc")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.xyz/bar")).WithSuffix(PATH_LITERAL(".abc")).c_str(), + PATH_LITERAL("/foo.xyz/bar.abc")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def")).WithSuffix(PATH_LITERAL(".xyz")).c_str(), + PATH_LITERAL("/foo.abc/bar.xyz")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo.abc/bar.def.ghi")).WithSuffix(PATH_LITERAL(".xyz")).c_str(), + PATH_LITERAL("/foo.abc/bar.def.xyz")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc")).WithSuffix(PATH_LITERAL(".xyz")).c_str(), + PATH_LITERAL("/foo/.bar.xyz")); + EXPECT_STREQ(Path::FromFS(PATH_LITERAL("/foo/.bar.abc.def")).WithSuffix(PATH_LITERAL(".xyz")).c_str(), + PATH_LITERAL("/foo/.bar.abc.xyz")); +} diff --git a/test/fs/meson.build b/test/fs/meson.build new file mode 100644 index 0000000..82048a1 --- /dev/null +++ b/test/fs/meson.build @@ -0,0 +1,31 @@ +test( + 'TestFs', + executable( + 'TestFs', + 'TestGlob.cxx', + 'TestLookupFile.cxx', + 'TestPath.cxx', + include_directories: inc, + dependencies: [ + fs_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +test( + 'TestParsePath', + executable( + 'TestParsePath', + 'TestParsePath.cxx', + '../../src/config/Path.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + fs_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) diff --git a/test/fuzzer/FuzzCueParser.cxx b/test/fuzzer/FuzzCueParser.cxx new file mode 100644 index 0000000..04f28f2 --- /dev/null +++ b/test/fuzzer/FuzzCueParser.cxx @@ -0,0 +1,23 @@ +#include "playlist/cue/CueParser.hxx" +#include "util/IterableSplitString.hxx" + +extern "C" { +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); +} + +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + CueParser parser; + + const std::string_view src{(const char *)data, size}; + + for (const auto line : IterableSplitString(src, '\n')) { + parser.Feed(line); + parser.Get(); + } + + parser.Finish(); + parser.Get(); + + return 0; +} diff --git a/test/fuzzer/meson.build b/test/fuzzer/meson.build new file mode 100644 index 0000000..6a87f99 --- /dev/null +++ b/test/fuzzer/meson.build @@ -0,0 +1,9 @@ +executable( + 'FuzzCueParser', + 'FuzzCueParser.cxx', + '../../src/playlist/cue/CueParser.cxx', + include_directories: inc, + dependencies: [ + tag_dep, + ], +) diff --git a/test/meson.build b/test/meson.build new file mode 100644 index 0000000..a67b973 --- /dev/null +++ b/test/meson.build @@ -0,0 +1,645 @@ +gtest_dep = dependency('gtest', main: true, + include_type: 'system', + fallback: ['gtest', 'gtest_main_dep']) + +subdir('util') +subdir('net') +subdir('time') +subdir('tag') +subdir('playlist') + +executable( + 'read_conf', + 'read_conf.cxx', + include_directories: inc, + dependencies: [ + config_dep, + fmt_dep, + ], +) + +test( + 'TestRewindInputStream', + executable( + 'TestRewindInputStream', + 'TestRewindInputStream.cxx', + include_directories: inc, + dependencies: [ + input_glue_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +test( + 'test_protocol', + executable( + 'test_protocol', + 'test_protocol.cxx', + '../src/protocol/ArgParser.cxx', + include_directories: inc, + dependencies: [ + gtest_dep, + fmt_dep, + ], + ), + protocol: 'gtest', +) + +test( + 'test_queue_priority', + executable( + 'test_queue_priority', + 'test_queue_priority.cxx', + '../src/queue/Queue.cxx', + include_directories: inc, + dependencies: [ + util_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +test( + 'TestIcu', + executable( + 'TestIcu', + 'TestIcu.cxx', + include_directories: inc, + dependencies: [ + util_dep, + icu_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +if zeroconf_dep.found() + executable( + 'RunZeroconf', + 'RunZeroconf.cxx', + 'ShutdownHandler.cxx', + include_directories: inc, + dependencies: [ + zeroconf_dep, + event_dep, + util_dep, + ], + ) +endif + +if enable_inotify + executable( + 'run_inotify', + 'run_inotify.cxx', + 'ShutdownHandler.cxx', + include_directories: inc, + dependencies: [ + log_dep, + event_dep, + util_dep, + ], + ) +endif + +executable( + 'run_resolver', + 'run_resolver.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + net_dep, + util_dep, + ], +) + +# +# I/O +# + +executable( + 'WriteFile', + 'WriteFile.cxx', + include_directories: inc, + dependencies: [ + fs_dep, + io_fs_dep, + ], +) + +executable( + 'dump_text_file', + 'dump_text_file.cxx', + include_directories: inc, + dependencies: [ + input_glue_dep, + archive_glue_dep, + ], +) + +if zlib_dep.found() + executable( + 'run_gzip', + 'run_gzip.cxx', + include_directories: inc, + dependencies: [ + zlib_dep, + util_dep, + ], + ) + + executable( + 'run_gunzip', + 'run_gunzip.cxx', + include_directories: inc, + dependencies: [ + fs_dep, + io_fs_dep, + zlib_dep, + ], + ) +endif + +# +# Filter +# + +executable( + 'ParseSongFilter', + 'ParseSongFilter.cxx', + include_directories: inc, + dependencies: [ + song_dep, + pcm_dep, + ], +) + +test( + 'TestSongFilter', + executable( + 'TestSongFilter', + 'TestStringFilter.cxx', + 'TestTagSongFilter.cxx', + include_directories: inc, + dependencies: [ + song_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +# +# Neighbor +# + +if neighbor_glue_dep.found() + executable( + 'run_neighbor_explorer', + 'run_neighbor_explorer.cxx', + 'ShutdownHandler.cxx', + include_directories: inc, + dependencies: [ + neighbor_glue_dep, + event_dep, + ], + ) +endif + +# +# Database +# + +if enable_database + executable( + 'run_storage', + 'run_storage.cxx', + '../src/TagSave.cxx', + include_directories: inc, + dependencies: [ + event_dep, + storage_glue_dep, + cmdline_dep, + ], + ) + + executable( + 'DumpDatabase', + 'DumpDatabase.cxx', + '../src/db/Configured.cxx', + '../src/db/DatabaseGlue.cxx', + '../src/db/Registry.cxx', + '../src/db/Selection.cxx', + '../src/db/PlaylistVector.cxx', + '../src/db/DatabaseLock.cxx', + '../src/SongSave.cxx', + '../src/TagSave.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + pcm_basic_dep, + song_dep, + fs_dep, + event_dep, + db_plugins_dep, + ], + ) + + executable( + 'LoadDatabase', + 'LoadDatabase.cxx', + '../src/db/PlaylistVector.cxx', + '../src/SongSave.cxx', + '../src/TagSave.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + pcm_basic_dep, + song_dep, + db_plugins_dep, + zlib_dep, + ], + ) + + test( + 'test_translate_song', + executable( + 'test_translate_song', + 'test_translate_song.cxx', + '../src/playlist/PlaylistSong.cxx', + '../src/SongLoader.cxx', + '../src/LocateUri.cxx', + include_directories: inc, + dependencies: [ + event_dep, + log_dep, + tag_dep, + fs_dep, + storage_plugins_dep, + gtest_dep, + ], + ), + protocol: 'gtest', + ) +endif + +# +# Input +# + +run_input = executable( + 'run_input', + 'run_input.cxx', + '../src/TagSave.cxx', + include_directories: inc, + dependencies: [ + log_dep, + input_glue_dep, + archive_glue_dep, + cmdline_dep, + ], +) + +if curl_dep.found() + executable( + 'RunCurl', + 'RunCurl.cxx', + 'ShutdownHandler.cxx', + include_directories: inc, + dependencies: [ + curl_dep, + event_dep, + ], + ) + + test( + 'test_icy_parser', + executable( + 'test_icy_parser', + 'test_icy_parser.cxx', + include_directories: inc, + dependencies: [ + icu_dep, + tag_dep, + gtest_dep, + ], + ), + protocol: 'gtest', + ) +endif + +# +# Archive +# + +if archive_glue_dep.found() + executable( + 'visit_archive', + 'visit_archive.cxx', + include_directories: inc, + dependencies: [ + archive_glue_dep, + ], + ) + + if libiso9660_dep.found() + if find_program('mkisofs', required: false).found() + test( + 'test_archive_iso9660', + find_program('test_archive_iso9660.sh'), + depends: run_input, + ) + endif + endif + + if libbz2_dep.found() + if find_program('bzip2', required: false).found() + test( + 'test_archive_bzip2', + find_program('test_archive_bzip2.sh'), + depends: run_input, + ) + endif + endif + + if libzzip_dep.found() + if find_program('zip', required: false).found() + test( + 'test_archive_zzip', + find_program('test_archive_zzip.sh'), + depends: run_input, + ) + endif + endif +endif + +# +# Playlist +# + +executable( + 'dump_playlist', + 'dump_playlist.cxx', + '../src/TagSave.cxx', + '../src/TagFile.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + playlist_glue_dep, + input_glue_dep, + archive_glue_dep, + decoder_glue_dep, + ], +) + +# +# Tag +# + +if chromaprint_dep.found() + executable( + 'RunChromaprint', + 'RunChromaprint.cxx', + '../src/lib/chromaprint/DecoderClient.cxx', + include_directories: inc, + dependencies: [ + decoder_glue_dep, + input_glue_dep, + archive_glue_dep, + chromaprint_dep, + cmdline_dep, + ], + ) +endif + +# +# Decoder +# + +executable( + 'run_decoder', + 'run_decoder.cxx', + 'DumpDecoderClient.cxx', + include_directories: inc, + dependencies: [ + log_dep, + decoder_glue_dep, + input_glue_dep, + archive_glue_dep, + cmdline_dep, + ], +) + +executable( + 'read_tags', + 'read_tags.cxx', + include_directories: inc, + dependencies: [ + decoder_glue_dep, + input_glue_dep, + archive_glue_dep, + ], +) + +executable( + 'ContainerScan', + 'ContainerScan.cxx', + '../src/SongSave.cxx', + '../src/TagSave.cxx', + include_directories: inc, + dependencies: [ + fmt_dep, + decoder_glue_dep, + input_glue_dep, + archive_glue_dep, + ], +) + +executable( + 'ReadApeTags', + 'ReadApeTags.cxx', + include_directories: inc, + dependencies: [ + tag_dep, + input_glue_dep, + archive_glue_dep, + ], +) + +if libid3tag_dep.found() + executable( + 'dump_rva2', + 'dump_rva2.cxx', + include_directories: inc, + dependencies: [ + tag_dep, + input_glue_dep, + archive_glue_dep, + libid3tag_dep, + ], + ) +endif + +if ogg_dep.found() + executable( + 'DumpOgg', + 'DumpOgg.cxx', + include_directories: inc, + dependencies: [ + ogg_dep, + input_glue_dep, + archive_glue_dep, + ], + ) +endif + +# +# Filter +# + +test( + 'test_pcm', + executable( + 'test_pcm', + 'TestAudioFormat.cxx', + 'test_pcm_dither.cxx', + 'test_pcm_pack.cxx', + 'test_pcm_channels.cxx', + 'test_pcm_format.cxx', + 'test_pcm_volume.cxx', + 'test_pcm_mix.cxx', + 'test_pcm_interleave.cxx', + 'test_pcm_export.cxx', + include_directories: inc, + dependencies: [ + pcm_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) + +executable( + 'run_filter', + 'run_filter.cxx', + 'ReadFrames.cxx', + include_directories: inc, + dependencies: [ + filter_glue_dep, + cmdline_dep, + ], +) + +executable( + 'software_volume', + 'software_volume.cxx', + include_directories: inc, + dependencies: [ + pcm_dep, + ], +) + +executable( + 'run_normalize', + 'run_normalize.cxx', + include_directories: inc, + dependencies: [ + pcm_dep, + ], +) + +executable( + 'run_convert', + 'run_convert.cxx', + include_directories: inc, + dependencies: [ + log_dep, + pcm_dep, + config_dep, + cmdline_dep, + ], +) + +executable( + 'RunReplayGainAnalyzer', + 'RunReplayGainAnalyzer.cxx', + 'ReadFrames.cxx', + include_directories: inc, + dependencies: [ + pcm_dep, + io_dep, + ], +) + +executable( + 'RunMixRampAnalyzer', + 'RunMixRampAnalyzer.cxx', + 'ReadFrames.cxx', + include_directories: inc, + dependencies: [ + pcm_dep, + io_dep, + ], +) + +# +# Encoder +# + +if need_encoder + executable( + 'run_encoder', + 'run_encoder.cxx', + include_directories: inc, + dependencies: [ + encoder_glue_dep, + ], + ) + + executable( + 'test_vorbis_encoder', + 'test_vorbis_encoder.cxx', + include_directories: inc, + dependencies: [ + encoder_glue_dep, + ], + ) +endif + +# +# Output +# + +executable( + 'run_output', + 'run_output.cxx', + include_directories: inc, + dependencies: [ + output_registry_dep, + encoder_glue_dep, + event_dep, + cmdline_dep, + ], +) + +# +# Mixer +# + +if alsa_dep.found() + # this debug program is still ALSA specific + + executable( + 'read_mixer', + 'read_mixer.cxx', + include_directories: inc, + dependencies: [ + mixer_plugins_dep, + ], + ) +endif + +subdir('fs') diff --git a/test/net/TestIPv4Address.cxx b/test/net/TestIPv4Address.cxx new file mode 100644 index 0000000..e6f2efa --- /dev/null +++ b/test/net/TestIPv4Address.cxx @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "net/Init.hxx" +#include "net/IPv4Address.hxx" +#include "net/ToString.hxx" +#include "util/Compiler.h" + +#include + +#include + +#ifndef _WIN32 +#include +#endif + +#if GCC_CHECK_VERSION(11,0) +/* suppress warning for calling GetSize() on uninitialized object */ +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + +TEST(IPv4AddressTest, Basic) +{ + IPv4Address dummy; + EXPECT_EQ(dummy.GetSize(), sizeof(struct sockaddr_in)); +} + +TEST(IPv4AddressTest, Port) +{ + IPv4Address a(12345); + EXPECT_EQ(a.GetPort(), 12345u); + + a.SetPort(42); + EXPECT_EQ(a.GetPort(), 42u); +} + +TEST(IPv4AddressTest, NumericAddress) +{ + IPv4Address a(12345); + EXPECT_EQ(a.GetNumericAddress(), 0u); + EXPECT_EQ(a.GetNumericAddressBE(), 0u); + + a = IPv4Address(192, 168, 1, 2, 42); + EXPECT_EQ(a.GetNumericAddress(), 0xc0a80102); + EXPECT_EQ(a.GetNumericAddressBE(), ToBE32(0xc0a80102)); +} + +TEST(IPv4AddressTest, Mask) +{ + EXPECT_EQ(IPv4Address::MaskFromPrefix(0).GetNumericAddress(), + IPv4Address(0, 0, 0, 0, 0).GetNumericAddress()); + EXPECT_EQ(IPv4Address::MaskFromPrefix(1).GetNumericAddress(), + IPv4Address(128, 0, 0, 0, 0).GetNumericAddress()); + EXPECT_EQ(IPv4Address::MaskFromPrefix(23).GetNumericAddress(), + IPv4Address(255, 255, 254, 0, 0).GetNumericAddress()); + EXPECT_EQ(IPv4Address::MaskFromPrefix(24).GetNumericAddress(), + IPv4Address(255, 255, 255, 0, 0).GetNumericAddress()); + EXPECT_EQ(IPv4Address::MaskFromPrefix(32).GetNumericAddress(), + IPv4Address(255, 255, 255, 255, 0).GetNumericAddress()); +} + +TEST(IPv4AddressTest, And) +{ + EXPECT_EQ((IPv4Address::MaskFromPrefix(32) & + IPv4Address(192, 168, 1, 2, 0)).GetNumericAddress(), + IPv4Address(192, 168, 1, 2, 0).GetNumericAddress()); + EXPECT_EQ((IPv4Address::MaskFromPrefix(24) & + IPv4Address(192, 168, 1, 2, 0)).GetNumericAddress(), + IPv4Address(192, 168, 1, 0, 0).GetNumericAddress()); + EXPECT_EQ((IPv4Address::MaskFromPrefix(16) & + IPv4Address(192, 168, 1, 2, 0)).GetNumericAddress(), + IPv4Address(192, 168, 0, 0, 0).GetNumericAddress()); + EXPECT_EQ((IPv4Address::MaskFromPrefix(8) & + IPv4Address(192, 168, 1, 2, 0)).GetNumericAddress(), + IPv4Address(192, 0, 0, 0, 0).GetNumericAddress()); + EXPECT_EQ((IPv4Address::MaskFromPrefix(0) & + IPv4Address(192, 168, 1, 2, 0)).GetNumericAddress(), + IPv4Address(0, 0, 0, 0, 0).GetNumericAddress()); +} + +static std::string +ToString(const struct in_addr &a) +{ +#ifdef _WIN32 + /* on mingw32, the parameter is non-const (PVOID) */ + const auto p = const_cast(&a); +#else + const auto p = &a; +#endif + + char buffer[256]; + const char *result = inet_ntop(AF_INET, p, buffer, sizeof(buffer)); + if (result == nullptr) + throw std::runtime_error("inet_ntop() failed"); + return result; +} + +TEST(IPv4Address, Octets) +{ + const ScopeNetInit net_init; + + static constexpr auto a = IPv4Address(11, 22, 33, 44, 1234); + EXPECT_EQ(ToString(a.GetAddress()), "11.22.33.44"); +} + +TEST(IPv4Address, Any) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(ToString(IPv4Address(1234).GetAddress()), "0.0.0.0"); + EXPECT_EQ(ToString(IPv4Address(1234)), "0.0.0.0:1234"); +} + +TEST(IPv4Address, Port) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(IPv4Address(0).GetPort(), 0); + EXPECT_EQ(IPv4Address(1).GetPort(), 1); + EXPECT_EQ(IPv4Address(1234).GetPort(), 1234); + EXPECT_EQ(IPv4Address(0xffff).GetPort(), 0xffff); +} + +TEST(IPv4Address, Loopback) +{ + const ScopeNetInit net_init; + + static constexpr auto a = IPv4Address(IPv4Address::Loopback(), 1234); + EXPECT_EQ(ToString(a.GetAddress()), "127.0.0.1"); +} + +TEST(IPv4Address, MaskFromPrefix) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(0).GetAddress()), "0.0.0.0"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(4).GetAddress()), "240.0.0.0"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(8).GetAddress()), "255.0.0.0"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(16).GetAddress()), "255.255.0.0"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(24).GetAddress()), "255.255.255.0"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(31).GetAddress()), "255.255.255.254"); + EXPECT_EQ(ToString(IPv4Address::MaskFromPrefix(32).GetAddress()), "255.255.255.255"); +} + +TEST(IPv4Address, Numeric) +{ + EXPECT_EQ(IPv4Address(1, 2, 3, 4, 0).GetNumericAddress(), 0x01020304u); + EXPECT_EQ(IPv4Address(1, 2, 3, 4, 0).GetNumericAddressBE(), htonl(0x01020304)); +} diff --git a/test/net/TestIPv6Address.cxx b/test/net/TestIPv6Address.cxx new file mode 100644 index 0000000..b751a1a --- /dev/null +++ b/test/net/TestIPv6Address.cxx @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "net/Init.hxx" +#include "net/IPv6Address.hxx" +#include "net/ToString.hxx" +#include "util/Compiler.h" + +#include + +#include + +#ifndef _WIN32 +#include +#endif + +#if GCC_CHECK_VERSION(11,0) +/* suppress warning for calling GetSize() on uninitialized object */ +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + +TEST(IPv6AddressTest, Basic) +{ + IPv6Address dummy; + EXPECT_EQ(dummy.GetSize(), sizeof(struct sockaddr_in6)); +} + +TEST(IPv6AddressTest, Port) +{ + IPv6Address a(12345); + EXPECT_EQ(a.GetPort(), 12345u); + + a.SetPort(42); + EXPECT_EQ(a.GetPort(), 42u); +} + +static bool +operator==(const struct in6_addr &a, const struct in6_addr &b) +{ + return memcmp(&a, &b, sizeof(a)) == 0; +} + +TEST(IPv6AddressTest, Mask) +{ + EXPECT_EQ(IPv6Address::MaskFromPrefix(0).GetAddress(), + IPv6Address(0, 0, 0, 0, 0, 0, 0, 0, 0).GetAddress()); + EXPECT_EQ(IPv6Address::MaskFromPrefix(128).GetAddress(), + IPv6Address(0xffff, 0xffff, 0xffff, 0xffff, + 0xffff, 0xffff, 0xffff, 0xffff, 0).GetAddress()); + EXPECT_EQ(IPv6Address::MaskFromPrefix(127).GetAddress(), + IPv6Address(0xffff, 0xffff, 0xffff, 0xffff, + 0xffff, 0xffff, 0xffff, 0xfffe, 0).GetAddress()); + EXPECT_EQ(IPv6Address::MaskFromPrefix(64).GetAddress(), + IPv6Address(0xffff, 0xffff, 0xffff, 0xffff, + 0, 0, 0, 0, 0).GetAddress()); + EXPECT_EQ(IPv6Address::MaskFromPrefix(56).GetAddress(), + IPv6Address(0xffff, 0xffff, 0xffff, 0xff00, + 0, 0, 0, 0, 0).GetAddress()); +} + +TEST(IPv6AddressTest, And) +{ + EXPECT_EQ((IPv6Address::MaskFromPrefix(128) & + IPv6Address::MaskFromPrefix(56)).GetAddress(), + IPv6Address::MaskFromPrefix(56).GetAddress()); + EXPECT_EQ((IPv6Address::MaskFromPrefix(48) & + IPv6Address(0x2a00, 0x1450, 0x4001, 0x816, + 0, 0, 0, 0x200e, 0)).GetAddress(), + IPv6Address(0x2a00, 0x1450, 0x4001, 0, + 0, 0, 0, 0, 0).GetAddress()); + EXPECT_EQ((IPv6Address::MaskFromPrefix(24) & + IPv6Address(0x2a00, 0x1450, 0x4001, 0x816, + 0, 0, 0, 0x200e, 0)).GetAddress(), + IPv6Address(0x2a00, 0x1400, 0, 0, + 0, 0, 0, 0, 0).GetAddress()); +} + +static std::string +ToString(const struct in6_addr &a) +{ +#ifdef _WIN32 + /* on mingw32, the parameter is non-const (PVOID) */ + const auto p = const_cast(&a); +#else + const auto p = &a; +#endif + + char buffer[256]; + const char *result = inet_ntop(AF_INET6, p, buffer, sizeof(buffer)); + if (result == nullptr) + throw std::runtime_error("inet_ntop() failed"); + return result; +} + +TEST(IPv6Address, Octets) +{ + const ScopeNetInit net_init; + + static constexpr auto a = IPv6Address(0x1110, 0x2220, 0x3330, 0x4440, + 0x5550, 0x6660, 0x7770, 0x8880, + 1234); + EXPECT_EQ(ToString(a.GetAddress()), "1110:2220:3330:4440:5550:6660:7770:8880"); +} + +TEST(IPv6Address, Any) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(ToString(IPv6Address(1234).GetAddress()), "::"); + EXPECT_EQ(ToString(IPv6Address(1234)), "[::]:1234"); +} + +TEST(IPv6Address, Port) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(IPv6Address(0).GetPort(), 0); + EXPECT_EQ(IPv6Address(1).GetPort(), 1); + EXPECT_EQ(IPv6Address(1234).GetPort(), 1234); + EXPECT_EQ(IPv6Address(0xffff).GetPort(), 0xffff); +} + +TEST(IPv6Address, MaskFromPrefix) +{ + const ScopeNetInit net_init; + + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(0).GetAddress()), "::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(1).GetAddress()), "8000::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(8).GetAddress()), "ff00::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(16).GetAddress()), "ffff::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(17).GetAddress()), "ffff:8000::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(32).GetAddress()), "ffff:ffff::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(64).GetAddress()), "ffff:ffff:ffff:ffff::"); + EXPECT_TRUE(/* glibc: */ + ToString(IPv6Address::MaskFromPrefix(112).GetAddress()) == "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0" || + /* macOS: */ + ToString(IPv6Address::MaskFromPrefix(112).GetAddress()) == "ffff:ffff:ffff:ffff:ffff:ffff:ffff::"); + EXPECT_EQ(ToString(IPv6Address::MaskFromPrefix(128).GetAddress()), "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); +} diff --git a/test/net/TestLocalSocketAddress.cxx b/test/net/TestLocalSocketAddress.cxx new file mode 100644 index 0000000..be9ee5c --- /dev/null +++ b/test/net/TestLocalSocketAddress.cxx @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "net/AllocatedSocketAddress.hxx" +#include "net/LocalSocketAddress.hxx" +#include "net/ToString.hxx" + +#include + +#include + +using std::string_view_literals::operator""sv; + +TEST(LocalSocketAddress, Path1) +{ + const char *path = "/run/foo/bar.socket"; + LocalSocketAddress a; + a.SetLocal(path); + EXPECT_TRUE(a.IsDefined()); + EXPECT_EQ(a.GetFamily(), AF_LOCAL); + EXPECT_EQ(ToString(a), path); + EXPECT_EQ(a.GetLocalRaw(), "/run/foo/bar.socket\0"sv); + EXPECT_STREQ(a.GetLocalPath(), path); + + const struct sockaddr *const sa = a; + const auto &sun = *(const struct sockaddr_un *)sa; + EXPECT_STREQ(sun.sun_path, path); + EXPECT_EQ(sun.sun_path + strlen(path) + 1, (const char *)sa + a.GetSize()); +} + +TEST(LocalSocketAddress, Path2) +{ + static constexpr const char *path = "/run/foo/bar.socket"; + static constexpr LocalSocketAddress a{path}; + EXPECT_TRUE(a.IsDefined()); + EXPECT_EQ(a.GetFamily(), AF_LOCAL); + EXPECT_EQ(ToString(a), path); + EXPECT_EQ(a.GetLocalRaw(), "/run/foo/bar.socket\0"sv); + EXPECT_STREQ(a.GetLocalPath(), path); + + const struct sockaddr *const sa = a; + const auto &sun = *(const struct sockaddr_un *)sa; + EXPECT_STREQ(sun.sun_path, path); + EXPECT_EQ(sun.sun_path + strlen(path) + 1, (const char *)sa + a.GetSize()); +} + +TEST(LocalSocketAddress, Path) +{ + const char *path = "/run/foo/bar.socket"; + AllocatedSocketAddress a; + a.SetLocal(path); + EXPECT_FALSE(a.IsNull()); + EXPECT_TRUE(a.IsDefined()); + EXPECT_EQ(a.GetFamily(), AF_LOCAL); + EXPECT_EQ(ToString(a), path); + EXPECT_EQ(a.GetLocalRaw(), "/run/foo/bar.socket\0"sv); + EXPECT_STREQ(a.GetLocalPath(), path); + + const auto &sun = *(const struct sockaddr_un *)a.GetAddress(); + EXPECT_STREQ(sun.sun_path, path); + EXPECT_EQ(sun.sun_path + strlen(path) + 1, (const char *)a.GetAddress() + a.GetSize()); +} + +#ifdef __linux__ + +TEST(LocalSocketAddress, Abstract1) +{ + const char *path = "@foo.bar"; + LocalSocketAddress a; + a.SetLocal(path); + EXPECT_TRUE(a.IsDefined()); + EXPECT_EQ(a.GetFamily(), AF_LOCAL); + EXPECT_EQ(ToString(a), path); + EXPECT_EQ(a.GetLocalRaw(), "\0foo.bar"sv); + EXPECT_EQ(a.GetLocalPath(), nullptr); + + const struct sockaddr *const sa = a; + const auto &sun = *(const struct sockaddr_un *)sa; + + /* Linux's abstract sockets start with a null byte, ... */ + EXPECT_EQ(sun.sun_path[0], 0); + + /* ... but are not null-terminated */ + EXPECT_EQ(memcmp(sun.sun_path + 1, path + 1, strlen(path) - 1), 0); + EXPECT_EQ(sun.sun_path + strlen(path), (const char *)sa + a.GetSize()); +} + +TEST(LocalSocketAddress, Abstract) +{ + const char *path = "@foo.bar"; + AllocatedSocketAddress a; + a.SetLocal(path); + EXPECT_FALSE(a.IsNull()); + EXPECT_TRUE(a.IsDefined()); + EXPECT_EQ(a.GetFamily(), AF_LOCAL); + EXPECT_EQ(ToString(a), path); + EXPECT_EQ(a.GetLocalRaw(), "\0foo.bar"sv); + EXPECT_EQ(a.GetLocalPath(), nullptr); + + const auto &sun = *(const struct sockaddr_un *)a.GetAddress(); + + /* Linux's abstract sockets start with a null byte, ... */ + EXPECT_EQ(sun.sun_path[0], 0); + + /* ... but are not null-terminated */ + EXPECT_EQ(memcmp(sun.sun_path + 1, path + 1, strlen(path) - 1), 0); + EXPECT_EQ(sun.sun_path + strlen(path), (const char *)a.GetAddress() + a.GetSize()); +} + +#endif diff --git a/test/net/meson.build b/test/net/meson.build new file mode 100644 index 0000000..ede17d0 --- /dev/null +++ b/test/net/meson.build @@ -0,0 +1,28 @@ +test_net_sources = [] + +if have_tcp + test_net_sources += 'TestIPv4Address.cxx' + if have_ipv6 + test_net_sources += 'TestIPv6Address.cxx' + endif +endif + +if have_local_socket + test_net_sources += 'TestLocalSocketAddress.cxx' +endif + +test( + 'TestNet', + executable( + 'TestNet', + test_net_sources, + include_directories: inc, + dependencies: [ + net_dep, + fs_dep, + util_dep, + gtest_dep, + ], + ), + protocol: 'gtest', +) diff --git a/test/playlist/PlaylistUtil.cxx b/test/playlist/PlaylistUtil.cxx new file mode 100644 index 0000000..38f088f --- /dev/null +++ b/test/playlist/PlaylistUtil.cxx @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistUtil.hxx" +#include "playlist/PlaylistRegistry.hxx" +#include "playlist/SongEnumerator.hxx" +#include "song/DetachedSong.hxx" +#include "input/MemoryInputStream.hxx" +#include "input/Ptr.hxx" +#include "thread/Mutex.hxx" +#include "io/BufferedOutputStream.hxx" +#include "io/StringOutputStream.hxx" +#include "util/SpanCast.hxx" +#include "SongSave.hxx" + +std::unique_ptr +ParsePlaylist(const char *uri, std::string_view contents) +{ + Mutex mutex; + InputStreamPtr input{new MemoryInputStream{uri, mutex, AsBytes(contents)}}; + return playlist_list_open_stream(std::move(input), uri); +} + +std::string +ToString(SongEnumerator &e) +{ + StringOutputStream sos; + + WithBufferedOutputStream(sos, [&e](auto &bos){ + while (const auto song = e.NextSong()) { + bos.Write('\n'); + song_save(bos, *song); + } + + bos.Write('\n'); + }); + + return std::move(sos).GetValue(); +} diff --git a/test/playlist/PlaylistUtil.hxx b/test/playlist/PlaylistUtil.hxx new file mode 100644 index 0000000..39cc23f --- /dev/null +++ b/test/playlist/PlaylistUtil.hxx @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#pragma once + +#include +#include + +class SongEnumerator; + +std::unique_ptr +ParsePlaylist(const char *uri, std::string_view contents); + +std::string +ToString(SongEnumerator &e); diff --git a/test/playlist/TestPlsPlaylistPlugin.cxx b/test/playlist/TestPlsPlaylistPlugin.cxx new file mode 100644 index 0000000..dfc874e --- /dev/null +++ b/test/playlist/TestPlsPlaylistPlugin.cxx @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "PlaylistUtil.hxx" +#include "playlist/PlaylistRegistry.hxx" +#include "playlist/SongEnumerator.hxx" +#include "config/Data.hxx" + +#include + +using std::string_view_literals::operator""sv; + +// from https://en.wikipedia.org/wiki/PLS_(file_format) +static constexpr auto pls1 = R"( +[playlist] +File1=https://e20.yesstreaming.net:8279/ +Title1=Here enter name of the station +NumberOfEntries=1 +)"sv; + +static constexpr auto expect1 = R"( +song_begin: https://e20.yesstreaming.net:8279/ +Title: Here enter name of the station +song_end + +)"sv; + +// from https://en.wikipedia.org/wiki/PLS_(file_format) +static constexpr auto pls2 = R"pls( +[playlist] + +File1=https://e20.yesstreaming.net:8279/ +Length1=-1 + +File2=example2.mp3 +Title2=Just some local audio that is 2mins long +Length2=120 + +File3=F:\Music\whatever.m4a +Title3=absolute path on Windows + +File4=%UserProfile%\Music\short.ogg +Title4=example for an Environment variable +Length4=5 + +NumberOfEntries=4 +Version=2 +)pls"sv; + +static constexpr auto expect2 = R"( +song_begin: https://e20.yesstreaming.net:8279/ +song_end + +song_begin: example2.mp3 +Time: 120 +Title: Just some local audio that is 2mins long +song_end + +song_begin: F:\Music\whatever.m4a +Title: absolute path on Windows +song_end + +song_begin: %UserProfile%\Music\short.ogg +Time: 5 +Title: example for an Environment variable +song_end + +)"sv; + +TEST(PlaylistPlugins, Pls) +{ + const ConfigData config; + ScopePlaylistPluginsInit playlist_plugins_init{config}; + + const char *uri = "dummy.pls"; + + { + const auto p = ParsePlaylist(uri, pls1); + ASSERT_TRUE(p); + EXPECT_EQ(ToString(*p), expect1); + } + + { + const auto p = ParsePlaylist(uri, pls2); + ASSERT_TRUE(p); + EXPECT_EQ(ToString(*p), expect2); + } +} diff --git a/test/playlist/meson.build b/test/playlist/meson.build new file mode 100644 index 0000000..98c110f --- /dev/null +++ b/test/playlist/meson.build @@ -0,0 +1,19 @@ +test( + 'TestPlaylistPlugins', + executable( + 'TestPlaylistPlugins', + 'PlaylistUtil.cxx', + 'TestPlsPlaylistPlugin.cxx', + '../../src/SongSave.cxx', + '../../src/TagSave.cxx', + '../../src/TagFile.cxx', + include_directories: inc, + dependencies: [ + gtest_dep, + playlist_glue_dep, + archive_glue_dep, + input_glue_dep, + decoder_glue_dep, + ], + ), +) diff --git a/test/read_conf.cxx b/test/read_conf.cxx new file mode 100644 index 0000000..e908235 --- /dev/null +++ b/test/read_conf.cxx @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config/Data.hxx" +#include "config/Param.hxx" +#include "config/File.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "util/PrintException.hxx" + +#include +#include + +int main(int argc, char **argv) +try { + if (argc != 3) { + fprintf(stderr, "Usage: read_conf FILE SETTING\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath config_path = argv[1]; + const char *name = argv[2]; + + const auto option = ParseConfigOptionName(name); + if (option == ConfigOption::MAX) + throw FmtRuntimeError("Unknown setting: {}", name); + + ConfigData config; + ReadConfigFile(config, config_path); + + const auto *param = config.GetParam(option); + if (param == nullptr) + throw FmtRuntimeError("No such setting: {}", name); + + printf("%s\n", param->value.c_str()); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/read_mixer.cxx b/test/read_mixer.cxx new file mode 100644 index 0000000..c95e468 --- /dev/null +++ b/test/read_mixer.cxx @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "NullMixerListener.hxx" +#include "mixer/Control.hxx" +#include "mixer/Mixer.hxx" +#include "mixer/plugins/AlsaMixerPlugin.hxx" +#include "filter/Registry.hxx" +#include "event/Loop.hxx" +#include "config/Block.hxx" +#include "util/PrintException.hxx" + +#include + +#include + +const FilterPlugin * +filter_plugin_by_name([[maybe_unused]] const char *name) noexcept +{ + assert(false); + return nullptr; +} + +int main(int argc, [[maybe_unused]] char **argv) +try { + int volume; + + if (argc != 2) { + fprintf(stderr, "Usage: read_mixer PLUGIN\n"); + return EXIT_FAILURE; + } + + EventLoop event_loop; + + NullMixerListener mixer_listener; + Mixer *mixer = mixer_new(event_loop, alsa_mixer_plugin, + /* ugly dangerous dummy pointer to + make the compiler happy; this + works with most mixers, because + they don't need the AudioOutput */ + *(AudioOutput *)0x1, + mixer_listener, + ConfigBlock()); + + volume = mixer->LockGetVolume(); + mixer_free(mixer); + + assert(volume >= -1 && volume <= 100); + + if (volume < 0) { + fprintf(stderr, "failed to read volume\n"); + return EXIT_FAILURE; + } + + printf("%d\n", volume); + return 0; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/read_tags.cxx b/test/read_tags.cxx new file mode 100644 index 0000000..ba68b8a --- /dev/null +++ b/test/read_tags.cxx @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "config.h" +#include "config/Data.hxx" +#include "event/Thread.hxx" +#include "decoder/DecoderList.hxx" +#include "decoder/DecoderPlugin.hxx" +#include "input/Init.hxx" +#include "input/InputStream.hxx" +#include "tag/Handler.hxx" +#include "tag/Generic.hxx" +#include "tag/Names.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "pcm/AudioFormat.hxx" +#include "lib/fmt/AudioFormatFormatter.hxx" +#include "util/ScopeExit.hxx" +#include "util/StringBuffer.hxx" +#include "util/PrintException.hxx" + +#include + +#include +#include + +#include +#include + +#ifdef HAVE_LOCALE_H +#include +#endif + +class DumpTagHandler final : public NullTagHandler { + bool empty = true; + +public: + DumpTagHandler() noexcept + :NullTagHandler(WANT_DURATION|WANT_TAG|WANT_PAIR|WANT_PICTURE) {} + + bool IsEmpty() const noexcept { + return empty; + } + + void OnDuration(SongTime duration) noexcept override { + fmt::print("duration={}\n", duration.ToDoubleS()); + } + + void OnTag(TagType type, std::string_view value) noexcept override { + fmt::print("[{}]={:?}\n", tag_item_names[type], value); + empty = false; + } + + void OnPair(std::string_view key, std::string_view value) noexcept override { + fmt::print("{:?}={:?}\n", key, value); + } + + void OnAudioFormat(AudioFormat af) noexcept override { + fmt::print("{}\n", af); + } + + void OnPicture(const char *mime_type, + std::span buffer) noexcept override { + fmt::print("picture mime={:?} size={}\n", + mime_type, buffer.size()); + } +}; + +int main(int argc, char **argv) +try { + const char *decoder_name; + const struct DecoderPlugin *plugin; + +#ifdef HAVE_LOCALE_H + /* initialize locale */ + setlocale(LC_CTYPE,""); +#endif + + if (argc != 3) { + fmt::print(stderr, "Usage: read_tags DECODER FILE\n"); + return EXIT_FAILURE; + } + + decoder_name = argv[1]; + const char *path = argv[2]; + + EventThread io_thread; + io_thread.Start(); + + const ScopeInputPluginsInit input_plugins_init(ConfigData(), + io_thread.GetEventLoop()); + + const ScopeDecoderPluginsInit decoder_plugins_init({}); + + plugin = decoder_plugin_from_name(decoder_name); + if (plugin == nullptr) { + fmt::print(stderr, "No such decoder: {:?}\n", decoder_name); + return EXIT_FAILURE; + } + + DumpTagHandler h; + bool success; + try { + success = plugin->ScanFile(FromNarrowPath(path), h); + } catch (...) { + PrintException(std::current_exception()); + success = false; + } + + Mutex mutex; + InputStreamPtr is; + + if (!success && plugin->scan_stream != nullptr) { + is = InputStream::OpenReady(path, mutex); + success = plugin->ScanStream(*is, h); + } + + if (!success) { + fmt::print(stderr, "Failed to read tags\n"); + return EXIT_FAILURE; + } + + if (h.IsEmpty()) { + if (is) + ScanGenericTags(*is, h); + else + ScanGenericTags(FromNarrowPath(path), h); + } + + return 0; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_convert.cxx b/test/run_convert.cxx new file mode 100644 index 0000000..fd6355c --- /dev/null +++ b/test/run_convert.cxx @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This program is a command line interface to MPD's PCM conversion + * library (pcm_convert.c). + * + */ + +#include "ConfigGlue.hxx" +#include "pcm/AudioParser.hxx" +#include "pcm/AudioFormat.hxx" +#include "pcm/Convert.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "io/FileDescriptor.hxx" +#include "util/StaticFifoBuffer.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "util/PrintException.hxx" +#include "Log.hxx" +#include "LogBackend.hxx" + +#include +#include + +#include +#include +#include +#include + +struct CommandLine { + AudioFormat in_audio_format, out_audio_format; + + FromNarrowPath config_path; + + bool verbose = false; +}; + +enum Option { + OPTION_CONFIG, + OPTION_VERBOSE, +}; + +static constexpr OptionDef option_defs[] = { + {"config", 0, true, "Load a MPD configuration file"}, + {"verbose", 'v', false, "Verbose logging"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_CONFIG: + c.config_path = o.value; + break; + + case OPTION_VERBOSE: + c.verbose = true; + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() != 2) + throw std::runtime_error("Usage: run_convert IN_FORMAT OUT_FORMAT OUT"); + + c.in_audio_format = ParseAudioFormat(args[0], false); + c.out_audio_format = c.in_audio_format.WithMask(ParseAudioFormat(args[1], false)); + return c; +} + +class GlobalInit { + const ConfigData config; + +public: + explicit GlobalInit(Path config_path) + :config(AutoLoadConfigFile(config_path)) + { + pcm_convert_global_init(config); + } +}; + +static void +RunConvert(PcmConvert &convert, size_t in_frame_size, + FileDescriptor in_fd, FileDescriptor out_fd) +{ + in_fd.SetBinaryMode(); + out_fd.SetBinaryMode(); + + StaticFifoBuffer buffer; + + while (true) { + { + const auto dest = buffer.Write(); + assert(!dest.empty()); + + ssize_t nbytes = in_fd.Read(dest); + if (nbytes <= 0) + break; + + buffer.Append(nbytes); + } + + auto src = buffer.Read(); + assert(!src.empty()); + + src = src.first(src.size() - src.size() % in_frame_size); + if (src.empty()) + continue; + + buffer.Consume(src.size()); + + auto output = convert.Convert(src); + out_fd.FullWrite(output); + } + + while (true) { + auto output = convert.Flush(); + if (output.data() == nullptr) + break; + + out_fd.FullWrite(output); + } +} + +int +main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + const GlobalInit init(c.config_path); + + PcmConvert state(c.in_audio_format, c.out_audio_format); + RunConvert(state, c.in_audio_format.GetFrameSize(), + FileDescriptor(STDIN_FILENO), + FileDescriptor(STDOUT_FILENO)); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_decoder.cxx b/test/run_decoder.cxx new file mode 100644 index 0000000..64d57bd --- /dev/null +++ b/test/run_decoder.cxx @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ConfigGlue.hxx" +#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" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "pcm/AudioFormat.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "util/PrintException.hxx" +#include "Log.hxx" +#include "LogBackend.hxx" + +#include +#include + +#include +#include +#include + +struct CommandLine { + const char *decoder = nullptr; + const char *uri = nullptr; + + FromNarrowPath config_path; + + bool verbose = false; + + SongTime seek_where{}; +}; + +enum Option { + OPTION_CONFIG, + OPTION_VERBOSE, + OPTION_SEEK, +}; + +static constexpr OptionDef option_defs[] = { + {"config", 0, true, "Load a MPD configuration file"}, + {"verbose", 'v', false, "Verbose logging"}, + {"seek", 0, true, "Seek to this position"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_CONFIG: + c.config_path = o.value; + break; + + case OPTION_VERBOSE: + c.verbose = true; + break; + + case OPTION_SEEK: + c.seek_where = SongTime::FromS(strtod(o.value, nullptr)); + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() != 2) + throw std::runtime_error("Usage: run_decoder [--verbose] [--config=FILE] DECODER URI"); + + c.decoder = args[0]; + c.uri = args[1]; + return c; +} + +class GlobalInit { + const ConfigData config; + EventThread io_thread; + const ScopeInputPluginsInit input_plugins_init; + const ScopeDecoderPluginsInit decoder_plugins_init; + +public: + explicit GlobalInit(Path config_path) + :config(AutoLoadConfigFile(config_path)), + input_plugins_init(config, io_thread.GetEventLoop()), + decoder_plugins_init(config) + { + io_thread.Start(); + } +}; + +class MyDecoderClient final : public DumpDecoderClient { + SongTime seek_where; + + unsigned sample_rate; + + bool seekable, seek_error = false; + +public: + explicit MyDecoderClient(SongTime _seek_where) noexcept + :seek_where(_seek_where) {} + + void Finish() { + if (!IsInitialized()) + throw "Unrecognized file"; + + if (seek_error) + throw "Seek error"; + + if (seek_where != SongTime{}) { + if (!seekable) + throw "Not seekable"; + + throw "Did not seek"; + } + } + + /* virtual methods from DecoderClient */ + void Ready(AudioFormat audio_format, + bool _seekable, SignedSongTime duration) noexcept override { + assert(!IsInitialized()); + + DumpDecoderClient::Ready(audio_format, _seekable, duration); + sample_rate = audio_format.sample_rate; + seekable = _seekable; + } + + DecoderCommand GetCommand() noexcept override { + if (seek_where != SongTime{}) { + if (!seekable) + return DecoderCommand::STOP; + + return DecoderCommand::SEEK; + } else if (seek_error) + return DecoderCommand::STOP; + else + return DumpDecoderClient::GetCommand(); + } + + void CommandFinished() noexcept override { + assert(!seek_error); + + if (seek_where != SongTime{}) + seek_where = {}; + else + DumpDecoderClient::CommandFinished(); + } + + SongTime GetSeekTime() noexcept override { + assert(seek_where != SongTime{}); + + return seek_where; + } + + uint64_t GetSeekFrame() noexcept override { + assert(seek_where != SongTime{}); + + return GetSeekTime().ToScale(sample_rate); + } + + void SeekError() noexcept override { + assert(seek_where != SongTime{}); + + seek_error = true; + seek_where = {}; + } +}; + +int main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + const GlobalInit init(c.config_path); + + const DecoderPlugin *plugin = decoder_plugin_from_name(c.decoder); + if (plugin == nullptr) { + fprintf(stderr, "No such decoder: %s\n", c.decoder); + return EXIT_FAILURE; + } + + MyDecoderClient client(c.seek_where); + if (plugin->SupportsUri(c.uri)) { + try { + plugin->UriDecode(client, c.uri); + } catch (StopDecoder) { + } + } else if (plugin->file_decode != nullptr) { + try { + plugin->FileDecode(client, FromNarrowPath(c.uri)); + } catch (StopDecoder) { + } + } else if (plugin->stream_decode != nullptr) { + auto is = InputStream::OpenReady(c.uri, client.mutex); + try { + plugin->StreamDecode(client, *is); + } catch (StopDecoder) { + } + } else { + fprintf(stderr, "Decoder plugin is not usable\n"); + return EXIT_FAILURE; + } + + client.Finish(); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_encoder.cxx b/test/run_encoder.cxx new file mode 100644 index 0000000..5292bf3 --- /dev/null +++ b/test/run_encoder.cxx @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "encoder/EncoderList.hxx" +#include "encoder/EncoderPlugin.hxx" +#include "encoder/EncoderInterface.hxx" +#include "encoder/ToOutputStream.hxx" +#include "pcm/AudioFormat.hxx" +#include "pcm/AudioParser.hxx" +#include "config/Block.hxx" +#include "io/StdioOutputStream.hxx" +#include "util/PrintException.hxx" + +#include +#include + +#include +#include +#include + +int main(int argc, char **argv) +try { + const char *encoder_name; + + /* parse command line */ + + if (argc > 3) { + fprintf(stderr, + "Usage: run_encoder [ENCODER] [FORMAT] OUT\n"); + return EXIT_FAILURE; + } + + if (argc > 1) + encoder_name = argv[1]; + else + encoder_name = "vorbis"; + + /* create the encoder */ + + const auto plugin = encoder_plugin_get(encoder_name); + if (plugin == nullptr) { + fprintf(stderr, "No such encoder: %s\n", encoder_name); + return EXIT_FAILURE; + } + + ConfigBlock block; + block.AddBlockParam("quality", "5.0", -1); + + std::unique_ptr p_encoder(encoder_init(*plugin, block)); + + /* open the encoder */ + + AudioFormat audio_format(44100, SampleFormat::S16, 2); + if (argc > 2) + audio_format = ParseAudioFormat(argv[2], false); + + std::unique_ptr encoder(p_encoder->Open(audio_format)); + + StdioOutputStream os(stdout); + + EncoderToOutputStream(os, *encoder); + + /* do it */ + + static std::byte buffer[32768]; + ssize_t nbytes; + while ((nbytes = read(0, buffer, sizeof(buffer))) > 0) { + encoder->Write(std::span{buffer}.first(nbytes)); + EncoderToOutputStream(os, *encoder); + } + + encoder->End(); + EncoderToOutputStream(os, *encoder); + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_filter.cxx b/test/run_filter.cxx new file mode 100644 index 0000000..7eb294e --- /dev/null +++ b/test/run_filter.cxx @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ConfigGlue.hxx" +#include "ReadFrames.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "lib/fmt/AudioFormatFormatter.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "filter/LoadOne.hxx" +#include "filter/Filter.hxx" +#include "filter/Prepared.hxx" +#include "pcm/AudioParser.hxx" +#include "pcm/AudioFormat.hxx" +#include "pcm/Volume.hxx" +#include "mixer/Control.hxx" +#include "system/Error.hxx" +#include "io/FileDescriptor.hxx" +#include "util/StringBuffer.hxx" +#include "util/PrintException.hxx" +#include "LogBackend.hxx" + +#include +#include +#include + +#include +#include + +struct CommandLine { + FromNarrowPath config_path; + + const char *filter_name = nullptr; + + AudioFormat audio_format{44100, SampleFormat::S16, 2}; + + bool verbose = false; +}; + +enum Option { + OPTION_VERBOSE, +}; + +static constexpr OptionDef option_defs[] = { + {"verbose", 'v', false, "Verbose logging"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_VERBOSE: + c.verbose = true; + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() < 2 || args.size() > 3) + throw std::runtime_error("Usage: run_filter CONFIG NAME [FORMAT] 2) + c.audio_format = ParseAudioFormat(args[2], false); + + return c; +} + +static std::unique_ptr +LoadFilter(const ConfigData &config, const char *name) +{ + const auto *param = config.FindBlock(ConfigBlockOption::AUDIO_FILTER, + "name", name); + if (param == nullptr) + throw FmtRuntimeError("No such configured filter: {}", + name); + + return filter_configured_new(*param); +} + +int main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + + /* read configuration file (mpd.conf) */ + + const auto config = AutoLoadConfigFile(c.config_path); + + auto audio_format = c.audio_format; + const size_t in_frame_size = audio_format.GetFrameSize(); + + /* initialize the filter */ + + auto prepared_filter = LoadFilter(config, argv[2]); + + /* open the filter */ + + auto filter = prepared_filter->Open(audio_format); + + const AudioFormat out_audio_format = filter->GetOutAudioFormat(); + fmt::print(stderr, "audio_format={}\n", out_audio_format); + + /* play */ + + FileDescriptor input_fd(STDIN_FILENO); + FileDescriptor output_fd(STDOUT_FILENO); + + while (true) { + std::byte buffer[4096]; + + ssize_t nbytes = ReadFrames(input_fd, buffer, sizeof(buffer), + in_frame_size); + if (nbytes == 0) + break; + + for (auto dest = filter->FilterPCM(std::span{buffer}.first(nbytes)); + !dest.empty(); dest = filter->ReadMore()) + output_fd.FullWrite(dest); + } + + while (true) { + auto dest = filter->Flush(); + if (dest.empty()) + break; + output_fd.FullWrite(dest); + } + + /* cleanup and exit */ + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_gunzip.cxx b/test/run_gunzip.cxx new file mode 100644 index 0000000..b8e9795 --- /dev/null +++ b/test/run_gunzip.cxx @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "lib/zlib/GunzipReader.hxx" +#include "io/FileReader.hxx" +#include "io/StdioOutputStream.hxx" +#include "fs/NarrowPath.hxx" +#include "util/PrintException.hxx" + +#include +#include +#include + +static void +Copy(OutputStream &dest, Reader &src) +{ + while (true) { + std::byte buffer[4096]; + std::size_t nbytes = src.Read(buffer); + if (nbytes == 0) + break; + + dest.Write(std::span{buffer}.first(nbytes)); + } +} + +static void +CopyGunzip(OutputStream &dest, Reader &_src) +{ + GunzipReader src(_src); + Copy(dest, src); +} + +static void +CopyGunzip(FILE *_dest, Path src_path) +{ + StdioOutputStream dest(_dest); + FileReader src(src_path); + CopyGunzip(dest, src); +} + +int +main(int argc, [[maybe_unused]] char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: run_gunzip PATH\n"); + return EXIT_FAILURE; + } + + FromNarrowPath path = argv[1]; + + CopyGunzip(stdout, path); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_gzip.cxx b/test/run_gzip.cxx new file mode 100644 index 0000000..bbdca75 --- /dev/null +++ b/test/run_gzip.cxx @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "lib/zlib/GzipOutputStream.hxx" +#include "io/StdioOutputStream.hxx" +#include "system/Error.hxx" +#include "util/PrintException.hxx" + +#include +#include +#include + +static void +Copy(OutputStream &dest, int src) +{ + while (true) { + std::byte buffer[4096]; + ssize_t nbytes = read(src, buffer, sizeof(buffer)); + if (nbytes <= 0) { + if (nbytes < 0) + throw MakeErrno("read() failed"); + + return; + } + + dest.Write(std::span{buffer}.first(nbytes)); + } +} + +static void +CopyGzip(OutputStream &_dest, int src) +{ + GzipOutputStream dest(_dest); + Copy(dest, src); + dest.Finish(); +} + +static void +CopyGzip(FILE *_dest, int src) +{ + StdioOutputStream dest(_dest); + CopyGzip(dest, src); +} + +int +main(int argc, [[maybe_unused]] char **argv) +try { + if (argc != 1) { + fprintf(stderr, "Usage: run_gzip\n"); + return EXIT_FAILURE; + } + + CopyGzip(stdout, STDIN_FILENO); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_inotify.cxx b/test/run_inotify.cxx new file mode 100644 index 0000000..d81d39f --- /dev/null +++ b/test/run_inotify.cxx @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ShutdownHandler.hxx" +#include "event/InotifyEvent.hxx" +#include "event/Loop.hxx" +#include "Log.hxx" + +#include + +#include + +static constexpr unsigned IN_MASK = +#ifdef IN_ONLYDIR + IN_ONLYDIR| +#endif + IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_DELETE_SELF + |IN_MOVE|IN_MOVE_SELF; + +struct Instance final : InotifyHandler { + EventLoop event_loop; + const ShutdownHandler shutdown_handler{event_loop}; + + InotifyEvent inotify_event{event_loop, *this}; + + std::exception_ptr error; + + /* virtual methods from class InotifyHandler */ + void OnInotify(int, unsigned mask, const char *name) override { + printf("mask=0x%x name='%s'\n", mask, name); + } + + void OnInotifyError(std::exception_ptr _error) noexcept override { + error = std::move(_error); + event_loop.Break(); + } +}; + +int main(int argc, char **argv) +try { + const char *path; + + if (argc != 2) { + fprintf(stderr, "Usage: run_inotify PATH\n"); + return EXIT_FAILURE; + } + + path = argv[1]; + + Instance instance; + + instance.inotify_event.AddWatch(path, IN_MASK); + + instance.event_loop.Run(); + + if (instance.error) + std::rethrow_exception(instance.error); + + return EXIT_SUCCESS; +} catch (...) { + LogError(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_input.cxx b/test/run_input.cxx new file mode 100644 index 0000000..02966ad --- /dev/null +++ b/test/run_input.cxx @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "TagSave.hxx" +#include "tag/Tag.hxx" +#include "ConfigGlue.hxx" +#include "input/InputStream.hxx" +#include "input/Init.hxx" +#include "input/Registry.hxx" +#include "input/InputPlugin.hxx" +#include "input/RemoteTagScanner.hxx" +#include "input/ScanTags.hxx" +#include "event/Thread.hxx" +#include "thread/Cond.hxx" +#include "Log.hxx" +#include "LogBackend.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "io/BufferedOutputStream.hxx" +#include "io/FileDescriptor.hxx" +#include "io/StdioOutputStream.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "util/PrintException.hxx" + +#include "archive/Features.h" // for ENABLE_ARCHIVE +#ifdef ENABLE_ARCHIVE +#include "archive/ArchiveList.hxx" +#endif + +#include + +#include +#include + +static constexpr std::size_t MAX_CHUNK_SIZE = 16384; + +struct CommandLine { + const char *uri = nullptr; + + FromNarrowPath config_path; + + std::size_t seek = 0; + + std::size_t chunk_size = MAX_CHUNK_SIZE; + + bool verbose = false; + + bool scan = false; +}; + +enum Option { + OPTION_CONFIG, + OPTION_VERBOSE, + OPTION_SCAN, + OPTION_SEEK, + OPTION_CHUNK_SIZE, +}; + +static constexpr OptionDef option_defs[] = { + {"config", 0, true, "Load a MPD configuration file"}, + {"verbose", 'v', false, "Verbose logging"}, + {"scan", 0, false, "Scan tags instead of reading raw data"}, + {"seek", 0, true, "Start reading at this position"}, + {"chunk-size", 0, true, "Read this number of bytes at a time"}, +}; + +static std::size_t +ParseSize(const char *s) +{ + char *endptr; + std::size_t value = std::strtoul(s, &endptr, 10); + if (endptr == s) + throw std::runtime_error("Failed to parse integer"); + + return value; +} + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_CONFIG: + c.config_path = o.value; + break; + + case OPTION_VERBOSE: + c.verbose = true; + break; + + case OPTION_SCAN: + c.scan = true; + break; + + case OPTION_SEEK: + c.seek = ParseSize(o.value); + break; + + case OPTION_CHUNK_SIZE: + c.chunk_size = ParseSize(o.value); + if (c.chunk_size <= 0 || c.chunk_size > MAX_CHUNK_SIZE) + throw std::runtime_error("Invalid chunk size"); + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() != 1) + throw std::runtime_error("Usage: run_input [--verbose] [--config=FILE] [--scan] [--chunk-size=BYTES] URI"); + + c.uri = args.front(); + return c; +} + +class GlobalInit { + const ConfigData config; + EventThread io_thread; + +#ifdef ENABLE_ARCHIVE + const ScopeArchivePluginsInit archive_plugins_init{config}; +#endif + + const ScopeInputPluginsInit input_plugins_init{config, io_thread.GetEventLoop()}; + +public: + explicit GlobalInit(Path config_path) + :config(AutoLoadConfigFile(config_path)) + { + io_thread.Start(); + } +}; + +static void +tag_save(FILE *file, const Tag &tag) +{ + StdioOutputStream sos(file); + WithBufferedOutputStream(sos, [&](auto &bos){ + tag_save(bos, tag); + }); +} + +static int +dump_input_stream(InputStream &is, FileDescriptor out, + offset_type seek, size_t chunk_size) +{ + out.SetBinaryMode(); + + std::unique_lock lock{is.mutex}; + + if (seek > 0) + is.Seek(lock, seek); + + /* print meta data */ + + if (is.HasMimeType()) + fprintf(stderr, "MIME type: %s\n", is.GetMimeType()); + + /* read data and tags from the stream */ + + while (!is.IsEOF()) { + { + auto tag = is.ReadTag(); + if (tag) { + fprintf(stderr, "Received a tag:\n"); + tag_save(stderr, *tag); + } + } + + std::byte buffer[MAX_CHUNK_SIZE]; + assert(chunk_size <= sizeof(buffer)); + size_t num_read = is.Read(lock, {buffer, chunk_size}); + if (num_read == 0) + break; + + out.FullWrite({buffer, num_read}); + } + + is.Check(); + + return 0; +} + +class DumpRemoteTagHandler final : public RemoteTagHandler { + Mutex mutex; + Cond cond; + + Tag tag; + std::exception_ptr error; + + bool done = false; + +public: + Tag Wait() { + std::unique_lock lock{mutex}; + cond.wait(lock, [this]{ return done; }); + + if (error) + std::rethrow_exception(error); + + return std::move(tag); + } + + /* virtual methods from RemoteTagHandler */ + void OnRemoteTag(Tag &&_tag) noexcept override { + const std::scoped_lock lock{mutex}; + tag = std::move(_tag); + done = true; + cond.notify_all(); + } + + void OnRemoteTagError(std::exception_ptr e) noexcept override { + const std::scoped_lock lock{mutex}; + error = std::move(e); + done = true; + cond.notify_all(); + } +}; + +static int +Scan(const char *uri) +{ + DumpRemoteTagHandler handler; + + auto scanner = InputScanTags(uri, handler); + if (!scanner) { + fprintf(stderr, "Unsupported URI\n"); + return EXIT_FAILURE; + } + + scanner->Start(); + tag_save(stdout, handler.Wait()); + return EXIT_SUCCESS; +} + +int main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + + /* initialize MPD */ + + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + const GlobalInit init(c.config_path); + + if (c.scan) + return Scan(c.uri); + + /* open the stream and dump it */ + + Mutex mutex; + auto is = InputStream::OpenReady(c.uri, mutex); + return dump_input_stream(*is, FileDescriptor(STDOUT_FILENO), + c.seek, c.chunk_size); +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_neighbor_explorer.cxx b/test/run_neighbor_explorer.cxx new file mode 100644 index 0000000..8ebe44c --- /dev/null +++ b/test/run_neighbor_explorer.cxx @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "ConfigGlue.hxx" +#include "neighbor/Listener.hxx" +#include "neighbor/Info.hxx" +#include "neighbor/Glue.hxx" +#include "fs/NarrowPath.hxx" +#include "fs/Path.hxx" +#include "event/Loop.hxx" +#include "ShutdownHandler.hxx" +#include "util/PrintException.hxx" + +#include +#include + +class MyNeighborListener final : public NeighborListener { + public: + /* virtual methods from class NeighborListener */ + void FoundNeighbor(const NeighborInfo &info) noexcept override { + printf("found '%s' (%s)\n", + info.display_name.c_str(), info.uri.c_str()); + } + + void LostNeighbor(const NeighborInfo &info) noexcept override { + printf("lost '%s' (%s)\n", + info.display_name.c_str(), info.uri.c_str()); + } +}; + +int +main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: run_neighbor_explorer CONFIG\n"); + return EXIT_FAILURE; + } + + const FromNarrowPath config_path = argv[1]; + + /* initialize the core */ + + EventLoop loop; + const ShutdownHandler shutdown_handler(loop); + + /* read configuration file (mpd.conf) */ + + const auto config = AutoLoadConfigFile(config_path); + + /* initialize neighbor plugins */ + + MyNeighborListener listener; + NeighborGlue neighbor; + neighbor.Init(config, loop, listener); + neighbor.Open(); + + /* dump initial list */ + + for (const auto &info : neighbor.GetList()) + printf("have '%s' (%s)\n", + info.display_name.c_str(), info.uri.c_str()); + + /* run */ + + loop.Run(); + neighbor.Close(); + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_normalize.cxx b/test/run_normalize.cxx new file mode 100644 index 0000000..592209b --- /dev/null +++ b/test/run_normalize.cxx @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +/* + * This program is a command line interface to MPD's normalize library + * (based on AudioCompress). + * + */ + +#include "pcm/Normalizer.hxx" +#include "pcm/AudioParser.hxx" +#include "pcm/AudioFormat.hxx" +#include "util/PrintException.hxx" +#include "util/SpanCast.hxx" + +#include + +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +try { + if (argc > 2) { + fprintf(stderr, "Usage: run_normalize [FORMAT] OUT\n"); + return 1; + } + + AudioFormat audio_format(48000, SampleFormat::S16, 2); + if (argc > 1) + audio_format = ParseAudioFormat(argv[1], false); + + PcmNormalizer normalizer; + + static std::byte buffer[4096]; + ssize_t nbytes; + while ((nbytes = read(0, buffer, sizeof(buffer))) > 0) { + static int16_t dest[2048]; + normalizer.ProcessS16(dest, FromBytesStrict(std::span{buffer}.first(nbytes))); + [[maybe_unused]] ssize_t ignored = write(1, dest, nbytes); + } + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_output.cxx b/test/run_output.cxx new file mode 100644 index 0000000..d8e2fb6 --- /dev/null +++ b/test/run_output.cxx @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "output/Interface.hxx" +#include "output/Registry.hxx" +#include "output/OutputPlugin.hxx" +#include "ConfigGlue.hxx" +#include "lib/fmt/AudioFormatFormatter.hxx" +#include "lib/fmt/RuntimeError.hxx" +#include "event/Thread.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "pcm/AudioParser.hxx" +#include "pcm/AudioFormat.hxx" +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "io/FileDescriptor.hxx" +#include "util/StringBuffer.hxx" +#include "util/ScopeExit.hxx" +#include "util/StaticFifoBuffer.hxx" +#include "util/PrintException.hxx" +#include "LogBackend.hxx" + +#include +#include + +#include +#include +#include + +struct CommandLine { + FromNarrowPath config_path; + + const char *output_name = nullptr; + + AudioFormat audio_format{44100, SampleFormat::S16, 2}; + + bool verbose = false; +}; + +enum Option { + OPTION_VERBOSE, +}; + +static constexpr OptionDef option_defs[] = { + {"verbose", 'v', false, "Verbose logging"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (Option(o.index)) { + case OPTION_VERBOSE: + c.verbose = true; + break; + } + } + + auto args = option_parser.GetRemaining(); + if (args.size() < 2 || args.size() > 3) + throw std::runtime_error("Usage: run_output CONFIG NAME [FORMAT] 2) + c.audio_format = ParseAudioFormat(args[2], false); + + return c; +} + +static std::unique_ptr +LoadAudioOutput(const ConfigData &config, EventLoop &event_loop, + const char *name) +{ + const auto *block = config.FindBlock(ConfigBlockOption::AUDIO_OUTPUT, + "name", name); + if (block == nullptr) + throw FmtRuntimeError("No such configured audio output: {}", + name); + + const char *plugin_name = block->GetBlockValue("type"); + if (plugin_name == nullptr) + throw std::runtime_error("Missing \"type\" configuration"); + + const auto *plugin = GetAudioOutputPluginByName(plugin_name); + if (plugin == nullptr) + throw FmtRuntimeError("No such audio output plugin: {}", + plugin_name); + + return std::unique_ptr(ao_plugin_init(event_loop, *plugin, + *block)); +} + +static void +RunOutput(AudioOutput &ao, AudioFormat audio_format, + FileDescriptor in_fd) +{ + in_fd.SetBinaryMode(); + + /* open the audio output */ + + ao.Enable(); + AtScopeExit(&ao) { ao.Disable(); }; + + ao.Open(audio_format); + AtScopeExit(&ao) { ao.Close(); }; + + fmt::print(stderr, "audio_format={}\n", audio_format); + + const size_t in_frame_size = audio_format.GetFrameSize(); + + /* play */ + + StaticFifoBuffer buffer; + + while (true) { + { + const auto dest = buffer.Write(); + assert(!dest.empty()); + + ssize_t nbytes = in_fd.Read(dest); + if (nbytes <= 0) + break; + + buffer.Append(nbytes); + } + + auto src = buffer.Read(); + assert(!src.empty()); + + src = src.first(src.size() - src.size() % in_frame_size); + if (src.empty()) + continue; + + size_t consumed = ao.Play(src); + + assert(consumed <= src.size()); + assert(consumed % in_frame_size == 0); + + buffer.Consume(consumed); + } + + ao.Drain(); +} + +int main(int argc, char **argv) +try { + const auto c = ParseCommandLine(argc, argv); + SetLogThreshold(c.verbose ? LogLevel::DEBUG : LogLevel::INFO); + + /* read configuration file (mpd.conf) */ + + const auto config = AutoLoadConfigFile(c.config_path); + + EventThread io_thread; + io_thread.Start(); + + /* initialize the audio output */ + + auto ao = LoadAudioOutput(config, io_thread.GetEventLoop(), + c.output_name); + + /* do it */ + + RunOutput(*ao, c.audio_format, FileDescriptor(STDIN_FILENO)); + + /* cleanup and exit */ + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_resolver.cxx b/test/run_resolver.cxx new file mode 100644 index 0000000..02f834e --- /dev/null +++ b/test/run_resolver.cxx @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "lib/fmt/SocketAddressFormatter.hxx" +#include "net/Resolver.hxx" +#include "net/AddressInfo.hxx" +#include "net/SocketAddress.hxx" +#include "util/PrintException.hxx" + +#include + +#include + +#include +#include + +int main(int argc, char **argv) +try { + if (argc != 2) { + fprintf(stderr, "Usage: run_resolver HOST\n"); + return EXIT_FAILURE; + } + + for (const auto &i : Resolve(argv[1], 80, AI_PASSIVE, SOCK_STREAM)) { + fmt::print("{}\n", i); + } + + return EXIT_SUCCESS; +} catch (...) { + PrintException(std::current_exception()); + return EXIT_FAILURE; +} diff --git a/test/run_storage.cxx b/test/run_storage.cxx new file mode 100644 index 0000000..4961f84 --- /dev/null +++ b/test/run_storage.cxx @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright The Music Player Daemon Project + +#include "cmdline/OptionDef.hxx" +#include "cmdline/OptionParser.hxx" +#include "event/Thread.hxx" +#include "ConfigGlue.hxx" +#include "tag/Tag.hxx" +#include "storage/Registry.hxx" +#include "storage/StorageInterface.hxx" +#include "storage/FileInfo.hxx" +#include "input/Init.hxx" +#include "input/InputStream.hxx" +#include "input/CondHandler.hxx" +#include "fs/Path.hxx" +#include "fs/NarrowPath.hxx" +#include "event/Thread.hxx" +#include "net/Init.hxx" +#include "io/BufferedOutputStream.hxx" +#include "io/FileDescriptor.hxx" +#include "io/StdioOutputStream.hxx" +#include "time/ChronoUtil.hxx" +#include "time/ISO8601.hxx" +#include "util/PrintException.hxx" +#include "util/StringAPI.hxx" +#include "util/StringBuffer.hxx" +#include "Log.hxx" +#include "LogBackend.hxx" +#include "TagSave.hxx" + +#include "archive/Features.h" // for ENABLE_ARCHIVE +#ifdef ENABLE_ARCHIVE +#include "archive/ArchiveList.hxx" +#endif + +#include +#include + +#include +#include +#include +#include + +static constexpr auto usage_text = R"(Usage: run_storage [OPTIONS] COMMAND URI ... + +Options: + --verbose + +Available commands: + ls URI PATH + stat URI PATH + cat URI PATH +)"; + +struct CommandLine { + FromNarrowPath config_path; + + bool verbose = false; + + const char *command; + + std::span args; +}; + +enum class Option { + CONFIG, + VERBOSE, +}; + +static constexpr OptionDef option_defs[] = { + {"config", 0, true, "Load a MPD configuration file"}, + {"verbose", 'v', false, "Verbose logging"}, +}; + +static CommandLine +ParseCommandLine(int argc, char **argv) +{ + CommandLine c; + + OptionParser option_parser(option_defs, argc, argv); + while (auto o = option_parser.Next()) { + switch (static_cast