[DEV] rename lib river in audio::river

This commit is contained in:
2015-04-11 09:38:30 +02:00
parent bf05f46f24
commit 26e71b2a92
46 changed files with 1806 additions and 1799 deletions

524
audio/river/Interface.cpp Normal file
View File

@@ -0,0 +1,524 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include "debug.h"
#include "Interface.h"
#include "io/Node.h"
#include <audio/drain/EndPointCallback.h>
#include <audio/drain/EndPointWrite.h>
#include <audio/drain/EndPointRead.h>
#include <audio/drain/Volume.h>
#undef __class__
#define __class__ "Interface"
audio::river::Interface::Interface(void) :
m_node(),
m_name("") {
static uint32_t uid = 0;
m_uid = uid++;
}
bool audio::river::Interface::init(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std11::shared_ptr<audio::river::io::Node>& _node,
const std11::shared_ptr<const ejson::Object>& _config) {
std::vector<audio::channel> map(_map);
m_node = _node;
m_config = _config;
m_mode = audio::river::modeInterface_unknow;
std::string type = m_config->getStringValue("io", "error");
static int32_t uid=0;
m_name = _node->getName() + "__" + (_node->isInput()==true?"input":"output") + "__" + type + "__" + etk::to_string(uid++);
if (type == "output") {
m_mode = audio::river::modeInterface_output;
} else if (type == "input") {
m_mode = audio::river::modeInterface_input;
} else if (type == "feedback") {
m_mode = audio::river::modeInterface_feedback;
}
// register interface to be notify from the volume change.
m_node->registerAsRemote(shared_from_this());
if (map.size() == 0) {
RIVER_INFO("Select auto map system ...");
map = m_node->getInterfaceFormat().getMap();
RIVER_INFO(" ==> " << map);
}
// Create convertion interface
if ( m_node->isInput() == true
&& m_mode == audio::river::modeInterface_input) {
m_process.setInputConfig(m_node->getInterfaceFormat());
// Add volume only if the Low level has a volume (otherwise it will be added by the application)
std11::shared_ptr<audio::drain::VolumeElement> tmpVolume = m_node->getVolume();
if (tmpVolume != nullptr) {
// add all time the volume stage :
std11::shared_ptr<audio::drain::Volume> algo = audio::drain::Volume::create();
//algo->setInputFormat(m_node->getInterfaceFormat());
algo->setName("volume");
m_process.pushBack(algo);
RIVER_INFO(" add volume for node");
algo->addVolumeStage(tmpVolume);
}
m_process.setOutputConfig(audio::drain::IOFormatInterface(map, _format, _freq));
} else if ( m_node->isOutput() == true
&& m_mode == audio::river::modeInterface_output) {
m_process.setInputConfig(audio::drain::IOFormatInterface(map, _format, _freq));
// Add volume only if the Low level has a volume (otherwise it will be added by the application)
std11::shared_ptr<audio::drain::VolumeElement> tmpVolume = m_node->getVolume();
if (tmpVolume != nullptr) {
// add all time the volume stage :
std11::shared_ptr<audio::drain::Volume> algo = audio::drain::Volume::create();
//algo->setOutputFormat(m_node->getInterfaceFormat());
algo->setName("volume");
m_process.pushBack(algo);
RIVER_INFO(" add volume for node");
algo->addVolumeStage(tmpVolume);
}
m_process.setOutputConfig(m_node->getInterfaceFormat());
} else if ( m_node->isOutput() == true
&& m_mode == audio::river::modeInterface_feedback) {
m_process.setInputConfig(m_node->getHarwareFormat());
// note : feedback has no volume stage ...
m_process.setOutputConfig(audio::drain::IOFormatInterface(map, _format, _freq));
} else {
RIVER_ERROR("Can not link virtual interface with type : " << m_mode << " to a hardware interface " << (m_node->isInput()==true?"input":"output"));
return false;
}
return true;
}
std11::shared_ptr<audio::river::Interface> audio::river::Interface::create(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std11::shared_ptr<audio::river::io::Node>& _node,
const std11::shared_ptr<const ejson::Object>& _config) {
std11::shared_ptr<audio::river::Interface> out = std11::shared_ptr<audio::river::Interface>(new audio::river::Interface());
out->init(_freq, _map, _format, _node, _config);
return out;
}
audio::river::Interface::~Interface() {
//stop(true, true);
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
//m_node->interfaceRemove(shared_from_this());
}
/*
bool audio::river::Interface::hasEndPoint() {
}
*/
void audio::river::Interface::setReadwrite() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
m_process.removeAlgoDynamic();
if (m_process.hasType<audio::drain::EndPoint>() ) {
RIVER_ERROR("Endpoint is already present ==> can not change");
return;
}
if (m_node->isInput() == true) {
m_process.removeIfLast<audio::drain::EndPoint>();
std11::shared_ptr<audio::drain::EndPointRead> algo = audio::drain::EndPointRead::create();
m_process.pushBack(algo);
} else {
m_process.removeIfFirst<audio::drain::EndPoint>();
std11::shared_ptr<audio::drain::EndPointWrite> algo = audio::drain::EndPointWrite::create();
m_process.pushFront(algo);
}
}
void audio::river::Interface::setOutputCallback(audio::drain::playbackFunction _function) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_mode != audio::river::modeInterface_output) {
RIVER_ERROR("Can not set output endpoint on other than a output IO");
return;
}
m_process.removeAlgoDynamic();
m_process.removeIfFirst<audio::drain::EndPoint>();
std11::shared_ptr<audio::drain::Algo> algo = audio::drain::EndPointCallback::create(_function);
m_process.pushFront(algo);
}
void audio::river::Interface::setInputCallback(audio::drain::recordFunction _function) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_mode == audio::river::modeInterface_output) {
RIVER_ERROR("Can not set output endpoint on other than a input or feedback IO");
return;
}
m_process.removeAlgoDynamic();
m_process.removeIfLast<audio::drain::EndPoint>();
std11::shared_ptr<audio::drain::Algo> algo = audio::drain::EndPointCallback::create(_function);
m_process.pushBack(algo);
}
void audio::river::Interface::setWriteCallback(audio::drain::playbackFunctionWrite _function) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_mode != audio::river::modeInterface_output) {
RIVER_ERROR("Can not set output endpoint on other than a output IO");
return;
}
m_process.removeAlgoDynamic();
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
return;
}
algo->setCallback(_function);
}
void audio::river::Interface::start(const std11::chrono::system_clock::time_point& _time) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
RIVER_DEBUG("start [BEGIN]");
m_process.updateInterAlgo();
m_node->interfaceAdd(shared_from_this());
RIVER_DEBUG("start [ END ]");
}
void audio::river::Interface::stop(bool _fast, bool _abort) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
RIVER_DEBUG("stop [BEGIN]");
m_node->interfaceRemove(shared_from_this());
RIVER_DEBUG("stop [ END]");
}
void audio::river::Interface::abort() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
RIVER_DEBUG("abort [BEGIN]");
// TODO :...
RIVER_DEBUG("abort [ END ]");
}
bool audio::river::Interface::setParameter(const std::string& _filter, const std::string& _parameter, const std::string& _value) {
RIVER_DEBUG("setParameter [BEGIN] : '" << _filter << "':'" << _parameter << "':'" << _value << "'");
bool out = false;
if ( _filter == "volume"
&& _parameter != "FLOW") {
RIVER_ERROR("Interface is not allowed to modify '" << _parameter << "' Volume just allowed to modify 'FLOW' volume");
return false;
}
std11::shared_ptr<audio::drain::Algo> algo = m_process.get<audio::drain::Algo>(_filter);
if (algo == nullptr) {
RIVER_ERROR("setParameter(" << _filter << ") ==> no filter named like this ...");
return false;
}
out = algo->setParameter(_parameter, _value);
RIVER_DEBUG("setParameter [ END ] : '" << out << "'");
return out;
}
std::string audio::river::Interface::getParameter(const std::string& _filter, const std::string& _parameter) const {
RIVER_DEBUG("getParameter [BEGIN] : '" << _filter << "':'" << _parameter << "'");
std::string out;
std11::shared_ptr<const audio::drain::Algo> algo = m_process.get<const audio::drain::Algo>(_filter);
if (algo == nullptr) {
RIVER_ERROR("setParameter(" << _filter << ") ==> no filter named like this ...");
return "[ERROR]";
}
out = algo->getParameter(_parameter);
RIVER_DEBUG("getParameter [ END ] : '" << out << "'");
return out;
}
std::string audio::river::Interface::getParameterProperty(const std::string& _filter, const std::string& _parameter) const {
RIVER_DEBUG("getParameterProperty [BEGIN] : '" << _filter << "':'" << _parameter << "'");
std::string out;
std11::shared_ptr<const audio::drain::Algo> algo = m_process.get<const audio::drain::Algo>(_filter);
if (algo == nullptr) {
RIVER_ERROR("setParameter(" << _filter << ") ==> no filter named like this ...");
return "[ERROR]";
}
out = algo->getParameterProperty(_parameter);
RIVER_DEBUG("getParameterProperty [ END ] : '" << out << "'");
return out;
}
void audio::river::Interface::write(const void* _value, size_t _nbChunk) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
m_process.updateInterAlgo();
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
return;
}
algo->write(_value, _nbChunk);
}
#if 0
// TODO : add API aCCess mutex for Read and write...
std::vector<int16_t> audio::river::Interface::read(size_t _nbChunk) {
// TODO :...
std::vector<int16_t> data;
/*
data.resize(_nbChunk*m_map.size(), 0);
m_mutex.lock();
int32_t nbChunkBuffer = m_circularBuffer.size() / m_map.size();
m_mutex.unlock();
while (nbChunkBuffer < _nbChunk) {
usleep(1000);
nbChunkBuffer = m_circularBuffer.size() / m_map.size();
}
m_mutex.lock();
for (size_t iii = 0; iii<data.size(); ++iii) {
data[iii] = m_circularBuffer[iii];
}
m_circularBuffer.erase(m_circularBuffer.begin(), m_circularBuffer.begin()+data.size());
m_mutex.unlock();
*/
return data;
}
#endif
void audio::river::Interface::read(void* _value, size_t _nbChunk) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
m_process.updateInterAlgo();
// TODO :...
}
size_t audio::river::Interface::size() const {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
// TODO :...
return 0;
}
void audio::river::Interface::setBufferSize(size_t _nbChunk) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request set buffer size for Interface that is not READ or WRITE mode ...");
return;
}
algo->setBufferSize(_nbChunk);
return;
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request set buffer size for Interface that is not READ or WRITE mode ...");
return;
}
algo->setBufferSize(_nbChunk);
}
void audio::river::Interface::setBufferSize(const std11::chrono::microseconds& _time) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request set buffer size for Interface that is not READ or WRITE mode ...");
return;
}
algo->setBufferSize(_time);
return;
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request set buffer size for Interface that is not READ or WRITE mode ...");
return;
}
algo->setBufferSize(_time);
}
size_t audio::river::Interface::getBufferSize() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return 0;
}
return algo->getBufferSize();
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return 0;
}
return algo->getBufferSize();
}
std11::chrono::microseconds audio::river::Interface::getBufferSizeMicrosecond() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return std11::chrono::microseconds(0);
}
return algo->getBufferSizeMicrosecond();
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return std11::chrono::microseconds(0);
}
return algo->getBufferSizeMicrosecond();
}
size_t audio::river::Interface::getBufferFillSize() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return 0;
}
return algo->getBufferFillSize();
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return 0;
}
return algo->getBufferFillSize();
}
std11::chrono::microseconds audio::river::Interface::getBufferFillSizeMicrosecond() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (m_node->isInput() == true) {
std11::shared_ptr<audio::drain::EndPointRead> algo = m_process.get<audio::drain::EndPointRead>(m_process.size()-1);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return std11::chrono::microseconds(0);
}
return algo->getBufferFillSizeMicrosecond();
}
std11::shared_ptr<audio::drain::EndPointWrite> algo = m_process.get<audio::drain::EndPointWrite>(0);
if (algo == nullptr) {
RIVER_ERROR("Request get buffer size for Interface that is not READ or WRITE mode ...");
return std11::chrono::microseconds(0);
}
return algo->getBufferFillSizeMicrosecond();
}
void audio::river::Interface::clearInternalBuffer() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
m_process.updateInterAlgo();
// TODO :...
}
std11::chrono::system_clock::time_point audio::river::Interface::getCurrentTime() const {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
// TODO :...
return std11::chrono::system_clock::time_point();
return std11::chrono::system_clock::now();
}
void audio::river::Interface::addVolumeGroup(const std::string& _name) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
RIVER_DEBUG("addVolumeGroup(" << _name << ")");
std11::shared_ptr<audio::drain::Volume> algo = m_process.get<audio::drain::Volume>("volume");
if (algo == nullptr) {
m_process.removeAlgoDynamic();
// add all time the volume stage :
algo = audio::drain::Volume::create();
algo->setName("volume");
if (m_node->isInput() == true) {
m_process.pushFront(algo);
} else {
m_process.pushBack(algo);
}
}
if (_name == "FLOW") {
// Local volume name
algo->addVolumeStage(std11::make_shared<audio::drain::VolumeElement>(_name));
} else {
// get manager unique instance:
std11::shared_ptr<audio::river::io::Manager> mng = audio::river::io::Manager::getInstance();
algo->addVolumeStage(mng->getVolumeGroup(_name));
}
}
void audio::river::Interface::systemNewInputData(std11::chrono::system_clock::time_point _time, const void* _data, size_t _nbChunk) {
std11::unique_lock<std11::recursive_mutex> lockProcess(m_mutex);
void * tmpData = const_cast<void*>(_data);
m_process.push(_time, tmpData, _nbChunk);
}
void audio::river::Interface::systemNeedOutputData(std11::chrono::system_clock::time_point _time, void* _data, size_t _nbChunk, size_t _chunkSize) {
std11::unique_lock<std11::recursive_mutex> lockProcess(m_mutex);
//RIVER_INFO("time : " << _time);
m_process.pull(_time, _data, _nbChunk, _chunkSize);
}
void audio::river::Interface::systemVolumeChange() {
std11::unique_lock<std11::recursive_mutex> lockProcess(m_mutex);
std11::shared_ptr<audio::drain::Volume> algo = m_process.get<audio::drain::Volume>("volume");
if (algo == nullptr) {
return;
}
algo->volumeChange();
}
static void link(etk::FSNode& _node, const std::string& _first, const std::string& _op, const std::string& _second, bool _isLink=true) {
if (_op == "->") {
if (_isLink) {
_node << " " << _first << " -> " << _second << ";\n";
} else {
_node << " " << _first << " -> " << _second << " [style=dashed];\n";
}
} else if (_op == "<-") {
_node << " " << _first << " -> " <<_second<< " [color=transparent];\n";
if (_isLink) {
_node << " " << _second << " -> " << _first << " [constraint=false];\n";
} else {
_node << " " << _second << " -> " << _first << " [constraint=false, style=dashed];\n";
}
}
}
std::string audio::river::Interface::getDotNodeName() const {
if (m_mode == audio::river::modeInterface_input) {
return "API_" + etk::to_string(m_uid) + "_input";
} else if (m_mode == audio::river::modeInterface_feedback) {
return "API_" + etk::to_string(m_uid) + "_feedback";
} else if (m_mode == audio::river::modeInterface_output) {
return "API_" + etk::to_string(m_uid) + "_output";
}
return "error";
}
void audio::river::Interface::generateDot(etk::FSNode& _node, const std::string& _nameIO, bool _isLink) {
_node << " subgraph clusterInterface_" << m_uid << " {\n";
_node << " color=orange;\n";
_node << " label=\"[" << m_uid << "] Interface : " << m_name << "\";\n";
std::string nameIn;
std::string nameOut;
if ( m_mode == audio::river::modeInterface_input
|| m_mode == audio::river::modeInterface_feedback) {
m_process.generateDot(_node, 3, 10000+m_uid, nameIn, nameOut, false);
} else {
m_process.generateDot(_node, 3, 10000+m_uid, nameIn, nameOut, true);
}
if ( m_mode == audio::river::modeInterface_input
|| m_mode == audio::river::modeInterface_feedback) {
link(_node, _nameIO, "->", nameIn, _isLink);
} else {
link(_node, _nameIO, "<-", nameOut, _isLink);
}
_node << " node [shape=Mdiamond];\n";
if (m_mode == audio::river::modeInterface_input) {
_node << " " << getDotNodeName() << " [ label=\"API\\nINPUT\" ];\n";
link(_node, nameOut, "->", getDotNodeName());
} else if (m_mode == audio::river::modeInterface_feedback) {
_node << " " << getDotNodeName() << " [ label=\"API\\nFEEDBACK\" ];\n";
link(_node, nameOut, "->", getDotNodeName());
} else if (m_mode == audio::river::modeInterface_output) {
_node << " " << getDotNodeName() << " [ label=\"API\\nOUTPUT\" ];\n";
link(_node, nameIn, "<-", getDotNodeName());
}
_node << " }\n \n";
}

334
audio/river/Interface.h Normal file
View File

