Initial commit

This commit is contained in:
santi 2014-06-29 15:35:39 +02:00
commit 45115830c0
30 changed files with 2923 additions and 0 deletions

26
src/audiolayerwidget.cpp Normal file
View file

@ -0,0 +1,26 @@
#include "audiolayerwidget.h"
AudioLayerWidget::AudioLayerWidget(QWidget *parent, QString name):
QGroupBox(parent)
{
folder = new QLabel(this);
file = new QLabel(this);
status = new QLabel(this);
vol = new QSlider(this);
vol->setMaximum(99);
mute = new QCheckBox(this);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(folder);
vbox->addWidget(file);
vbox->addWidget(status);
vbox->addWidget(vol);
vbox->addWidget(mute);
this->setLayout(vbox);
}
AudioLayerWidget::~AudioLayerWidget()
{
}

45
src/audiolayerwidget.h Normal file
View file

@ -0,0 +1,45 @@
#ifndef AUDIOLAYERWIDGET_H
#define AUDIOLAYERWIDGET_H
#include <QtGui>
//#include "ui_audiolayerwidget.h"
/*
namespace Ui {
class AudioLayerWidget;
}*/
class AudioLayerWidget : public QGroupBox
{
Q_OBJECT
public:
AudioLayerWidget(QWidget *parent, QString name);
~AudioLayerWidget();
inline void setFile(QString file) const
{
this->file->setText(file);
}
inline void setFolder(QString folder) const
{
this->folder->setText(folder);
}
inline void setVol(float vol) const
{
this->vol->setValue(vol);
}
private:
QLabel *file;
QLabel *folder;
QSlider *vol;
QCheckBox *mute;
QLabel *status;
};
#endif // AUDIOLAYERWIDGET_H

20
src/audiomasterwidget.cpp Normal file
View file

@ -0,0 +1,20 @@
#include "audiomasterwidget.h"
AudioMasterWidget::AudioMasterWidget(QWidget *parent) :
QGroupBox(parent)
{
status = new QLabel(this);
vol = new QSlider(this);
mute = new QCheckBox(this);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(status);
vbox->addWidget(vol);
vbox->addWidget(mute);
this->setLayout(vbox);
}
AudioMasterWidget::~AudioMasterWidget()
{
}

33
src/audiomasterwidget.h Normal file
View file

@ -0,0 +1,33 @@
#ifndef AUDIOMASTERWIDGET_H
#define AUDIOMASTERWIDGET_H
#include <QLabel>
#include <QtGui>
//#include "ui_audiomasterwidget.h"
/*
namespace Ui {
class AudioMasterWidget;
}*/
class AudioMasterWidget : public QGroupBox //, public Ui::AudioMasterWidget
{
Q_OBJECT
public:
AudioMasterWidget(QWidget *parent);
~AudioMasterWidget();
private:
QLabel *file;
QLabel *folder;
QSlider *vol;
QCheckBox *mute;
QLabel *status;
};
#endif // AUDIOMASTERWIDGET_H

380
src/audiomotor.cpp Normal file
View file

