M2-PT-DRP/source/Client.hpp

65 lines
1.4 KiB
C++

#pragma once
#include <condition_variable>
#include <mutex>
#include <portaudio.h>
#include <queue>
#include <thread>
#include "packets/AudioPacket.hpp"
// TODO(Faraphel): should be moved somewhere else
struct AudioPacketsComparator {
bool operator() (const AudioPacket &a, const AudioPacket &b) const {
return a.timePlay > b.timePlay;
}
};
/**
* the audio Client.
* Receive audio packets and play them at a specific time.
*/
class Client {
public:
explicit Client();
~Client();
/**
* Update the current audio stream
* @param channels the number of channels
* @param sampleFormat the sample format type
* @param sampleRate the audio rate
*/
void updateStream(int channels, std::uint32_t sampleFormat, double sampleRate);
/**
* Indefinitely receive and play audio data.
*/
void loop();
private:
/**
* Indefinitely receive audio data.
*/
void loopReceiver();
/**
* Indefinitely play audio data.
*/
void loopPlayer();
PaStream* stream;
int streamChannels;
std::uint32_t streamSampleFormat;
double streamRate;
std::priority_queue<AudioPacket, std::vector<AudioPacket>, AudioPacketsComparator> audioQueue;
std::mutex audioMutex;
std::unique_lock<std::mutex> audioLock;
std::condition_variable audioCondition;
std::thread receiverThread;
std::thread playerThread;
};