@@ -0,0 +1,334 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_INTERFACE_H__
#define __AUDIO_RIVER_INTERFACE_H__
#include <string>
#include <vector>
#include <stdint.h>
#include <etk/mutex.h>
#include <etk/chrono.h>
#include <etk/functional.h>
#include <etk/memory.h>
#include <audio/format.h>
#include <audio/channel.h>
#include <audio/drain/Process.h>
#include <audio/drain/EndPointCallback.h>
#include <audio/drain/EndPointWrite.h>
#include <ejson/ejson.h>
#include <etk/os/FSNode.h>
namespace audio {
namespace river {
namespace io {
class Node;
class NodeAirTAudio;
class NodeAEC;
class NodeMuxer;
}
enum modeInterface {
modeInterface_unknow,
modeInterface_input,
modeInterface_output,
modeInterface_feedback,
};
/**
* @brief Interface is the basic handle to manage the input output stream
* @note To create this class see @ref audio::river::Manager class
*/
class Interface : public std11::enable_shared_from_this<Interface> {
friend class io::Node;
friend class io::NodeAirTAudio;
friend class io::NodeAEC;
friend class io::NodeMuxer;
friend class Manager;
protected:
uint32_t m_uid; //!< unique ID for interface
protected:
/**
* @brief Constructor (use factory)
*/
Interface();
/**
* @brief Initilize the Class (do all that is not manage by constructor) Call by factory.
* @param[in] _freq Frequency.
* @param[in] _map Channel map organization.
* @param[in] _format Sample format
* @param[in] _node Low level interface to connect the flow.
* @param[in] _config Special configuration of this interface.
* @return true Configuration done corectly.
* @return false the configuration has an error.
*/
bool init(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std11::shared_ptr<audio::river::io::Node>& _node,
const std11::shared_ptr<const ejson::Object>& _config);
/**
* @brief Factory of this interface (called by class audio::river::Manager)
* @param[in] _freq Frequency.
* @param[in] _map Channel map organization.
* @param[in] _format Sample format
* @param[in] _node Low level interface to connect the flow.
* @param[in] _config Special configuration of this interface.
* @return nullptr The configuration does not work.
* @return pointer The interface has been corectly created.
*/
static std11::shared_ptr<Interface> create(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std11::shared_ptr<audio::river::io::Node>& _node,
const std11::shared_ptr<const ejson::Object>& _config);
public:
/**
* @brief Destructor
*/
virtual ~Interface();
protected:
mutable std11::recursive_mutex m_mutex; //!< Local mutex to protect data
std11::shared_ptr<const ejson::Object> m_config; //!< configuration set by the user.
protected:
enum modeInterface m_mode; //!< interface type (input/output/feedback)
public:
/**
* @brief Get mode type of the current interface.
* @return The mode requested.
*/
enum modeInterface getMode() {
return m_mode;
}
protected:
audio::drain::Process m_process; //!< Algorithme processing engine
public:
/**
* @brief Get the interface format configuration.
* @return The current format.
*/
const audio::drain::IOFormatInterface& getInterfaceFormat() {
if ( m_mode == modeInterface_input
|| m_mode == modeInterface_feedback) {
return m_process.getOutputConfig();
} else {
return m_process.getInputConfig();
}
}
protected:
std11::shared_ptr<audio::river::io::Node> m_node; //!< Hardware interface to/from stream audio flow.
protected:
std::string m_name; //!< Name of the interface.
public:
/**
* @brief Get interface name.
* @return The current name.
*/
virtual std::string getName() {
return m_name;
};
/**
* @brief Set the interface name
* @param[in] _name new name of the interface
*/
virtual void setName(const std::string& _name) {
m_name = _name;
};
/**
* @brief set the read/write mode enable.
* @note If you not set a output/input callback you must call this function.
*/
virtual void setReadwrite();
/**
* @brief When we want to implement a Callback Mode:
*/
/**
* @brief Set a callback on the write mode interface to know when data is needed in the buffer
* @param[in] _function Function to call
*/
virtual void setWriteCallback(audio::drain::playbackFunctionWrite _function);
/**
* @brief Set Output callback mode with the specify callback.
* @param[in] _function Function to call
*/
virtual void setOutputCallback(audio::drain::playbackFunction _function);
/**
* @brief Set Input callback mode with the specify callback.
* @param[in] _function Function to call
*/
virtual void setInputCallback(audio::drain::recordFunction _function);
/**
* @brief Add a volume group of the current channel.
* @note If you do not call this function with the group "FLOW" you chan not have a channel volume.
* @note the set volume stage can not be set after the start.
* @param[in] _name Name of the group classicle common group:
* - FLOW for channel volume.
* - MEDIA for multimedia volume control (audio player, player video, web streaming ...).
* - TTS for Test-to-speech volume control.
* - COMMUNICATION for user communication volume control.
* - NOTIFICATION for urgent notification volume control.
* - NOISE for small noise volume control.
*/
virtual void addVolumeGroup(const std::string& _name);
public:
/**
* @brief Start the Audio interface flow.
* @param[in] _time Time to start the flow (0) to start as fast as possible...
* @note _time to play buffer when output interface (if possible)
* @note _time to read buffer when inut interface (if possible)
*/
virtual void start(const std11::chrono::system_clock::time_point& _time = std11::chrono::system_clock::time_point());
/**
* @brief Stop the current flow.
* @param[in] _fast The stream stop as fast as possible (not write all the buffer in speaker) but apply cross fade out.
* @param[in] _abort The stream stop whith no garenty of good audio stop.
*/
virtual void stop(bool _fast=false, bool _abort=false);
/**
* @brief Abort flow (no audio garenty)
*/
virtual void abort();
/**
* @brief Set a parameter in the stream flow
* @param[in] _filter name of the filter (if you added some personels)
* @param[in] _parameter Parameter name.
* @param[in] _value Value to set.
* @return true set done
* @return false An error occured
* @example : setParameter("volume", "FLOW", "-3dB");
* @example : setParameter("LowPassFilter", "cutFrequency", "1000Hz");
*/
virtual bool setParameter(const std::string& _filter, const std::string& _parameter, const std::string& _value);
/**
* @brief Get a parameter value
* @param[in] _filter name of the filter (if you added some personels)
* @param[in] _parameter Parameter name.
* @return The requested value.
* @example : getParameter("volume", "FLOW"); can return something like "-3dB"
* @example : getParameter("LowPassFilter", "cutFrequency"); can return something like "[-120..0]dB"
*/
virtual std::string getParameter(const std::string& _filter, const std::string& _parameter) const;
/**
* @brief Get a parameter value
* @param[in] _filter name of the filter (if you added some personels)
* @param[in] _parameter Parameter name.
* @return The requested value.
* @example : getParameter("volume", "FLOW"); can return something like "[-120..0]dB"
* @example : getParameter("LowPassFilter", "cutFreqiency"); can return something like "]100..10000]Hz"
*/
virtual std::string getParameterProperty(const std::string& _filter, const std::string& _parameter) const;
/**
* @brief write some audio sample in the speakers
* @param[in] _value Data To write on output
* @param[in] _nbChunk Number of audio chunk to write
*/
// TODO : TimeOut ???
virtual void write(const void* _value, size_t _nbChunk);
/**
* @brief read some audio sample from Microphone
* @param[in] _value Data To write on output
* @param[in] _nbChunk Number of audio chunk to write
*/
// TODO : TimeOut ???
virtual void read(void* _value, size_t _nbChunk);
/**
* @brief Get number of chunk in the local buffer
* @return Number of chunk
*/
virtual size_t size() const;
/**
* @brief Set buffer size in chunk number
* @param[in] _nbChunk Number of chunk in the buffer
*/
virtual void setBufferSize(size_t _nbChunk);
/**
* @brief Set buffer size size of the buffer with the stored time in <20>s
* @param[in] _time Time in microsecond of the buffer
*/
virtual void setBufferSize(const std11::chrono::microseconds& _time);
/**
* @brief get buffer size in chunk number
* @return Number of chunk that can be written in the buffer
*/
virtual size_t getBufferSize();
/**
* @brief Set buffer size size of the buffer with the stored time in <20>s
* @return Time in microsecond that can be written in the buffer
*/
virtual std11::chrono::microseconds getBufferSizeMicrosecond();
/**
* @brief Get buffer size filled in chunk number
* @return Number of chunk in the buffer (that might be read/write)
*/
virtual size_t getBufferFillSize();
/**
* @brief Set buffer size size of the buffer with the stored time in <20>s
* @return Time in microsecond of the buffer (that might be read/write)
*/
virtual std11::chrono::microseconds getBufferFillSizeMicrosecond();
/**
* @brief Remove internal Buffer
*/
virtual void clearInternalBuffer();
/**
* @brief Write : Get the time of the next sample time to write in the local buffer
* @brief Read : Get the time of the next sample time to read in the local buffer
*/
virtual std11::chrono::system_clock::time_point getCurrentTime() const;
private:
/**
* @brief Node Call interface : Input interface node has new data.
* @param[in] _time Time where the first sample has been capture.
* @param[in] _data Pointer on the new data.
* @param[in] _nbChunk Number of chunk in the buffer.
*/
virtual void systemNewInputData(std11::chrono::system_clock::time_point _time, const void* _data, size_t _nbChunk);
/**
* @brief Node Call interface: Output interface node need new data.
* @param[in] _time Time where the data might be played
* @param[in] _data Pointer on the data.
* @param[in] _nbChunk Number of chunk that might be write
* @param[in] _chunkSize Chunk size.
*/
virtual void systemNeedOutputData(std11::chrono::system_clock::time_point _time, void* _data, size_t _nbChunk, size_t _chunkSize);
/**
* @brief Node Call interface: A volume has change.
*/
virtual void systemVolumeChange();
public:
/**
* @brief Create the dot in the FileNode stream.
* @param[in,out] _node File node to write data.
* @param[in] _nameIO Name to link the interface node
* @param[in] _isLink True if the node is connected on the current interface.
*/
virtual void generateDot(etk::FSNode& _node, const std::string& _nameIO, bool _isLink=true);
/**
* @brief Get the current 'dot' name of the interface
* @return The anme requested.
*/
virtual std::string getDotNodeName() const;
protected:
/**
* @brief Interfanel generate of status
* @param[in] _origin status source
* @param[in] _status Event status
*/
void generateStatus(const std::string& _origin, const std::string& _status) {
m_process.generateStatus(_origin, _status);
}
public:
/**
* @brief Set status callback
* @param[in] _newFunction Function to call
*/
void setStatusFunction(audio::drain::statusFunction _newFunction) {
m_process.setStatusFunction(_newFunction);
}
};
}
}
#endif

229
audio/river/Manager.cpp Normal file
View File

@@ -0,0 +1,229 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include "Manager.h"
#include "Interface.h"
#include <stdexcept>
#include "io/Manager.h"
#include "io/Node.h"
#include "debug.h"
#include <ejson/ejson.h>
#undef __class__
#define __class__ "Manager"
static std11::mutex g_mutex;
static std::vector<std11::weak_ptr<audio::river::Manager> > g_listOfAllManager;
std11::shared_ptr<audio::river::Manager> audio::river::Manager::create(const std::string& _applicationUniqueId) {
std11::unique_lock<std11::mutex> lock(g_mutex);
for (size_t iii=0; iii<g_listOfAllManager.size() ; ++iii) {
std11::shared_ptr<audio::river::Manager> tmp = g_listOfAllManager[iii].lock();
if (tmp == nullptr) {
continue;
}
if (tmp->m_applicationUniqueId == _applicationUniqueId) {
return tmp;
}
}
// create a new one:
std11::shared_ptr<audio::river::Manager> out = std11::shared_ptr<audio::river::Manager>(new audio::river::Manager(_applicationUniqueId));
// add it at the list:
for (size_t iii=0; iii<g_listOfAllManager.size() ; ++iii) {
if (g_listOfAllManager[iii].expired() == true) {
g_listOfAllManager[iii] = out;
return out;
}
}
g_listOfAllManager.push_back(out);
return out;
}
audio::river::Manager::Manager(const std::string& _applicationUniqueId) :
m_applicationUniqueId(_applicationUniqueId),
m_listOpenInterface() {
}
audio::river::Manager::~Manager() {
// TODO : Stop all interfaces...
}
std::vector<std::string> audio::river::Manager::getListStreamInput() {
std::vector<std::string> output;
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
} else {
output = manager->getListStreamInput();
}
return output;
}
std::vector<std::string> audio::river::Manager::getListStreamOutput() {
std::vector<std::string> output;
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
} else {
output = manager->getListStreamOutput();
}
return output;
}
std::vector<std::string> audio::river::Manager::getListStreamVirtual() {
std::vector<std::string> output;
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
} else {
output = manager->getListStreamVirtual();
}
return output;
}
std::vector<std::string> audio::river::Manager::getListStream() {
std::vector<std::string> output;
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
} else {
output = manager->getListStream();
}
return output;
}
bool audio::river::Manager::setVolume(const std::string& _volumeName, float _valuedB) {
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return false;
}
return manager->setVolume(_volumeName, _valuedB);
}
float audio::river::Manager::getVolume(const std::string& _volumeName) const {
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return false;
}
return manager->getVolume(_volumeName);
}
std::pair<float,float> audio::river::Manager::getVolumeRange(const std::string& _volumeName) const {
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return std::make_pair<float,float>(0.0f,0.0f);
}
return manager->getVolumeRange(_volumeName);
}
std11::shared_ptr<audio::river::Interface> audio::river::Manager::createOutput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _streamName,
const std::string& _options) {
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return std11::shared_ptr<audio::river::Interface>();
}
// get the output or input channel :
std11::shared_ptr<audio::river::io::Node> node = manager->getNode(_streamName);
if (node == nullptr) {
RIVER_ERROR("Can not get the Requested stream '" << _streamName << "' ==> not listed in : " << manager->getListStream());
return std11::shared_ptr<audio::river::Interface>();
}
if (node->isOutput() != true) {
RIVER_ERROR("Can not Connect output on other thing than output ... for stream '" << _streamName << "'");;
return std11::shared_ptr<audio::river::Interface>();
}
// create user iterface:
std11::shared_ptr<audio::river::Interface> interface;
std11::shared_ptr<ejson::Object> tmpOption = ejson::Object::create(_options);
tmpOption->addString("io", "output");
interface = audio::river::Interface::create(_freq, _map, _format, node, tmpOption);
// store it in a list (needed to apply some parameters).
m_listOpenInterface.push_back(interface);
return interface;
}
std11::shared_ptr<audio::river::Interface> audio::river::Manager::createInput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _streamName,
const std::string& _options) {
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return std11::shared_ptr<audio::river::Interface>();
}
// get the output or input channel :
std11::shared_ptr<audio::river::io::Node> node = manager->getNode(_streamName);
if (node == nullptr) {
RIVER_ERROR("Can not get the Requested stream '" << _streamName << "' ==> not listed in : " << manager->getListStream());
return std11::shared_ptr<audio::river::Interface>();
}
if (node->isInput() != true) {
RIVER_ERROR("Can not Connect input on other thing than input ... for stream '" << _streamName << "'");;
return std11::shared_ptr<audio::river::Interface>();
}
// create user iterface:
std11::shared_ptr<audio::river::Interface> interface;
std11::shared_ptr<ejson::Object> tmpOption = ejson::Object::create(_options);
tmpOption->addString("io", "input");
interface = audio::river::Interface::create(_freq, _map, _format, node, tmpOption);
// store it in a list (needed to apply some parameters).
m_listOpenInterface.push_back(interface);
return interface;
}
std11::shared_ptr<audio::river::Interface> audio::river::Manager::createFeedback(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _streamName,
const std::string& _options) {
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Unable to load harware IO manager ... ");
return std11::shared_ptr<audio::river::Interface>();
}
// get the output or input channel :
std11::shared_ptr<audio::river::io::Node> node = manager->getNode(_streamName);
if (node == nullptr) {
RIVER_ERROR("Can not get the Requested stream '" << _streamName << "' ==> not listed in : " << manager->getListStream());
return std11::shared_ptr<audio::river::Interface>();
}
if (node->isOutput() != true) {
RIVER_ERROR("Can not Connect feedback on other thing than output ... for stream '" << _streamName << "'");;
return std11::shared_ptr<audio::river::Interface>();
}
// create user iterface:
std11::shared_ptr<audio::river::Interface> interface;
std11::shared_ptr<ejson::Object> tmpOption = ejson::Object::create(_options);
tmpOption->addString("io", "feedback");
interface = audio::river::Interface::create(_freq, _map, _format, node, tmpOption);
// store it in a list (needed to apply some parameters).
m_listOpenInterface.push_back(interface);
return interface;
}
void audio::river::Manager::generateDotAll(const std::string& _filename) {
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
if (manager == nullptr) {
RIVER_ERROR("Can not get the harware manager");
return;
}
manager->generateDot(_filename);
}

140
audio/river/Manager.h Normal file
View File

