Skip to content

File AudioConverter.h

File List > Amplitude > DSP > AudioConverter.h

Go to the documentation of this file

// Copyright (c) 2024-present Sparky Studios. All rights reserved.
//
// 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
//
//     http://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.

#pragma once

#ifndef _AM_DSP_AUDIO_CONVERTER_H
#define _AM_DSP_AUDIO_CONVERTER_H

#include <SparkyStudios/Audio/Amplitude/Core/AudioBuffer.h>
#include <SparkyStudios/Audio/Amplitude/DSP/Resampler.h>

namespace SparkyStudios::Audio::Amplitude
{
    class AudioConverter final
    {
    public:
        struct Settings
        {
            AmUInt32 m_sourceSampleRate;

            AmUInt32 m_targetSampleRate;

            AmUInt16 m_sourceChannelCount;

            AmUInt16 m_targetChannelCount;
        };

        AudioConverter();

        ~AudioConverter();

        bool Configure(const Settings& settings);

        void Process(const AudioBuffer& input, AmUInt64& inputFrames, AudioBuffer& output, AmUInt64& outputFrames);

        void SetSampleRate(AmUInt64 sourceSampleRate, AmUInt64 targetSampleRate);

        [[nodiscard]] AmUInt64 GetRequiredInputFrameCount(AmUInt64 outputFrameCount) const;

        [[nodiscard]] AmUInt64 GetExpectedOutputFrameCount(AmUInt64 inputFrameCount) const;

        [[nodiscard]] AmUInt64 GetInputLatency() const;

        [[nodiscard]] AmUInt64 GetOutputLatency() const;

        void Reset();

    private:
        enum ChannelConversionMode
        {
            kChannelConversionModeDisabled,
            kChannelConversionModeStereoToMono,
            kChannelConversionModeMonoToStereo,
        };

        static void ConvertStereoFromMono(const AudioBuffer& input, AudioBuffer& output);

        static void ConvertMonoFromStereo(const AudioBuffer& input, AudioBuffer& output);

        std::shared_ptr<ResamplerInstance> _resampler;
        ChannelConversionMode _channelConversionMode;

        bool _needResampling;
        bool _srcInitialized;

        Settings _settings;

        AudioBuffer _tempBuffer;
    };
} // namespace SparkyStudios::Audio::Amplitude

#endif // _AM_DSP_AUDIO_CONVERTER_H