@ -0,0 +1,380 @@
#include "audiomotor.h"
#define PAUSE 2
#define PLAY 0
#define STOP 1
#define MAX_DATA = 1024;
AudioMotor *AudioMotor::_instance = 0;
AudioMotor *AudioMotor::getInstance() {
if (_instance == 0) {
_instance = new AudioMotor();
Q_CHECK_PTR(_instance);
}
return _instance;
}
AudioMotor::AudioMotor(QObject *parent) :
QObject(parent),
m_startaudio(0),
m_writePD(NULL),
m_readPD(NULL),
m_pd_audio(NULL),
m_connectedSocket(NULL),
m_gui(true)
{
qsrand(qrand());
qDebug() << "Init MotorAudio";
}
AudioMotor::~AudioMotor()
{
close();
}
/** Init the engine
*/
bool AudioMotor::init()
{
/* Sets the socket an connections for the comunication with PD
QFile socket(SOCKET);
if (socket.exists())
{
socket.remove();
}*/
// Socket para mandar órdenes a Pure Data
m_writePD = new QTcpSocket(this);
Q_CHECK_PTR(m_writePD);
connect(m_writePD, SIGNAL(connected()),this, SLOT(newConexion()));
connect(m_writePD, SIGNAL(error(QAbstractSocket::SocketError)) , this, SLOT(errorWrite(QAbstractSocket::SocketError)));
// Servidor para recibir feedback de Pure Data
m_readPD = new QTcpServer(this);
Q_CHECK_PTR(m_readPD);
connect(m_readPD, SIGNAL(newConnection()),this, SLOT(newPeer()));
if (m_readPD->listen(QHostAddress::LocalHost, PDPORT)) {
qDebug(QString("AudioMotor| Listening to PD on TCP port %1").arg(PDPORT).toLatin1());
} else {
qErrnoWarning(QString("AudioMotor::init() can not init TCP Server on port %1").arg(PDPORT).toLatin1());
}
// Start the pd process an set up PD
m_pd_audio = new QProcess(this);
connect(m_pd_audio, SIGNAL(readyReadStandardError()), this, SLOT(stdout()));
connect(m_pd_audio, SIGNAL(finished(int)), this, SLOT(restartAudio()));
QString arguments;
// arguments.append("./puredata/pd -alsa -channels 2 -audiodev 1 -stderr -nostdpath -path ./puredata/externals/ -open ./puredata/lms-audio.pd ");
arguments.append("./puredata/pd -channels 2 -stderr -nostdpath -path ./puredata/externals/ -open ./puredata/lms-audio.pd ");
if (!m_gui)
arguments.append("-nogui");
qDebug() << "PD starts with arguments: " << arguments;
m_pd_audio->start(arguments);
if (m_pd_audio->waitForStarted(3000)){
qDebug("AudioMotor| PD started.");
}
else
{
qWarning("AudioMotor| PD not started!");
qErrnoWarning("AudioMotor| Can not init PD");
return false;
}
m_startaudio++;
return true;
}
/** Close the engine
*/
bool AudioMotor::close()
{
disconnect(m_pd_audio, SIGNAL(readyReadStandardError()), this, SLOT(stdout()));
disconnect(m_pd_audio, SIGNAL(finished(int)), this, SLOT(restartAudio()));
m_pd_audio->terminate();
m_pd_audio->waitForFinished(1000);
delete m_pd_audio;
m_pd_audio = NULL;
if (m_writePD != NULL)
{
disconnect(m_writePD, SIGNAL(connected()),this, SLOT(newConexion()));
m_writePD->close();
delete m_writePD;
m_writePD = NULL;
}
if (m_readPD != NULL)
{
disconnect(m_readPD, SIGNAL(newConnection()),this, SLOT(newPeer()));
m_readPD->close();
delete m_readPD;
m_readPD = NULL;
}
/*
QFile socket(SOCKET);
if (socket.exists())
{
socket.remove();
}*/
}
/** Set the numbers of layers
*/
void AudioMotor::setLayers (int layers){
}
/** Get the number of layers
*/
int AudioMotor::getlayers(){
}
/** Load a file in memory
*
*/
bool AudioMotor::load(int layer, QString file)
{
if (!QFile::exists(file))
return false;
QString message = tr("%1 ").arg(layer +201);
message.append("open ");
message.append(file);
message.append(";");
qDebug() << "AudioMotor::load " << message;
if (QAbstractSocket::ConnectedState != m_writePD->state())
{
qErrnoWarning("AudioMotor::load(): Socket not conected: ");
return false;
}
if (message.size() != m_writePD->write(message.toAscii().constData(), message.size()))
{
qErrnoWarning("AudioMotor::load(): Can not write to socket");
return false;
}
return true;
}
/** Starts the playback at start position
*
*/
bool AudioMotor::play(int layer)
{
QString buffer = tr("%1 %2 %3;").arg(layer).arg(PLAYBACK).arg(PLAY);
if (!sendPacket(buffer.toAscii().constData(), buffer.size()))
{
errorSending();
return false;
}
return true;
}
/** Unpause the playback
*/
bool AudioMotor::pause(int layer)
{
QString buffer = tr("%1 %2 %3;").arg(layer).arg(PLAYBACK).arg(PAUSE);
if (!sendPacket(buffer.toAscii().constData(), buffer.size()))
{
errorSending();
return false;
}
return true;
}
/** Stops/pause the playback
*
*/
bool AudioMotor::stop(int layer)
{
QString buffer = tr("%1 %2 %3;").arg(layer).arg(PLAYBACK).arg(STOP);
if (!sendPacket(buffer.toAscii().constData(), buffer.size()))
{
errorSending();
return false;
}
return true;
}
/** Sets the start playback position
*
*/
void AudioMotor::setEntryPoint(int layer, int entry)
{
}
/** Sets the final playback position
*
*/
void AudioMotor::setExitPoint(int layer, int exit)
{
}
/** Set the volumen in one layer
* @param int vol Normalized 0 to 1
@param int layer the layer which applied
*/
void AudioMotor::setLayerVolume(int layer, float vol)
{
QString buffer = tr("%1 %2 %3;").arg(layer).arg(VOLUME_COARSE).arg(vol);
if (!sendPacket(buffer.toAscii().constData(), buffer.size()))
{
errorSending();
}
}
/** Set pan in one layer
*
* @param int vol Normalized 0 (Left) to 1 (Right)
@param int layer the layer which applied
*/
void AudioMotor::setLayerPan(int layer, float pan)
{
QString buffer = tr("%1 %2 %3;").arg(layer).arg(PAN).arg(pan);
if (!sendPacket(buffer.toAscii().constData(), buffer.size()))
{
errorSending();
}
}
/** Set Volumen master.
* All layers are limited by this master
* 0 will mute all the outputs
*/
void AudioMotor::setMasterVolume(int vol){
}
/** Set pan master
* Will pan the master output of sound
*/
void AudioMotor::setMasterPan(int pan){
}
/** Restart the audio process
*
*/
void AudioMotor::restartAudio()
{
close();
init();
}
/** New conexion on TCP Server
*
*/
void AudioMotor::newPeer()
{
m_connectedSocket = m_readPD->nextPendingConnection();
connect(m_connectedSocket, SIGNAL(readyRead()),this, SLOT(newMessage()));
}
/** New message in a TCP socket stablished connection
*
*/
void AudioMotor::newMessage()
{
if (m_connectedSocket == NULL)
{
qDebug()<<("AudioMotor::newMessage() Socket not connected. Trying open it...");
newPeer();
return;
}
QString message = m_connectedSocket->readAll();
parse(message);
}
void AudioMotor::parse(QString message)
{
int aux;
QStringList list = message.split("\n", QString::SkipEmptyParts);
for (int i = 0; i < list.size(); i ++) {
if (list.at(i).size() > 0) {
qDebug() << "AudioMotor::newMessage() message received: " << list.at(i);
QChar val = list.at(i).at(0);
switch (val.digitValue()) {
case 0:
qDebug() << "AudioMotor::newMessage() Loadbang from PD Audio received...";
// Conectamos a Pure Data para escribir
m_writePD->connectToHost(QHostAddress::LocalHost, SOCKET, QIODevice::WriteOnly);
if (m_writePD->waitForConnected(30000))
emit loadbang();
break;
case 9:
if (list.at(i).at(2).digitValue() == 0)
emit (volChanged(list.at(i).at(4).digitValue(), ( ( list.at(i).at(6).digitValue() * 10 ) + list.at(i).at(7).digitValue() ) ) );
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
QStringList folders = list.at(i).split("/", QString::SkipEmptyParts);
if (folders.size() >= 2)
emit (mediaLoaded(val.digitValue(), folders.at(folders.size() -2), folders.at(folders.size() -1)));
break;
}
}
}
}
/** Error writing to PD
*
*/
void AudioMotor::errorWrite(QAbstractSocket::SocketError error)
{
// QString error = m_writePD->errorString();
qErrnoWarning(QString("AudioMotor::errorWrite() %1").arg(error).toLatin1());
}
/** Sends packets to Pure Data audio
*
*/
bool AudioMotor::sendPacket(const char *buffer, int bufferLen)
{
if (m_writePD == NULL) {
return false;
}
if (QAbstractSocket::ConnectedState != m_writePD->state())
{
return false;
}
if (bufferLen != m_writePD->write((const char*)buffer, bufferLen))
{
return false;
}
return true;
}
// Function error sending packets to PD audio
void AudioMotor::errorSending() {
qDebug() << "AudioMotor| Can not send packets to PD";
}

142
src/audiomotor.h Normal file
View file