@@ -0,0 +1,140 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_MANAGER_H__
#define __AUDIO_RIVER_MANAGER_H__
#include <string>
#include <stdint.h>
#include <etk/memory.h>
#include <audio/river/Interface.h>
#include <audio/format.h>
#include <audio/channel.h>
#include <ejson/ejson.h>
namespace audio {
namespace river {
/**
* @brief Audio interface manager : Single interface for every application that want to access on the Audio input/output
*/
class Manager : public std11::enable_shared_from_this<Manager> {
private:
const std::string& m_applicationUniqueId; //!< name of the application that open the Audio Interface.
std::vector<std11::weak_ptr<audio::river::Interface> > m_listOpenInterface; //!< List of all open Stream.
protected:
/**
* @brief Constructor
*/
Manager(const std::string& _applicationUniqueId);
public:
/**
* @brief factory of the manager. Every Application will have only one maager for all his flow. this permit to manage all of it
* @param[in] _applicationUniqueId Unique name of the application
* @return Pointer on the manager or nullptr if an error occured
*/
static std11::shared_ptr<audio::river::Manager> create(const std::string& _applicationUniqueId);
/**
* @brief Destructor
*/
virtual ~Manager();
public:
/**
* @brief Get all input audio stream.
* @return a list of all availlables input stream name
*/
std::vector<std::string> getListStreamInput();
/**
* @brief Get all output audio stream.
* @return a list of all availlables output stream name
*/
std::vector<std::string> getListStreamOutput();
/**
* @brief Get all audio virtual stream.
* @return a list of all availlables virtual stream name
*/
std::vector<std::string> getListStreamVirtual();
/**
* @brief Get all audio stream.
* @return a list of all availlables stream name
*/
std::vector<std::string> getListStream();
/**
* @brief Set a volume for a specific group
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @param[in] _value Volume in dB to set.
* @return true set done
* @return false An error occured
* @example : setVolume("MASTER", -3.0f);
*/
virtual bool setVolume(const std::string& _volumeName, float _valuedB);
/**
* @brief Get a volume value
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @return The Volume value in dB.
* @example ret = getVolume("MASTER"); can return something like ret = -3.0f
*/
virtual float getVolume(const std::string& _volumeName) const;
/**
* @brief Get a parameter value
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @return The requested value Range.
* @example ret = getVolumeRange("MASTER"); can return something like ret=(-120.0f,0.0f)
*/
virtual std::pair<float,float> getVolumeRange(const std::string& _volumeName) const;
/**
* @brief Create output Interface
* @param[in] _freq Frequency to open Interface [8,16,22,32,48] kHz
* @param[in] _map ChannelMap of the Output
* @param[in] _format Sample Format to open the stream [int8_t, int16_t, ...]
* @param[in] _streamName Stream name to open: "" or "default" open current selected output
* @param[in] _options Json option to configure default resampling and many other things.
* @return a pointer on the interface
*/
virtual std11::shared_ptr<Interface> createOutput(float _freq = 48000,
const std::vector<audio::channel>& _map = std::vector<audio::channel>(),
audio::format _format = audio::format_int16,
const std::string& _streamName = "",
const std::string& _options = "");
/**
* @brief Create input Interface
* @param[in] _freq Frequency to open Interface [8,16,22,32,48] kHz
* @param[in] _map ChannelMap of the Output
* @param[in] _format Sample Format to open the stream [int8_t, int16_t, ...]
* @param[in] _streamName Stream name to open: "" or "default" open current selected input
* @param[in] _options Json option to configure default resampling and many other things.
* @return a pointer on the interface
*/
virtual std11::shared_ptr<Interface> createInput(float _freq = 48000,
const std::vector<audio::channel>& _map = std::vector<audio::channel>(),
audio::format _format = audio::format_int16,
const std::string& _streamName = "",
const std::string& _options = "");
/**
* @brief Create input Feedback Interface
* @param[in] _freq Frequency to open Interface [8,16,22,32,48] kHz
* @param[in] _map ChannelMap of the Output
* @param[in] _format Sample Format to open the stream [int8_t, int16_t, ...]
* @param[in] _streamName Stream name to open: "" or "default" open current selected input
* @param[in] _options Json option to configure default resampling and many other things.
* @return a pointer on the interface
*/
virtual std11::shared_ptr<Interface> createFeedback(float _freq = 48000,
const std::vector<audio::channel>& _map = std::vector<audio::channel>(),
audio::format _format = audio::format_int16,
const std::string& _streamName = "",
const std::string& _options = "");
/**
* @brief Generate the dot file corresponding at all the actif nodes.
* @param[in] _filename Name of the file to write data.
*/
virtual void generateDotAll(const std::string& _filename);
};
}
}
#endif

13
audio/river/debug.cpp Normal file
View File

@@ -0,0 +1,13 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/debug.h>
int32_t audio::river::getLogId() {
static int32_t g_val = etk::log::registerInstance("river");
return g_val;
}

65
audio/river/debug.h Normal file
View File

@@ -0,0 +1,65 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_DEBUG_H__
#define __AUDIO_RIVER_DEBUG_H__
#include <etk/log.h>
namespace audio {
namespace river {
int32_t getLogId();
}
}
#define RIVER_BASE(info,data) TK_LOG_BASE(audio::river::getLogId(),info,data)
#define RIVER_CRITICAL(data) RIVER_BASE(1, data)
#define RIVER_ERROR(data) RIVER_BASE(2, data)
#define RIVER_WARNING(data) RIVER_BASE(3, data)
#ifdef DEBUG
#define RIVER_INFO(data) RIVER_BASE(4, data)
#define RIVER_DEBUG(data) RIVER_BASE(5, data)
#define RIVER_VERBOSE(data) RIVER_BASE(6, data)
#define RIVER_TODO(data) RIVER_BASE(4, "TODO : " << data)
#else
#define RIVER_INFO(data) do { } while(false)
#define RIVER_DEBUG(data) do { } while(false)
#define RIVER_VERBOSE(data) do { } while(false)
#define RIVER_TODO(data) do { } while(false)
#endif
#define RIVER_ASSERT(cond,data) \
do { \
if (!(cond)) { \
RIVER_CRITICAL(data); \
assert(!#cond); \
} \
} while (0)
#define RIVER_SAVE_FILE_MACRO(type,fileName,dataPointer,nbElement) \
do { \
static FILE *pointerOnFile = nullptr; \
static bool errorOpen = false; \
if (pointerOnFile == nullptr) { \
RIVER_WARNING("open file '" << fileName << "' type=" << #type); \
pointerOnFile = fopen(fileName,"w"); \
if ( errorOpen == false \
&& pointerOnFile == nullptr) { \
RIVER_ERROR("ERROR OPEN file ... '" << fileName << "' type=" << #type); \
errorOpen=true; \
} \
} \
if (pointerOnFile != nullptr) { \
fwrite((dataPointer), sizeof(type), (nbElement), pointerOnFile); \
/* fflush(pointerOnFile);*/ \
} \
}while(0)
#endif

21
audio/river/debugRemove.h Normal file
View File

@@ -0,0 +1,21 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifdef __AUDIO_RIVER_DEBUG_H__
#undef __AUDIO_RIVER_DEBUG_H__
#undef RIVER_BASE
#undef RIVER_CRITICAL
#undef RIVER_ERROR
#undef RIVER_WARNING
#undef RIVER_INFO
#undef RIVER_DEBUG
#undef RIVER_VERBOSE
#undef RIVER_TODO
#undef RIVER_ASSERT
#endif

145
audio/river/io/Group.cpp Normal file
View File

@@ -0,0 +1,145 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/io/Group.h>
#include <audio/river/debug.h>
#include "Node.h"
#include "NodeAEC.h"
#include "NodeOrchestra.h"
#include "NodePortAudio.h"
#include "Node.h"
#undef __class__
#define __class__ "io::Group"
void audio::river::io::Group::createFrom(const ejson::Document& _obj, const std::string& _name) {
RIVER_INFO("Create Group[" << _name << "] (START) ___________________________");
for (size_t iii=0; iii<_obj.size(); ++iii) {
const std11::shared_ptr<const ejson::Object> tmpObject = _obj.getObject(_obj.getKey(iii));
if (tmpObject == nullptr) {
continue;
}
std::string groupName = tmpObject->getStringValue("group", "");
if (groupName == _name) {
RIVER_INFO("Add element in Group[" << _name << "]: " << _obj.getKey(iii));
// get type : io
std::string ioType = tmpObject->getStringValue("io", "error");
#ifdef __AIRTAUDIO_INFERFACE__
if ( ioType == "input"
|| ioType == "output") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodeOrchestra::create(_obj.getKey(iii), tmpObject);
tmp->setGroup(shared_from_this());
m_list.push_back(tmp);
}
#endif
#ifdef __PORTAUDIO_INFERFACE__
if ( ioType == "PAinput"
|| ioType == "PAoutput") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodePortAudio::create(_obj.getKey(iii), tmpObject);
tmp->setGroup(shared_from_this());
m_list.push_back(tmp);
}
#endif
}
}
// Link all the IO together : (not needed if one device ...
// Note : The interlink work only for alsa (NOW) and with AirTAudio...
if(m_list.size() > 1) {
#ifdef __AIRTAUDIO_INFERFACE__
std11::shared_ptr<audio::river::io::NodeOrchestra> linkRef = std11::dynamic_pointer_cast<audio::river::io::NodeOrchestra>(m_list[0]);
for (size_t iii=1; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
std11::shared_ptr<audio::river::io::NodeOrchestra> link = std11::dynamic_pointer_cast<audio::river::io::NodeOrchestra>(m_list[iii]);
linkRef->m_adac.isMasterOf(link->m_adac);
}
}
#endif
}
/*
// manage Link Between Nodes :
if (m_link != nullptr) {
RIVER_INFO("******** START LINK ************");
std11::shared_ptr<audio::river::io::NodeOrchestra> link = std11::dynamic_pointer_cast<audio::river::io::NodeOrchestra>(m_link);
if (link == nullptr) {
RIVER_ERROR("Can not link 2 Interface with not the same type (reserved for HW interface)");
return;
}
link->m_adac.isMasterOf(m_adac);
// TODO : Add return ...
RIVER_INFO("******** LINK might be done ************");
}
*/
RIVER_INFO("Create Group[" << _name << "] ( END ) ___________________________");
RIVER_INFO("Group[" << _name << "] List elements : ");
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
RIVER_INFO(" " << m_list[iii]->getName());
}
}
}
std11::shared_ptr<audio::river::io::Node> audio::river::io::Group::getNode(const std::string& _name) {
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
if (m_list[iii]->getName() == _name) {
return m_list[iii];
}
}
}
return std11::shared_ptr<audio::river::io::Node>();
}
void audio::river::io::Group::start() {
RIVER_ERROR("request start ");
int32_t count = 0;
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
count += m_list[iii]->getNumberOfInterface();
}
}
RIVER_ERROR(" have " << count << " interfaces ...");
if (count == 1) {
RIVER_ERROR("GROUP :::::::::::: START() [START]");
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
m_list[iii]->start();
}
}
RIVER_ERROR("GROUP :::::::::::: START() [DONE]");
}
}
void audio::river::io::Group::stop() {
RIVER_ERROR("request stop ");
int32_t count = 0;
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
count += m_list[iii]->getNumberOfInterface();
}
}
RIVER_ERROR(" have " << count << " interfaces ...");
if (count == 0) {
RIVER_ERROR("GROUP :::::::::::: STOP() [START]");
for (int32_t iii=m_list.size()-1; iii>=0; --iii) {
if (m_list[iii] != nullptr) {
m_list[iii]->stop();
}
}
RIVER_ERROR("GROUP :::::::::::: STOP() [DONE]");
}
}
void audio::river::io::Group::generateDot(etk::FSNode& _node, bool _hardwareNode) {
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] != nullptr) {
if (m_list[iii]->isHarwareNode() == _hardwareNode) {
m_list[iii]->generateDot(_node);
}
}
}
}

78
audio/river/io/Group.h Normal file
View File

@@ -0,0 +1,78 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_GROUP_H__
#define __AUDIO_RIVER_IO_GROUP_H__
#include <string>
#include <vector>
#include <ejson/ejson.h>
#include <etk/os/FSNode.h>
namespace audio {
namespace river {
namespace io {
class Node;
class Manager;
/**
* @brief Group is contituate to manage some input and output in the same start and stop.
* It link N interface in a group. The start and the sopt is requested in Node inside the
* group they will start and stop when the first start is requested and stop when the last
* is stopped.
* @note For the Alsa interface a low level link is availlable with AirTAudio for Alsa (One thread)
*/
class Group : public std11::enable_shared_from_this<Group> {
public:
/**
* @brief Contructor. No special thing to do.
*/
Group() {}
/**
* @brief Destructor
*/
~Group() {
// TODO : ...
}
private:
std::vector< std11::shared_ptr<Node> > m_list; //!< List of all node in the group
public:
/**
* @brief Create a group with all node needed to syncronize together
* @param[in] _obj json document to create all the node in the group named _name
* @param[in] _name Name of the group to create
*/
void createFrom(const ejson::Document& _obj, const std::string& _name);
/**
* @brief Get a node in the group (if the node is not in the group nothing append).
* @param[in] _name Name of the node requested.
* @return nullptr The node named _name was not found.
* @return pointer The node was find in this group.
*/
std11::shared_ptr<audio::river::io::Node> getNode(const std::string& _name);
/**
* @brief Start the group.
* @note all sub-node will be started.
*/
void start();
/**
* @brief Stop the group.
* @note All sub-node will be stopped at the reserve order that they start.
*/
void stop();
/**
* @brief Create the dot in the FileNode stream.
* @param[in,out] _node File node to write data.
* @param[in] _hardwareNode true if user want only display the hardware
* node and not the software node. false The oposite.
*/
void generateDot(etk::FSNode& _node, bool _hardwareNode);
};
}
}
}
#endif

389
audio/river/io/Manager.cpp Normal file
View File

@@ -0,0 +1,389 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/io/Manager.h>
#include <audio/river/debug.h>
#include <audio/river/river.h>
#include <audio/river/io/Node.h>
#include <audio/river/io/NodeAEC.h>
#include <audio/river/io/NodeMuxer.h>
#include <audio/river/io/NodeOrchestra.h>
#include <audio/river/io/NodePortAudio.h>
#include <etk/os/FSNode.h>
#include <etk/memory.h>
#include <etk/types.h>
#include <utility>
#undef __class__
#define __class__ "io::Manager"
#ifdef __PORTAUDIO_INFERFACE__
#include <portaudio.h>
#endif
static std::string basicAutoConfig =
"{\n"
" microphone:{\n"
" io:'input',\n"
" map-on:{\n"
" interface:'auto',\n"
" name:'default',\n"
" },\n"
" frequency:0,\n"
" channel-map:[\n"
" 'front-left', 'front-right'\n"
" ],\n"
" type:'auto',\n"
" nb-chunk:1024\n"
" },\n"
" speaker:{\n"
" io:'output',\n"
" map-on:{\n"
" interface:'auto',\n"
" name:'default',\n"
" },\n"
" frequency:0,\n"
" channel-map:[\n"
" 'front-left', 'front-right',\n"
" ],\n"
" type:'auto',\n"
" nb-chunk:1024,\n"
" volume-name:'MASTER'\n"
" }\n"
"}\n";
audio::river::io::Manager::Manager() {
#ifdef __PORTAUDIO_INFERFACE__
PaError err = Pa_Initialize();
if(err != paNoError) {
RIVER_WARNING("Can not initialize portaudio : " << Pa_GetErrorText(err));
}
#endif
}
void audio::river::io::Manager::init(const std::string& _filename) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (_filename == "") {
RIVER_INFO("Load default config");
m_config.parse(basicAutoConfig);
} else if (m_config.load(_filename) == false) {
RIVER_ERROR("you must set a basic configuration file for harware configuration: '" << _filename << "'");
}
}
void audio::river::io::Manager::initString(const std::string& _data) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
m_config.parse(_data);
}
void audio::river::io::Manager::unInit() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
// TODO : ...
}
audio::river::io::Manager::~Manager() {
#ifdef __PORTAUDIO_INFERFACE__
PaError err = Pa_Terminate();
if(err != paNoError) {
RIVER_WARNING("Can not initialize portaudio : " << Pa_GetErrorText(err));
}
#endif
};
std11::shared_ptr<audio::river::io::Manager> audio::river::io::Manager::getInstance() {
if (audio::river::isInit() == false) {
return std11::shared_ptr<audio::river::io::Manager>();
}
static std11::shared_ptr<audio::river::io::Manager> manager(new Manager());
return manager;
}
std::vector<std::string> audio::river::io::Manager::getListStreamInput() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std::vector<std::string> output;
std::vector<std::string> keys = m_config.getKeys();
for (size_t iii=0; iii<keys.size(); ++iii) {
const std11::shared_ptr<const ejson::Object> tmppp = m_config.getObject(keys[iii]);
if (tmppp != nullptr) {
std::string type = tmppp->getStringValue("io", "error");
if ( type == "input"
|| type == "PAinput") {
output.push_back(keys[iii]);
}
}
}
return output;
}
std::vector<std::string> audio::river::io::Manager::getListStreamOutput() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std::vector<std::string> output;
std::vector<std::string> keys = m_config.getKeys();
for (size_t iii=0; iii<keys.size(); ++iii) {
const std11::shared_ptr<const ejson::Object> tmppp = m_config.getObject(keys[iii]);
if (tmppp != nullptr) {
std::string type = tmppp->getStringValue("io", "error");
if ( type == "output"
|| type == "PAoutput") {
output.push_back(keys[iii]);
}
}
}
return output;
}
std::vector<std::string> audio::river::io::Manager::getListStreamVirtual() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std::vector<std::string> output;
std::vector<std::string> keys = m_config.getKeys();
for (size_t iii=0; iii<keys.size(); ++iii) {
const std11::shared_ptr<const ejson::Object> tmppp = m_config.getObject(keys[iii]);
if (tmppp != nullptr) {
std::string type = tmppp->getStringValue("io", "error");
if ( type != "input"
&& type != "PAinput"
&& type != "output"
&& type != "PAoutput"
&& type != "error") {
output.push_back(keys[iii]);
}
}
}
return output;
}
std::vector<std::string> audio::river::io::Manager::getListStream() {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std::vector<std::string> output;
std::vector<std::string> keys = m_config.getKeys();
for (size_t iii=0; iii<keys.size(); ++iii) {
const std11::shared_ptr<const ejson::Object> tmppp = m_config.getObject(keys[iii]);
if (tmppp != nullptr) {
std::string type = tmppp->getStringValue("io", "error");
if (type != "error") {
output.push_back(keys[iii]);
}
}
}
return output;
}
std11::shared_ptr<audio::river::io::Node> audio::river::io::Manager::getNode(const std::string& _name) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
RIVER_WARNING("Get node : " << _name);
// search in the standalone list :
for (size_t iii=0; iii<m_list.size(); ++iii) {
std11::shared_ptr<audio::river::io::Node> tmppp = m_list[iii].lock();
if ( tmppp != nullptr
&& _name == tmppp->getName()) {
RIVER_WARNING(" find it ... in standalone");
return tmppp;
}
}
// search in the group list:
{
for (std::map<std::string, std11::shared_ptr<audio::river::io::Group> >::iterator it(m_listGroup.begin());
it != m_listGroup.end();
++it) {
if (it->second != nullptr) {
std11::shared_ptr<audio::river::io::Node> node = it->second->getNode(_name);
if (node != nullptr) {
RIVER_WARNING(" find it ... in group: " << it->first);
return node;
}
}
}
}
RIVER_WARNING("Create a new one : " << _name);
// check if the node can be open :
const std11::shared_ptr<const ejson::Object> tmpObject = m_config.getObject(_name);
if (tmpObject != nullptr) {
//Check if it is in a group:
std::string groupName = tmpObject->getStringValue("group", "");
// get type : io
std::string ioType = tmpObject->getStringValue("io", "error");
if ( groupName != ""
&& ( ioType == "input"
|| ioType == "output"
|| ioType == "PAinput"
|| ioType == "PAoutput") ) {
std11::shared_ptr<audio::river::io::Group> tmpGroup = getGroup(groupName);
if (tmpGroup == nullptr) {
RIVER_WARNING("Can not get group ... '" << groupName << "'");
return std11::shared_ptr<audio::river::io::Node>();
}
return tmpGroup->getNode(_name);
} else {
if (groupName != "") {
RIVER_WARNING("Group is only availlable for Hardware interface ... '" << _name << "'");
}
// TODO : Create a standalone group for every single element ==> simplify understanding ... but not for virtual interface ...
#ifdef __AIRTAUDIO_INFERFACE__
if ( ioType == "input"
|| ioType == "output") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodeOrchestra::create(_name, tmpObject);
m_list.push_back(tmp);
return tmp;
}
#endif
#ifdef __PORTAUDIO_INFERFACE__
if ( ioType == "PAinput"
|| ioType == "PAoutput") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodePortAudio::create(_name, tmpObject);
m_list.push_back(tmp);
return tmp;
}
#endif
if (ioType == "aec") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodeAEC::create(_name, tmpObject);
m_list.push_back(tmp);
return tmp;
}
if (ioType == "muxer") {
std11::shared_ptr<audio::river::io::Node> tmp = audio::river::io::NodeMuxer::create(_name, tmpObject);
m_list.push_back(tmp);
return tmp;
}
}
}
RIVER_ERROR("Can not create the interface : '" << _name << "' the node is not DEFINED in the configuration file availlable : " << m_config.getKeys());
return std11::shared_ptr<audio::river::io::Node>();
}
std11::shared_ptr<audio::drain::VolumeElement> audio::river::io::Manager::getVolumeGroup(const std::string& _name) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
if (_name == "") {
RIVER_ERROR("Try to create an audio group with no name ...");
return std11::shared_ptr<audio::drain::VolumeElement>();
}
for (size_t iii=0; iii<m_volumeGroup.size(); ++iii) {
if (m_volumeGroup[iii] == nullptr) {
continue;
}
if (m_volumeGroup[iii]->getName() == _name) {
return m_volumeGroup[iii];
}
}
RIVER_DEBUG("Add a new volume group : '" << _name << "'");
std11::shared_ptr<audio::drain::VolumeElement> tmpVolume = std11::make_shared<audio::drain::VolumeElement>(_name);
m_volumeGroup.push_back(tmpVolume);
return tmpVolume;
}
bool audio::river::io::Manager::setVolume(const std::string& _volumeName, float _valuedB) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std11::shared_ptr<audio::drain::VolumeElement> volume = getVolumeGroup(_volumeName);
if (volume == nullptr) {
RIVER_ERROR("Can not set volume ... : '" << _volumeName << "'");
return false;
}
if ( _valuedB < -300
|| _valuedB > 300) {
RIVER_ERROR("Can not set volume ... : '" << _volumeName << "' out of range : [-300..300]");
return false;
}
volume->setVolume(_valuedB);
for (size_t iii=0; iii<m_list.size(); ++iii) {
std11::shared_ptr<audio::river::io::Node> val = m_list[iii].lock();
if (val != nullptr) {
val->volumeChange();
}
}
return true;
}
float audio::river::io::Manager::getVolume(const std::string& _volumeName) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std11::shared_ptr<audio::drain::VolumeElement> volume = getVolumeGroup(_volumeName);
if (volume == nullptr) {
RIVER_ERROR("Can not get volume ... : '" << _volumeName << "'");
return 0.0f;
}
return volume->getVolume();
}
std::pair<float,float> audio::river::io::Manager::getVolumeRange(const std::string& _volumeName) const {
return std::make_pair<float,float>(-300, 300);
}
void audio::river::io::Manager::generateDot(const std::string& _filename) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
etk::FSNode node(_filename);
RIVER_INFO("Generate the DOT files: " << node);
if (node.fileOpenWrite() == false) {
RIVER_ERROR("Can not Write the dot file (fail to open) : " << node);
return;
}
node << "digraph G {" << "\n";
node << " rankdir=\"LR\";\n";
// First Step : Create all HW interface:
{
// standalone
for (size_t iii=0; iii<m_list.size(); ++iii) {
std11::shared_ptr<audio::river::io::Node> val = m_list[iii].lock();
if (val != nullptr) {
if (val->isHarwareNode() == true) {
val->generateDot(node);
}
}
}
for (std::map<std::string, std11::shared_ptr<audio::river::io::Group> >::iterator it(m_listGroup.begin());
it != m_listGroup.end();
++it) {
if (it->second != nullptr) {
it->second->generateDot(node, true);
}
}
}
// All other ...
{
// standalone
for (size_t iii=0; iii<m_list.size(); ++iii) {
std11::shared_ptr<audio::river::io::Node> val = m_list[iii].lock();
if (val != nullptr) {
if (val->isHarwareNode() == false) {
val->generateDot(node);
}
}
}
for (std::map<std::string, std11::shared_ptr<audio::river::io::Group> >::iterator it(m_listGroup.begin());
it != m_listGroup.end();
++it) {
if (it->second != nullptr) {
it->second->generateDot(node, false);
}
}
}
node << "}" << "\n";
node.fileClose();
RIVER_INFO("Generate the DOT files: " << node << " (DONE)");
}
std11::shared_ptr<audio::river::io::Group> audio::river::io::Manager::getGroup(const std::string& _name) {
std11::unique_lock<std11::recursive_mutex> lock(m_mutex);
std11::shared_ptr<audio::river::io::Group> out;
std::map<std::string, std11::shared_ptr<audio::river::io::Group> >::iterator it = m_listGroup.find(_name);
if (it == m_listGroup.end()) {
RIVER_INFO("Create a new group: " << _name << " (START)");
out = std11::make_shared<audio::river::io::Group>();
if (out != nullptr) {
out->createFrom(m_config, _name);
std::pair<std::string, std11::shared_ptr<audio::river::io::Group> > plop(std::string(_name), out);
m_listGroup.insert(plop);
RIVER_INFO("Create a new group: " << _name << " ( END )");
} else {
RIVER_ERROR("Can not create new group: " << _name << " ( END )");
}
} else {
out = it->second;
}
return out;
}

