First working PCM decoder
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -27,7 +27,6 @@ extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/error.h>
|
||||
#include <libavutil/log.h>
|
||||
}
|
||||
|
||||
@@ -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<char, 128> 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 };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -138,5 +138,4 @@ namespace lms::audio::ffmpeg
|
||||
{
|
||||
return _tagReader.get();
|
||||
}
|
||||
|
||||
} // namespace lms::audio::ffmpeg
|
||||
} // namespace lms::audio::ffmpeg
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <string_view>
|
||||
|
||||
#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
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "FFmpegTypes.hpp"
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavcodec/packet.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libswresample/swresample.h>
|
||||
}
|
||||
|
||||
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
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <memory>
|
||||
|
||||
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<AVCodecContext, AvCodecContextDeleter>;
|
||||
|
||||
struct AvFormatContextDeleter
|
||||
{
|
||||
void operator()(AVFormatContext* ctx) const noexcept;
|
||||
};
|
||||
using AVFormatContextPtr = std::unique_ptr<AVFormatContext, AvFormatContextDeleter>;
|
||||
|
||||
struct AvFrameDeleter
|
||||
{
|
||||
void operator()(AVFrame* frame) const noexcept;
|
||||
};
|
||||
using AVFramePtr = std::unique_ptr<AVFrame, AvFrameDeleter>;
|
||||
|
||||
struct AVPacketDeleter
|
||||
{
|
||||
void operator()(AVPacket* packet) const noexcept;
|
||||
};
|
||||
using AVPacketPtr = std::unique_ptr<AVPacket, AVPacketDeleter>;
|
||||
|
||||
struct SwrContextDeleter
|
||||
{
|
||||
void operator()(SwrContext* ctx) const noexcept;
|
||||
};
|
||||
using SwrContextPtr = std::unique_ptr<SwrContext, SwrContextDeleter>;
|
||||
} // namespace lms::audio::ffmpeg
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "PcmDecoder.hpp"
|
||||
|
||||
#include <array>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavcodec/packet.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/samplefmt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
}
|
||||
|
||||
#include "core/ILogger.hpp"
|
||||
|
||||
#include "audio/Exception.hpp"
|
||||
#include "audio/IPcmDecoder.hpp"
|
||||
|
||||
#include "Exception.hpp"
|
||||
|
||||
namespace lms::audio
|
||||
{
|
||||
std::unique_ptr<IPcmDecoder> createPcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters)
|
||||
{
|
||||
return std::make_unique<ffmpeg::PcmDecoder>(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<int>(_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<WritableBuffer> 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<uint8_t*, AV_NUM_DATA_POINTERS> outData{};
|
||||
for (size_t i = 0; i < outputChannelBuffers.size(); ++i)
|
||||
outData[i] = reinterpret_cast<uint8_t*>(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<int>(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<std::size_t>(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<int>(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
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#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<WritableBuffer> 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
|
||||
@@ -19,8 +19,23 @@
|
||||
|
||||
#include "Utils.hpp"
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavutil/error.h>
|
||||
}
|
||||
|
||||
namespace lms::audio::ffmpeg::utils
|
||||
{
|
||||
std::string averrorToString(int error)
|
||||
{
|
||||
std::array<char, 128> buf{ 0 };
|
||||
|
||||
if (::av_strerror(error, buf.data(), buf.size()) == 0)
|
||||
return buf.data();
|
||||
|
||||
return "Unknown error";
|
||||
}
|
||||
|
||||
std::span<const std::filesystem::path> getSupportedExtensions()
|
||||
{
|
||||
// TODO: list demuxers to retrieve supported formats
|
||||
|
||||
@@ -24,5 +24,7 @@
|
||||
|
||||
namespace lms::audio::ffmpeg::utils
|
||||
{
|
||||
std::string averrorToString(int error);
|
||||
|
||||
std::span<const std::filesystem::path> getSupportedExtensions();
|
||||
} // namespace lms::audio::ffmpeg::utils
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <bit>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
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<std::byte>;
|
||||
|
||||
// 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<WritableBuffer> outputChannelBuffers, std::size_t maxSamplesPerChannel) = 0;
|
||||
virtual bool finished() const = 0;
|
||||
};
|
||||
|
||||
// Throw on error
|
||||
std::unique_ptr<IPcmDecoder> createPcmDecoder(const std::filesystem::path& filePath, const PcmDecoderParameters& parameters);
|
||||
} // namespace lms::audio
|
||||
@@ -1,3 +1,4 @@
|
||||
add_subdirectory(db-generator)
|
||||
add_subdirectory(audioinfo)
|
||||
add_subdirectory(audiodecode)
|
||||
add_subdirectory(db-generator)
|
||||
add_subdirectory(recommendation)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
add_executable(lms-audiodecode
|
||||
LmsAudioDecode.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(lms-audiodecode PRIVATE
|
||||
lmsaudio
|
||||
lmscore
|
||||
Boost::program_options
|
||||
)
|
||||
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <bit>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
|
||||
#include <boost/program_options.hpp>
|
||||
|
||||
#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<std::string>()->required(), "Input audio file path")
|
||||
("output",program_options::value<std::string>()->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::string>() };
|
||||
std::filesystem::path outputPath{ vm["output"].as<std::string>() };
|
||||
if (!std::filesystem::exists(inputPath))
|
||||
throw std::runtime_error{ "File '" + inputPath.string() + "' does not exist!" };
|
||||
|
||||
core::Service<core::logging::ILogger> 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::byte>;
|
||||
|
||||
std::array<Buffer, 2> channelBuffers;
|
||||
constexpr std::chrono::milliseconds bufferDuration{ 50 };
|
||||
const std::size_t sampleCountPerChannel{ static_cast<std::size_t>(std::chrono::duration_cast<std::chrono::microseconds>(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<std::byte>{ channelBuffers[0].data(), channelBuffers[0].size() },
|
||||
std::span<std::byte>{ 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<double>(totalSampleCount) / static_cast<double>(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;
|
||||
}
|
||||
@@ -200,7 +200,10 @@ int main(int argc, char* argv[])
|
||||
("track-count-per-release", program_options::value<unsigned>()->default_value(defaultParams.trackCountPerRelease), "Number of tracks per release")
|
||||
("track-embedded-image-count",program_options::value<unsigned>()->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<float>()->default_value(defaultParams.compilationRatio), "Compilation ratio (compilation means all tracks have a different artist)")
|
||||
("track-path",program_options::value<std::string>()->required(), "Path of a valid track file, that will be used for all generated tracks")("genre-count", program_options::value<unsigned>()->default_value(defaultParams.genreCount), "Number of genres to generate")("genre-count-per-track", program_options::value<unsigned>()->default_value(defaultParams.genreCountPerTrack), "Number of genres to assign to each track")("mood-count", program_options::value<unsigned>()->default_value(defaultParams.moodCount), "Number of moods to generate")
|
||||
("track-path",program_options::value<std::string>()->required(), "Path of a valid track file, that will be used for all generated tracks")
|
||||
("genre-count", program_options::value<unsigned>()->default_value(defaultParams.genreCount), "Number of genres to generate")
|
||||
("genre-count-per-track", program_options::value<unsigned>()->default_value(defaultParams.genreCountPerTrack), "Number of genres to assign to each track")
|
||||
("mood-count", program_options::value<unsigned>()->default_value(defaultParams.moodCount), "Number of moods to generate")
|
||||
("mood-count-per-track", program_options::value<unsigned>()->default_value(defaultParams.moodCountPerTrack), "Number of moods to assign to each track")("help,h", "produce help message");
|
||||
// clang-format on
|
||||
|
||||
|
||||
Reference in New Issue
Block a user