@ -0,0 +1,142 @@
#ifndef AUDIOMOTOR_H
#define AUDIOMOTOR_H
#include <QObject>
#include <QtDebug>
#include <QtNetwork>
#include <QTcpServer>
#include <QLocalSocket>
#include <QTcpSocket>
#include <QChar>
#include "dmxPersonality.h"
#define PDPORT 9198
#define SOCKET 9197 // "/tmp/socket"
class AudioMotor : public QObject
{
Q_OBJECT
public:
static AudioMotor *getInstance();
/** Init the engine
*/
bool init();
/** Close the engine
*/
bool close();
/** Set the numbers of layers
*/
void setLayers (int layers);
/** Get the number of layers
*/
int getlayers();
/** Load a file in memory
*
*/
bool load(int layer, QString file);
/** Starts the playback at start position
*
*/
bool play(int layer);
/** Pause/unpause the playback
*/
bool pause(int layer);
/** Stops the playback and reset the media to the start position
*
*/
bool stop(int layer);
/** Sets the start playback position
*
*/
void setEntryPoint(int layer, int entry);
/** Sets the final playback position
*
*/
void setExitPoint(int layer, int exit);
/** Set the volumen in one layer
*
*/
void setLayerVolume(int layer, float vol);
/** Set pan in one layer
*/
void setLayerPan(int layer, float pan);
/** Set Volumen master.
* All layers are limited by this master
* 0 will mute all the outputs
*/
void setMasterVolume(int vol);
/** Set pan master
* Will pan the master output of sound
*/
void setMasterPan(int pan);
inline void setGui(bool gui) { m_gui = gui; }
private:
AudioMotor(QObject *parent = 0);
virtual ~AudioMotor();
static AudioMotor *_instance;
bool m_gui;
int m_layersNumber;
QProcess *m_pd_audio; // Pure Data process for audio
// Audio TCP Sockets
QTcpSocket *m_writePD;
QTcpServer *m_readPD;
QTcpSocket *m_connectedSocket; // connected socket to server
int m_startaudio; // Counter starts audio engine. Debugging purpose
bool sendPacket(const char *buffer, int bufferLen);
void errorSending();
void parse(QString message);
signals:
void loadbang();
void newConnection();
void mediaLoaded(int layer, QString folder, QString file);
void volChanged(int layer, int vol);
private slots:
void newPeer();
inline void newConexion() { qDebug() << "AudioMotor write socket connected to PD"; }
void restartAudio();
void newMessage();
void errorWrite(QAbstractSocket::SocketError error);
/**
*
* Listen the terminal exit of PD
*
*/
// Sacamos la salida de Pure Data Audio en la terminal
inline void stdout() {
QString out = m_pd_audio->readAllStandardError();
out.chop(1);
if (!out.isEmpty())
{
qDebug() << "AudioMotor from PD: " << out;
}
}
};
#endif // AUDIOMOTOR_H

31
src/audiowidget.cpp Normal file
View file

@ -0,0 +1,31 @@
#include "audiowidget.h"
AudioWidget::AudioWidget(QWidget *parent) :
QWidget(parent)
{
layout = new QHBoxLayout();
for (int i= 0; i < LAYERS_NUMBER; i++ ) {
// Conectar los slots
layout->insertWidget(i, new AudioLayerWidget(this, tr("Layer %1").arg(i)));
}
setLayout(layout);
qDebug( "Init AudioWidget");
}
void AudioWidget::mediaLoaded(int layer, QString folder, QString file)
{
QLayoutItem * const item = layout->itemAt(layer - 1);
qDebug() << "AudioWidget::mediaLoaded Received layer: " << layer
<< "Folder: " << folder
<<"File : " << file;
dynamic_cast<AudioLayerWidget *>(item->widget())->setFolder(folder);
dynamic_cast<AudioLayerWidget *>(item->widget())->setFile(file);
}
void AudioWidget::volChanged(int layer, int vol) {
QLayoutItem * const item = layout->itemAt(layer - 1);
qDebug() << "AudioWidget::volChanged Received layer: " << layer
<< "Vol : " << vol;
dynamic_cast<AudioLayerWidget *>(item->widget())->setVol(vol);
}

34
src/audiowidget.h Normal file
View file

@ -0,0 +1,34 @@
#ifndef AUDIOWIDGET_H
#define AUDIOWIDGET_H
#include <QObject>
#include <QWidget>
#include <QVBoxLayout>
#include "audiomasterwidget.h"
#include "audiolayerwidget.h"
#include "defines.h"
class AudioWidget : public QWidget
{
Q_OBJECT
public:
AudioWidget(QWidget *parent);
private:
// QList<AudioLayerWidget*> *list;
QHBoxLayout *layout;
signals:
public slots:
void mediaLoaded(int layer, QString folder, QString file);
void volChanged(int layer, int vol);
};
#endif // AUDIOWIDGET_H

8
src/defines.h Normal file
View file

@ -0,0 +1,8 @@
#ifndef DEFINES_H
#define DEFINES_H
#define LAYERS_NUMBER 4
#endif // DEFINES_H

36
src/dmxPersonality.h Normal file
View file

@ -0,0 +1,36 @@
#ifndef DMXPERSONALITY_H
#define DMXPERSONALITY_H
/** Define the DMX personality to avoid dealing with
* numbers and change it easyly in case
*
1 - Volumen Coarse
2 - Pan
3 - Folder
4 - File
5 - Playback
0-24 : Play. Reproduce desde el inicio del fichero.
25-49: Stop.
50-74: Resume. Reproduce desde el punto desde el que se paró, o desde el punto designado por Entry Point.
6 - Control - Reservado, sin uso en este momento.
7 - Volume Fine
8 - Entry Point Coarse - Punto de entrada de reproducción.
9 - Entry Point Fine - El valor de estos dos canales en centésimas de segundo.
*/
// ToDo: Tiene bastante sentido cambiar estos defines por un enum
// ¿Ganaría algo en eficiencia? En claridad del código sí.
#define VOLUME_COARSE 0
#define PAN 1
#define DMX_FOLDER 2
#define DMX_FILE 3
#define PLAYBACK 4
#define CONTROL 5
#define VOLUME_FINE 6
#define ENTRY_POINT_COARSE 7
#define ENTRY_POINT_FINE 8
#define LAYER_CHANNELS 5
#endif // DMXPERSONALITY_H

245
src/libremediaserver-audio.cpp Executable file
View file