145
audio/river/io/Manager.h Normal file
View File

@@ -0,0 +1,145 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_MANAGER_H__
#define __AUDIO_RIVER_IO_MANAGER_H__
#include <string>
#include <vector>
#include <map>
#include <list>
#include <stdint.h>
#include <etk/mutex.h>
#include <etk/chrono.h>
#include <etk/functional.h>
#include <etk/memory.h>
#include <audio/format.h>
#include <audio/channel.h>
#include <ejson/ejson.h>
#include <audio/drain/Volume.h>
#include <audio/river/io/Group.h>
namespace audio {
namespace river {
namespace io {
class Node;
/**
* @brief Internal sigleton of all Flow hadware and virtuals.
* @note this class will be initialize by the audio::river::init() function at the start of the application.
*/
class Manager : public std11::enable_shared_from_this<Manager> {
private:
mutable std11::recursive_mutex m_mutex; //!< prevent multiple access
private:
/**
* @brief Constructor
*/
Manager();
public:
static std11::shared_ptr<Manager> getInstance();
/**
* @brief Destructor
*/
~Manager();
/**
* @brief Called by audio::river::init() to set the hardware configuration file.
* @param[in] _filename Name of the file to initialize.
*/
void init(const std::string& _filename);
/**
* @brief Called by audio::river::initString() to set the hardware configuration string.
* @param[in] _data json configuration string.
*/
void initString(const std::string& _data);
/**
* @brief Called by audio::river::inInit() to uninitialize all the low level interface.
*/
void unInit();
private:
ejson::Document m_config; //!< harware configuration
std::vector<std11::shared_ptr<audio::river::io::Node> > m_listKeepAlive; //!< list of all Node that might be keep alive sone/all time
std::vector<std11::weak_ptr<audio::river::io::Node> > m_list; //!< List of all IO node
public:
/**
* @brief Get a node with his name (the name is set in the description file.
* @param[in] _name Name of the node
* @return Pointer on the noe or a nullptr if the node does not exist in the file or an error occured.
*/
std11::shared_ptr<audio::river::io::Node> getNode(const std::string& _name);
private:
std::vector<std11::shared_ptr<audio::drain::VolumeElement> > m_volumeGroup; //!< List of All global volume in the Low level interface.
public:
/**
* @brief Get a volume in the global list of vilume
* @param[in] _name Name of the volume.
* @return pointer on the requested volume (create it if does not exist). nullptr if the name is empty.
*/
std11::shared_ptr<audio::drain::VolumeElement> getVolumeGroup(const std::string& _name);
/**
* @brief Get all input audio stream.
* @return a list of all availlables input stream name
*/
std::vector<std::string> getListStreamInput();
/**
* @brief Get all output audio stream.
* @return a list of all availlables output stream name
*/
std::vector<std::string> getListStreamOutput();
/**
* @brief Get all audio virtual stream.
* @return a list of all availlables virtual stream name
*/
std::vector<std::string> getListStreamVirtual();
/**
* @brief Get all audio stream.
* @return a list of all availlables stream name
*/
std::vector<std::string> getListStream();
/**
* @brief Set a volume for a specific group
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @param[in] _value Volume in dB to set.
* @return true set done
* @return false An error occured
* @example : setVolume("MASTER", -3.0f);
*/
bool setVolume(const std::string& _volumeName, float _valuedB);
/**
* @brief Get a volume value
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @return The Volume value in dB.
* @example ret = getVolume("MASTER"); can return something like ret = -3.0f
*/
float getVolume(const std::string& _volumeName);
/**
* @brief Get a parameter value
* @param[in] _volumeName Name of the volume (MASTER, MATER_BT ...)
* @return The requested value Range.
* @example ret = getVolumeRange("MASTER"); can return something like ret=(-120.0f,0.0f)
*/
std::pair<float,float> getVolumeRange(const std::string& _volumeName) const;
/**
* @brief Generate the dot file corresponding at the actif nodes.
* @param[in] _filename Name of the file to write data.
*/
void generateDot(const std::string& _filename);
private:
std::map<std::string, std11::shared_ptr<audio::river::io::Group> > m_listGroup; //!< List of all groups
/**
* @brief get a low level interface group.
* @param[in] _name Name of the group.
* @return Pointer on the requested group or nullptr if the group does not existed.
*/
std11::shared_ptr<audio::river::io::Group> getGroup(const std::string& _name);
};
}
}
}
#endif

368
audio/river/io/Node.cpp Normal file
View File

