~aleteoryx/muditaos

ref: c7513c2c65f87eb42176a70b9ecdaadd32279195 muditaos/module-audio/board/linux/LinuxAudioDevice.cpp -rw-r--r-- 7.2 KiB
c7513c2c — Adam Dobrowolski [EGD-8208] Post rebase and review cleanup 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "LinuxAudioDevice.hpp"
#include <Audio/Stream.hpp>
#include <log/log.hpp>

namespace audio
{
    namespace
    {
        class PortAudio
        {
          public:
            PortAudio();
            PortAudio(const PortAudio &) = delete;
            PortAudio(PortAudio &&)      = delete;
            PortAudio &operator=(const PortAudio &) = delete;
            PortAudio &operator=(PortAudio &&) = delete;
            ~PortAudio() noexcept;
        };

        PortAudio::PortAudio()
        {
            if (const auto errorCode = Pa_Initialize(); errorCode == paNoError) {
                LOG_INFO("Portaudio initialized successfully");
            }
            else {
                LOG_ERROR("Error (code %d) initiializing Portaudio: %s", errorCode, Pa_GetErrorText(errorCode));
            }
        }

        PortAudio::~PortAudio() noexcept
        {
            if (const auto errorCode = Pa_Terminate(); errorCode == paNoError) {
                LOG_INFO("Portaudio terminated successfully");
            }
            else {
                LOG_ERROR("Error (code %d) while terminating Portaudio: %s", errorCode, Pa_GetErrorText(errorCode));
            }
        }
    } // namespace

    LinuxAudioDevice::LinuxAudioDevice(const float initialVolume)
        : supportedFormats(
              audio::AudioFormat::makeMatrix(supportedSampleRates, supportedBitWidths, supportedChannelModes))
    {
        setOutputVolume(initialVolume);

        static PortAudio portAudio;
    }

    LinuxAudioDevice::~LinuxAudioDevice()
    {
        if (stream != nullptr) {
            closeStream();
        }
    }

    void LinuxAudioDevice::closeStream()
    {
        if (const auto errorCode = Pa_AbortStream(stream); errorCode != paNoError) {
            LOG_ERROR("Error (code %d) while stopping Portaudio stream: %s", errorCode, Pa_GetErrorText(errorCode));
        }
        if (const auto errorCode = Pa_CloseStream(stream); errorCode != paNoError) {
            LOG_ERROR("Error (code %d) while closing Portaudio stream: %s", errorCode, Pa_GetErrorText(errorCode));
        }
    }

    auto LinuxAudioDevice::Start() -> RetCode
    {
        if (!isSinkConnected()) {
            return AudioDevice::RetCode::Failure;
        }
        return AudioDevice::RetCode::Success;
    }

    auto LinuxAudioDevice::Stop() -> RetCode
    {
        return AudioDevice::RetCode::Success;
    }

    auto LinuxAudioDevice::setOutputVolume(float vol) -> RetCode
    {
        constexpr auto minVolume = .0f;
        constexpr auto maxVolume = 10.0f;
        vol                      = std::clamp(vol, minVolume, maxVolume);
        volumeFactor             = 1.0f * (vol / maxVolume);
        return RetCode::Success;
    }

    auto LinuxAudioDevice::setInputGain([[maybe_unused]] float gain) -> RetCode
    {
        return RetCode::Success;
    }

    auto LinuxAudioDevice::getTraits() const -> Traits
    {
        return Traits{};
    }

    auto LinuxAudioDevice::getSupportedFormats() -> std::vector<audio::AudioFormat>
    {
        return supportedFormats;
    }

    auto LinuxAudioDevice::getSourceFormat() -> audio::AudioFormat
    {
        return currentFormat;
    }

    void LinuxAudioDevice::onDataSend()
    {
        audio::Stream::Span dataSpan;
        Sink::_stream->peek(dataSpan);
        auto streamData = reinterpret_cast<std::int16_t *>(dataSpan.data);
        cache.insert(cache.end(), &streamData[0], &streamData[dataSpan.dataSize / sizeof(std::int16_t)]);
        Sink::_stream->consume();
    }

    void LinuxAudioDevice::onDataReceive()
    {}

    void LinuxAudioDevice::enableInput()
    {}

    void LinuxAudioDevice::enableOutput()
    {
        LOG_INFO("Enabling audio output...");
        if (!isSinkConnected()) {
            LOG_ERROR("Output stream is not connected!");
            return;
        }

        currentFormat                = Sink::_stream->getOutputTraits().format;
        const auto numOutputChannels = currentFormat.getChannels();
        auto callback                = [](const void *input,
                           void *output,
                           unsigned long frameCount,
                           const PaStreamCallbackTimeInfo *timeInfo,
                           PaStreamCallbackFlags statusFlags,
                           void *userData) -> int {
            LinuxAudioDevice *dev = static_cast<LinuxAudioDevice *>(userData);
            return dev->streamCallback(input, output, frameCount, timeInfo, statusFlags);
        };
        auto errorCode = Pa_OpenDefaultStream(&stream,
                                              0,
                                              numOutputChannels,
                                              paInt16,
                                              currentFormat.getSampleRate(),
                                              paFramesPerBufferUnspecified,
                                              callback,
                                              this);
        if (errorCode != paNoError) {
            LOG_ERROR("Error (code %d) while creating portaudio stream: %s", errorCode, Pa_GetErrorText(errorCode));
            return;
        }
        if (errorCode = Pa_StartStream(stream); errorCode != paNoError) {
            LOG_ERROR("Error (code %d) while starting portaudio stream: %s", errorCode, Pa_GetErrorText(errorCode));
            return;
        }
    }

    void LinuxAudioDevice::disableInput()
    {}

    void LinuxAudioDevice::disableOutput()
    {
        LOG_INFO("Disabling audio output...");
        if (!isSinkConnected()) {
            LOG_ERROR("Error while stopping Linux Audio Device! Null stream.");
            return;
        }

        closeStream();
        stream        = nullptr;
        currentFormat = {};
    }

    int LinuxAudioDevice::streamCallback([[maybe_unused]] const void *input,
                                         void *output,
                                         unsigned long frameCount,
                                         [[maybe_unused]] const PaStreamCallbackTimeInfo *timeInfo,
                                         [[maybe_unused]] PaStreamCallbackFlags statusFlags)
    {
        if (!isSinkConnected()) {
            return paAbort;
        }

        const auto expectedBufferSize = frameCount * currentFormat.getChannels();
        if (!isCacheReady(expectedBufferSize)) {
            onDataSend();
        }

        const auto dataReadySize = std::min(expectedBufferSize, cache.size());
        cacheToOutputBuffer(static_cast<std::int16_t *>(output), dataReadySize);

        return paContinue;
    }

    bool LinuxAudioDevice::isCacheReady(std::size_t expectedSize) const noexcept
    {
        return cache.size() >= expectedSize;
    }

    void LinuxAudioDevice::cacheToOutputBuffer(std::int16_t *buffer, std::size_t size)
    {
        for (size_t i = 0; i < size; ++i) {
            const auto adjustedValue = static_cast<float>(cache[i]) * volumeFactor;
            *(buffer)                = static_cast<std::int16_t>(adjustedValue);
            buffer++;
        }
        cache.erase(cache.begin(), cache.begin() + size);
    }
} // namespace audio