@ -0,0 +1,245 @@
/*
Pure Media Server - A Media Server Sotfware for stage and performing
Copyright (C) 2012-2013 Santi Noreña libremediaserver@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libremediaserver-audio.h"
/**
/ Constructor
*/
libreMediaServerAudio::libreMediaServerAudio(QStringList args, QWidget *parent)
: QMainWindow(parent)
{
ola = new olaThread();
qDebug() << "********************************************************************************";
qDebug() << QDate::currentDate() << QTime::currentTime();
qDebug() << VERSION;
qDebug() << COPYRIGHT;
qDebug() << LICENSE;
// Inicia el User Interface
ui.setupUi(this);
// Inicia la lectura de dmx a través de ola
ola->start(QThread::TimeCriticalPriority );
ola->blockSignals(true);
// Inicia el widget Terminal
textEdit = new QTextEdit(this);
textEdit->append(QString::fromAscii(VERSION));
textEdit->append(QString::fromAscii(LICENSE));
textEdit->append(QString::fromAscii(COPYRIGHT));
QDockWidget *bottomWidget = new QDockWidget(tr("Terminal"), this);
bottomWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
bottomWidget->setWidget(textEdit);
addDockWidget(Qt::BottomDockWidgetArea, bottomWidget);
// Inicia el widget central de audio
aw = new AudioWidget(this);
setCentralWidget(aw);
// Inicia el widget Master. No implementado todavía
/*
amw = new AudioMasterWidget(this);
QDockWidget *topWidget = new QDockWidget(tr("Master"), this);
topWidget->setAllowedAreas(Qt::TopDockWidgetArea);
topWidget->setWidget(amw);
addDockWidget(Qt::TopDockWidgetArea, topWidget);
*/
// Parse the command line options
if (args.contains("-gui"))
{
qDebug()<< "libremediaserver Constructor option GUI detected";
AudioMotor::getInstance()->setGui(true);
textEdit->append("Pure Data GUI's will be shown");
} else { AudioMotor::getInstance()->setGui(false); }
if (args.contains("-log"))
{
textEdit->append("Log to file");
}
// Conectamos los menus
connect(ui.actionOpen_conf, SIGNAL(triggered()), this, SLOT(openFile()));
connect(ui.actionSave_conf, SIGNAL(triggered()), this, SLOT(saveFile()));
connect(ui.actionChange_Media_Path, SIGNAL(triggered()), this, SLOT(ChangeMediaPath()));
connect(ui.actionLaunch_OLA_Setup, SIGNAL(triggered()), this, SLOT(olasetup()));
Settings *set = new Settings();
// Iniciamos Pure Data
AudioMotor::getInstance()->init();
connect(set, SIGNAL( layersNumber(int)),
ola, SLOT( setLayersNumber(int)));
connect(set, SIGNAL( DMXConf(dmxSetting ) ),
ola, SLOT( setDMXConf(dmxSetting) ) );
connect(AudioMotor::getInstance(), SIGNAL(mediaLoaded(int, QString, QString)),
aw, SLOT(mediaLoaded(int, QString, QString)));
connect(AudioMotor::getInstance(), SIGNAL(volChanged(int, int)),
aw, SLOT(volChanged(int, int)));
connect(AudioMotor::getInstance(), SIGNAL(loadbang()),
this, SLOT (loadbang()));
connect(ola, SIGNAL( dmxOutput(int, int, int) ),
this, SLOT( dmxInput(int, int, int) ) );
// Lee la configuración por defecto
set->readDefaultFile();
ola->blockSignals(false);
}
///////////////////////////////////////////////////////////////////
// Destructor
///////////////////////////////////////////////////////////////////
libreMediaServerAudio::~libreMediaServerAudio()
{
// save_finish();
delete MediaLibrary::getInstance();
ola->stop();
AudioMotor::getInstance()->close();
// qDebug() << "PD Audio restarts: " << m_startaudio;
qDebug() << QDate::currentDate() << QTime::currentTime();
qDebug() << "********************************************************************************";
return;
}
///////////////////////////////////////////////////////////////////
// Menu File
///////////////////////////////////////////////////////////////////
// Open a configuration File
void libreMediaServerAudio::openFile()
{
QFileDialog dialog(this);
if (!dialog.exec())
return;
QStringList fileNames;
fileNames = dialog.selectedFiles();
QFile file(fileNames.at(0));
// open(&file);
}
// Save configuration File
void libreMediaServerAudio::saveFile()
{
QFileDialog dialog(this);
if (!dialog.exec())
return;
QStringList fileNames;
fileNames = dialog.selectedFiles();
QFile file(fileNames.at(0));
// save(&file);
}
// Change Media path
void libreMediaServerAudio::ChangeMediaPath()
{
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::Directory);
QStringList fileNames;
if (!dialog.exec())
return;
fileNames = dialog.selectedFiles();
QString file = fileNames.at(0);
MediaLibrary::getInstance()->setPath(file);
QString desc = tr("Media Path Changed to: %1").arg(m_pathmedia);
textEdit->append(desc.toAscii());
}
///////////////////////////////////////////////////////////////////
// OLA Stuff
///////////////////////////////////////////////////////////////////
void libreMediaServerAudio::olasetup()
{
QWebView *view = new QWebView();
view->load(QUrl("http://localhost:9090/ola.html"));
view->show();
}
/**
* Parse the nes dmx information
*/
void libreMediaServerAudio::dmxInput(int layer, int channel, int value)
{
// This qDebug slows all the program. Uncomment only for debugging purpouse and comment again in normal use
// qDebug() << tr("olaInterface|") << "newdmx layer" << layer << "channel" << channel << "value" << value;
QString mediaFile = NULL;
int aux;
float vol;
switch(channel){
case DMX_FOLDER:// Folder
aux = ola->getValue(layer, DMX_FILE);
mediaFile = MediaLibrary::getInstance()->requestNewFile(value, aux);
if (QFile::exists(mediaFile))
AudioMotor::getInstance()->load(layer, mediaFile);
break;
case DMX_FILE:// File
aux = ola->getValue(layer, DMX_FOLDER);
mediaFile = MediaLibrary::getInstance()->requestNewFile(aux, value);
if (QFile::exists(mediaFile))
AudioMotor::getInstance()->load(layer, mediaFile);
break;
case VOLUME_COARSE:
vol = ( value * 0x100 ) + ola->getValue(layer, VOLUME_FINE);
AudioMotor::getInstance()->setLayerVolume(layer, vol/65535);
break;
case VOLUME_FINE:
vol = ( ola->getValue(layer, VOLUME_COARSE) * 0x100 ) + value;
AudioMotor::getInstance()->setLayerVolume(layer, vol/65535);
break;
case PAN:
AudioMotor::getInstance()->setLayerPan(layer, value/255);
break;
case PLAYBACK:
aux = value / 25;
switch (aux) {
case 0 :
AudioMotor::getInstance()->play(layer);
break;
case 1 :
AudioMotor::getInstance()->stop(layer);
break;
case 2 :
AudioMotor::getInstance()->pause(layer);
break;
}
default:
// emit dmxInput(layer, channel, value);
break;
}
}
/**
* Send the DMX info to Pure Data in init
*
*/
void libreMediaServerAudio::loadbang() {
ola->resendDmx();
}

108
src/libremediaserver-audio.h Executable file
View file