@@ -0,0 +1,368 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include "Node.h"
#include <audio/river/debug.h>
#undef __class__
#define __class__ "io::Node"
audio::river::io::Node::Node(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) :
m_config(_config),
m_name(_name),
m_isInput(false) {
static uint32_t uid=0;
m_uid = uid++;
RIVER_INFO("-----------------------------------------------------------------");
RIVER_INFO("-- CREATE NODE --");
RIVER_INFO("-----------------------------------------------------------------");
audio::drain::IOFormatInterface interfaceFormat;
audio::drain::IOFormatInterface hardwareFormat;
/**
io:"input", # input, output or aec
frequency:48000, # frequency to open device
channel-map:[ # mapping of the harware device (to change map if needed)
"front-left", "front-right",
"read-left", "rear-right",
],
# format to open device (int8, int16, int16-on-ont32, int24, int32, float)
type:"int16",
# muxer/demuxer format type (int8-on-int16, int16-on-int32, int24-on-int32, int32-on-int64, float)
mux-demux-type:"int16_on_int32",
*/
std::string interfaceType = m_config->getStringValue("io");
RIVER_INFO("interfaceType=" << interfaceType);
if ( interfaceType == "input"
|| interfaceType == "PAinput"
|| interfaceType == "aec"
|| interfaceType == "muxer") {
m_isInput = true;
} else {
m_isInput = false;
}
int32_t frequency = m_config->getNumberValue("frequency", 1);
// Get audio format type:
std::string type = m_config->getStringValue("type", "int16");
enum audio::format formatType = audio::getFormatFromString(type);
// Get volume stage :
std::string volumeName = m_config->getStringValue("volume-name", "");
if (volumeName != "") {
RIVER_INFO("add node volume stage : '" << volumeName << "'");
// use global manager for volume ...
m_volume = audio::river::io::Manager::getInstance()->getVolumeGroup(volumeName);
}
// Get map type :
std::vector<audio::channel> map;
const std11::shared_ptr<const ejson::Array> listChannelMap = m_config->getArray("channel-map");
if ( listChannelMap == nullptr
|| listChannelMap->size() == 0) {
// set default channel property:
map.push_back(audio::channel_frontLeft);
map.push_back(audio::channel_frontRight);
} else {
for (size_t iii=0; iii<listChannelMap->size(); ++iii) {
std::string value = listChannelMap->getStringValue(iii);
map.push_back(audio::getChannelFromString(value));
}
}
hardwareFormat.set(map, formatType, frequency);
std::string muxerDemuxerConfig;
if (m_isInput == true) {
muxerDemuxerConfig = m_config->getStringValue("mux-demux-type", "int16");
} else {
muxerDemuxerConfig = m_config->getStringValue("mux-demux-type", "int16-on-int32");
}
enum audio::format muxerFormatType = audio::getFormatFromString(muxerDemuxerConfig);
if (m_isInput == true) {
if (muxerFormatType != audio::format_int16) {
RIVER_CRITICAL("not supported demuxer type ... " << muxerFormatType << " for INPUT set in file:" << muxerDemuxerConfig);
}
} else {
if (muxerFormatType != audio::format_int16_on_int32) {
RIVER_CRITICAL("not supported demuxer type ... " << muxerFormatType << " for OUTPUT set in file:" << muxerDemuxerConfig);
}
}
// no map change and no frequency change ...
interfaceFormat.set(map, muxerFormatType, frequency);
// configure process interface
if (m_isInput == true) {
m_process.setInputConfig(hardwareFormat);
m_process.setOutputConfig(interfaceFormat);
} else {
m_process.setOutputConfig(hardwareFormat);
m_process.setInputConfig(interfaceFormat);
}
//m_process.updateInterAlgo();
}
audio::river::io::Node::~Node() {
RIVER_INFO("-----------------------------------------------------------------");
RIVER_INFO("-- DESTROY NODE --");
RIVER_INFO("-----------------------------------------------------------------");
};
size_t audio::river::io::Node::getNumberOfInterface(enum audio::river::modeInterface _interfaceType) {
size_t out = 0;
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (m_list[iii] == nullptr) {
continue;
}
if (m_list[iii]->getMode() == _interfaceType) {
out++;
}
}
return out;
}
size_t audio::river::io::Node::getNumberOfInterfaceAvaillable(enum audio::river::modeInterface _interfaceType) {
size_t out = 0;
for (size_t iii=0; iii<m_listAvaillable.size(); ++iii) {
std11::shared_ptr<audio::river::Interface> element = m_listAvaillable[iii].lock();
if (element == nullptr) {
continue;
}
if (element->getMode() == _interfaceType) {
out++;
}
}
return out;
}
void audio::river::io::Node::registerAsRemote(const std11::shared_ptr<audio::river::Interface>& _interface) {
std::vector<std11::weak_ptr<audio::river::Interface> >::iterator it = m_listAvaillable.begin();
while (it != m_listAvaillable.end()) {
if (it->expired() == true) {
it = m_listAvaillable.erase(it);
continue;
}
++it;
}
m_listAvaillable.push_back(_interface);
}
void audio::river::io::Node::interfaceAdd(const std11::shared_ptr<audio::river::Interface>& _interface) {
{
std11::unique_lock<std11::mutex> lock(m_mutex);
for (size_t iii=0; iii<m_list.size(); ++iii) {
if (_interface == m_list[iii]) {
return;
}
}
RIVER_INFO("ADD interface for stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
m_list.push_back(_interface);
}
if (m_list.size() == 1) {
startInGroup();
}
}
void audio::river::io::Node::interfaceRemove(const std11::shared_ptr<audio::river::Interface>& _interface) {
{
std11::unique_lock<std11::mutex> lock(m_mutex);
for (size_t iii=0; iii< m_list.size(); ++iii) {
if (_interface == m_list[iii]) {
m_list.erase(m_list.begin()+iii);
RIVER_INFO("RM interface for stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
break;
}
}
}
if (m_list.size() == 0) {
stopInGroup();
}
return;
}
void audio::river::io::Node::volumeChange() {
for (size_t iii=0; iii< m_listAvaillable.size(); ++iii) {
std11::shared_ptr<audio::river::Interface> node = m_listAvaillable[iii].lock();
if (node != nullptr) {
node->systemVolumeChange();
}
}
}
void audio::river::io::Node::newInput(const void* _inputBuffer,
uint32_t _nbChunk,
const std11::chrono::system_clock::time_point& _time) {
if (_inputBuffer == nullptr) {
return;
}
const int16_t* inputBuffer = static_cast<const int16_t *>(_inputBuffer);
for (size_t iii=0; iii< m_list.size(); ++iii) {
if (m_list[iii] == nullptr) {
continue;
}
if (m_list[iii]->getMode() != audio::river::modeInterface_input) {
continue;
}
RIVER_VERBOSE(" IO name="<< m_list[iii]->getName());
m_list[iii]->systemNewInputData(_time, inputBuffer, _nbChunk);
}
RIVER_VERBOSE("data Input size request :" << _nbChunk << " [ END ]");
return;
}
void audio::river::io::Node::newOutput(void* _outputBuffer,
uint32_t _nbChunk,
const std11::chrono::system_clock::time_point& _time) {
if (_outputBuffer == nullptr) {
return;
}
std::vector<int32_t> output;
RIVER_VERBOSE("resize=" << _nbChunk*m_process.getInputConfig().getMap().size());
output.resize(_nbChunk*m_process.getInputConfig().getMap().size(), 0);
// TODO : set here the mixer selection ...
if (true) {
const int32_t* outputTmp = nullptr;
std::vector<uint8_t> outputTmp2;
RIVER_VERBOSE("resize=" << sizeof(int32_t)*m_process.getInputConfig().getMap().size()*_nbChunk);
outputTmp2.resize(sizeof(int32_t)*m_process.getInputConfig().getMap().size()*_nbChunk, 0);
for (size_t iii=0; iii< m_list.size(); ++iii) {
if (m_list[iii] == nullptr) {
continue;
}
if (m_list[iii]->getMode() != audio::river::modeInterface_output) {
continue;
}
RIVER_VERBOSE(" IO name="<< m_list[iii]->getName() << " " << iii);
// clear datas ...
memset(&outputTmp2[0], 0, sizeof(int32_t)*m_process.getInputConfig().getMap().size()*_nbChunk);
RIVER_VERBOSE(" request Data="<< _nbChunk << " time=" << _time);
m_list[iii]->systemNeedOutputData(_time, &outputTmp2[0], _nbChunk, sizeof(int32_t)*m_process.getInputConfig().getMap().size());
outputTmp = reinterpret_cast<const int32_t*>(&outputTmp2[0]);
RIVER_VERBOSE(" Mix it ...");
// Add data to the output tmp buffer :
for (size_t kkk=0; kkk<output.size(); ++kkk) {
output[kkk] += outputTmp[kkk];
}
}
}
RIVER_VERBOSE(" End stack process data ...");
m_process.processIn(&output[0], _nbChunk, _outputBuffer, _nbChunk);
RIVER_VERBOSE(" Feedback :");
for (size_t iii=0; iii< m_list.size(); ++iii) {
if (m_list[iii] == nullptr) {
continue;
}
if (m_list[iii]->getMode() != audio::river::modeInterface_feedback) {
continue;
}
RIVER_VERBOSE(" IO name="<< m_list[iii]->getName() << " (feedback) time=" << _time);
m_list[iii]->systemNewInputData(_time, _outputBuffer, _nbChunk);
}
RIVER_VERBOSE("data Output size request :" << _nbChunk << " [ END ]");
return;
}
static void link(etk::FSNode& _node, const std::string& _first, const std::string& _op, const std::string& _second) {
if (_op == "->") {
_node << " " << _first << " -> " << _second << ";\n";
} else if (_op == "<-") {
_node << " " << _first << " -> " <<_second<< " [color=transparent];\n";
_node << " " << _second << " -> " << _first << " [constraint=false];\n";
}
}
void audio::river::io::Node::generateDot(etk::FSNode& _node) {
_node << " subgraph clusterNode_" << m_uid << " {\n";
_node << " color=blue;\n";
_node << " label=\"[" << m_uid << "] IO::Node : " << m_name << "\";\n";
if (m_isInput == true) {
_node << " node [shape=rarrow];\n";
_node << " NODE_" << m_uid << "_HW_interface [ label=\"HW interface\\n interface=ALSA\\n stream=" << m_name << "\\n type=input\" ];\n";
std::string nameIn;
std::string nameOut;
m_process.generateDotProcess(_node, 3, m_uid, nameIn, nameOut, false);
_node << " node [shape=square];\n";
_node << " NODE_" << m_uid << "_demuxer [ label=\"DEMUXER\\n format=" << etk::to_string(m_process.getOutputConfig().getFormat()) << "\" ];\n";
// Link all nodes :
_node << " NODE_" << m_uid << "_HW_interface -> " << nameIn << " [arrowhead=\"open\"];\n";
_node << " " << nameOut << " -> NODE_" << m_uid << "_demuxer [arrowhead=\"open\"];\n";
} else {
size_t nbOutput = getNumberOfInterfaceAvaillable(audio::river::modeInterface_output);
size_t nbfeedback = getNumberOfInterfaceAvaillable(audio::river::modeInterface_feedback);
_node << " node [shape=larrow];\n";
_node << " NODE_" << m_uid << "_HW_interface [ label=\"HW interface\\n interface=ALSA\\n stream=" << m_name << "\\n type=output\" ];\n";
std::string nameIn;
std::string nameOut;
if (nbOutput>0) {
m_process.generateDotProcess(_node, 3, m_uid, nameIn, nameOut, true);
}
_node << " node [shape=square];\n";
if (nbOutput>0) {
_node << " NODE_" << m_uid << "_muxer [ label=\"MUXER\\n format=" << etk::to_string(m_process.getInputConfig().getFormat()) << "\" ];\n";
}
if (nbfeedback>0) {
_node << " NODE_" << m_uid << "_demuxer [ label=\"DEMUXER\\n format=" << etk::to_string(m_process.getOutputConfig().getFormat()) << "\" ];\n";
}
// Link all nodes :
if (nbOutput>0) {
link(_node, "NODE_" + etk::to_string(m_uid) + "_HW_interface", "<-", nameOut);
link(_node, nameIn, "<-", "NODE_" + etk::to_string(m_uid) + "_muxer");
}
if (nbfeedback>0) {
_node << " NODE_" << m_uid << "_HW_interface -> NODE_" << m_uid << "_demuxer [arrowhead=\"open\"];\n";
}
if ( nbOutput>0
&& nbfeedback>0) {
_node << " { rank=same; NODE_" << m_uid << "_demuxer; NODE_" << m_uid << "_muxer }\n";
}
}
_node << " }\n \n";
for (size_t iii=0; iii< m_listAvaillable.size(); ++iii) {
if (m_listAvaillable[iii].expired() == true) {
continue;
}
std11::shared_ptr<audio::river::Interface> element = m_listAvaillable[iii].lock();
if (element == nullptr) {
continue;
}
bool isLink = false;
for (size_t jjj=0; jjj<m_list.size(); ++jjj) {
if (element == m_list[jjj]) {
isLink = true;
}
}
if (element != nullptr) {
if (element->getMode() == modeInterface_input) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else if (element->getMode() == modeInterface_output) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_muxer", isLink);
} else if (element->getMode() == modeInterface_feedback) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else {
}
}
}
}
void audio::river::io::Node::startInGroup() {
std11::shared_ptr<audio::river::io::Group> group = m_group.lock();
if (group != nullptr) {
group->start();
} else {
start();
}
}
void audio::river::io::Node::stopInGroup() {
std11::shared_ptr<audio::river::io::Group> group = m_group.lock();
if (group != nullptr) {
group->stop();
} else {
stop();
}
}

226
audio/river/io/Node.h Normal file
View File

@@ -0,0 +1,226 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_NODE_H__
#define __AUDIO_RIVER_IO_NODE_H__
#include <string>
#include <vector>
#include <list>
#include <stdint.h>
#include <etk/chrono.h>
#include <etk/functional.h>
#include <etk/memory.h>
#include <audio/format.h>
#include <audio/channel.h>
#include "Manager.h"
#include <audio/river/Interface.h>
#include <audio/drain/IOFormatInterface.h>
#include <audio/drain/Volume.h>
#include <etk/os/FSNode.h>
namespace audio {
namespace river {
namespace io {
class Manager;
class Group;
/**
* @brief A node is the base for input/output interface. When a output id declared, we automaticly have a feedback associated.
* this manage the muxing of data for output an the demuxing for input.
*/
class Node : public std11::enable_shared_from_this<Node> {
friend class audio::river::io::Group;
protected:
uint32_t m_uid; //!< uniqueNodeID use for debug an dot generation.
protected:
/**
* @brief Constructor
* @param[in] _name Name of the node.
* @param[in] _config Configuration of the node.
*/
Node(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
public:
/**
* @brief Destructor
*/
virtual ~Node();
/**
* @brief Get the status of this node acces on harware or acces on other node (virtual).
* @return true This is an harware interface.
* @return false this is a virtual interface.
*/
virtual bool isHarwareNode() {
return false;
};
protected:
mutable std11::mutex m_mutex; //!< prevent open/close/write/read access that is multi-threaded.
std11::shared_ptr<const ejson::Object> m_config; //!< configuration description.
protected:
audio::drain::Process m_process; //!< Low level algorithms
public:
/**
* @brief Get the uper client interface configuration.
* @return process configuration.
*/
const audio::drain::IOFormatInterface& getInterfaceFormat() {
if (m_isInput == true) {
return m_process.getOutputConfig();
} else {
return m_process.getInputConfig();
}
}
/**
* @brief Get the harware client interface configuration.
* @return process configuration.
*/
const audio::drain::IOFormatInterface& getHarwareFormat() {
if (m_isInput == true) {
return m_process.getInputConfig();
} else {
return m_process.getOutputConfig();
}
}
protected:
std11::shared_ptr<audio::drain::VolumeElement> m_volume; //!< if a volume is set it is set here ... for hardware interface only.
protected:
std::vector<std11::weak_ptr<audio::river::Interface> > m_listAvaillable; //!< List of all interface that exist on this Node
std::vector<std11::shared_ptr<audio::river::Interface> > m_list; //!< List of all connected interface at this node.
/**
* @brief Get the number of interface with a specific type.
* @param[in] _interfaceType Type of the interface.
* @return Number of interface connected.
*/
size_t getNumberOfInterface(enum audio::river::modeInterface _interfaceType);
/**
* @brief Get the number of interface with a specific type that can connect on the Node.
* @param[in] _interfaceType Type of the interface.
* @return Number of interface that can connect.
*/
size_t getNumberOfInterfaceAvaillable(enum audio::river::modeInterface _interfaceType);
public:
/**
* @brief Get the number of interface connected
* @return Number of interfaces.
*/
size_t getNumberOfInterface() {
return m_list.size();
}
public:
/**
* @brief Register an interface that can connect on it. (might be done in the Interface Init)
* @note We keep a std::weak_ptr. this is the reason why we do not have a remove.
* @param[in] _interface Pointer on the interface to register.
*/
void registerAsRemote(const std11::shared_ptr<audio::river::Interface>& _interface);
/**
* @brief Request this interface might receve/send dat on the flow. (start/resume)
* @param[in] _interface Pointer on the interface to register.
*/
void interfaceAdd(const std11::shared_ptr<audio::river::Interface>& _interface);
/**
* @brief Un-register the interface as an availlable read/write interface. (suspend/stop)
* @param[in] _interface Pointer on the interface to register.
*/
void interfaceRemove(const std11::shared_ptr<audio::river::Interface>& _interface);
protected:
std::string m_name; //!< Name of the interface
public:
/**
* @brief Get the interface name.
* @return Current name.
*/
const std::string& getName() {
return m_name;
}
protected:
bool m_isInput; //!< sense of the stream
public:
/**
* @brief Check if it is an input stream
* @return true if it is an input/ false otherwise
*/
bool isInput() {
return m_isInput;
}
/**
* @brief Check if it is an output stream
* @return true if it is an output/ false otherwise
*/
bool isOutput() {
return !m_isInput;
}
protected:
std11::weak_ptr<audio::river::io::Group> m_group; //!< reference on the group. If available.
public:
/**
* @brief Set this node in a low level group.
* @param[in] _group Group reference.
*/
void setGroup(std11::shared_ptr<audio::river::io::Group> _group) {
m_group = _group;
}
protected:
/**
* @brief Start the flow in the group (start if no group)
*/
void startInGroup();
/**
* @brief Stop the flow in the group (stop if no group)
*/
void stopInGroup();
/**
* @brief Real start of the stream
*/
virtual void start() = 0;
/**
* @brief Real stop of the stream
*/
virtual void stop() = 0;
public:
/**
* @brief If this iss an hardware interface we can have a resuest of the volume stage:
* @return pointer on the requested volume.
*/
const std11::shared_ptr<audio::drain::VolumeElement>& getVolume() {
return m_volume;
}
public:
/**
* @brief Called when a group wolume has been change to update all volume stage.
*/
void volumeChange();
protected:
/**
* @brief Call by child classes to process data in all interface linked on the current Node. Have new input to process.
* @param[in] _inputBuffer Pointer on the data.
* @param[in] _nbChunk Number of chunk in the buffer.
* @param[in] _time Time where the first sample has been capture.
*/
void newInput(const void* _inputBuffer,
uint32_t _nbChunk,
const std11::chrono::system_clock::time_point& _time);
/**
* @brief Call by child classes to process data in all interface linked on the current Node. Have new output to get. this call the feedback too.
* @param[in,out] _outputBuffer Pointer on the buffer to write the data.
* @param[in] _nbChunk Number of chunk to write in the buffer.
* @param[in] _time Time where the data might be played.
*/
void newOutput(void* _outputBuffer,
uint32_t _nbChunk,
const std11::chrono::system_clock::time_point& _time);
public:
/**
* @brief Generate the node dot file section
* @param[in] _node File node to generate the data.
*/
virtual void generateDot(etk::FSNode& _node);
};
}
}
}
#endif

371
audio/river/io/NodeAEC.cpp Normal file
View File

@@ -0,0 +1,371 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/io/NodeAEC.h>
#include <audio/river/debug.h>
#include <etk/types.h>
#include <etk/memory.h>
#include <etk/functional.h>
#undef __class__
#define __class__ "io::NodeAEC"
std11::shared_ptr<audio::river::io::NodeAEC> audio::river::io::NodeAEC::create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) {
return std11::shared_ptr<audio::river::io::NodeAEC>(new audio::river::io::NodeAEC(_name, _config));
}
std11::shared_ptr<audio::river::Interface> audio::river::io::NodeAEC::createInput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _objectName,
const std::string& _name) {
// check if the output exist
const std11::shared_ptr<const ejson::Object> tmppp = m_config->getObject(_objectName);
if (tmppp == nullptr) {
RIVER_ERROR("can not open a non existance virtual interface: '" << _objectName << "' not present in : " << m_config->getKeys());
return std11::shared_ptr<audio::river::Interface>();
}
std::string streamName = tmppp->getStringValue("map-on", "error");
m_nbChunk = m_config->getNumberValue("nb-chunk", 1024);
// check if it is an Output:
std::string type = tmppp->getStringValue("io", "error");
if ( type != "input"
&& type != "feedback") {
RIVER_ERROR("can not open in output a virtual interface: '" << streamName << "' configured has : " << type);
return std11::shared_ptr<audio::river::Interface>();
}
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
// get the output or input channel :
std11::shared_ptr<audio::river::io::Node> node = manager->getNode(streamName);
// create user iterface:
std11::shared_ptr<audio::river::Interface> interface;
interface = audio::river::Interface::create(_freq, _map, _format, node, tmppp);
if (interface != nullptr) {
interface->setName(_name);
}
return interface;
}
audio::river::io::NodeAEC::NodeAEC(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) :
Node(_name, _config),
m_P_attaqueTime(1),
m_P_releaseTime(100),
m_P_minimumGain(10),
m_P_threshold(2),
m_P_latencyTime(100) {
audio::drain::IOFormatInterface interfaceFormat = getInterfaceFormat();
audio::drain::IOFormatInterface hardwareFormat = getHarwareFormat();
m_sampleTime = std11::chrono::nanoseconds(1000000000/int64_t(hardwareFormat.getFrequency()));
/**
# connect in input mode
map-on-microphone:{
# generic virtual definition
io:"input",
map-on:"microphone",
resampling-type:"speexdsp",
resampling-option:"quality=10"
},
# connect in feedback mode
map-on-feedback:{
io:"feedback",
map-on:"speaker",
resampling-type:"speexdsp",
resampling-option:"quality=10",
},
# AEC algo definition
algo:"river-remover",
algo-mode:"cutter",
*/
std::vector<audio::channel> feedbackMap;
feedbackMap.push_back(audio::channel_frontCenter);
RIVER_INFO("Create FEEDBACK : ");
m_interfaceFeedBack = createInput(hardwareFormat.getFrequency(),
feedbackMap,
hardwareFormat.getFormat(),
"map-on-feedback",
_name + "-AEC-feedback");
if (m_interfaceFeedBack == nullptr) {
RIVER_ERROR("Can not opne virtual device ... map-on-feedback in " << _name);
return;
}
RIVER_INFO("Create MICROPHONE : ");
m_interfaceMicrophone = createInput(hardwareFormat.getFrequency(),
hardwareFormat.getMap(),
hardwareFormat.getFormat(),
"map-on-microphone",
_name + "-AEC-microphone");
if (m_interfaceMicrophone == nullptr) {
RIVER_ERROR("Can not opne virtual device ... map-on-microphone in " << _name);
return;
}
// set callback mode ...
m_interfaceFeedBack->setInputCallback(std11::bind(&audio::river::io::NodeAEC::onDataReceivedFeedBack,
this,
std11::placeholders::_1,
std11::placeholders::_2,
std11::placeholders::_3,
std11::placeholders::_4,
std11::placeholders::_5,
std11::placeholders::_6));
// set callback mode ...
m_interfaceMicrophone->setInputCallback(std11::bind(&audio::river::io::NodeAEC::onDataReceivedMicrophone,
this,
std11::placeholders::_1,
std11::placeholders::_2,
std11::placeholders::_3,
std11::placeholders::_4,
std11::placeholders::_5,
std11::placeholders::_6));
m_bufferMicrophone.setCapacity(std11::chrono::milliseconds(1000),
audio::getFormatBytes(hardwareFormat.getFormat())*hardwareFormat.getMap().size(),
hardwareFormat.getFrequency());
m_bufferFeedBack.setCapacity(std11::chrono::milliseconds(1000),
audio::getFormatBytes(hardwareFormat.getFormat()), // only one channel ...
hardwareFormat.getFrequency());
m_process.updateInterAlgo();
}
audio::river::io::NodeAEC::~NodeAEC() {
RIVER_INFO("close input stream");
stop();
m_interfaceFeedBack.reset();
m_interfaceMicrophone.reset();
};
void audio::river::io::NodeAEC::start() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
if (m_interfaceFeedBack != nullptr) {
RIVER_INFO("Start FEEDBACK : ");
m_interfaceFeedBack->start();
}
if (m_interfaceMicrophone != nullptr) {
RIVER_INFO("Start Microphone : ");
m_interfaceMicrophone->start();
}
}
void audio::river::io::NodeAEC::stop() {
std11::unique_lock<std11::mutex> lock(m_mutex);
if (m_interfaceFeedBack != nullptr) {
m_interfaceFeedBack->stop();
}
if (m_interfaceMicrophone != nullptr) {
m_interfaceMicrophone->stop();
}
}
void audio::river::io::NodeAEC::onDataReceivedMicrophone(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map) {
RIVER_DEBUG("Microphone Time=" << _time << " _nbChunk=" << _nbChunk << " _map=" << _map << " _format=" << _format << " freq=" << _frequency);
RIVER_DEBUG(" next=" << _time + std11::chrono::nanoseconds(_nbChunk*1000000000LL/int64_t(_frequency)) );
if (_format != audio::format_int16) {
RIVER_ERROR("call wrong type ... (need int16_t)");
}
// push data synchronize
std11::unique_lock<std11::mutex> lock(m_mutex);
m_bufferMicrophone.write(_data, _nbChunk, _time);
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_Microphone.raw", _data, _nbChunk*_map.size());
process();
}
void audio::river::io::NodeAEC::onDataReceivedFeedBack(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map) {
RIVER_DEBUG("FeedBack Time=" << _time << " _nbChunk=" << _nbChunk << " _map=" << _map << " _format=" << _format << " freq=" << _frequency);
RIVER_DEBUG(" next=" << _time + std11::chrono::nanoseconds(_nbChunk*1000000000LL/int64_t(_frequency)) );
if (_format != audio::format_int16) {
RIVER_ERROR("call wrong type ... (need int16_t)");
}
// push data synchronize
std11::unique_lock<std11::mutex> lock(m_mutex);
m_bufferFeedBack.write(_data, _nbChunk, _time);
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_FeedBack.raw", _data, _nbChunk*_map.size());
process();
}
void audio::river::io::NodeAEC::process() {
if ( m_bufferMicrophone.getSize() <= m_nbChunk
|| m_bufferFeedBack.getSize() <= m_nbChunk) {
return;
}
std11::chrono::system_clock::time_point MicTime = m_bufferMicrophone.getReadTimeStamp();
std11::chrono::system_clock::time_point fbTime = m_bufferFeedBack.getReadTimeStamp();
std11::chrono::nanoseconds delta;
if (MicTime < fbTime) {
delta = fbTime - MicTime;
} else {
delta = MicTime - fbTime;
}
RIVER_INFO("check delta " << delta.count() << " > " << m_sampleTime.count());
if (delta > m_sampleTime) {
// Synchronize if possible
if (MicTime < fbTime) {
RIVER_INFO("micTime < fbTime : Change Microphone time start " << fbTime);
RIVER_INFO(" old time stamp=" << m_bufferMicrophone.getReadTimeStamp());
m_bufferMicrophone.setReadPosition(fbTime);
RIVER_INFO(" new time stamp=" << m_bufferMicrophone.getReadTimeStamp());
}
if (MicTime > fbTime) {
RIVER_INFO("micTime > fbTime : Change FeedBack time start " << MicTime);
RIVER_INFO(" old time stamp=" << m_bufferFeedBack.getReadTimeStamp());
m_bufferFeedBack.setReadPosition(MicTime);
RIVER_INFO(" new time stamp=" << m_bufferFeedBack.getReadTimeStamp());
}
}
// check if enought time after synchronisation ...
if ( m_bufferMicrophone.getSize() <= m_nbChunk
|| m_bufferFeedBack.getSize() <= m_nbChunk) {
return;
}
MicTime = m_bufferMicrophone.getReadTimeStamp();
fbTime = m_bufferFeedBack.getReadTimeStamp();
if (MicTime-fbTime > m_sampleTime) {
RIVER_ERROR("Can not synchronize flow ... : " << MicTime << " != " << fbTime << " delta = " << (MicTime-fbTime).count()/1000 << " µs");
return;
}
std::vector<uint8_t> dataMic;
std::vector<uint8_t> dataFB;
dataMic.resize(m_nbChunk*sizeof(int16_t)*2, 0);
dataFB.resize(m_nbChunk*sizeof(int16_t), 0);
while (true) {
MicTime = m_bufferMicrophone.getReadTimeStamp();
fbTime = m_bufferFeedBack.getReadTimeStamp();
RIVER_INFO(" process 256 samples ... micTime=" << MicTime << " fbTime=" << fbTime << " delta = " << (MicTime-fbTime).count());
m_bufferMicrophone.read(&dataMic[0], m_nbChunk);
m_bufferFeedBack.read(&dataFB[0], m_nbChunk);
RIVER_SAVE_FILE_MACRO(int16_t, "REC_Microphone_sync.raw", &dataMic[0], m_nbChunk*getHarwareFormat().getMap().size());
RIVER_SAVE_FILE_MACRO(int16_t, "REC_FeedBack_sync.raw", &dataFB[0], m_nbChunk);
// if threaded : send event / otherwise, process ...
processAEC(&dataMic[0], &dataFB[0], m_nbChunk, MicTime);
if ( m_bufferMicrophone.getSize() <= m_nbChunk
|| m_bufferFeedBack.getSize() <= m_nbChunk) {
return;
}
}
}
void audio::river::io::NodeAEC::processAEC(void* _dataMic, void* _dataFB, uint32_t _nbChunk, const std11::chrono::system_clock::time_point& _time) {
audio::drain::IOFormatInterface hardwareFormat = getHarwareFormat();
// TODO : Set all these parameter in the parameter configuration section ...
int32_t attaqueTime = std::min(std::max(0,m_P_attaqueTime),1000);
int32_t releaseTime = std::min(std::max(0,m_P_releaseTime),1000);
int32_t min_gain = 32767 * std::min(std::max(0,m_P_minimumGain),1000) / 1000;
int32_t threshold = 32767 * std::min(std::max(0,m_P_threshold),1000) / 1000;
int32_t latencyTime = std::min(std::max(0,m_P_latencyTime),1000);
int32_t nb_sample_latency = (hardwareFormat.getFrequency()/1000)*latencyTime;
int32_t increaseSample = 32767;
if (attaqueTime != 0) {
increaseSample = 32767/(hardwareFormat.getFrequency() * attaqueTime / 1000);
}
int32_t decreaseSample = 32767;
if (attaqueTime != 0) {
decreaseSample = 32767/(hardwareFormat.getFrequency() * releaseTime / 1000);
}
// Process section:
int16_t* dataMic = static_cast<int16_t*>(_dataMic);
int16_t* dataFB = static_cast<int16_t*>(_dataFB);
for (size_t iii=0; iii<_nbChunk; ++iii) {
if (abs(*dataFB++) > threshold) {
m_sampleCount = 0;
} else {
m_sampleCount++;
}
if (m_sampleCount > nb_sample_latency) {
m_gainValue += decreaseSample;
if (m_gainValue >= 32767) {
m_gainValue = 32767;
}
} else {
if (m_gainValue <= increaseSample) {
m_gainValue = 0;
} else {
m_gainValue -= increaseSample;
}
if (m_gainValue < min_gain) {
m_gainValue = min_gain;
}
}
for (size_t jjj=0; jjj<hardwareFormat.getMap().size(); ++jjj) {
*dataMic = static_cast<int16_t>((*dataMic * m_gainValue) >> 15);
dataMic++;
}
}
RIVER_SAVE_FILE_MACRO(int16_t, "REC_Microphone_clean.raw", _dataMic, _nbChunk*getHarwareFormat().getMap().size());
// simply send to upper requester...
newInput(_dataMic, _nbChunk, _time);
}
void audio::river::io::NodeAEC::generateDot(etk::FSNode& _node) {
_node << " subgraph clusterNode_" << m_uid << " {\n";
_node << " color=blue;\n";
_node << " label=\"[" << m_uid << "] IO::Node : " << m_name << "\";\n";
_node << " NODE_" << m_uid << "_HW_AEC [ label=\"AEC\\n channelMap=" << etk::to_string(getInterfaceFormat().getMap()) << "\" ];\n";
std::string nameIn;
std::string nameOut;
m_process.generateDot(_node, 3, m_uid, nameIn, nameOut, false);
_node << " node [shape=square];\n";
_node << " NODE_" << m_uid << "_demuxer [ label=\"DEMUXER\\n format=" << etk::to_string(m_process.getOutputConfig().getFormat()) << "\" ];\n";
// Link all nodes :
_node << " NODE_" << m_uid << "_HW_AEC -> " << nameIn << ";\n";
_node << " " << nameOut << " -> NODE_" << m_uid << "_demuxer;\n";
_node << " }\n";
if (m_interfaceMicrophone != nullptr) {
_node << " " << m_interfaceMicrophone->getDotNodeName() << " -> NODE_" << m_uid << "_HW_AEC;\n";
}
if (m_interfaceFeedBack != nullptr) {
_node << " " << m_interfaceFeedBack->getDotNodeName() << " -> NODE_" << m_uid << "_HW_AEC;\n";
}
_node << " \n";
for (size_t iii=0; iii< m_listAvaillable.size(); ++iii) {
if (m_listAvaillable[iii].expired() == true) {
continue;
}
std11::shared_ptr<audio::river::Interface> element = m_listAvaillable[iii].lock();
if (element == nullptr) {
continue;
}
bool isLink = false;
for (size_t jjj=0; jjj<m_list.size(); ++jjj) {
if (element == m_list[jjj]) {
isLink = true;
}
}
if (element != nullptr) {
if (element->getMode() == modeInterface_input) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else if (element->getMode() == modeInterface_output) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_muxer", isLink);
} else if (element->getMode() == modeInterface_feedback) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else {
}
}
}
}

