* Copyright (c) 2025 Huawei Device Co., Ltd.
* 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.
*/
#ifndef LIVESTREAM_AUDIOQUEUE_H
#define LIVESTREAM_AUDIOQUEUE_H
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <vector>
#include <cstdint>
#include <atomic>
using namespace std::chrono_literals;
class AudioBgmQueue {
public:
AudioBgmQueue() : m_stop(true) {}
AudioBgmQueue(const AudioBgmQueue&) = delete;
AudioBgmQueue& operator=(const AudioBgmQueue&) = delete;
void push(int16_t* data, size_t sampleCount)
{
if (data == nullptr || sampleCount == 0) return;
std::lock_guard<std::mutex> lock(m_mutex);
m_buffer.insert(m_buffer.end(), data, data + sampleCount);
m_cv.notify_one();
}
size_t pop(int16_t* output, size_t requestedSamples)
{
if (output == nullptr || requestedSamples == 0) return 0;
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait_for(lock, 2ms, [this, requestedSamples]() {
return m_stop || m_buffer.size() >= requestedSamples;
});
if (m_stop) return 0;
size_t actualSamples = std::min(requestedSamples, m_buffer.size());
std::copy(m_buffer.begin(), m_buffer.begin() + actualSamples, output);
m_buffer.erase(m_buffer.begin(), m_buffer.begin() + actualSamples);
return actualSamples;
}
void Start()
{
m_stop = false;
m_cv.notify_all();
}
void Stop()
{
m_stop = true;
m_cv.notify_all();
}
bool IsStart()
{
return !m_stop;
}
void Clear()
{
std::lock_guard<std::mutex> lock(m_mutex);
m_buffer.clear();
}
bool Empty() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_buffer.empty();
}
size_t size() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_buffer.size();
}
private:
mutable std::mutex m_mutex;
std::condition_variable m_cv;
std::vector<int16_t> m_buffer;
std::atomic<bool> m_stop;
};
#endif