@ -0,0 +1,108 @@
/*
Libre Media Server - A Media Server Sotfware for stage and performing
Copyright (C) 2012-2013 Santiago Noreña libremediaserver@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBREMEDIASERVER_H
#define LIBREMEDIASERVER_H
#include <QMainWindow>
//#include <QApplication>
#include <QObject>
#include <QDesktopWidget>
#include <QtGui>
#include <QFile>
#include <QFileInfo>
#include <QFileDialog>
#include <QTextStream>
#include <QWebView>
#include <QUrl>
#include <QVBoxLayout>
#include <QTextEdit>
#include "settings.h"
#include "audiomotor.h"
#include "olathread.h"
#include "audiolayerwidget.h"
#include "audiomasterwidget.h"
#include "audiowidget.h"
#include "ui_libremediaserver-audio.h"
#define VERSION "LibreMediaServer-Audio Version 0.1.0"
#define COPYRIGHT "(C) 2014 Santi Norena libremediaserver@gmail.com"
#define LICENSE "GPL 3 License. See LICENSE.txt and credits.txt for details"
class QMenu;
class QProcess;
class libreMediaServerAudio : public QMainWindow
{
Q_OBJECT
public:
libreMediaServerAudio (QStringList args, QWidget *parent = 0);
virtual ~libreMediaServerAudio();
Ui::LibreMediaServerAudio ui;
protected:
QString m_pathmedia; // Path to Medias
QProcess *m_ola; // OLA daemon process
bool m_gui;
private:
QTextEdit *textEdit; // Terminal de feedback
AudioMasterWidget *amw;
// AudioLayerWidget *alw;
AudioWidget *aw;
olaThread *ola;
void open_start();
void save_finish();
void open(QFile *file);
void save(QFile *file);
// void MessageHandler(QtMsgType type, const char *msg);
public slots:
private slots:
/**
* @brief loadbang The audio motor engine is setup. Resend the dmx info to maintain aupdated to the current state
*/
void loadbang();
void olasetup();
void dmxInput(int layer, int channel, int value);
// Menu File
void openFile();
void saveFile();
void ChangeMediaPath();// Change the path to medias
};
#endif // LIBREMEDIASERVER_H

51
src/libremediaserver-audio.pro Executable file
View file

@ -0,0 +1,51 @@
TEMPLATE = app
TARGET = libremediaserver-audio
QT += network script webkit
CONFIG += debug
DESTDIR = ./debug
HEADERS += libremediaserver-audio.h \
medialibrary.h \
audiomotor.h \
olathread.h \
audiolayerwidget.h \
dmxPersonality.h \
audiowidget.h \
audiomasterwidget.h \
defines.h \
settings.h
SOURCES += main.cpp \
libremediaserver-audio.cpp \
medialibrary.cpp \
audiomotor.cpp \
olathread.cpp \
audiolayerwidget.cpp \
audiowidget.cpp \
audiomasterwidget.cpp \
settings.cpp
FORMS += \
libremediaserver-audio.ui
#INCLUDEPATH += ./
LIBS += -L./debug -lola -lolacommon
#win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../debug/release/ -lcitp
#else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../debug/debug/ -lcitp
#else:symbian: LIBS += -lcitp
#else:unix: LIBS += -L$$PWD/../debug/ -lcitp
#INCLUDEPATH += $$PWD/../debug
#DEPENDPATH += $$PWD/../debug
RESOURCES =
OTHER_FILES += \
../LICENSE.txt \
../instalacion.txt \
../credits.txt \
../compiling.txt \
../changelog.txt \
../lms-audio.xlm

84
src/libremediaserver-audio.ui Executable file
View file

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<author>Santi Noreña belfegor@gmail.com</author>
<class>LibreMediaServerAudio</class>
<widget class="QMainWindow" name="LibreMediaServerAudio">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>745</width>
<height>636</height>
</rect>
</property>
<property name="windowTitle">
<string>LibreMediaServer</string>
</property>
<widget class="QWidget" name="centralwidget"/>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>745</width>
<height>29</height>
</rect>
</property>
<widget class="QMenu" name="menuFile">
<property name="title">
<string>File</string>
</property>
<addaction name="actionOpen_conf"/>
<addaction name="actionSave_conf"/>
<addaction name="actionChange_Media_Path"/>
<addaction name="actionLaunch_OLA_Setup"/>
</widget>
<addaction name="menuFile"/>
</widget>
<action name="actionExit">
<property name="text">
<string>Exit</string>
</property>
</action>
<action name="actionOpen_conf">
<property name="text">
<string>Open Configuration</string>
</property>
</action>
<action name="actionSave_conf">
<property name="text">
<string>Save Configuration</string>
</property>
</action>
<action name="actionChange_Media_Path">
<property name="text">
<string>Change Media Path</string>
</property>
</action>
<action name="actionInitMSEX">
<property name="checkable">
<bool>false</bool>
</property>
<property name="text">
<string>Init</string>
</property>
</action>
<action name="actionIP_Address">
<property name="text">
<string>IP Address</string>
</property>
</action>
<action name="actionMake_Thumbs">
<property name="text">
<string>Make Thumbs</string>
</property>
</action>
<action name="actionLaunch_OLA_Setup">
<property name="text">
<string>OLA Setup</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>

122
src/main.cpp Executable file
View file