110
audio/river/io/NodeAEC.h Normal file
View File

@@ -0,0 +1,110 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_NODE_AEC_H__
#define __AUDIO_RIVER_IO_NODE_AEC_H__
#include <audio/river/io/Node.h>
#include <audio/river/Interface.h>
#include <audio/drain/CircularBuffer.h>
namespace audio {
namespace river {
namespace io {
class Manager;
class NodeAEC : public Node {
protected:
/**
* @brief Constructor
*/
NodeAEC(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
public:
/**
* @brief Factory of this Virtual Node.
* @param[in] _name Name of the node.
* @param[in] _config Configuration of the node.
*/
static std11::shared_ptr<NodeAEC> create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
/**
* @brief Destructor
*/
virtual ~NodeAEC();
protected:
virtual void start();
virtual void stop();
std11::shared_ptr<audio::river::Interface> m_interfaceMicrophone; //!< Interface on the Microphone.
std11::shared_ptr<audio::river::Interface> m_interfaceFeedBack; //!< Interface on the feedback of speaker.
/**
* @brief Internal: create an input with the specific parameter:
* @param[in] _freq Frequency.
* @param[in] _map Channel map organization.
* @param[in] _format Sample format
* @param[in] _streamName
* @param[in] _name
* @return Interfae Pointer.
*/
std11::shared_ptr<audio::river::Interface> createInput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _streamName,
const std::string& _name);
/**
* @brief Stream data input callback
* @todo : copy doc ..
*/
void onDataReceivedMicrophone(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map);
/**
* @brief Stream data input callback
* @todo : copy doc ..
*/
void onDataReceivedFeedBack(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map);
protected:
audio::drain::CircularBuffer m_bufferMicrophone; //!< temporary buffer to synchronize data.
audio::drain::CircularBuffer m_bufferFeedBack; //!< temporary buffer to synchronize data.
std11::chrono::nanoseconds m_sampleTime; //!< represent the sample time at the specify frequency.
/**
* @brief Process synchronization on the 2 flow.
*/
void process();
/**
* @brief Process algorithm on the current 2 syncronize flow.
* @param[in] _dataMic Pointer in the Microphione interface.
* @param[in] _dataFB Pointer on the beedback buffer.
* @param[in] _nbChunk Number of chunk to process.
* @param[in] _time Time on the firsta sample that data has been captured.
* @return
*/
void processAEC(void* _dataMic, void* _dataFB, uint32_t _nbChunk, const std11::chrono::system_clock::time_point& _time);
public:
virtual void generateDot(etk::FSNode& _node);
private:
int32_t m_nbChunk;
int32_t m_gainValue;
int32_t m_sampleCount;
int32_t m_P_attaqueTime; //ms
int32_t m_P_releaseTime; //ms
int32_t m_P_minimumGain; // %
int32_t m_P_threshold; // %
int32_t m_P_latencyTime; // ms
};
}
}
}
#endif

View File

