From e0f1e4a1ec64f972406acd3ed0047bd5708723ec Mon Sep 17 00:00:00 2001 From: emeric Date: Sun, 18 Jan 2026 11:13:17 +0100 Subject: [PATCH] First working PCM decoder --- src/libs/audio/CMakeLists.txt | 4 +- src/libs/audio/impl/ffmpeg/AudioFile.cpp | 33 +-- src/libs/audio/impl/ffmpeg/AudioFileInfo.cpp | 3 +- src/libs/audio/impl/ffmpeg/Exception.hpp | 43 +++ src/libs/audio/impl/ffmpeg/FFmpegTypes.cpp | 64 ++++ src/libs/audio/impl/ffmpeg/FFmpegTypes.hpp | 64 ++++ src/libs/audio/impl/ffmpeg/PcmDecoder.cpp | 289 +++++++++++++++++++ src/libs/audio/impl/ffmpeg/PcmDecoder.hpp | 56 ++++ src/libs/audio/impl/ffmpeg/Utils.cpp | 15 + src/libs/audio/impl/ffmpeg/Utils.hpp | 2 + src/libs/audio/include/audio/IPcmDecoder.hpp | 62 ++++ src/tools/CMakeLists.txt | 3 +- src/tools/audiodecode/CMakeLists.txt | 10 + src/tools/audiodecode/LmsAudioDecode.cpp | 112 +++++++ src/tools/db-generator/LmsDbGenerator.cpp | 5 +- 15 files changed, 734 insertions(+), 31 deletions(-) create mode 100644 src/libs/audio/impl/ffmpeg/Exception.hpp create mode 100644 src/libs/audio/impl/ffmpeg/FFmpegTypes.cpp create mode 100644 src/libs/audio/impl/ffmpeg/FFmpegTypes.hpp create mode 100644 src/libs/audio/impl/ffmpeg/PcmDecoder.cpp create mode 100644 src/libs/audio/impl/ffmpeg/PcmDecoder.hpp create mode 100644 src/libs/audio/include/audio/IPcmDecoder.hpp create mode 100644 src/tools/audiodecode/CMakeLists.txt create mode 100644 src/tools/audiodecode/LmsAudioDecode.cpp diff --git a/src/libs/audio/CMakeLists.txt b/src/libs/audio/CMakeLists.txt index 0979b975..64990785 100644 --- a/src/libs/audio/CMakeLists.txt +++ b/src/libs/audio/CMakeLists.txt @@ -1,11 +1,13 @@ -pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libavformat) +pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libavformat libswresample) pkg_check_modules(Taglib REQUIRED IMPORTED_TARGET taglib) add_library(lmsaudio STATIC impl/ffmpeg/AudioFile.cpp impl/ffmpeg/AudioFileInfo.cpp impl/ffmpeg/AudioFileInfoParser.cpp + impl/ffmpeg/FFmpegTypes.cpp impl/ffmpeg/ImageReader.cpp + impl/ffmpeg/PcmDecoder.cpp impl/ffmpeg/TagReader.cpp impl/ffmpeg/Transcoder.cpp impl/ffmpeg/Utils.cpp diff --git a/src/libs/audio/impl/ffmpeg/AudioFile.cpp b/src/libs/audio/impl/ffmpeg/AudioFile.cpp index 22f64749..3d43eb2e 100644 --- a/src/libs/audio/impl/ffmpeg/AudioFile.cpp +++ b/src/libs/audio/impl/ffmpeg/AudioFile.cpp @@ -27,7 +27,6 @@ extern "C" { #include #include -#include #include } @@ -35,7 +34,8 @@ extern "C" #include "core/ITraceLogger.hpp" #include "core/String.hpp" -#include "audio/Exception.hpp" +#include "Exception.hpp" +#include "Utils.hpp" #define LMS_FFMPEG_HAS_AV_DICT_ITERATE (LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 37, 100)) @@ -43,25 +43,6 @@ namespace lms::audio::ffmpeg { namespace { - std::string averror_to_string(int error) - { - std::array buf{ 0 }; - - if (::av_strerror(error, buf.data(), buf.size()) == 0) - return buf.data(); - - return "Unknown error"; - } - - class AvException : public Exception - { - public: - AvException(int avError) - : Exception{ averror_to_string(avError) } - { - } - }; - void extractMetaDataFromDictionnary(AVDictionary* dictionnary, AudioFile::MetadataMap& res) { if (!dictionnary) @@ -75,7 +56,6 @@ namespace lms::audio::ffmpeg AVDictionaryEntry* tag{}; while ((tag = av_dict_get(dictionnary, "", tag, AV_DICT_IGNORE_SUFFIX))) res[core::stringUtils::stringToUpper(tag->key)] = tag->value; - #endif // LMS_FFMPEG_HAS_AV_DICT_ITERATE } @@ -249,21 +229,22 @@ namespace lms::audio::ffmpeg { LMS_SCOPED_TRACE_DETAILED("MetaData", "FFmpegParseFile"); + // TODO move this static AvInitializer init; int error{ avformat_open_input(&_context, _p.c_str(), nullptr, nullptr) }; if (error < 0) { - LMS_LOG(AUDIO, ERROR, "Cannot open " << _p << ": " << averror_to_string(error)); - throw AvException{ error }; + LMS_LOG(AUDIO, ERROR, "Cannot open " << _p << ": " << utils::averrorToString(error)); + throw FFmpegException{ "Cannot open '" + _p.string() + "'", error }; } error = avformat_find_stream_info(_context, nullptr); if (error < 0) { - LMS_LOG(AUDIO, ERROR, "Cannot find stream information on " << _p << ": " << averror_to_string(error)); + LMS_LOG(AUDIO, ERROR, "Cannot find stream information in " << _p << ": " << utils::averrorToString(error)); avformat_close_input(&_context); - throw AvException{ error }; + throw FFmpegException{ "Cannot find stream information in '" + _p.string() + "'", error }; } } diff --git a/src/libs/audio/impl/ffmpeg/AudioFileInfo.cpp b/src/libs/audio/impl/ffmpeg/AudioFileInfo.cpp index e987412e..5314464f 100644 --- a/src/libs/audio/impl/ffmpeg/AudioFileInfo.cpp +++ b/src/libs/audio/impl/ffmpeg/AudioFileInfo.cpp @@ -138,5 +138,4 @@ namespace lms::audio::ffmpeg { return _tagReader.get(); } - -} // namespace lms::audio::ffmpeg +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/Exception.hpp b/src/libs/audio/impl/ffmpeg/Exception.hpp new file mode 100644 index 00000000..8f83686a --- /dev/null +++ b/src/libs/audio/impl/ffmpeg/Exception.hpp @@ -0,0 +1,43 @@ + +/* + * Copyright (C) 2025 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#include + +#include "audio/Exception.hpp" + +#include "Utils.hpp" + +namespace lms::audio::ffmpeg +{ + class FFmpegException : public Exception + { + public: + FFmpegException(std::string_view msg, int avError) + : Exception{ std::string{ msg } + ": " + utils::averrorToString(avError) } + , _avError{ avError } + { + } + + int getAvError() const { return _avError; } + + private: + int _avError; + }; +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/FFmpegTypes.cpp b/src/libs/audio/impl/ffmpeg/FFmpegTypes.cpp new file mode 100644 index 00000000..9f68f37a --- /dev/null +++ b/src/libs/audio/impl/ffmpeg/FFmpegTypes.cpp @@ -0,0 +1,64 @@ + +/* + * Copyright (C) 2025 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#include "FFmpegTypes.hpp" + +extern "C" +{ +#include +#include +#include +#include +} + +namespace lms::audio::ffmpeg +{ + void AvCodecContextDeleter::operator()(AVCodecContext* ctx) const noexcept + { + if (ctx) + ::avcodec_free_context(&ctx); + } + + void AvFormatContextDeleter::operator()(AVFormatContext* ctx) const noexcept + { + if (!ctx) + return; + + ::avformat_close_input(&ctx); + } + + void AvFrameDeleter::operator()(AVFrame* frame) const noexcept + { + if (frame) + ::av_frame_free(&frame); + } + + void AVPacketDeleter::operator()(AVPacket* packet) const noexcept + { + if (packet) + ::av_packet_free(&packet); + } + + void SwrContextDeleter::operator()(SwrContext* ctx) const noexcept + { + if (ctx) + ::swr_free(&ctx); + } +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/FFmpegTypes.hpp b/src/libs/audio/impl/ffmpeg/FFmpegTypes.hpp new file mode 100644 index 00000000..0cca2e45 --- /dev/null +++ b/src/libs/audio/impl/ffmpeg/FFmpegTypes.hpp @@ -0,0 +1,64 @@ + +/* + * Copyright (C) 2025 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#include + +extern "C" +{ + struct AVCodecContext; + struct AVFormatContext; + struct AVFrame; + struct AVPacket; + + struct SwrContext; +} + +namespace lms::audio::ffmpeg +{ + struct AvCodecContextDeleter + { + void operator()(AVCodecContext* ctx) const noexcept; + }; + using AVCodecContextPtr = std::unique_ptr; + + struct AvFormatContextDeleter + { + void operator()(AVFormatContext* ctx) const noexcept; + }; + using AVFormatContextPtr = std::unique_ptr; + + struct AvFrameDeleter + { + void operator()(AVFrame* frame) const noexcept; + }; + using AVFramePtr = std::unique_ptr; + + struct AVPacketDeleter + { + void operator()(AVPacket* packet) const noexcept; + }; + using AVPacketPtr = std::unique_ptr; + + struct SwrContextDeleter + { + void operator()(SwrContext* ctx) const noexcept; + }; + using SwrContextPtr = std::unique_ptr; +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/PcmDecoder.cpp b/src/libs/audio/impl/ffmpeg/PcmDecoder.cpp new file mode 100644 index 00000000..b418f428 --- /dev/null +++ b/src/libs/audio/impl/ffmpeg/PcmDecoder.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2026 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#include "PcmDecoder.hpp" + +#include + +extern "C" +{ +#include +#include +#include +#include +#include +#include +} + +#include "core/ILogger.hpp" + +#include "audio/Exception.hpp" +#include "audio/IPcmDecoder.hpp" + +#include "Exception.hpp" + +namespace lms::audio +{ + std::unique_ptr createPcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters) + { + return std::make_unique(filePath, parameters); + } +} // namespace lms::audio + +namespace lms::audio::ffmpeg +{ + namespace + { + ::AVSampleFormat toAvSampleFormat(PcmDecodeSampleType type, bool planar) + { + switch (type) + { + case PcmDecodeSampleType::Signed16: + return planar ? AV_SAMPLE_FMT_S16P : AV_SAMPLE_FMT_S16; + case PcmDecodeSampleType::Signed32: + return planar ? AV_SAMPLE_FMT_S32P : AV_SAMPLE_FMT_S32; + case PcmDecodeSampleType::Float32: + return planar ? AV_SAMPLE_FMT_FLTP : AV_SAMPLE_FMT_FLT; + case PcmDecodeSampleType::Float64: + return planar ? AV_SAMPLE_FMT_DBLP : AV_SAMPLE_FMT_DBL; + } + + throw Exception("Unsupported PcmDecodeSampleType"); + } + } // namespace + + PcmDecoder::PcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters) + : _parameters{ parameters } + { + if (_parameters.channelCount > AV_NUM_DATA_POINTERS) + throw Exception("Channel count exceeds maximum supported channels"); + + { + ::AVFormatContext* context{}; + int error{ ::avformat_open_input(&context, filePath.c_str(), nullptr, nullptr) }; + if (error < 0) + { + LMS_LOG(AUDIO, ERROR, "Cannot open " << filePath << ": " << utils::averrorToString(error)); + throw FFmpegException{ "Cannot open '" + filePath.string() + "'", error }; + } + _context = AVFormatContextPtr{ context }; + } + + { + int error{ ::avformat_find_stream_info(_context.get(), nullptr) }; + if (error < 0) + { + LMS_LOG(AUDIO, ERROR, "Cannot find stream information in " << filePath << ": " << utils::averrorToString(error)); + throw FFmpegException{ "Cannot find stream information in '" + filePath.string() + "'", error }; + } + } + + const ::AVCodec* decoder{}; + _inputStreamIndex = ::av_find_best_stream(_context.get(), + AVMEDIA_TYPE_AUDIO, + -1, // auto + -1, // auto + &decoder, + 0); + + if (_inputStreamIndex < 0) + { + LMS_LOG(AUDIO, ERROR, "Cannot find best audio stream in " << filePath << ": " << utils::averrorToString(_inputStreamIndex)); + throw FFmpegException{ "Cannot find best audio stream in '" + filePath.string() + "'", _inputStreamIndex }; + } + + _decoderContext = AVCodecContextPtr{ ::avcodec_alloc_context3(decoder) }; + if (!_decoderContext) + throw Exception{ "Cannot allocate decoder context" }; + + { + int error{ ::avcodec_parameters_to_context(_decoderContext.get(), _context->streams[_inputStreamIndex]->codecpar) }; + if (error < 0) + throw FFmpegException{ "Cannot init decoder parameters", error }; + } + + { + int error{ ::avcodec_open2(_decoderContext.get(), decoder, nullptr) }; + if (error < 0) + throw FFmpegException("Cannot open decoder", error); + } + + _decodedFrame = AVFramePtr{ av_frame_alloc() }; + if (!_decodedFrame) + throw Exception{ "Cannot allocate decoded frame" }; + + _inputPacket = AVPacketPtr{ ::av_packet_alloc() }; + if (!_inputPacket) + throw Exception{ "Cannot allocate input packet" }; + + // Resampler + const ::AVSampleFormat outFmt{ toAvSampleFormat(_parameters.sampleType, _parameters.planar) }; + AVChannelLayout outLayout; + ::av_channel_layout_default(&outLayout, _parameters.channelCount); + + { + ::SwrContext* context{}; + ::swr_alloc_set_opts2( + &context, // existing context + &outLayout, // out layout + outFmt, // out format + static_cast(_parameters.sampleRate), // out rate + &_decoderContext->ch_layout, // in layout + _decoderContext->sample_fmt, // in format + _decoderContext->sample_rate, // in rate + 0, // log offset + nullptr); + ::av_channel_layout_uninit(&outLayout); + + if (!context) + throw Exception{ "Cannot allocate resampler context" }; + + _resampleContext = SwrContextPtr{ context }; + } + + { + int error{ ::swr_init(_resampleContext.get()) }; + if (error < 0) + throw FFmpegException{ "Cannot initialize resampler", error }; + } + } + + PcmDecoder::~PcmDecoder() = default; + + std::size_t PcmDecoder::readSamples(std::span outputChannelBuffers, std::size_t maxSamplesPerChannel) + { + assert(outputChannelBuffers.size() <= AV_NUM_DATA_POINTERS); + + if (_finished) + return 0; + + if (_parameters.planar) + { + if (outputChannelBuffers.size() != _parameters.channelCount) + throw Exception{ "Expected " + std::to_string(_parameters.channelCount) + " buffers for planar output" }; + } + else + { + if (outputChannelBuffers.size() != 1) + throw Exception{ "Expected a single buffer for interleaved output" }; + } + + std::array outData{}; + for (size_t i = 0; i < outputChannelBuffers.size(); ++i) + outData[i] = reinterpret_cast(outputChannelBuffers[i].data()); + + while (true) + { + if (!_eof) + feedDecoder(); + + // Try to receive a decoded frame + int recvErr{ ::avcodec_receive_frame(_decoderContext.get(), _decodedFrame.get()) }; + if (recvErr == AVERROR(EAGAIN)) + { + if (!_eof) + continue; // need more input + + _draining = true; + } + else if (recvErr == AVERROR_EOF) + { + _draining = true; + } + else if (recvErr < 0) + { + throw FFmpegException{ "avcodec_receive_frame failed", recvErr }; + } + else + { + // Resample decoded audio + const int outSampleCount{ ::swr_convert( + _resampleContext.get(), + outData.data(), + static_cast(maxSamplesPerChannel), + (const uint8_t**)_decodedFrame->data, + _decodedFrame->nb_samples) }; + ::av_frame_unref(_decodedFrame.get()); + + if (outSampleCount < 0) + throw FFmpegException{ "swr_convert failed", outSampleCount }; + + if (outSampleCount > 0) + return static_cast(outSampleCount); + + continue; // Rare but legal: frame produced no output (delay accumulation) + } + + // Drain resampler once decoder is drained + if (_draining) + { + const int outSampleCount = ::swr_convert(_resampleContext.get(), + outData.data(), + static_cast(maxSamplesPerChannel), + nullptr, + 0); + + if (outSampleCount < 0) + throw FFmpegException{ "swr_convert (drain) failed", outSampleCount }; + + if (outSampleCount > 0) + return outSampleCount; + + _finished = true; + return 0; + } + } + + return 0; + } + + bool PcmDecoder::finished() const + { + return _finished; + } + + void PcmDecoder::feedDecoder() + { + assert(!_eof); + + const int readError{ ::av_read_frame(_context.get(), _inputPacket.get()) }; + if (readError == AVERROR_EOF) + { + _eof = true; + // flush decoder + ::avcodec_send_packet(_decoderContext.get(), nullptr); + } + else if (readError < 0) + { + throw FFmpegException{ "av_read_frame failed", readError }; + } + else + { + if (_inputPacket->stream_index == _inputStreamIndex) + { + const int sendError{ ::avcodec_send_packet(_decoderContext.get(), _inputPacket.get()) }; + ::av_packet_unref(_inputPacket.get()); + if (sendError < 0) + throw FFmpegException{ "avcodec_send_packet failed", sendError }; + } + else + ::av_packet_unref(_inputPacket.get()); + } + } +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/PcmDecoder.hpp b/src/libs/audio/impl/ffmpeg/PcmDecoder.hpp new file mode 100644 index 00000000..a136e007 --- /dev/null +++ b/src/libs/audio/impl/ffmpeg/PcmDecoder.hpp @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2026 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#pragma once + +#include "audio/IPcmDecoder.hpp" + +#include "FFmpegTypes.hpp" + +namespace lms::audio::ffmpeg +{ + class PcmDecoder : public IPcmDecoder + { + public: + PcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters); + ~PcmDecoder() override; + + PcmDecoder(const PcmDecoder&) = delete; + PcmDecoder& operator=(const PcmDecoder&) = delete; + + private: + std::size_t readSamples(std::span outputChannelBuffers, std::size_t maxSamplesPerChannel) override; + bool finished() const override; + + void feedDecoder(); + + const PcmDecoderParameters _parameters; + + bool _finished{}; + bool _eof{}; + bool _draining{}; + + AVFormatContextPtr _context; + int _inputStreamIndex{}; + AVCodecContextPtr _decoderContext; + AVFramePtr _decodedFrame; + AVPacketPtr _inputPacket; + SwrContextPtr _resampleContext; + }; +} // namespace lms::audio::ffmpeg \ No newline at end of file diff --git a/src/libs/audio/impl/ffmpeg/Utils.cpp b/src/libs/audio/impl/ffmpeg/Utils.cpp index 0dab5030..34d0c9fd 100644 --- a/src/libs/audio/impl/ffmpeg/Utils.cpp +++ b/src/libs/audio/impl/ffmpeg/Utils.cpp @@ -19,8 +19,23 @@ #include "Utils.hpp" +extern "C" +{ +#include +} + namespace lms::audio::ffmpeg::utils { + std::string averrorToString(int error) + { + std::array buf{ 0 }; + + if (::av_strerror(error, buf.data(), buf.size()) == 0) + return buf.data(); + + return "Unknown error"; + } + std::span getSupportedExtensions() { // TODO: list demuxers to retrieve supported formats diff --git a/src/libs/audio/impl/ffmpeg/Utils.hpp b/src/libs/audio/impl/ffmpeg/Utils.hpp index 35d7be48..17087088 100644 --- a/src/libs/audio/impl/ffmpeg/Utils.hpp +++ b/src/libs/audio/impl/ffmpeg/Utils.hpp @@ -24,5 +24,7 @@ namespace lms::audio::ffmpeg::utils { + std::string averrorToString(int error); + std::span getSupportedExtensions(); } // namespace lms::audio::ffmpeg::utils \ No newline at end of file diff --git a/src/libs/audio/include/audio/IPcmDecoder.hpp b/src/libs/audio/include/audio/IPcmDecoder.hpp new file mode 100644 index 00000000..b84cc848 --- /dev/null +++ b/src/libs/audio/include/audio/IPcmDecoder.hpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2026 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace lms::audio +{ + enum class PcmDecodeSampleType + { + Signed16, + Signed32, + Float32, + Float64, + }; + + struct PcmDecoderParameters + { + unsigned channelCount; + unsigned sampleRate; + PcmDecodeSampleType sampleType; + std::endian byteOrder; + bool planar; + }; + + class IPcmDecoder + { + public: + virtual ~IPcmDecoder() = default; + + using WritableBuffer = std::span; + + // Returns the number of samples written per channel. Returns 0 only once all remaining samples are drained. + // Provide one buffer per channel if planar, or a single buffer containing all channels interleaved + virtual std::size_t readSamples(std::span outputChannelBuffers, std::size_t maxSamplesPerChannel) = 0; + virtual bool finished() const = 0; + }; + + // Throw on error + std::unique_ptr createPcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters); +} // namespace lms::audio \ No newline at end of file diff --git a/src/tools/CMakeLists.txt b/src/tools/CMakeLists.txt index 4759645e..8b3a307b 100644 --- a/src/tools/CMakeLists.txt +++ b/src/tools/CMakeLists.txt @@ -1,3 +1,4 @@ -add_subdirectory(db-generator) add_subdirectory(audioinfo) +add_subdirectory(audiodecode) +add_subdirectory(db-generator) add_subdirectory(recommendation) diff --git a/src/tools/audiodecode/CMakeLists.txt b/src/tools/audiodecode/CMakeLists.txt new file mode 100644 index 00000000..9a756106 --- /dev/null +++ b/src/tools/audiodecode/CMakeLists.txt @@ -0,0 +1,10 @@ + +add_executable(lms-audiodecode + LmsAudioDecode.cpp + ) + +target_link_libraries(lms-audiodecode PRIVATE + lmsaudio + lmscore + Boost::program_options + ) diff --git a/src/tools/audiodecode/LmsAudioDecode.cpp b/src/tools/audiodecode/LmsAudioDecode.cpp new file mode 100644 index 00000000..cf8c8ced --- /dev/null +++ b/src/tools/audiodecode/LmsAudioDecode.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2026 Emeric Poupon + * + * This file is part of LMS. + * + * LMS 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 3 of the License, or + * (at your option) any later version. + * + * LMS 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 LMS. If not, see . + */ + +#include +#include +#include + +#include + +#include "core/ILogger.hpp" + +#include "audio/Exception.hpp" +#include "audio/IPcmDecoder.hpp" + +int main(int argc, char* argv[]) +{ + try + { + using namespace lms; + namespace program_options = boost::program_options; + + program_options::options_description options{ "Options" }; + // clang-format off + options.add_options() + ("help,h", "Display this help message") + ("input",program_options::value()->required(), "Input audio file path") + ("output",program_options::value()->required(), "Output audio file path"); + // clang-format on + + program_options::variables_map vm; + program_options::store(program_options::parse_command_line(argc, argv, options), vm); + + if (vm.count("help")) + { + std::cout << options << "\n"; + return EXIT_SUCCESS; + } + + // notify required params + program_options::notify(vm); + + std::filesystem::path inputPath{ vm["input"].as() }; + std::filesystem::path outputPath{ vm["output"].as() }; + if (!std::filesystem::exists(inputPath)) + throw std::runtime_error{ "File '" + inputPath.string() + "' does not exist!" }; + + core::Service logger{ core::logging::createLogger(core::logging::Severity::DEBUG) }; + + try + { + audio::PcmDecoderParameters decoderParams; + decoderParams.byteOrder = std::endian::little; + decoderParams.channelCount = 2; + decoderParams.sampleRate = 48000; + decoderParams.planar = true; + decoderParams.sampleType = audio::PcmDecodeSampleType::Float32; + + auto decoder{ audio::createPcmDecoder(inputPath, decoderParams) }; + + using Buffer = std::vector; + + std::array channelBuffers; + constexpr std::chrono::milliseconds bufferDuration{ 50 }; + const std::size_t sampleCountPerChannel{ static_cast(std::chrono::duration_cast(bufferDuration).count() * decoderParams.sampleRate / std::chrono::microseconds::period::den) }; + std::cout << "Using buffer size of " << sampleCountPerChannel << " samples per channel" << std::endl; + for (auto& buffer : channelBuffers) + buffer.resize(sampleCountPerChannel * sizeof(float)); + + std::size_t totalSampleCount{ 0 }; + while (!decoder->finished()) + { + std::array outputBuffers{ + std::span{ channelBuffers[0].data(), channelBuffers[0].size() }, + std::span{ channelBuffers[1].data(), channelBuffers[1].size() } + }; + const std::size_t sampleCount{ decoder->readSamples(outputBuffers, sampleCountPerChannel) }; + totalSampleCount += sampleCount; + } + + std::cout << "Decoding finished, total samples per channel: " << totalSampleCount << std::endl; + std::cout << "Estimated duration: " << static_cast(totalSampleCount) / static_cast(decoderParams.sampleRate) << " seconds" << std::endl; + } + catch (audio::Exception& e) + { + std::cerr << "Caught audio exception: " << e.what() << std::endl; + return EXIT_FAILURE; + } + } + catch (std::exception& e) + { + std::cerr << "Caught exception: " << e.what() << std::endl; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} \ No newline at end of file diff --git a/src/tools/db-generator/LmsDbGenerator.cpp b/src/tools/db-generator/LmsDbGenerator.cpp index ffff6c14..06b3de29 100644 --- a/src/tools/db-generator/LmsDbGenerator.cpp +++ b/src/tools/db-generator/LmsDbGenerator.cpp @@ -200,7 +200,10 @@ int main(int argc, char* argv[]) ("track-count-per-release", program_options::value()->default_value(defaultParams.trackCountPerRelease), "Number of tracks per release") ("track-embedded-image-count",program_options::value()->default_value(defaultParams.trackEmbeddedImagePerRelease), "Number of different embedded track images for the whole release (each track has one different embedded image)") ("compilation-ratio",program_options::value()->default_value(defaultParams.compilationRatio), "Compilation ratio (compilation means all tracks have a different artist)") - ("track-path",program_options::value()->required(), "Path of a valid track file, that will be used for all generated tracks")("genre-count", program_options::value()->default_value(defaultParams.genreCount), "Number of genres to generate")("genre-count-per-track", program_options::value()->default_value(defaultParams.genreCountPerTrack), "Number of genres to assign to each track")("mood-count", program_options::value()->default_value(defaultParams.moodCount), "Number of moods to generate") + ("track-path",program_options::value()->required(), "Path of a valid track file, that will be used for all generated tracks") + ("genre-count", program_options::value()->default_value(defaultParams.genreCount), "Number of genres to generate") + ("genre-count-per-track", program_options::value()->default_value(defaultParams.genreCountPerTrack), "Number of genres to assign to each track") + ("mood-count", program_options::value()->default_value(defaultParams.moodCount), "Number of moods to generate") ("mood-count-per-track", program_options::value()->default_value(defaultParams.moodCountPerTrack), "Number of moods to assign to each track")("help,h", "produce help message"); // clang-format on