@ -0,0 +1,122 @@
/*
Libre Media Server - A media server for audio playback in stage arts
controlled by lingting protocols (DMX, ArtNet, ACN,...)
Copyright (C) 2015 Santiago Noreña libremediaserver@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include "libremediaserver-audio.h"
// Handler for pipe the stderr to a log file
bool initMessageHandler = false;
QFile outFile;
void MessageHandler(QtMsgType type, const char *msg)
{
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
abort();
}
// Create the log dir and log file
if (!initMessageHandler)
{
QDir dir;
if (!dir.exists("log"))
{
if (!dir.mkdir("log"))
{
qDebug()<<"MessageHandler: Can not create log folder";
return;
}
}
QString filename;
QDate date = QDate::currentDate();
QTime time = QTime::currentTime();
filename.append("./log/log_");
filename.append(date.toString("ddMMyy-"));
filename.append(time.toString("hhmmss.txt"));
outFile.setFileName(filename);
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append))
{
qDebug()<<"main/MessageHandler/Qfile::open: can not open log file";
return;
}
initMessageHandler = true;
}
QTextStream ts(&outFile);
ts << txt << endl;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = app.arguments();
// parse the command line
if (args.size() > 1)
{
if (args.contains("-v") > 0)
{
qDebug() << VERSION;
qDebug() << COPYRIGHT;
qDebug() << LICENSE;
return 0;
}
if (args.contains("-h") > 0)
{
qDebug() << VERSION;
qDebug() << COPYRIGHT;
qDebug() << LICENSE;
qDebug() << "Help for command line options:";
qDebug() << "-v show the version and exits";
qDebug() << "-gui show the Pure Data GUI's";
qDebug() << "-log write the debug information to a log file instead stderr";
qDebug() << "-h this help";
return 0;
}
if (args.contains("-log"))
{
qInstallMsgHandler(MessageHandler);
}
if (!args.contains("-gui"))
{
for (int i=1; i<args.size();i++)
{
qDebug() << "Option not known: " << args.at(i);
}
qDebug() <<"Write ./libremediaserver-audio -h for help in command line arguments";
return 0;
}
}
libreMediaServerAudio libreMediaServerAudio(args);
libreMediaServerAudio.show();
return app.exec();
}

92
src/medialibrary.cpp Normal file
View file

@ -0,0 +1,92 @@
#include "medialibrary.h"
MediaLibrary *MediaLibrary::_instance = 0;
MediaLibrary *MediaLibrary::getInstance() {
if (_instance == 0) {
_instance = new MediaLibrary();
Q_CHECK_PTR(_instance);
}
return _instance;
}
MediaLibrary::MediaLibrary(QObject *parent) :
QObject(parent)
{
initMediaLibrary();
qDebug("Init MediaLibrary");
}
/** Initializes the media library and the media information
* from the path to media in m_pathmedia
*/
void MediaLibrary::initMediaLibrary() {
QDir dir;
if (!dir.cd(m_pathmedia)) {
qWarning("olaInterface::initMediaLibrary| Can not cd to the path: ");
qWarning(m_pathmedia.toAscii().constData());
return;
}
m_media = new QList<MediaFolder>;
dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList filelist = dir.entryInfoList();
dir.setFilter(QDir::Files);
QFileInfo fileInfo;
struct MediaFolder mediai;
for (int i = 0; i < filelist.size(); ++i) {
fileInfo = filelist.at(i);
QString name = fileInfo.absoluteFilePath();
dir.cd(fileInfo.baseName());
mediai.m_Id = i;
mediai.m_Name = name;
mediai.m_ElementCount = dir.count();
mediai.m_MediaInformation = getMediaInformation(dir);
dir.cdUp();
m_media->append(mediai);
}
}
/**
* This set every media file included in one library/folder
*/
QList<MediaFile> MediaLibrary::getMediaInformation(QDir dir)
{
QList<MediaFile> mediaList;
MediaFile mediainf;
dir.setFilter(QDir::Files);
QFileInfoList filelist = dir.entryInfoList();
QFileInfo fileInfo;
for (int i = 0; i < filelist.size(); ++i) {
fileInfo = filelist.at(i);
// Update the data base with the new file
mediainf.Number = i;
mediainf.MediaName = fileInfo.absoluteFilePath();
mediainf.MediaLength = 1000; // ¿?¿?¿?¿?
mediaList.append(mediainf);
}
return mediaList;
}
/** Selects one media name
*
*/
QString MediaLibrary::requestNewFile(int folder, int file){
// Select one mediafile from the media library
QString newfile;
if (folder < m_media->size()) {
if (file < m_media->at(folder).m_MediaInformation.size()) {
newfile = m_media->at(folder).m_MediaInformation.at(file).MediaName;
} else {
qDebug("MediaLibrary::requestNewFile(): Requested file is greater than files in library");
}
} else {
qDebug("MediaLibrary::requestNewFile(): Requested folder is greater than media libraries");
}
return newfile;
}

67
src/medialibrary.h Normal file
View file

@ -0,0 +1,67 @@
#ifndef MEDIALIBRARY_H
#define MEDIALIBRARY_H
#include <QObject>
#include <QDir>
// Media Information for MELIn packages. v1.0
struct MediaFile {
quint8 Number; // 0-based contiguous index of the media.
QString MediaName;// Media name.
quint32 MediaLength;// Media length (in frames).
};
// Media Library for ELin packages v1.0
struct MediaFolder {
quint8 m_Id; // Library id.
QString m_Name;// Library name.
quint8 m_ElementCount;// Number of elements in the library.
QList<MediaFile> m_MediaInformation; // Pointer to the Medias Information List of this Library
};
class MediaLibrary : public QObject
{
Q_OBJECT
public:
static MediaLibrary *getInstance();
inline void setPath(QString path) { m_pathmedia = path; rescanMediaLibrary();}
QString requestNewFile(int folder, int layer);
private:
explicit MediaLibrary(QObject *parent = 0);
static MediaLibrary *_instance;
inline QString getPath () { return m_pathmedia; } // Get the path to the medias folder tree.
inline void deleteMediaLibrary() { delete m_media; m_media = NULL; }
/**
* Change library/path
*/
inline void rescanMediaLibrary()
{
deleteMediaLibrary();
initMediaLibrary();
}
QList<MediaFolder> *m_media; // Library to save the folders/media libraries and index each media file inside
QString m_pathmedia; // Path to Medias
void initMediaLibrary();
/** Called when there is a change in the channels folder or file
* this is called. Creates a new source.
*/
QList<MediaFile> getMediaInformation(QDir dir); // Get all the information of each media file in a dir
signals:
public slots:
};
#endif // MEDIALIBRARY_H

51
src/olainterface.cpp Executable file
View file

@ -0,0 +1,51 @@
/* olainterface.cpp
Santi Noreña 2013
It includes two classes:
olaWorker is the threading class that reads raw DMX from ola daemon and save it into a buffer ordered in layers
olaInterface controls olaWorker and translates DMX values received from olaWorker into orders to RenderingManager and Source
*/
#include "olainterface.h"
olaInterface::olaInterface()
{
qDebug() << tr("olaInterface|") << "Starting";
m_thread = NULL;
m_thread = new QThread;
Q_CHECK_PTR(m_thread);
worker = new olaWorker();
Q_CHECK_PTR(worker);
connect (worker, SIGNAL(dmx(int,int,int)), this, SLOT(dmx(int,int,int)), Qt::QueuedConnection); // The DMX values.
worker->moveToThread(m_thread);
connect(m_thread, SIGNAL(started()), worker, SLOT(olastart()));
connect(m_thread, SIGNAL(finished()), m_thread, SLOT(deleteLater()));
m_thread->start();
}
olaInterface::~olaInterface()
{
close();
}
// Close olaWorker and finish the thread
void olaInterface::close()
{
worker->blockSignals(true);
worker->olastop();
delete worker;
}
////////////////////////////////////////////////////////////
//
// Parse new DMX
//
////////////////////////////////////////////////////////////
//New dmx. Connected with signal newdmx from olaInterface->Worker
void olaInterface::dmx(int layer, int channel, int value)
{
}