@@ -0,0 +1,486 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/io/NodeMuxer.h>
#include <audio/river/debug.h>
#include <etk/types.h>
#include <etk/memory.h>
#include <etk/functional.h>
#undef __class__
#define __class__ "io::NodeMuxer"
std11::shared_ptr<audio::river::io::NodeMuxer> audio::river::io::NodeMuxer::create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) {
return std11::shared_ptr<audio::river::io::NodeMuxer>(new audio::river::io::NodeMuxer(_name, _config));
}
std11::shared_ptr<audio::river::Interface> audio::river::io::NodeMuxer::createInput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _objectName,
const std::string& _name) {
// check if the output exist
const std11::shared_ptr<const ejson::Object> tmppp = m_config->getObject(_objectName);
if (tmppp == nullptr) {
RIVER_ERROR("can not open a non existance virtual interface: '" << _objectName << "' not present in : " << m_config->getKeys());
return std11::shared_ptr<audio::river::Interface>();
}
std::string streamName = tmppp->getStringValue("map-on", "error");
// check if it is an Output:
std::string type = tmppp->getStringValue("io", "error");
if ( type != "input"
&& type != "feedback") {
RIVER_ERROR("can not open in output a virtual interface: '" << streamName << "' configured has : " << type);
return std11::shared_ptr<audio::river::Interface>();
}
// get global hardware interface:
std11::shared_ptr<audio::river::io::Manager> manager = audio::river::io::Manager::getInstance();
// get the output or input channel :
std11::shared_ptr<audio::river::io::Node> node = manager->getNode(streamName);
// create user iterface:
std11::shared_ptr<audio::river::Interface> interface;
interface = audio::river::Interface::create(_freq, _map, _format, node, tmppp);
if (interface != nullptr) {
interface->setName(_name);
}
return interface;
}
audio::river::io::NodeMuxer::NodeMuxer(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) :
Node(_name, _config) {
audio::drain::IOFormatInterface interfaceFormat = getInterfaceFormat();
audio::drain::IOFormatInterface hardwareFormat = getHarwareFormat();
m_sampleTime = std11::chrono::nanoseconds(1000000000/int64_t(hardwareFormat.getFrequency()));
/**
# connect in input mode
map-on-input-1:{
# generic virtual definition
io:"input",
map-on:"microphone",
resampling-type:"speexdsp",
resampling-option:"quality=10"
},
# connect in feedback mode
map-on-input-2:{
io:"feedback",
map-on:"speaker",
resampling-type:"speexdsp",
resampling-option:"quality=10",
},
input-2-remap:["rear-left", "rear-right"], # remap the IO inputs ...
# AEC algo definition
algo:"river-remover",
algo-mode:"cutter",
*/
RIVER_INFO("Create IN 1 : ");
m_interfaceInput1 = createInput(hardwareFormat.getFrequency(),
std::vector<audio::channel>(),
hardwareFormat.getFormat(),
"map-on-input-1",
_name + "-muxer-in1");
if (m_interfaceInput1 == nullptr) {
RIVER_ERROR("Can not opne virtual device ... map-on-input-1 in " << _name);
return;
}
std11::shared_ptr<const ejson::Array> listChannelMap = m_config->getArray("input-1-remap");
if ( listChannelMap == nullptr
|| listChannelMap->size() == 0) {
m_mapInput1 = m_interfaceInput1->getInterfaceFormat().getMap();
} else {
m_mapInput1.clear();
for (size_t iii=0; iii<listChannelMap->size(); ++iii) {
std::string value = listChannelMap->getStringValue(iii);
m_mapInput1.push_back(audio::getChannelFromString(value));
}
if (m_mapInput1.size() != m_interfaceInput1->getInterfaceFormat().getMap().size()) {
RIVER_ERROR("Request remap of the Input 1 the 2 size is wrong ... request=");
m_mapInput1 = m_interfaceInput1->getInterfaceFormat().getMap();
}
}
RIVER_INFO("Create IN 2 : ");
m_interfaceInput2 = createInput(hardwareFormat.getFrequency(),
std::vector<audio::channel>(),
hardwareFormat.getFormat(),
"map-on-input-2",
_name + "-muxer-in2");
if (m_interfaceInput2 == nullptr) {
RIVER_ERROR("Can not opne virtual device ... map-on-input-2 in " << _name);
return;
}
listChannelMap = m_config->getArray("input-2-remap");
if ( listChannelMap == nullptr
|| listChannelMap->size() == 0) {
m_mapInput2 = m_interfaceInput2->getInterfaceFormat().getMap();
} else {
m_mapInput2.clear();
for (size_t iii=0; iii<listChannelMap->size(); ++iii) {
std::string value = listChannelMap->getStringValue(iii);
m_mapInput2.push_back(audio::getChannelFromString(value));
}
if (m_mapInput2.size() != m_interfaceInput2->getInterfaceFormat().getMap().size()) {
RIVER_ERROR("Request remap of the Input 2 the 2 size is wrong ... request=");
m_mapInput2 = m_interfaceInput2->getInterfaceFormat().getMap();
}
}
// set callback mode ...
m_interfaceInput1->setInputCallback(std11::bind(&audio::river::io::NodeMuxer::onDataReceivedInput1,
this,
std11::placeholders::_1,
std11::placeholders::_2,
std11::placeholders::_3,
std11::placeholders::_4,
std11::placeholders::_5,
std11::placeholders::_6));
// set callback mode ...
m_interfaceInput2->setInputCallback(std11::bind(&audio::river::io::NodeMuxer::onDataReceivedInput2,
this,
std11::placeholders::_1,
std11::placeholders::_2,
std11::placeholders::_3,
std11::placeholders::_4,
std11::placeholders::_5,
std11::placeholders::_6));
m_bufferInput1.setCapacity(std11::chrono::milliseconds(1000),
audio::getFormatBytes(hardwareFormat.getFormat())*m_mapInput1.size(),
hardwareFormat.getFrequency());
m_bufferInput2.setCapacity(std11::chrono::milliseconds(1000),
audio::getFormatBytes(hardwareFormat.getFormat())*m_mapInput2.size(),
hardwareFormat.getFrequency());
m_process.updateInterAlgo();
}
audio::river::io::NodeMuxer::~NodeMuxer() {
RIVER_INFO("close input stream");
stop();
m_interfaceInput1.reset();
m_interfaceInput2.reset();
};
void audio::river::io::NodeMuxer::start() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
if (m_interfaceInput1 != nullptr) {
RIVER_INFO("Start FEEDBACK : ");
m_interfaceInput1->start();
}
if (m_interfaceInput2 != nullptr) {
RIVER_INFO("Start Microphone : ");
m_interfaceInput2->start();
}
}
void audio::river::io::NodeMuxer::stop() {
std11::unique_lock<std11::mutex> lock(m_mutex);
if (m_interfaceInput1 != nullptr) {
m_interfaceInput1->stop();
}
if (m_interfaceInput2 != nullptr) {
m_interfaceInput2->stop();
}
}
void audio::river::io::NodeMuxer::onDataReceivedInput1(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map) {
RIVER_DEBUG("Microphone Time=" << _time << " _nbChunk=" << _nbChunk << " _map=" << _map << " _format=" << _format << " freq=" << _frequency);
RIVER_DEBUG(" next=" << _time + std11::chrono::nanoseconds(_nbChunk*1000000000LL/int64_t(_frequency)) );
if (_format != audio::format_int16) {
RIVER_ERROR("call wrong type ... (need int16_t)");
}
// push data synchronize
std11::unique_lock<std11::mutex> lock(m_mutex);
m_bufferInput1.write(_data, _nbChunk, _time);
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_Microphone.raw", _data, _nbChunk*_map.size());
process();
}
void audio::river::io::NodeMuxer::onDataReceivedInput2(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map) {
RIVER_DEBUG("FeedBack Time=" << _time << " _nbChunk=" << _nbChunk << " _map=" << _map << " _format=" << _format << " freq=" << _frequency);
RIVER_DEBUG(" next=" << _time + std11::chrono::nanoseconds(_nbChunk*1000000000LL/int64_t(_frequency)) );
if (_format != audio::format_int16) {
RIVER_ERROR("call wrong type ... (need int16_t)");
}
// push data synchronize
std11::unique_lock<std11::mutex> lock(m_mutex);
m_bufferInput2.write(_data, _nbChunk, _time);
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_FeedBack.raw", _data, _nbChunk*_map.size());
process();
}
void audio::river::io::NodeMuxer::process() {
if (m_bufferInput1.getSize() <= 256) {
return;
}
if (m_bufferInput2.getSize() <= 256) {
return;
}
std11::chrono::system_clock::time_point in1Time = m_bufferInput1.getReadTimeStamp();
std11::chrono::system_clock::time_point in2Time = m_bufferInput2.getReadTimeStamp();
std11::chrono::nanoseconds delta;
if (in1Time < in2Time) {
delta = in2Time - in1Time;
} else {
delta = in1Time - in2Time;
}
RIVER_INFO("check delta " << delta.count() << " > " << m_sampleTime.count());
if (delta > m_sampleTime) {
// Synchronize if possible
if (in1Time < in2Time) {
RIVER_INFO("in1Time < in2Time : Change Microphone time start " << in2Time);
RIVER_INFO(" old time stamp=" << m_bufferInput1.getReadTimeStamp());
m_bufferInput1.setReadPosition(in2Time);
RIVER_INFO(" new time stamp=" << m_bufferInput1.getReadTimeStamp());
}
if (in1Time > in2Time) {
RIVER_INFO("in1Time > in2Time : Change FeedBack time start " << in1Time);
RIVER_INFO(" old time stamp=" << m_bufferInput2.getReadTimeStamp());
m_bufferInput2.setReadPosition(in1Time);
RIVER_INFO(" new time stamp=" << m_bufferInput2.getReadTimeStamp());
}
}
// check if enought time after synchronisation ...
if (m_bufferInput1.getSize() <= 256) {
return;
}
if (m_bufferInput2.getSize() <= 256) {
return;
}
in1Time = m_bufferInput1.getReadTimeStamp();
in2Time = m_bufferInput2.getReadTimeStamp();
if (in1Time-in2Time > m_sampleTime) {
RIVER_ERROR("Can not synchronize flow ... : " << in1Time << " != " << in2Time << " delta = " << (in1Time-in2Time).count()/1000 << " µs");
return;
}
std::vector<uint8_t> dataIn1;
std::vector<uint8_t> dataIn2;
dataIn1.resize(256*sizeof(int16_t)*m_mapInput1.size(), 0);
dataIn2.resize(256*sizeof(int16_t)*m_mapInput2.size(), 0);
m_data.resize(256*sizeof(int16_t)*getInterfaceFormat().getMap().size(), 0);
while (true) {
in1Time = m_bufferInput1.getReadTimeStamp();
in2Time = m_bufferInput2.getReadTimeStamp();
//RIVER_INFO(" process 256 samples ... in1Time=" << in1Time << " in2Time=" << in2Time << " delta = " << (in1Time-in2Time).count());
m_bufferInput1.read(&dataIn1[0], 256);
m_bufferInput2.read(&dataIn2[0], 256);
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_INPUT1.raw", &dataIn1[0], 256 * m_mapInput1.size());
//RIVER_SAVE_FILE_MACRO(int16_t, "REC_INPUT2.raw", &dataIn2[0], 256 * m_mapInput2.size());
// if threaded : send event / otherwise, process ...
processMuxer(&dataIn1[0], &dataIn2[0], 256, in1Time);
if ( m_bufferInput1.getSize() <= 256
|| m_bufferInput2.getSize() <= 256) {
return;
}
}
}
void audio::river::io::NodeMuxer::reorder(void* _output, uint32_t _nbChunk, void* _input, const std::vector<audio::channel>& _mapInput) {
// real process: (only depend of data size):
switch (getInterfaceFormat().getFormat()) {
case audio::format_int8:
{
RIVER_VERBOSE("convert " << _mapInput << " ==> " << getInterfaceFormat().getMap());
int8_t* in = static_cast<int8_t*>(_input);
int8_t* out = static_cast<int8_t*>(_output);
for (size_t kkk=0; kkk<getInterfaceFormat().getMap().size(); ++kkk) {
int32_t convertId = -1;
if ( _mapInput.size() == 1
&& _mapInput[0] == audio::channel_frontCenter) {
convertId = 0;
} else {
for (size_t jjj=0; jjj<_mapInput.size(); ++jjj) {
if (getInterfaceFormat().getMap()[kkk] == _mapInput[jjj]) {
convertId = jjj;
break;
}
}
}
RIVER_VERBOSE(" " << convertId << " ==> " << kkk);
if (convertId != -1) {
for (size_t iii=0; iii<_nbChunk; ++iii) {
out[iii*getInterfaceFormat().getMap().size()+kkk] = in[iii*_mapInput.size()+convertId];
}
}
}
}
break;
default:
case audio::format_int16:
if (getInterfaceFormat().getMap().size() == 1) {
RIVER_VERBOSE("convert " << _mapInput << " ==> " << getInterfaceFormat().getMap());
int16_t* in = static_cast<int16_t*>(_input);
int16_t* out = static_cast<int16_t*>(_output);
for (size_t iii=0; iii<_nbChunk; ++iii) {
int32_t val = 0;
for (size_t jjj=0; jjj<_mapInput.size(); ++jjj) {
val += in[iii*_mapInput.size()+jjj];
}
out[iii] = val/_mapInput.size();
}
} else {
RIVER_VERBOSE("convert " << _mapInput << " ==> " << getInterfaceFormat().getMap());
int16_t* in = static_cast<int16_t*>(_input);
int16_t* out = static_cast<int16_t*>(_output);
for (size_t kkk=0; kkk<getInterfaceFormat().getMap().size(); ++kkk) {
int32_t convertId = -1;
if ( _mapInput.size() == 1
&& _mapInput[0] == audio::channel_frontCenter) {
convertId = 0;
} else {
for (size_t jjj=0; jjj<_mapInput.size(); ++jjj) {
if (getInterfaceFormat().getMap()[kkk] == _mapInput[jjj]) {
convertId = jjj;
break;
}
}
}
RIVER_VERBOSE(" " << convertId << " ==> " << kkk);
if (convertId != -1) {
for (size_t iii=0; iii<_nbChunk; ++iii) {
out[iii*getInterfaceFormat().getMap().size()+kkk] = in[iii*_mapInput.size()+convertId];
}
}
}
}
break;
case audio::format_int16_on_int32:
case audio::format_int24:
case audio::format_int32:
case audio::format_float:
{
RIVER_VERBOSE("convert (2) " << _mapInput << " ==> " << getInterfaceFormat().getMap());
uint32_t* in = static_cast<uint32_t*>(_input);
uint32_t* out = static_cast<uint32_t*>(_output);
for (size_t kkk=0; kkk<getInterfaceFormat().getMap().size(); ++kkk) {
int32_t convertId = -1;
if ( _mapInput.size() == 1
&& _mapInput[0] == audio::channel_frontCenter) {
convertId = 0;
} else {
for (size_t jjj=0; jjj<_mapInput.size(); ++jjj) {
if (getInterfaceFormat().getMap()[kkk] == _mapInput[jjj]) {
convertId = jjj;
break;
}
}
}
if (convertId != -1) {
for (size_t iii=0; iii<_nbChunk; ++iii) {
out[iii*getInterfaceFormat().getMap().size()+kkk] = in[iii*_mapInput.size()+convertId];
}
}
}
}
break;
case audio::format_double:
{
RIVER_VERBOSE("convert (2) " << _mapInput << " ==> " << getInterfaceFormat().getMap());
uint64_t* in = static_cast<uint64_t*>(_input);
uint64_t* out = static_cast<uint64_t*>(_output);
for (size_t kkk=0; kkk<getInterfaceFormat().getMap().size(); ++kkk) {
int32_t convertId = -1;
if ( _mapInput.size() == 1
&& _mapInput[0] == audio::channel_frontCenter) {
convertId = 0;
} else {
for (size_t jjj=0; jjj<_mapInput.size(); ++jjj) {
if (getInterfaceFormat().getMap()[kkk] == _mapInput[jjj]) {
convertId = jjj;
break;
}
}
}
if (convertId != -1) {
for (size_t iii=0; iii<_nbChunk; ++iii) {
out[iii*getInterfaceFormat().getMap().size()+kkk] = in[iii*_mapInput.size()+convertId];
}
}
}
}
break;
}
}
void audio::river::io::NodeMuxer::processMuxer(void* _dataIn1, void* _dataIn2, uint32_t _nbChunk, const std11::chrono::system_clock::time_point& _time) {
//RIVER_INFO("must Mux data : " << m_mapInput1 << " + " << m_mapInput2 << " ==> " << getInterfaceFormat().getMap());
memset(&m_data[0], 0, m_data.size());
reorder(&m_data[0], _nbChunk, _dataIn1, m_mapInput1);
reorder(&m_data[0], _nbChunk, _dataIn2, m_mapInput2);
newInput(&m_data[0], _nbChunk, _time);
}
void audio::river::io::NodeMuxer::generateDot(etk::FSNode& _node) {
_node << " subgraph clusterNode_" << m_uid << " {\n";
_node << " color=blue;\n";
_node << " label=\"[" << m_uid << "] IO::Node : " << m_name << "\";\n";
_node << " node [shape=box];\n";
// TODO : Create a structure ...
_node << " NODE_" << m_uid << "_HW_MUXER [ label=\"Muxer\\n channelMap=" << etk::to_string(getInterfaceFormat().getMap()) << "\" ];\n";
std::string nameIn;
std::string nameOut;
m_process.generateDot(_node, 3, m_uid, nameIn, nameOut, false);
_node << " node [shape=square];\n";
_node << " NODE_" << m_uid << "_demuxer [ label=\"DEMUXER\\n format=" << etk::to_string(m_process.getOutputConfig().getFormat()) << "\" ];\n";
// Link all nodes :
_node << " NODE_" << m_uid << "_HW_MUXER -> " << nameIn << ";\n";
_node << " " << nameOut << " -> NODE_" << m_uid << "_demuxer;\n";
_node << " }\n";
if (m_interfaceInput2 != nullptr) {
_node << " " << m_interfaceInput2->getDotNodeName() << " -> NODE_" << m_uid << "_HW_MUXER;\n";
}
if (m_interfaceInput1 != nullptr) {
_node << " " << m_interfaceInput1->getDotNodeName() << " -> NODE_" << m_uid << "_HW_MUXER;\n";
}
_node << " \n";
for (size_t iii=0; iii< m_listAvaillable.size(); ++iii) {
if (m_listAvaillable[iii].expired() == true) {
continue;
}
std11::shared_ptr<audio::river::Interface> element = m_listAvaillable[iii].lock();
if (element == nullptr) {
continue;
}
bool isLink = false;
for (size_t jjj=0; jjj<m_list.size(); ++jjj) {
if (element == m_list[jjj]) {
isLink = true;
}
}
if (element != nullptr) {
if (element->getMode() == modeInterface_input) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else if (element->getMode() == modeInterface_output) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_muxer", isLink);
} else if (element->getMode() == modeInterface_feedback) {
element->generateDot(_node, "NODE_" + etk::to_string(m_uid) + "_demuxer", isLink);
} else {
}
}
}
_node << "\n";
}

View File