68
src/olainterface.h Executable file
View file

@ -0,0 +1,68 @@
/* olainterface.h
Santi Noreña 2013
It includes two classes:
olaWorker is the threading class that reads raw DMX from ola daemon
olaInterface controls olaWorker and translates DMX values received from olaWorker into orders to RenderingManager and Source
*/
#ifndef OLAINTERFACE_H
#define OLAINTERFACE_H
//#define DMX_SOURCETYPE 7
#define LAYER_CHANNELS 15 // The numer of control channels per video layer
#define MAX_SOURCE_DMX 8 // Number of maximum Sources controlled by DMX. It should be equal to MAX_SOURCE_COUNT
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <QObject>
#include <QDebug>
#include <QXmlStreamReader>
#include <QFile>
#include <QMessageBox>
#include <QProcess>
// The OLA Library
#include <ola/OlaClientWrapper.h>
#include <ola/OlaCallbackClient.h>
//#include <ola/OlaClient.h>
#include "libremediaserver.h"
using namespace ola;
class olaInterface : public QObject
{
Q_OBJECT
public:
explicit olaInterface();
virtual ~olaInterface();
void open(); // Starts the thread and open the connection with olad
void close(); // Close the connection with olad
olaWorker *worker; // The thread of connection with ola.
protected:
QThread *m_thread; // The thread for olaWorker
private:
void readDataFromXML(); // Read the DMX configuration from the file dmx.xml
public slots:
void dmx(int layer, int channel, int value); // Connected with signal dmx from olaWorker. This is the horsepower of all this. Converts DMX orders
// into orders to RenderingManager and Source. Mantains updated the videolayer struct.
signals:
};
#endif // OLAINTERFACE_H

138
src/olathread.cpp Normal file
View file

@ -0,0 +1,138 @@
#include "olathread.h"
olaThread::olaThread(QObject *parent)
// : QObject(parent)
{
m_universe = new QList<int>();
m_counter = 0;
gettimeofday(&m_last_data, NULL);
dmxSetting newsetting;
newsetting.address = -1;
newsetting.universe = -1;
newsetting.updated = false;
m_layersNumber = LAYERS_NUMBER;
for (int i=0; i < LAYERS_NUMBER; i++)
{
newsetting.layer = i;
m_settings.append(newsetting);
for (int j=0; j < LAYER_CHANNELS; j++)
{
m_dmx[i][j] = 0;
}
}
/* int argc = 1;
char argv[] = "-l 3";
if (!ola::AppInit (&argc, &argv,"LMS", "DMX sound media server"))
qCritical("Can not init ola");*/
// set up ola connection
m_clientWrapper = new ola::client::OlaClientWrapper;
Q_CHECK_PTR(m_clientWrapper);
if (!m_clientWrapper->Setup()) { qErrnoWarning("olaThread::olaStart| Failed Setup() in Client Wrapper"); }
m_client = m_clientWrapper->GetClient();
ola::InitLogging(ola::OLA_LOG_INFO , ola::OLA_LOG_STDERR);
m_client->SetDMXCallback(ola::NewCallback(this, &olaThread::NewDmx));
m_clientWrapper->GetSelectServer()->RegisterRepeatingTimeout(4000, ola::NewCallback(this, &olaThread::CheckDataLoss));
qDebug() << "Init olaThread";
}
// --- DECONSTRUCTOR ---
olaThread::~olaThread() {
stop();
}
/** Open the connection with olad and start processing data.
*/
void olaThread::run() {
/* register the universe
if (!m_client->RegisterUniverse(m_universe, ola::REGISTER,ola::NewSingleCallback(&RegisterComplete))) {
qDebug() << "Can not register universe %1".arg(m_universe);
}*/
m_clientWrapper->GetSelectServer()->Run();
qDebug()<< tr("olaThread|") << "Running";
}
void olaThread::stop()
{
if (m_clientWrapper != NULL)
{
for (int i = 0; i < m_universe->size(); i++) {
m_client->RegisterUniverse(m_universe->at(i), ola::client::UNREGISTER, ola::NewSingleCallback(this, &olaThread::RegisterComplete));
}
m_clientWrapper->GetSelectServer()->Terminate();
m_client = NULL;
m_clientWrapper = NULL;
}
}
/**
* RepeteableDMXCallBack
* Callback2<void, const DMXMetada&, const DmxBuffer&>
* from OLA daemon when there is new DMX data. This is called one for second if there is not updated in the DMX frame. We need emit only the channels that
* has changed to save resources.
*/
// ToDo: It can be more efficient making the dmx buffer a DmxBuffer class instead a int array and compare with the new if there is changes at start. Also all access to the buffer it should be get/set. I should profile this
// typedef Callback2<void, const DMXMetadata&, const DmxBuffer&> ola::client::RepeatableDMXCallback
void olaThread::NewDmx(const ola::client::DMXMetadata &data,
const ola::DmxBuffer &buffer)
{
m_counter++;
gettimeofday(&m_last_data, NULL);
int universe = data.universe;
for (int i = 0; i < m_layersNumber; i++) { // loop for reading the channels by layer.
if((m_settings.at(i).universe == universe)
&& ( m_settings.at(i).address > -1 )) { // Compare if the layer is from this universe
// AND if the DMX address is 0 or greater, process this layer.
for (int j = 0; j < LAYER_CHANNELS; j++){
int value = buffer.Get((m_settings.at(i).address) + j); // Get the value for this channel.
if (m_dmx[i][j] != value) { // Compare the new value with the old value.
emit dmxOutput(i,j,value); // Connected with dmx slot in olaInterface.
m_dmx[i][j] = value;
}
}
}
}
}
/**
* Check for data loss each 4 seconds.
*/
bool olaThread::CheckDataLoss() {
struct timeval now, diff;
if (timerisset(&m_last_data)) {
gettimeofday(&now, NULL);
timersub(&now, &m_last_data, &diff);
if (diff.tv_sec > 4 || (diff.tv_sec == 4 && diff.tv_usec > 4000000)) {
// loss of data
qDebug()<< "olaThread| Can not read one or several universes";
// return false; // Retorna false para deshabilitar el callback
}
}
return true;
}
void olaThread::setLayersNumber(int layersNumber) { m_layersNumber = layersNumber; }
void olaThread::resendDmx()
{
for (int i = 0; i < m_layersNumber; i++) { // loop for reading the channels by layer.
for (int j = 0; j < LAYER_CHANNELS; j++){
emit dmxOutput(i, j, m_dmx[i][j]); // Connected with dmx slot in olaInterface.
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////

126
src/olathread.h Normal file
View file

@ -0,0 +1,126 @@
#ifndef OLATHREAD_H
#define OLATHREAD_H
#include <QObject>
#include <QThread>
#include <QDebug>
#include <string>
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/OlaClientWrapper.h>
#include <ola/client/OlaClient.h>
#include <ola/DmxBuffer.h>
#include <ola/client/ClientTypes.h>
#include "defines.h"
#include "dmxPersonality.h"
// struct where save the DMX settings for each layer
struct dmxSetting {
int address;
uint universe;
bool updated;
int layer;
};
class olaThread : public QThread
{
Q_OBJECT
public:
olaThread(QObject *parent = 0);
virtual ~olaThread();
/** Retorna el valor de un canal
*@param int layer the layer for we want the channel
*@param int channel the channel for the value wanted
*@return int the value
*/
inline int getValue(int layer, int channel) {
return m_dmx[layer][channel];
}
/**
* @brief resendDMX emite todo el buffer DMX
*/
void resendDmx();
private:
void run ();
ola::client::OlaClientWrapper *m_clientWrapper;
ola::client::OlaClient *m_client;
unsigned int m_counter;
struct timeval m_last_data; // Last DMX frame received
// DMX Conf
// Cambiar para múltiples universos. Array? método de de ola::client?
QList<int> *m_universe; // Registered universes.
int m_layersNumber; // Number of layers in wich divide the dmx frame. Each layer, one source.
int m_dmx[LAYERS_NUMBER][LAYER_CHANNELS]; // DMX Buffer. Habría que cambiarlo si queremos hacer las capas dinámicas
QList<dmxSetting> m_settings;
inline void registerUniverse(int universe)
{
// void ola::client::OlaClient::RegisterUniverse(unsigned int universe,RegisterAction register_action,SetCallback * callback
m_client->RegisterUniverse(universe, ola::client::REGISTER,ola::NewSingleCallback(this, &olaThread::RegisterComplete));
}
/**
* Control de errores en el registro de Universos en OLA
*/
// typedef SingleUseCallback1<void, const Result&> ola::client::SetCallback
inline void RegisterComplete(const ola::client::Result &error) {
if (error.Success()) {
qDebug() << "Register Universe success";
} else {
qWarning() << "olaThread|" << "Register command failed" << QString::fromStdString(error.Error());
}
}
bool CheckDataLoss();
// typedef Callback2<void, const DMXMetadata&, const DmxBuffer&> ola::client::RepeatableDMXCallback
void NewDmx(const ola::client::DMXMetadata &dmx_meta, const ola::DmxBuffer &buffer); // Callback from OlaCLient when there is new dmx info
public slots:
void stop(); // Close the connection with olad.
void setLayersNumber(int layersNumber);
inline void setDMXConf(dmxSetting set)
{
if (set.layer >= m_layersNumber) { return; }
m_settings.replace(set.layer, set);
// ToDo: registro del nuevo universo si no está registrado ya
if (!m_universe->contains(set.universe)) {
registerUniverse(set.universe);
m_universe->append(set.universe);
}
}
protected slots:
signals:
void finished(); // Signal for closing. Not used now.
void dmxOutput(int layer, int channel, int value); // Signal when a channel has changed
};
#endif // OLATHREAD_H

81
src/settings.cpp Normal file
View file

@ -0,0 +1,81 @@
#include "settings.h"
Settings::Settings(QObject *parent) :
QObject(parent)
{
readDefaultFile();
}
// Read the dmx settings for dmx.xml At the moment we need:
// - The path to the medias folder tree
// - The number of sources/layers controlled by DMX
// - The first DMX channel of each source/layer
// - The universe to bind in OLA
// All this is being moved to settingsDialog Class
void Settings::readFromFile(QString file) {
QFile* xmlFile = new QFile(file);
if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::critical(NULL,"Load XML File Problem",
QString("Couldn't open %1 to load settings for olaInterface").arg(file),
QMessageBox::Ok);
return;
}
QXmlStreamReader* xmlReader = new QXmlStreamReader(xmlFile);
int counter = 0;
//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
// Read next element
QXmlStreamReader::TokenType token = xmlReader->readNext();
//If token is just StartDocument - go to next
if(token == QXmlStreamReader::StartDocument) {
continue;
}
//If token is StartElement - read it
if(token == QXmlStreamReader::StartElement) {
if(xmlReader->name() == "dmxSettings") {
int version = xmlReader->attributes().value("fileVersion").toLocal8Bit().toInt();
if(version == 1) {
int layers = xmlReader->attributes().value("layersNumber").toLocal8Bit().toInt();
emit layersNumber(layers);
MediaLibrary::getInstance()->setPath (xmlReader->attributes().value("path").toLocal8Bit());
continue;
}
}
/* if (worker->m_layersNumber > MAX_SOURCE_DMX) {
worker->m_layersNumber = MAX_SOURCE_DMX;
}*/
QString add = "layer";
add.append(QString("%1").arg(counter));
if((xmlReader->name() == add)) {
dmxSetting temp;
temp.address = xmlReader->attributes().value("dmx").toLocal8Bit().toInt() - 1;
temp.universe = xmlReader->attributes().value("universe").toLocal8Bit().toInt();
temp.layer = counter;
emit DMXConf(temp);
// If the universe is not in the list, append it.
// if(!worker->m_universe.contains(temp.universe)) {
// worker->m_universe.append(temp.universe);
// }
}
counter++;
}
}
if(xmlReader->hasError()) {
QMessageBox::critical(NULL,"File xml Parse Error ", xmlReader->errorString(), QMessageBox::Ok);
}
//close reader and flush file
xmlReader->clear();
xmlFile->close();
delete xmlReader;
delete xmlFile;
}
/** Read the default file
*
*/
void Settings::readDefaultFile() {
readFromFile(DEFAULT_FILE);
}

32
src/settings.h Normal file
View file

@ -0,0 +1,32 @@
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QObject>
#include <QXmlStreamReader>
#include <QFile>
#include <QMessageBox>
#include "olathread.h"
#include "audiomotor.h"
#include "medialibrary.h"
#define DEFAULT_FILE "lms-audio.xlm"
class Settings : public QObject
{
Q_OBJECT
public:
explicit Settings(QObject *parent = 0);
void readFromFile(QString file);
void readDefaultFile();
signals:
void pathChanged(QString path);
void layersNumber(int number);
void DMXConf(dmxSetting universe);
public slots:
};
#endif // SETTINGS_H