@@ -0,0 +1,70 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_NODE_MUXER_H__
#define __AUDIO_RIVER_IO_NODE_MUXER_H__
#include <audio/river/io/Node.h>
#include <audio/river/Interface.h>
#include <audio/drain/CircularBuffer.h>
namespace audio {
namespace river {
namespace io {
class Manager;
class NodeMuxer : public Node {
protected:
/**
* @brief Constructor
*/
NodeMuxer(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
public:
static std11::shared_ptr<NodeMuxer> create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
/**
* @brief Destructor
*/
virtual ~NodeMuxer();
protected:
virtual void start();
virtual void stop();
std11::shared_ptr<audio::river::Interface> m_interfaceInput1;
std11::shared_ptr<audio::river::Interface> m_interfaceInput2;
std11::shared_ptr<audio::river::Interface> createInput(float _freq,
const std::vector<audio::channel>& _map,
audio::format _format,
const std::string& _streamName,
const std::string& _name);
void onDataReceivedInput1(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map);
void onDataReceivedInput2(const void* _data,
const std11::chrono::system_clock::time_point& _time,
size_t _nbChunk,
enum audio::format _format,
uint32_t _frequency,
const std::vector<audio::channel>& _map);
std::vector<audio::channel> m_mapInput1;
std::vector<audio::channel> m_mapInput2;
audio::drain::CircularBuffer m_bufferInput1;
audio::drain::CircularBuffer m_bufferInput2;
std11::chrono::nanoseconds m_sampleTime; //!< represent the sample time at the specify frequency.
void process();
void processMuxer(void* _dataMic, void* _dataFB, uint32_t _nbChunk, const std11::chrono::system_clock::time_point& _time);
std::vector<uint8_t> m_data;
public:
virtual void generateDot(etk::FSNode& _node);
private:
void reorder(void* _output, uint32_t _nbChunk, void* _input, const std::vector<audio::channel>& _mapInput);
};
}
}
}
#endif

View File

@@ -0,0 +1,271 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifdef AUDIO_RIVER_BUILD_ORCHESTRA
#include <audio/river/io/NodeOrchestra.h>
#include <audio/river/debug.h>
#include <etk/memory.h>
#undef __class__
#define __class__ "io::NodeOrchestra"
static std::string asString(const std11::chrono::system_clock::time_point& tp) {
// convert to system time:
std::time_t t = std11::chrono::system_clock::to_time_t(tp);
// convert in human string
std::string ts = std::ctime(&t);
// remove \n
ts.resize(ts.size()-1);
return ts;
}
int32_t audio::river::io::NodeOrchestra::recordCallback(const void* _inputBuffer,
const std11::chrono::system_clock::time_point& _timeInput,
uint32_t _nbChunk,
const std::vector<audio::orchestra::status>& _status) {
std11::unique_lock<std11::mutex> lock(m_mutex);
// TODO : Manage status ...
RIVER_VERBOSE("data Input size request :" << _nbChunk << " [BEGIN] status=" << _status << " nbIO=" << m_list.size());
newInput(_inputBuffer, _nbChunk, _timeInput);
return 0;
}
int32_t audio::river::io::NodeOrchestra::playbackCallback(void* _outputBuffer,
const std11::chrono::system_clock::time_point& _timeOutput,
uint32_t _nbChunk,
const std::vector<audio::orchestra::status>& _status) {
std11::unique_lock<std11::mutex> lock(m_mutex);
// TODO : Manage status ...
RIVER_VERBOSE("data Output size request :" << _nbChunk << " [BEGIN] status=" << _status << " nbIO=" << m_list.size());
newOutput(_outputBuffer, _nbChunk, _timeOutput);
return 0;
}
std11::shared_ptr<audio::river::io::NodeOrchestra> audio::river::io::NodeOrchestra::create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) {
return std11::shared_ptr<audio::river::io::NodeOrchestra>(new audio::river::io::NodeOrchestra(_name, _config));
}
audio::river::io::NodeOrchestra::NodeOrchestra(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) :
Node(_name, _config) {
audio::drain::IOFormatInterface interfaceFormat = getInterfaceFormat();
audio::drain::IOFormatInterface hardwareFormat = getHarwareFormat();
/**
map-on:{ # select hardware interface and name
interface:"alsa", # interface : "alsa", "pulse", "core", ...
name:"default", # name of the interface
},
nb-chunk:1024 # number of chunk to open device (create the latency anf the frequency to call user)
*/
enum audio::orchestra::type typeInterface = audio::orchestra::type_undefined;
std::string streamName = "default";
const std11::shared_ptr<const ejson::Object> tmpObject = m_config->getObject("map-on");
if (tmpObject == nullptr) {
RIVER_WARNING("missing node : 'map-on' ==> auto map : 'auto:default'");
} else {
std::string value = tmpObject->getStringValue("interface", "default");
typeInterface = audio::orchestra::getTypeFromString(value);
streamName = tmpObject->getStringValue("name", "default");
}
int32_t nbChunk = m_config->getNumberValue("nb-chunk", 1024);
// intanciate specific API ...
m_adac.instanciate(typeInterface);
m_adac.setName(_name);
// TODO : Check return ...
std::string type = m_config->getStringValue("type", "int16");
if (streamName == "") {
streamName = "default";
}
// search device ID :
RIVER_INFO("Open :");
RIVER_INFO(" m_streamName=" << streamName);
RIVER_INFO(" m_freq=" << hardwareFormat.getFrequency());
RIVER_INFO(" m_map=" << hardwareFormat.getMap());
RIVER_INFO(" m_format=" << hardwareFormat.getFormat());
RIVER_INFO(" m_isInput=" << m_isInput);
int32_t deviceId = -1;
// TODO : Remove this from here (create an extern interface ...)
RIVER_INFO("Device list:");
for (int32_t iii=0; iii<m_adac.getDeviceCount(); ++iii) {
m_info = m_adac.getDeviceInfo(iii);
RIVER_INFO(" " << iii << " name :" << m_info.name);
m_info.display(2);
}
// special case for default IO:
if (streamName == "default") {
if (m_isInput == true) {
deviceId = m_adac.getDefaultInputDevice();
} else {
deviceId = m_adac.getDefaultOutputDevice();
}
} else {
for (int32_t iii=0; iii<m_adac.getDeviceCount(); ++iii) {
m_info = m_adac.getDeviceInfo(iii);
if (m_info.name == streamName) {
RIVER_INFO(" Select ... id =" << iii);
deviceId = iii;
}
}
}
// TODO : Check if the devace with the specific name exist ...
/*
if (deviceId == -1) {
RIVER_ERROR("Can not find the " << streamName << " audio interface ... (use O default ...)");
deviceId = 0;
}
*/
// Open specific ID :
if (deviceId == -1) {
m_info = m_adac.getDeviceInfo(streamName);
} else {
m_info = m_adac.getDeviceInfo(deviceId);
}
// display property :
{
RIVER_INFO("Device " << deviceId << " - '" << streamName << "' property :");
m_info.display();
if (etk::isIn(hardwareFormat.getFormat(), m_info.nativeFormats) == false) {
if (type == "auto") {
if (etk::isIn(audio::format_int16, m_info.nativeFormats) == true) {
hardwareFormat.setFormat(audio::format_int16);
RIVER_INFO("auto set format: " << hardwareFormat.getFormat());
} else if (etk::isIn(audio::format_float, m_info.nativeFormats) == true) {
hardwareFormat.setFormat(audio::format_float);
RIVER_INFO("auto set format: " << hardwareFormat.getFormat());
} else if (etk::isIn(audio::format_int16_on_int32, m_info.nativeFormats) == true) {
hardwareFormat.setFormat(audio::format_int16_on_int32);
RIVER_INFO("auto set format: " << hardwareFormat.getFormat());
} else if (etk::isIn(audio::format_int24, m_info.nativeFormats) == true) {
hardwareFormat.setFormat(audio::format_int24);
RIVER_INFO("auto set format: " << hardwareFormat.getFormat());
} else if (m_info.nativeFormats.size() != 0) {
hardwareFormat.setFormat(m_info.nativeFormats[0]);
RIVER_INFO("auto set format: " << hardwareFormat.getFormat());
} else {
RIVER_CRITICAL("auto set format no element in the configuration: " << m_info.nativeFormats);
}
} else {
RIVER_CRITICAL("Can not manage input transforamtion: " << hardwareFormat.getFormat() << " not in " << m_info.nativeFormats);
}
}
if (etk::isIn(hardwareFormat.getFrequency(), m_info.sampleRates) == false) {
if (etk::isIn(48000, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(48000);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (etk::isIn(44100, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(44100);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (etk::isIn(32000, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(32000);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (etk::isIn(16000, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(16000);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (etk::isIn(8000, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(8000);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (etk::isIn(96000, m_info.sampleRates) == true) {
hardwareFormat.setFrequency(96000);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency());
} else if (m_info.sampleRates.size() != 0) {
hardwareFormat.setFrequency(m_info.sampleRates[0]);
RIVER_INFO("auto set frequency: " << hardwareFormat.getFrequency() << "(first element in list) in " << m_info.sampleRates);
} else {
RIVER_CRITICAL("Can not manage input transforamtion:" << hardwareFormat.getFrequency() << " not in " << m_info.sampleRates);
}
interfaceFormat.setFrequency(hardwareFormat.getFrequency());
}
}
// open Audio device:
audio::orchestra::StreamParameters params;
params.deviceId = deviceId;
params.deviceName = streamName;
params.nChannels = hardwareFormat.getMap().size();
if (m_isInput == true) {
if (m_info.inputChannels < params.nChannels) {
RIVER_CRITICAL("Can not open hardware device with more channel (" << params.nChannels << ") that is autorized by hardware (" << m_info.inputChannels << ").");
}
} else {
if (m_info.outputChannels < params.nChannels) {
RIVER_CRITICAL("Can not open hardware device with more channel (" << params.nChannels << ") that is autorized by hardware (" << m_info.inputChannels << ").");
}
}
audio::orchestra::StreamOptions option;
etk::from_string(option.mode, tmpObject->getStringValue("timestamp-mode", "soft"));
RIVER_DEBUG("interfaceFormat=" << interfaceFormat);
RIVER_DEBUG("hardwareFormat=" << hardwareFormat);
m_rtaudioFrameSize = nbChunk;
RIVER_INFO("Open output stream nbChannels=" << params.nChannels);
enum audio::orchestra::error err = audio::orchestra::error_none;
if (m_isInput == true) {
m_process.setInputConfig(hardwareFormat);
m_process.setOutputConfig(interfaceFormat);
err = m_adac.openStream(nullptr, &params,
hardwareFormat.getFormat(), hardwareFormat.getFrequency(), &m_rtaudioFrameSize,
std11::bind(&audio::river::io::NodeOrchestra::recordCallback,
this,
std11::placeholders::_1,
std11::placeholders::_2,
std11::placeholders::_5,
std11::placeholders::_6),
option
);
} else {
m_process.setInputConfig(interfaceFormat);
m_process.setOutputConfig(hardwareFormat);
err = m_adac.openStream(&params, nullptr,
hardwareFormat.getFormat(), hardwareFormat.getFrequency(), &m_rtaudioFrameSize,
std11::bind(&audio::river::io::NodeOrchestra::playbackCallback,
this,
std11::placeholders::_3,
std11::placeholders::_4,
std11::placeholders::_5,
std11::placeholders::_6),
option
);
}
if (err != audio::orchestra::error_none) {
RIVER_ERROR("Create stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not create stream " << err);
}
m_process.updateInterAlgo();
}
audio::river::io::NodeOrchestra::~NodeOrchestra() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("close input stream");
if (m_adac.isStreamOpen() ) {
m_adac.closeStream();
}
};
void audio::river::io::NodeOrchestra::start() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
enum audio::orchestra::error err = m_adac.startStream();
if (err != audio::orchestra::error_none) {
RIVER_ERROR("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not start stream ... " << err);
}
}
void audio::river::io::NodeOrchestra::stop() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Stop stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
enum audio::orchestra::error err = m_adac.stopStream();
if (err != audio::orchestra::error_none) {
RIVER_ERROR("Stop stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not stop stream ... " << err);
}
}
#endif

View File

@@ -0,0 +1,78 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_NODE_AIRTAUDIO_H__
#define __AUDIO_RIVER_IO_NODE_AIRTAUDIO_H__
#ifdef AUDIO_RIVER_BUILD_ORCHESTRA
#include <audio/river/io/Node.h>
#include <audio/orchestra/Interface.h>
namespace audio {
namespace river {
namespace io {
class Manager;
class Group;
/**
* @brief Low level node that is manage on the interface with the extern lib airtaudio
*/
class NodeOrchestra : public audio::river::io::Node {
friend class audio::river::io::Group;
protected:
/**
* @brief Constructor
*/
NodeOrchestra(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
public:
static std11::shared_ptr<NodeOrchestra> create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
/**
* @brief Destructor
*/
virtual ~NodeOrchestra();
virtual bool isHarwareNode() {
return true;
};
protected:
audio::orchestra::Interface m_adac; //!< Real airtaudio interface
audio::orchestra::DeviceInfo m_info; //!< information on the stream.
unsigned int m_rtaudioFrameSize; // DEPRECATED soon...
public:
/**
* @brief Input Callback . Have recaive new data to process.
* @param[in] _inputBuffer Pointer on the data buffer.
* @param[in] _timeInput Time on the fist sample has been recorded.
* @param[in] _nbChunk Number of chunk in the buffer
* @param[in] _status DEPRECATED soon
* @return DEPRECATED soon
*/
int32_t recordCallback(const void* _inputBuffer,
const std11::chrono::system_clock::time_point& _timeInput,
uint32_t _nbChunk,
const std::vector<audio::orchestra::status>& _status);
/**
* @brief Playback callback. Request new data on output
* @param[in,out] _outputBuffer Pointer on the buffer to fill data.
* @param[in] _timeOutput Time on wich the data might be played.
* @param[in] _nbChunk Number of chunk in the buffer
* @param[in] _status DEPRECATED soon
* @return DEPRECATED soon
*/
int32_t playbackCallback(void* _outputBuffer,
const std11::chrono::system_clock::time_point& _timeOutput,
uint32_t _nbChunk,
const std::vector<audio::orchestra::status>& _status);
protected:
virtual void start();
virtual void stop();
};
}
}
}
#endif
#endif

View File

@@ -0,0 +1,147 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifdef AUDIO_RIVER_BUILD_PORTAUDIO
#include <audio/river/io/NodePortAudio.h>
#include <audio/river/debug.h>
#include <etk/memory.h>
#undef __class__
#define __class__ "io::NodePortAudio"
static std::string asString(const std11::chrono::system_clock::time_point& tp) {
// convert to system time:
std::time_t t = std11::chrono::system_clock::to_time_t(tp);
// convert in human string
std::string ts = std::ctime(&t);
// remove \n
ts.resize(ts.size()-1);
return ts;
}
static int portAudioStreamCallback(const void *_input,
void *_output,
unsigned long _frameCount,
const PaStreamCallbackTimeInfo* _timeInfo,
PaStreamCallbackFlags _statusFlags,
void *_userData) {
audio::river::io::NodePortAudio* myClass = reinterpret_cast<audio::river::io::NodePortAudio*>(_userData);
int64_t sec = int64_t(_timeInfo->inputBufferAdcTime);
int64_t nsec = (_timeInfo->inputBufferAdcTime-double(sec))*1000000000LL;
std11::chrono::system_clock::time_point timeInput = std11::chrono::system_clock::from_time_t(sec) + std11::chrono::nanoseconds(nsec);
sec = int64_t(_timeInfo->outputBufferDacTime);
nsec = (_timeInfo->outputBufferDacTime-double(sec))*1000000000LL;
std11::chrono::system_clock::time_point timeOutput = std11::chrono::system_clock::from_time_t(sec) + std11::chrono::nanoseconds(nsec);
return myClass->duplexCallback(_input,
timeInput,
_output,
timeOutput,
_frameCount,
_statusFlags);
}
int32_t audio::river::io::NodePortAudio::duplexCallback(const void* _inputBuffer,
const std11::chrono::system_clock::time_point& _timeInput,
void* _outputBuffer,
const std11::chrono::system_clock::time_point& _timeOutput,
uint32_t _nbChunk,
PaStreamCallbackFlags _status) {
std11::unique_lock<std11::mutex> lock(m_mutex);
// TODO : Manage status ...
if (_inputBuffer != nullptr) {
RIVER_VERBOSE("data Input size request :" << _nbChunk << " [BEGIN] status=" << _status << " nbIO=" << m_list.size());
newInput(_inputBuffer, _nbChunk, _timeInput);
}
if (_outputBuffer != nullptr) {
RIVER_VERBOSE("data Output size request :" << _nbChunk << " [BEGIN] status=" << _status << " nbIO=" << m_list.size());
newOutput(_outputBuffer, _nbChunk, _timeOutput);
}
return 0;
}
std11::shared_ptr<audio::river::io::NodePortAudio> audio::river::io::NodePortAudio::create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) {
return std11::shared_ptr<audio::river::io::NodePortAudio>(new audio::river::io::NodePortAudio(_name, _config));
}
audio::river::io::NodePortAudio::NodePortAudio(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config) :
Node(_name, _config) {
audio::drain::IOFormatInterface interfaceFormat = getInterfaceFormat();
audio::drain::IOFormatInterface hardwareFormat = getHarwareFormat();
/**
map-on:{ # select hardware interface and name
interface:"alsa", # interface : "alsa", "pulse", "core", ...
name:"default", # name of the interface
},
nb-chunk:1024 # number of chunk to open device (create the latency anf the frequency to call user)
*/
enum audio::orchestra::type typeInterface = audio::orchestra::type_undefined;
std::string streamName = "default";
const std11::shared_ptr<const ejson::Object> tmpObject = m_config->getObject("map-on");
if (tmpObject == nullptr) {
RIVER_WARNING("missing node : 'map-on' ==> auto map : 'auto:default'");
} else {
std::string value = tmpObject->getStringValue("interface", "default");
typeInterface = audio::orchestra::getTypeFromString(value);
streamName = tmpObject->getStringValue("name", "default");
}
int32_t nbChunk = m_config->getNumberValue("nb-chunk", 1024);
PaError err = 0;
if (m_isInput == true) {
err = Pa_OpenDefaultStream(&m_stream,
hardwareFormat.getMap().size(),
0,
paInt16,
hardwareFormat.getFrequency(),
nbChunk,
&portAudioStreamCallback,
this);
} else {
err = Pa_OpenDefaultStream(&m_stream,
0,
hardwareFormat.getMap().size(),
paInt16,
hardwareFormat.getFrequency(),
nbChunk,
&portAudioStreamCallback,
this);
}
if( err != paNoError ) {
RIVER_ERROR("Can not create Stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " err : " << Pa_GetErrorText(err));
}
m_process.updateInterAlgo();
}
audio::river::io::NodePortAudio::~NodePortAudio() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("close input stream");
PaError err = Pa_CloseStream( m_stream );
if( err != paNoError ) {
RIVER_ERROR("Remove stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not Remove stream ... " << Pa_GetErrorText(err));
}
};
void audio::river::io::NodePortAudio::start() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
PaError err = Pa_StartStream(m_stream);
if( err != paNoError ) {
RIVER_ERROR("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not start stream ... " << Pa_GetErrorText(err));
}
}
void audio::river::io::NodePortAudio::stop() {
std11::unique_lock<std11::mutex> lock(m_mutex);
RIVER_INFO("Stop stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") );
PaError err = Pa_StopStream(m_stream);
if( err != paNoError ) {
RIVER_ERROR("Start stream : '" << m_name << "' mode=" << (m_isInput?"input":"output") << " can not stop stream ... " << Pa_GetErrorText(err));
}
}
#endif

View File

@@ -0,0 +1,55 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_IO_NODE_PORTAUDIO_H__
#define __AUDIO_RIVER_IO_NODE_PORTAUDIO_H__
#ifdef AUDIO_RIVER_BUILD_PORTAUDIO
#include <audio/river/Interface.h>
#include <audio/river/io/Node.h>
#include <portaudio.h>
namespace audio {
namespace river {
namespace io {
class Manager;
//! @not-in-doc
class NodePortAudio : public Node {
protected:
/**
* @brief Constructor
*/
NodePortAudio(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
public:
static std11::shared_ptr<NodePortAudio> create(const std::string& _name, const std11::shared_ptr<const ejson::Object>& _config);
/**
* @brief Destructor
*/
virtual ~NodePortAudio();
virtual bool isHarwareNode() {
return true;
};
protected:
PaStream* m_stream;
public:
int32_t duplexCallback(const void* _inputBuffer,
const std11::chrono::system_clock::time_point& _timeInput,
void* _outputBuffer,
const std11::chrono::system_clock::time_point& _timeOutput,
uint32_t _nbChunk,
PaStreamCallbackFlags _status);
protected:
virtual void start();
virtual void stop();
};
}
}
}
#endif
#endif

59
audio/river/river.cpp Normal file
View File

@@ -0,0 +1,59 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <audio/river/river.h>
#include <audio/river/debug.h>
#include <audio/river/io/Manager.h>
static bool river_isInit = false;
static std::string river_configFile = "";
void audio::river::init(const std::string& _filename) {
if (river_isInit == false) {
river_isInit = true;
river_configFile = _filename;
RIVER_DEBUG("init RIVER :" << river_configFile);
std11::shared_ptr<audio::river::io::Manager> mng = audio::river::io::Manager::getInstance();
if (mng != nullptr) {
mng->init(river_configFile);
}
} else {
RIVER_ERROR("River is already init not use : " << _filename);
}
}
void audio::river::initString(const std::string& _config) {
if (river_isInit == false) {
river_isInit = true;
river_configFile = _config;
RIVER_DEBUG("init RIVER with config.");
std11::shared_ptr<audio::river::io::Manager> mng = audio::river::io::Manager::getInstance();
if (mng != nullptr) {
mng->initString(river_configFile);
}
} else {
RIVER_ERROR("River is already init not use Data ...");
}
}
void audio::river::unInit() {
if (river_isInit == true) {
river_isInit = false;
RIVER_DEBUG("un-init RIVER.");
std11::shared_ptr<audio::river::io::Manager> mng = audio::river::io::Manager::getInstance();
if (mng != nullptr) {
RIVER_ERROR("Can not get on the RIVER hardware manager !!!");
mng->unInit();
}
}
}
bool audio::river::isInit() {
return river_isInit;
}

40
audio/river/river.h Normal file
View File

@@ -0,0 +1,40 @@
/** @file
* @author Edouard DUPIN
* @copyright 2015, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#ifndef __AUDIO_RIVER_H__
#define __AUDIO_RIVER_H__
#include <etk/types.h>
namespace audio {
namespace river {
/**
* @brief Initialize the River Library
* @param[in] _filename Name of the configuration file (if "" ==> default config file)
*/
void init(const std::string& _filename);
/**
* @brief Initialize the River Library with a json data string
* @param[in] _config json sting data
*/
void initString(const std::string& _config);
/**
* @brief Un-initialize the River Library
* @note this close all stream of all interfaces.
* @note really good for test.
*/
void unInit();
/**
* @brief Get the status of initialisation
* @return true River is init
* @return false River is NOT init
*/
bool isInit();
}
}
#endif