Merge branch 'sfml'

Added Singleton to AudioWidget

Conflicts:
	lms-audio.xlm
	puredata/layer_audio.pd
	src/audiolayerwidget.cpp
	src/audiolayerwidget.h
	src/audiomasterwidget.cpp
	src/audiomasterwidget.h
	src/audiomotor.cpp
	src/audiomotor.h
	src/audiowidget.cpp
	src/defines.h
	src/libremediaserver-audio.cpp
	src/libremediaserver-audio.h
	src/libremediaserver-audio.pro
	src/libremediaserver-audio.ui
	src/medialibrary.cpp
	src/medialibrary.h
	src/olathread.cpp
	src/olathread.h
	src/settings.cpp
	src/settings.h
This commit is contained in:
santi 2014-10-03 13:17:00 +02:00
commit 2d16fb6af7
31 changed files with 1112 additions and 1296 deletions

46
.gitignore vendored Normal file
View file

@ -0,0 +1,46 @@
# C++ objects and libs
*.slo
*.lo
*.o
*.a
*.la
*.lai
*.so
*.dll
*.dylib
# Qt-es
/.qmake.cache
/.qmake.stash
*.pro.user
*.pro.user.*
*.moc
moc_*.cpp
qrc_*.cpp
ui_*.h
Makefile*
*-build-*
# QtCreator
*.autosave
# binarios
puredata/pd
puredata/externals/**
# Folders
bin/**
tcl/**
src/debug/**
src/release/**
log/**
# Backups
*~
*.autosave

View file

@ -23,9 +23,9 @@ Lbre Media Server ChangeLog
******************************************************************************* *******************************************************************************
v 0.1-1 v 0.1.0
+ First Version: 4 layers playing .ogg + First Version: 4 layers playing .ogg
+ Needs Open Lighting Arquitecture => 0.9.0 + Needs Open Lighting Arquitecture => 0.9.0
+ Pure Data as audio engine + Qt5 and QtMultimedia sound engine

View file

@ -21,23 +21,19 @@ You should have received a copy of the GNU General Public License along with thi
If you have troubles, or you are in another distro, you can try compiling from the source code. If you have troubles, or you are in another distro, you can try compiling from the source code.
0. Requisites 0. Prerequisites
tcl tk --> To compile Pure Data, not necesary to execute it without GUI (-gui option in command line)
build-essential
make
qmake
gcc
g++
libtool
ola-dev
1. Building pd Install OLA binaries and headers:
$./configure add deb http://apt.openlighting.org/debian wheezy main to your /etc/sources.list
$make #apt-get update
#apt-get install ola ola-dev
2. LibreMediaserver Audio Install Qtcreator from http://qt-project.org/downloads
We are using version 5.3.1
Open the file libremediaserver-audio.pro with QtCreator and compile it. 1. LibreMediaserver Audio
Open the file libremediaserver-audio.pro with QtCreator, configure the project and compile it.
or or
@ -45,16 +41,6 @@ If you have troubles, or you are in another distro, you can try compiling from t
$ qmake-qt4 libremediaserver-audio.pro -r -spec linux-g++ $ qmake-qt4 libremediaserver-audio.pro -r -spec linux-g++
$ make -w $ make -w
3. Putting all together. 2. Copy lms-audio.xml to the working directory or set the project working directoroy to the folder containing this file
Make a directory. Copy in it:
- libremediaserver binary
- Folder scripts
- Folder puredata
- the tcl folder in the pd sources. This is only necessary to show the Pure Data GUI's. You don't need if you don't want the GUI's. Only it's good for debugging purpouses and developing, for normal use you can skip this step.
In the folder puredata copy:
- the pd executable
- Make a folder named externals and copy all the externals to it. All the externals compiled must be in ~HOME/pd-external.

View file

@ -1,4 +1,2 @@
Pure Data: Copyright © Miller Miller Puckette and others - BSD License. LibreMediaServer Santiago Noreña Sobrado libremediaserver@gmail.com
pdogg~/oggread~: Copyright © 2002-2004 by Olaf Matthes - GPL License.

View file

@ -23,23 +23,13 @@ You should have received a copy of the GNU General Public License along with thi
LMS Audio está desarrollado y probado en Debian Wheezy y derivados. LMS Audio está desarrollado y probado en Debian Wheezy y derivados.
Para resolver dependencias es necesario tener conexión a internet en el ordenador durante el proceso de instalación. 1. Instala Open Lighting Arquitecture desde su repositorio:
LMS se comunica con Pure Data mediante puertos TCP, del 9195 al 9198. Open Lighting Arquitecure utiliza el puerto 9090 para su servidor web. Es necesario que estos puertos no estén siendo utilizados por otras aplicaciones.
1. Instala Open Lignting Arquitecture
Añadimos el repositorio de Open Lighting al archivo /etc/apt/sources.list: Añadimos el repositorio de Open Lighting al archivo /etc/apt/sources.list:
$ echo "deb http://apt.openlighting.org/debian/ wheezy main" >> /etc/apt/sources.list $ echo "deb http://apt.openlighting.org/debian/ wheezy main" >> /etc/apt/sources.list
Actualizamos las fuentes: Actualiza las fuentes: $ apt-get update
Instalamos los paquetes necesarios: $ apt-get install ola
$ apt-get update
Instalamos los paquetes necesarios:
$ apt-get -y --force-yes install ola libqtcore4 libqtgui4
2. Configuración 2. Configuración
@ -61,6 +51,6 @@ Si quieres usar el mismo ordenador como mesa y media server edit el archivo ~/.o
e. Pincha en el menu File -> Change Media Path y elige el directorio donde estén tus medias. e. Pincha en el menu File -> Change Media Path y elige el directorio donde estén tus medias.
f. La configuración de los universos de ola a los que LMS Audio escucha y las direcciones DMX de las capas se configuran en el fichero lms.xlm. En el campo Universe tienes que poner el universo de ola que has definido anteriormente. Edita este fichero con un editor de texto plano y reinicia el programa. De momento no se puede configurar mediante GUI. f. La configuración de los universos de ola a los que LMS Audio escucha y las direcciones DMX de las capas se configuran en el fichero lms-audio.xlm. En el campo Universe tienes que poner el universo de ola que has definido anteriormente. Edita este fichero con un editor de texto plano y reinicia el programa. De momento no se puede configurar mediante GUI.

View file

@ -4,8 +4,12 @@
<layer1 dmx="21" universe="1" /> <layer1 dmx="21" universe="1" />
<layer2 dmx="41" universe="1" /> <layer2 dmx="41" universe="1" />
<layer3 dmx="61" universe="1" /> <layer3 dmx="61" universe="1" />
<<<<<<< HEAD
<layer4 dmx="257" universe="1" /> <layer4 dmx="257" universe="1" />
<layer5 dmx="321" universe="1" /> <layer5 dmx="321" universe="1" />
<layer6 dmx="385" universe="1" /> <layer6 dmx="385" universe="1" />
<layer7 dmx="449" universe="1" /> <layer7 dmx="449" universe="1" />
=======
<layer4 dmx="81" universe="1" />
>>>>>>> sfml
</dmxSettings> </dmxSettings>

View file

@ -1,94 +0,0 @@
#N canvas 459 153 904 466 10;
#N canvas 818 90 547 469 audio_player 0;
#X msg 203 93 start;
#X msg 259 95 stop;
#X obj 119 140 oggread~;
#X msg 301 92 resume;
#X obj 22 9 inlet;
#X obj 219 31 r \$0-c5;
#X obj 77 213 *~ 0;
#X obj 136 213 *~ 0;
#X obj 158 450 dac~;
#X obj 382 129 r \$0-c1;
#X obj 211 234 r \$0-c2;
#X obj 219 71 select 0 1 2;
#X msg 119 101 seek \$1;
#X obj 119 36 r \$0-c8;
#X obj 119 67 * 0.01;
#X obj 210 358 line~;
#X msg 210 337 \$1 1;
#X obj 117 350 line~;
#X msg 117 329 \$1 1;
#X obj 194 378 *~;
#X obj 101 375 *~;
#X floatatom 309 148 5 0 0 0 - - -;
#X obj 333 386 outlet;
#X obj 333 347 int;
#X obj 335 305 * 100;
#X msg 236 308 0.5;
#X obj 238 274 loadbang;
#X obj 383 157 dbtorms;
#X floatatom 423 207 5 0 0 0 - - -;
#X floatatom 385 259 5 0 0 0 - - -;
#X obj 117 297 - 1;
#X text 208 155;
#X connect 0 0 2 0;
#X connect 1 0 2 0;
#X connect 2 0 6 0;
#X connect 2 1 7 0;
#X connect 2 2 21 0;
#X connect 3 0 2 0;
#X connect 4 0 2 0;
#X connect 5 0 11 0;
#X connect 6 0 20 0;
#X connect 7 0 19 0;
#X connect 9 0 27 0;
#X connect 9 0 28 0;
#X connect 10 0 16 0;
#X connect 10 0 30 0;
#X connect 11 0 0 0;
#X connect 11 1 1 0;
#X connect 11 2 3 0;
#X connect 12 0 2 0;
#X connect 13 0 14 0;
#X connect 14 0 12 0;
#X connect 15 0 19 1;
#X connect 16 0 15 0;
#X connect 17 0 20 1;
#X connect 18 0 17 0;
#X connect 19 0 8 1;
#X connect 20 0 8 0;
#X connect 23 0 22 0;
#X connect 24 0 23 0;
#X connect 25 0 16 0;
#X connect 25 0 30 0;
#X connect 26 0 25 0;
#X connect 27 0 7 1;
#X connect 27 0 6 1;
#X connect 27 0 24 0;
#X connect 27 0 29 0;
#X connect 30 0 18 0;
#X restore 219 -234 pd audio_player;
#X obj 19 -18 s \$0-c1;
#X obj 79 -19 s \$0-c2;
#X obj 135 -18 s \$0-c3;
#X obj 197 -16 s \$0-c4;
#X obj 268 -15 s \$0-c5;
#X obj 335 -234 outlet;
#X text 465 -274 c1 Vol Coarse c2 pan c3 folder c4 file c5 playback
c6 Control c7 Volumen fino 8 Entry point Coarse 9 Entry point fine
;
#X obj 106 -273 inlet;
#X obj 219 -270 inlet;
#X obj 106 -160 route 0 1 2 3 4;
#X obj 619 -56 outlet;
#X connect 0 0 11 0;
#X connect 8 0 10 0;
#X connect 9 0 0 0;
#X connect 9 0 6 0;
#X connect 10 0 1 0;
#X connect 10 1 2 0;
#X connect 10 2 3 0;
#X connect 10 3 4 0;
#X connect 10 4 5 0;
#X coords 0 466 1 465 0 0 0;

View file

@ -1,134 +0,0 @@
#N canvas 1 460 1700 561 10;
#X obj -297 249 layer_audio;
#X msg -673 125 \; pd dsp 1;
#X obj -400 57 loadbang;
#X msg -297 279 send 1 \$1;
#X obj -260 502 netsend;
#X msg -149 270 send 2 \$1;
#X msg -5 272 send 3 \$1;
#X msg 140 270 send 4 \$1;
#X msg 279 269 send 5 \$1;
#X msg 429 273 send 6 \$1;
#X msg 571 272 send 7 \$1;
#X msg 732 266 send 8 \$1;
#X obj -539 202 delay 50;
#X msg -539 224 send 0;
#X msg -704 203 connect localhost 9198;
#N canvas 1 110 1192 300 receive 0;
#X floatatom 380 -469 5 0 0 0 - - -;
#X obj 412 -371 route 201 202 203 204 205 206 207 208;
#X obj -197 -369 send dmx1;
#X obj 332 -369 send dmx8;
#X obj 259 -369 send dmx7;
#X obj 183 -369 send dmx6;
#X obj 110 -369 send dmx5;
#X obj 25 -369 send dmx4;
#X obj -48 -369 send dmx3;
#X obj -124 -369 send dmx2;
#X obj 118 -280 s file1;
#X obj 178 -280 s file2;
#X obj 240 -280 s file3;
#X obj 300 -280 s file4;
#X obj 358 -281 s file5;
#X obj 418 -281 s file6;
#X obj 480 -281 s file7;
#X obj 540 -281 s file8;
#X obj 207 -451 route 0 1 2 3 4 5 6 7;
#X obj 207 -486 netreceive 9197;
#X connect 1 0 10 0;
#X connect 1 1 11 0;
#X connect 1 2 12 0;
#X connect 1 3 13 0;
#X connect 1 4 14 0;
#X connect 1 5 15 0;
#X connect 1 6 16 0;
#X connect 1 7 17 0;
#X connect 18 0 2 0;
#X connect 18 1 9 0;
#X connect 18 2 8 0;
#X connect 18 3 7 0;
#X connect 18 4 6 0;
#X connect 18 5 5 0;
#X connect 18 6 4 0;
#X connect 18 7 3 0;
#X connect 18 8 1 0;
#X connect 19 0 18 0;
#X connect 19 1 0 0;
#X restore -156 105 pd receive;
#X obj -297 227 r dmx1;
#X obj -261 192 r file1;
#X obj -149 228 r dmx2;
#X obj -5 229 r dmx3;
#X obj 29 180 r file3;
#X obj 140 229 r dmx4;
#X obj 170 179 r file4;
#X obj 279 226 r dmx5;
#X obj 353 226 r file 5;
#X obj 429 230 r dmx6;
#X obj 503 228 r file6;
#X obj 571 227 r dmx7;
#X obj 645 226 r file 7;
#X obj 730 224 r dmx8;
#X obj 804 224 r file8;
#X obj -111 199 r file2;
#X msg -784 99 \; pd dsp 0;
#X obj -673 103 delay 100;
#X obj -5 251 layer_audio;
#X obj 140 250 layer_audio;
#X obj 279 249 layer_audio;
#X obj -149 251 layer_audio;
#X obj 429 253 layer_audio;
#X obj 571 250 layer_audio;
#X obj 730 246 layer_audio;
#X msg -269 326 send 9 0 1 \$1;
#X msg -126 337 send 9 0 2 \$1;
#X msg 4 318 send 9 0 3 \$1;
#X msg 147 323 send 9 0 4 \$1;
#X connect 0 0 3 0;
#X connect 0 1 41 0;
#X connect 2 0 14 0;
#X connect 2 0 12 0;
#X connect 2 0 32 0;
#X connect 2 0 33 0;
#X connect 3 0 4 0;
#X connect 5 0 4 0;
#X connect 6 0 4 0;
#X connect 7 0 4 0;
#X connect 8 0 4 0;
#X connect 9 0 4 0;
#X connect 10 0 4 0;
#X connect 11 0 4 0;
#X connect 12 0 13 0;
#X connect 13 0 4 0;
#X connect 14 0 4 0;
#X connect 16 0 0 0;
#X connect 17 0 0 1;
#X connect 18 0 37 0;
#X connect 19 0 34 0;
#X connect 20 0 34 1;
#X connect 21 0 35 0;
#X connect 22 0 35 1;
#X connect 23 0 36 0;
#X connect 24 0 36 1;
#X connect 25 0 38 0;
#X connect 26 0 38 1;
#X connect 27 0 39 0;
#X connect 28 0 39 1;
#X connect 29 0 40 0;
#X connect 30 0 40 1;
#X connect 31 0 37 1;
#X connect 33 0 1 0;
#X connect 34 0 6 0;
#X connect 34 1 43 0;
#X connect 35 0 7 0;
#X connect 35 1 44 0;
#X connect 36 0 8 0;
#X connect 37 0 5 0;
#X connect 37 1 42 0;
#X connect 38 0 9 0;
#X connect 39 0 10 0;
#X connect 40 0 11 0;
#X connect 41 0 4 0;
#X connect 42 0 4 0;
#X connect 43 0 4 0;
#X connect 44 0 4 0;

View file

@ -1,55 +0,0 @@
皾湏毄讍悊€潫憙嚈曀寑剛扰臓崙櫗泛疮鷼岸沪瓲驖か<EFBFBD><EFBFBD><EFBFBD><EFBFBD>堪彪Й称蛽咴斕与栧蚜赁尬履匾娤了脜绿衼祧<EFBFBD><EFBFBD><EFBFBD><EFBFBD>雠疰鬻惆<EFBFBD><EFBFBD>
堀阜刀ā相槜灜鬯勖
и拍媚菀<EFBFBD>彏帶寣巼秮憯剴€煥覆蝶趱毤丁窚但К煯缚<EFBFBD>溟驷钽伿谠訖<EFBFBD>
増唵檮儌劀煘潨嚉櫂棅晹搾崘<EFBFBD><EFBFBD><EFBFBD>┅沪イ⒕ 榭〖缓垢范胆
≡顡嫄欃稚惹婆拿禽肋掭苒谫<EFBFBD>
哦剨廖研镱盱腓蹊珂邃汊帱
<EFBFBD><EFBFBD>魂膂豸篁耩崚崒媻増噺<EFBFBD>
桋圯諐倽湜殭槜攭敁拺惎<EFBFBD><EFBFBD>
故貔铘赭<EFBFBD>綘烤郊缓护范荡巢睘<EFBFBD>
呖敂崐槡棕寐晾咿蒉勤儇字赵佄
枚安ū菌勘钩鼬汊徉<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>鲺趔<EFBFBD>
銋咽吓浭盅俾棙儌亐煘潥嚉櫂棖晹悗
冨耜镥皇鲴<EFBFBD><EFBFBD>臣烤郊缓归<EFBFBD>荡巢毕脱
拶稚惹婆拿垒肋掭苒谯<EFBFBD>
拍稍右研镱镳腙殍珂彐<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>鲺趔蝰饙<EFBFBD>
煘棅増噯厔仦亐煘潨洏<EFBFBD>
妳姇敁拺惎<EFBFBD><EFBFBD><EFBFBD>ěΗ<EFBFBD>
卑綘烤郊缓护范荡巢蓖<EFBFBD>
咿资扇瞧拍赁晾咿蒈圬<EFBFBD>
刈中扔已畜铐潆鲩桤琦溷赆<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>牾趔黜饛帊悑妷帥唴寖<EFBFBD>
亐煔亷<EFBFBD>妊厞晹搾崘<EFBFBD><EFBFBD>┅沪イ<EFBFBD>
郊痪オ则牯‘毕夏兴适邵婆穆蘖肋掭苒谂
刈盅攘皠摢掣<EFBFBD>觊脲<EFBFBD>溏除<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>鲺麸
蝰饖挓筝軟攪唴劅倎仐倽湜泤槜枙敁拺<EFBFBD>
<EFBFBD><EFBFBD>犯婶鲲黪瘗臣烤嫉Ш够丢荡吵<EFBFBD>瓮趟噬熔
婆拿铝肋<EFBFBD>
蒈圳儇字稍右研镱眇腙殍珂邃<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>鲺趔蝽饛帊寢妷攪唴剝倎€優潨洑櫂棅晹搾憪<EFBFBD><EFBFBD>Е<EFBFBD>烤郊Ш垢范荡钞毕瓮趟噬郧婆拿铝烂掭苒谫刈收杂已酗铖
<EFBFBD>鲩桤驽溷恺<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>鲺趔铖饛帒寢妷<EFBFBD>
噯厔儌亣優湝泦櫃枱墧捛悓
<EFBFBD><EFBFBD><EFBFBD>┊沪が<EFBFBD>烤〖翰工
范荡巢馍彝趟收惹婆孛铝烂
掭苒谫嬓收杂彝酗铐痣觊棼
驽溷忉锄恺<EFBFBD><EFBFBD><EFBFBD>鲺梵篑驌
帊寢妷蹆殔厓倽€煘潃洓櫂<EFBFBD>
枙敁拺惃箔<EFBFBD><EFBFBD>ěΕ
窘蓟汗攵<EFBFBD>闯箔衔吞资扇勤
拍寐晾屵淋圳倌字赵弦研矧
盱腙殍存<EFBFBD>汊狳<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
豸篁耩軒憣媻墧噯厔焸亐焸
潨洑櫂臇墧搾憣<EFBFBD><EFBFBD>藩┄Ш
<EFBFBD>炀〖缓工范荡<EFBFBD>毕窝
趟噬惹暸孛铝烂掭苒瀑刈稚
杂已酗巾痣觊棼驽溷<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
<EFBFBD><EFBFBD><EFBFBD>ヵ梵蝰饟帊寢枆垏啓
柵偀€湆<EFBFBD>
湜殭剠剦唩巸偝<EFBFBD><EFBFBD>订ěЧぃ伎窘姬汗缚<EFBFBD>闯脖衔托
耸扇瞧牌<EFBFBD>
杏芡塘紊<EFBFBD>
倨字赵右托耦盱腙轸瑛邃汊徉泾泓<EFBFBD><EFBFBD>麝蹶篁耩弾憣晩増噯厴
憪潃煘潃
泦檮棅晥搸憣<EFBFBD><EFBFBD><EFBFBD>Е<EFBFBD>
⒔牐尽姬亥斧订疮箔弦托
酥稍勤
<EFBFBD>

View file

@ -1,27 +1,110 @@
#include "audiolayerwidget.h" #include "audiolayerwidget.h"
#include<iostream>
#include <QDebug>
#include <QVBoxLayout>
#include <QFile>
#include <QTime>
//#include <time.h> // nanosleep y la chapuza de liberar el buffer
AudioLayerWidget::AudioLayerWidget(QWidget *parent, QString name): AudioLayerWidget::AudioLayerWidget(QWidget *parent, QString name):
QGroupBox(parent) QGroupBox(parent)
, m_suspendResumeButton(0)
, m_watchDMX(new QTimer(this))
// , m_progressCounter(new QTime(0,0,0,1))
// , m_progressMs(0)
, m_currentMedia(" ")
, m_running(false)
{ {
Q_UNUSED(parent);
this->setTitle(name);
folder = new QLabel(this);
folder->setMaximumWidth(150);
file = new QLabel(this);
file->setMaximumWidth(150);
status = new QLabel(this);
vol = new QSlider(Qt::Horizontal, this);
vol->setMaximum(99);
vol->setMaximumWidth(150);
// mute = new QCheckBox(this);
QVBoxLayout *vbox = new QVBoxLayout; this->setTitle(name);
vbox->addWidget(folder);
vbox->addWidget(file); QVBoxLayout *layout = new QVBoxLayout;
vbox->addWidget(status);
vbox->addWidget(vol); QHBoxLayout *status = new QHBoxLayout;
// vbox->addWidget(mute); m_statusLabel = new QLabel;
this->setLayout(vbox); m_statusLabel->setText(STATUS_LABEL);
m_statusValue = new QLabel;
// m_receiveDMX = new QCheckBox("Receiving DMX", this);
// m_receiveDMX->setChecked(false);
// status->addWidget(m_receiveDMX);
status->addWidget(m_statusLabel);
status->addWidget(m_statusValue);
layout->addLayout(status);
QHBoxLayout *folderLoaded = new QHBoxLayout;
m_folderLabel = new QLabel;
m_folderLabel->setText(FOLDER_LABEL);
m_folderValue = new QLabel;
m_folderValue->setMaximumWidth(150);
folderLoaded->addWidget(m_folderLabel);
folderLoaded->addWidget(m_folderValue);
layout->addLayout(folderLoaded);
QHBoxLayout *fileLoaded = new QHBoxLayout;
m_fileLabel = new QLabel;
m_fileLabel->setText(FILE_LABEL);
m_fileValue = new QLabel;
m_fileValue->setMaximumWidth(150);
fileLoaded->addWidget(m_fileLabel);
fileLoaded->addWidget(m_fileValue);
layout->addLayout(fileLoaded);
QHBoxLayout *volumeBox = new QHBoxLayout;
m_volumeLabel = new QLabel;
m_volumeLabel->setText(tr(VOLUME_LABEL));
m_volumeSlider = new QSlider(Qt::Horizontal);
m_volumeSlider->setMinimum(0);
m_volumeSlider->setMaximum(80);
m_volumeSlider->setSingleStep(1);
connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(volumeChanged(int)));
volumeBox->addWidget(m_volumeLabel);
volumeBox->addWidget(m_volumeSlider);
layout->addLayout(volumeBox);
QGridLayout *progressTime = new QGridLayout;
m_progressTimeLabel = new QLabel;
m_progressTimeLabel->setText(PROGRESS_TIME_LABEL);
m_progressTime = new QTimeEdit;
m_progressTime->text();
m_progressTime->setDisplayFormat("h:mm:ss:zzz");
m_progressTime->setReadOnly(true);
m_progressTime->setButtonSymbols(QAbstractSpinBox::NoButtons);
m_progressTime->setMaximumWidth(80);
progressTime->addWidget(m_progressTimeLabel, 0 ,0);
progressTime->addWidget(m_progressTime,0 ,1);
m_totalTimeLabel = new QLabel;
m_totalTimeLabel->setText(TOTAL_TIME_LABEL);
m_totalTimeValue = new QTimeEdit;
m_totalTimeValue->setDisplayFormat("h:mm:ss:zzz");
m_totalTimeValue->setReadOnly(true);
m_totalTimeValue->setButtonSymbols(QAbstractSpinBox::NoButtons);
m_totalTimeValue->setMaximumWidth(80);
progressTime->addWidget(m_totalTimeLabel,1 , 0);
progressTime->addWidget(m_totalTimeValue, 1 ,1);
layout->addLayout(progressTime);
QHBoxLayout *progressSlider = new QHBoxLayout;
m_progressLabel = new QLabel;
m_progressLabel->setText(PROGRESS_LABEL);
m_progressSlider = new QSlider(Qt::Horizontal);
progressSlider->addWidget(m_progressLabel);
progressSlider->addWidget(m_progressSlider);
layout->addLayout(progressSlider);
m_suspendResumeButton = new QPushButton(this);
m_suspendResumeButton->setText(tr(SUSPEND_LABEL));
connect(m_suspendResumeButton, SIGNAL(clicked()), SLOT(toggleSuspendResume()));
layout->addWidget(m_suspendResumeButton);
this->setLayout(layout);
connect(m_watchDMX, SIGNAL(timeout()),
this, SLOT(watchDMXExpired()));
m_watchDMX->start(243);
} }
AudioLayerWidget::~AudioLayerWidget() AudioLayerWidget::~AudioLayerWidget()
@ -29,3 +112,129 @@ AudioLayerWidget::~AudioLayerWidget()
} }
void AudioLayerWidget::volumeChanged(int value)
{
m_music.setVolume(value);
}
// volume range 0 -100
void AudioLayerWidget::setVol(qreal vol)
{
m_music.setVolume(vol);
m_volumeSlider->blockSignals(true);
m_volumeSlider->setValue(vol);
m_volumeSlider->blockSignals(false);
}
void AudioLayerWidget::loadMedia(QString file)
{
if (m_currentMedia == file ) {
fileLoaded(file);
return;
}
if (!QFile::exists(file)) {
qWarning("Can not access to file %s", file.toLatin1().constData());
return;
}
// Load an ogg music file
if (!m_music.openFromFile(file.toStdString())) {
qWarning("Can not open file %s", file.toLatin1().constData());
return;
}
m_music.setAttenuation(0);
// m_progressCounter->restart();
durationChanged(m_music.getDuration().asMilliseconds());
fileLoaded(file);
// Display music informations
std::cout << "File loaded: " << file.toLatin1().constData() << " : " << std::endl;
std::cout << " " << m_music.getDuration().asSeconds() << " seconds";
std::cout << " " << m_music.getSampleRate() << " samples / sec";
std::cout << " " << m_music.getChannelCount() << " channels";
}
void AudioLayerWidget::fileLoaded(QString file)
{
QStringList list = file.split("/");
int size = list.size();
if (size >= 2) {
m_folderValue->setText(list.at(size - 2));
m_fileValue->setText(list.at(size - 1));
}
// m_progressMs = 0;
// m_progressTime->setTime(QTime::fromMSecsSinceStartOfDay(m_progressMs));
}
/*
void AudioLayerWidget::notified()
{
}
*/
// duration in miliseconds
void AudioLayerWidget::durationChanged(qint64 dur)
{
m_progressSlider->setMaximum(dur);
m_totalTimeValue->setTime(QTime::fromMSecsSinceStartOfDay(dur));
}
void AudioLayerWidget::play()
{
m_music.play();
// m_progressCounter->restart();
}
void AudioLayerWidget::pause()
{
m_music.pause();
// m_progressCounter->restart();
}
void AudioLayerWidget::stop()
{
m_music.stop();
}
void AudioLayerWidget::watchDMXExpired() {
// m_receiveDMX->setChecked(false);
int progress;
switch (m_music.getStatus()) {
case sf::SoundSource::Playing:
// m_progressMs += m_progressCounter->restart();
progress = m_music.getPlayingOffset().asMilliseconds();
m_progressSlider->setValue(progress);
m_progressTime->setTime(QTime::fromMSecsSinceStartOfDay(progress));
m_statusValue->setText(PLAY_LABEL);
m_suspendResumeButton->setText(tr(SUSPEND_LABEL));
break;
case sf::SoundSource::Paused:
m_statusValue->setText(PAUSE_LABEL);
m_suspendResumeButton->setText(tr(RESUME_LABEL));
break;
case sf::SoundSource::Stopped:
// m_progressCounter->restart();
// m_progressMs = 0;
m_progressTime->setTime(QTime::fromMSecsSinceStartOfDay(0));
m_statusValue->setText(STOP_LABEL);
m_suspendResumeButton->setText(tr(RESUME_LABEL));
m_progressSlider->setValue(0);
break;
}
}
/*
void AudioLayerWidget::updateWatchDMX(bool b)
{
// m_receiveDMX->setChecked(b);
}
*/
void AudioLayerWidget::toggleSuspendResume()
{
if (m_music.getStatus() == sf::SoundSource::Playing) {
m_music.pause();
// m_suspendResumeButton->setText(tr(SUSPEND_LABEL));
} else {
m_music.play();
// m_suspendResumeButton->setText(tr(PLAY_LABEL));
}
}

View file

@ -1,13 +1,21 @@
#ifndef AUDIOLAYERWIDGET_H #ifndef AUDIOLAYERWIDGET_H
#define AUDIOLAYERWIDGET_H #define AUDIOLAYERWIDGET_H
#include <QtGui> #include <QByteArray>
//#include "ui_audiolayerwidget.h" #include <QLabel>
/* #include <QPushButton>
namespace Ui { #include <QSlider>
class AudioLayerWidget; #include <QTimer>
}*/ #include <QTime>
#include <QTimeEdit>
#include <QGroupBox>
#include <QCheckBox>
#include "SFML/Audio.hpp"
#include "SFML/System.hpp"
#include "defines.h"
class AudioLayerWidget : public QGroupBox class AudioLayerWidget : public QGroupBox
{ {
@ -15,31 +23,66 @@ class AudioLayerWidget : public QGroupBox
public: public:
AudioLayerWidget(QWidget *parent, QString name); explicit AudioLayerWidget(QWidget *parent = 0, QString name = "Layer");
~AudioLayerWidget(); ~AudioLayerWidget();
inline void setFile(QString file) const void loadMedia(QString file);
{ void play();
this->file->setText(file); void stop();
} void pause();
void setVol(qreal vol);
void resume();
// void updateWatchDMX(bool b);
inline void setFolder(QString folder) const public slots:
{
this->folder->setText(folder);
}
inline void setVol(float vol) const
{
this->vol->setValue(vol);
}
void toggleSuspendResume();
void volumeChanged(int vol);
private: private:
QLabel *file;
QLabel *folder; QPushButton *m_suspendResumeButton;
QSlider *vol;
// QCheckBox *mute; QLabel *m_statusLabel;
QLabel *status; QLabel * m_statusValue;
QLabel *m_volumeLabel;
QSlider *m_volumeSlider;
QLabel * m_progressLabel;
QSlider *m_progressSlider;
QLabel *m_progressTimeLabel;
QTimeEdit *m_progressTime;
QLabel *m_totalTimeLabel;
QTimeEdit *m_totalTimeValue;
QLabel *m_fileLabel;
QLabel *m_fileValue;
QLabel * m_folderLabel;
QLabel * m_folderValue;
QCheckBox *m_receiveDMX;
QTimer *m_watchDMX;
// QTime *m_progressCounter;
// quint64 m_progressMs;
QString m_currentMedia;
bool m_running;
sf::Music m_music;
private slots:
// void notified();
void fileLoaded(QString file);
void durationChanged(qint64 dur);
void watchDMXExpired();
}; };
#endif // AUDIOLAYERWIDGET_H #endif // AUDIOLAYERWIDGET_H

View file

@ -1,5 +1,7 @@
#include "audiomasterwidget.h" #include "audiomasterwidget.h"
#include <QVBoxLayout>
AudioMasterWidget::AudioMasterWidget(QWidget *parent) : AudioMasterWidget::AudioMasterWidget(QWidget *parent) :
QGroupBox(parent) QGroupBox(parent)
, m_file(new QLabel) , m_file(new QLabel)
@ -14,6 +16,7 @@ AudioMasterWidget::AudioMasterWidget(QWidget *parent) :
// vbox->addWidget(status); // vbox->addWidget(status);
// vbox->addWidget(vol); // vbox->addWidget(vol);
// vbox->addWidget(mute); // vbox->addWidget(mute);
m_receiveDMX->setText("Receiving DMX");
vbox->addWidget(m_receiveDMX); vbox->addWidget(m_receiveDMX);
this->setLayout(vbox); this->setLayout(vbox);
connect(m_watchDMX, SIGNAL(timeout()), connect(m_watchDMX, SIGNAL(timeout()),

View file

@ -5,6 +5,8 @@
#include <QLabel> #include <QLabel>
#include <QSlider> #include <QSlider>
#include <QCheckBox> #include <QCheckBox>
#include <QGroupBox>
//#include "ui_audiomasterwidget.h" //#include "ui_audiomasterwidget.h"
@ -37,8 +39,6 @@ private:
private slots: private slots:
void watchDMXExpired(); void watchDMXExpired();
}; };
#endif // AUDIOMASTERWIDGET_H #endif // AUDIOMASTERWIDGET_H

View file

@ -1,385 +0,0 @@
#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_gui(true),
m_layersNumber(0),
m_pd_audio(NULL),
m_writePD(NULL),
m_readPD(NULL),
m_connectedSocket(NULL),
m_startaudio(0)
{
qsrand(qrand());
/* 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());
emit toTerminal(QString("AudioMotor::init() can not init TCP Server on port)" + PDPORT));
}
// 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()));
qDebug() << "Init MotorAudio";
}
AudioMotor::~AudioMotor()
{
close();
}
/** Init the engine
*/
bool AudioMotor::init()
{
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");
m_pd_audio->start(arguments);
if (m_pd_audio->waitForStarted(3000)){
qDebug("AudioMotor| PD started");
emit toTerminal(QString("AudioMotor| PD started"));
}
else
{
emit toTerminal("AudioMotor| Can not init PD");
qErrnoWarning("AudioMotor| Can not init PD");
return false;
}
m_startaudio++;
return true;
}
/** Close the engine
*/
void AudioMotor::close()
{
// disconnect(m_pd_audio, SIGNAL(readyReadStandardError()), this, SLOT(stdout()));
disconnect(m_pd_audio, SIGNAL(finished(int)), this, SLOT(restartAudio()));
// if (!m_pd_audio->waitForFinished(1000))
m_pd_audio->terminate();
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){
Q_UNUSED(layers);
}
/** Get the number of layers
*/
int AudioMotor::getlayers(){
return m_layersNumber;
}
/** 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: ");
emit toTerminal("AudioMotor::load(): Socket not connectedt");
return false;
}
if (message.size() != m_writePD->write(message.toAscii().constData(), message.size()))
{
qErrnoWarning("AudioMotor::load(): Can not write to socket");
emit toTerminal("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)
{
Q_UNUSED(layer);
Q_UNUSED(entry);
}
/** Sets the final playback position
*
*/
void AudioMotor::setExitPoint(int layer, int exit)
{
Q_UNUSED(layer);
Q_UNUSED(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){
Q_UNUSED(vol);
}
/** Set pan master
* Will pan the master output of sound
*/
void AudioMotor::setMasterPan(int pan){
Q_UNUSED(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...");
emit toTerminal("AudioMotor::newMessage() Socket not connected. Trying open it...");
newPeer();
return;
}
QString message = m_connectedSocket->readAll();
parse(message);
}
void AudioMotor::parse(QString message)
{
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";
emit toTerminal("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();
connect(m_pd_audio, SIGNAL(finished(int)), this, SLOT(restartAudio()));
}
break;
case 9:
if (list.at(i).at(2).digitValue() == 0) {
if (list.at(i).at(7).isDigit() )
emit (volChanged(list.at(i).at(4).digitValue(), ( ( list.at(i).at(6).digitValue() * 10 ) + list.at(i).at(7).digitValue() ) ) );
else
emit (volChanged(list.at(i).at(4).digitValue(), ( ( list.at(i).at(6).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)
{
qErrnoWarning(QString("AudioMotor::errorWrite() %1").arg(error).toLatin1());
emit toTerminal(QString("AudioMotor::errorWrite() ") + error);
}
/** 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";
emit toTerminal("AudioMotor| Can not send packets to PD");
}

View file

@ -1,141 +0,0 @@
#ifndef AUDIOMOTOR_H
#define AUDIOMOTOR_H
#include <QObject>
#include <QtDebug>
#include <QtNetwork>
#include <QTcpServer>
#include <QLocalSocket>
#include <QTcpSocket>
#include <QChar>
#include "dmxPersonality.h"
#include "defines.h"
class AudioMotor : public QObject
{
Q_OBJECT
public:
static AudioMotor *getInstance();
/** Init the engine
*/
bool init();
/** Close the engine
*/
void 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);
void toTerminal(QString message);
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

View file

@ -1,30 +1,61 @@
#include "audiowidget.h" #include "audiowidget.h"
AudioWidget::AudioWidget(QWidget *parent) : AudioWidget *AudioWidget::_instance = 0;
QWidget(parent)
AudioWidget *AudioWidget::getInstance() {
if (_instance == 0) {
_instance = new AudioWidget();
Q_CHECK_PTR(_instance);
}
return _instance;
}
AudioWidget::AudioWidget()
{ {
layout = new QHBoxLayout(); layout = new QHBoxLayout();
for (int i= 0; i < LAYERS_NUMBER; i++ ) { for (int i= 0; i < Settings::getInstance()->getLayersNumber(); i++ ) {
// Conectar los slots
layout->insertWidget(i, new AudioLayerWidget(this, tr("Layer %1").arg(i))); layout->insertWidget(i, new AudioLayerWidget(this, tr("Layer %1").arg(i)));
} }
setLayout(layout); setLayout(layout);
qDebug( "Init AudioWidget"); // qDebug( "Init AudioWidget");
} }
void AudioWidget::mediaLoaded(int layer, QString folder, QString file) void AudioWidget::mediaLoaded(int layer, QString media)
{ {
QLayoutItem * const item = layout->itemAt(layer - 1); QLayoutItem * const item = layout->itemAt(layer);
/* qDebug() << "AudioWidget::mediaLoaded Received layer: " << layer dynamic_cast<AudioLayerWidget *>(item->widget())->loadMedia(media);
<< "Folder: " << folder // qDebug() << "AudioWidget::mediaLoaded Received layer: " << layer
<<"File : " << file;*/ // << "Media: " << media;
dynamic_cast<AudioLayerWidget *>(item->widget())->setFolder(folder);
dynamic_cast<AudioLayerWidget *>(item->widget())->setFile(file);
} }
void AudioWidget::volChanged(int layer, int vol) { void AudioWidget::volChanged(int layer, qreal vol) {
QLayoutItem * const item = layout->itemAt(layer - 1); QLayoutItem * const item = layout->itemAt(layer);
/*qDebug() << "AudioWidget::volChanged Received layer: " << layer
<< "Vol : " << vol;*/
dynamic_cast<AudioLayerWidget *>(item->widget())->setVol(vol); dynamic_cast<AudioLayerWidget *>(item->widget())->setVol(vol);
// qDebug() << "AudioWidget::volChanged Received layer: " << layer
// << "Vol : " << vol;
} }
void AudioWidget::playbackChanged(int layer, Status status)
{
QLayoutItem * const item = layout->itemAt(layer);
switch (status) {
case Playing:
dynamic_cast<AudioLayerWidget *>(item->widget())->play();
break;
case Stopped:
dynamic_cast<AudioLayerWidget *>(item->widget())->stop();
break;
case Paused:
dynamic_cast<AudioLayerWidget *>(item->widget())->pause();
break;
}
}
/*
void AudioWidget::layerReceived(int layer)
{
QLayoutItem * const item = layout->itemAt(layer);
dynamic_cast<AudioLayerWidget *>(item->widget())->updateWatchDMX(true);
}*/

View file

@ -7,27 +7,34 @@
#include "audiomasterwidget.h" #include "audiomasterwidget.h"
#include "audiolayerwidget.h" #include "audiolayerwidget.h"
#include "defines.h" #include "defines.h"
#include "settings.h"
#include "SFML/Audio/SoundSource.hpp"
class AudioWidget : public QWidget class AudioWidget : public QWidget
{ {
friend class libreMediaServerAudio;
Q_OBJECT Q_OBJECT
public: public:
AudioWidget(QWidget *parent); protected:
static AudioWidget *getInstance();
void mediaLoaded(int layer, QString media );
void volChanged(int layer, qreal vol);
void playbackChanged(int layer, Status status);
private: private:
// QList<AudioLayerWidget*> *list; static AudioWidget *_instance;
AudioWidget();
QHBoxLayout *layout; QHBoxLayout *layout;
signals: signals:
public slots: public slots:
void mediaLoaded(int layer, QString folder, QString file);
void volChanged(int layer, int vol);
}; };

View file

@ -1,18 +1,39 @@
#ifndef DEFINES_H #ifndef DEFINES_H
#define DEFINES_H #define DEFINES_H
#define LAYERS_NUMBER 3 #define VERSION "LibreMediaServer-Audio 0.1.1"
// Ports tcp to comunicate with Pure Data
#define PDPORT 9198
#define SOCKET 9197 // "/tmp/socket"
#define VERSION "Libre Media Server Audio 0.1.0"
#define COPYRIGHT "(C) 2014 Santi Norena libremediaserver@gmail.com" #define COPYRIGHT "(C) 2014 Santi Norena libremediaserver@gmail.com"
#define LICENSE "GPL 3 License. See LICENSE.txt and credits.txt for details" #define LICENSE "GPL 3 License. See LICENSE.txt and credits.txt for details"
#define LAYERS_NUMBER 3
#define DEFAULT_FILE "lms-audio.xlm" #define DEFAULT_FILE "lms-audio.xlm"
const int DurationSeconds = 1;
const int ToneSampleRateHz = 600;
const int DataSampleRateHz = 44100;
const int BufferSize = 262144;
#define SUSPEND_LABEL "Pause playback"
#define RESUME_LABEL "Resume playback"
#define PLAY_LABEL "Playing"
#define STOP_LABEL "Stopped"
#define PAUSE_LABEL "Pause"
#define IDDLE_LABEL "Iddle playback"
#define VOLUME_LABEL "Volume"
#define PROGRESS_LABEL "Progress"
#define PROGRESS_TIME_LABEL "Current"
#define REMAINING_TIME "Remaining Time: "
#define TOTAL_TIME_LABEL "Total"
#define FILE_LABEL "File:"
#define FOLDER_LABEL "Folder:"
#define STATUS_LABEL " Status: "
#define NOTIFY_INTERVAL 150
#define PULL_TIMER_INTERVAL 10
// struct where save the DMX settings for each layer // struct where save the DMX settings for each layer
struct dmxSetting { struct dmxSetting {
int address; int address;
@ -36,5 +57,12 @@ struct MediaFolder {
QList<MediaFile> m_MediaInformation; // Pointer to the Medias Information List of this Library QList<MediaFile> m_MediaInformation; // Pointer to the Medias Information List of this Library
}; };
enum Status
{
Stopped, ///< Sound is not playing
Paused, ///< Sound is paused
Playing ///< Sound is playing
};
#endif // DEFINES_H #endif // DEFINES_H

View file

@ -18,6 +18,8 @@
*/ */
#include "libremediaserver-audio.h" #include "libremediaserver-audio.h"
// QTextEdit * libreMediaServerAudio::textEdit = 0;
/** /**
/ Constructor / Constructor
*/ */
@ -25,30 +27,44 @@
libreMediaServerAudio::libreMediaServerAudio(QStringList args, QWidget *parent) libreMediaServerAudio::libreMediaServerAudio(QStringList args, QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
{ {
qDebug() << "********************************************************************************"; Q_UNUSED(args);
qDebug() << QDate::currentDate() << QTime::currentTime();
qDebug() << VERSION;
qDebug() << COPYRIGHT;
qDebug() << LICENSE;
// Inicia el User Interface
ui.setupUi(this); ui.setupUi(this);
this->setWindowTitle(VERSION); this->setWindowTitle(VERSION);
// Inicia el widget Terminal // Lee la configuración por defecto
textEdit = new QTextEdit(this); Settings::getInstance()->readFile();
textEdit->append(QString::fromAscii(VERSION));
textEdit->append(QString::fromAscii(LICENSE));
textEdit->append(QString::fromAscii(COPYRIGHT));
// Inicia el objeto de conexión a ola
ola = new olaThread();
Q_CHECK_PTR(ola);
/*
if (args.contains("-log")) {
// Inicia el widget Terminal
textEdit = new QTextEdit;
textEdit->setReadOnly(true);
QDockWidget *bottomWidget = new QDockWidget(tr("Terminal"), this); QDockWidget *bottomWidget = new QDockWidget(tr("Terminal"), this);
bottomWidget->setAllowedAreas(Qt::BottomDockWidgetArea); bottomWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
bottomWidget->setWidget(textEdit); bottomWidget->setWidget(textEdit);
addDockWidget(Qt::BottomDockWidgetArea, bottomWidget); addDockWidget(Qt::BottomDockWidgetArea, bottomWidget);
connect(ola, SIGNAL(toTerminal(QString)),
textEdit, SLOT(append(QString)), Qt::QueuedConnection);
}*/
// Inicia el widget central de audio /* connect(MediaLibrary::getInstance(), SIGNAL(debug(QString)),
aw = new AudioWidget(this); textEdit, SLOT(append(QString)), Qt::QueuedConnection);
setCentralWidget(aw);
connect(MediaLibrary::getInstance(), SIGNAL(warning(QString)),
textEdit, SLOT(append(QString)), Qt::QueuedConnection);
*/
this->setWindowTitle(VERSION);
// qDebug() << QDate::currentDate().toString() << " "<< QTime::currentTime().toString();
qDebug() << VERSION;
qDebug() << COPYRIGHT;
qDebug() << LICENSE;
setCentralWidget(AudioWidget::getInstance());
// Inicia el widget Master. // Inicia el widget Master.
amw = new AudioMasterWidget(this); amw = new AudioMasterWidget(this);
@ -63,63 +79,23 @@ libreMediaServerAudio::libreMediaServerAudio(QStringList args, QWidget *parent)
connect(ui.actionChange_Media_Path, SIGNAL(triggered()), this, SLOT(ChangeMediaPath())); connect(ui.actionChange_Media_Path, SIGNAL(triggered()), this, SLOT(ChangeMediaPath()));
connect(ui.actionLaunch_OLA_Setup, SIGNAL(triggered()), this, SLOT(olasetup())); connect(ui.actionLaunch_OLA_Setup, SIGNAL(triggered()), this, SLOT(olasetup()));
Settings *set = new Settings(); connect(Settings::getInstance(), SIGNAL( registerUniverse(int) ),
ola, SLOT( registerUniverse(int) ) );
// Inicia la lectura de dmx a través de ola ola->registerUniverse(); // register now all the universes
ola = new olaThread();
Q_CHECK_PTR(ola);
connect(ola, SIGNAL(toTerminal(QString)),
this, SLOT(toTerminal(QString)));
ola->start(QThread::TimeCriticalPriority );
ola->blockSignals(true); ola->blockSignals(true);
connect(ola, SIGNAL (layerReceived()),
connect(set, SIGNAL( layersNumber(int)),
ola, SLOT( setLayersNumber(int)));
connect(set, SIGNAL( DMXConf(dmxSetting ) ),
ola, SLOT( setDMXConf(dmxSetting) ) );
// Lee la configuración por defecto
if (!set->readDefaultFile()) {
// Dar la oportunidad de cargar otro fichero de configuración
// Crear el fichero por defecto.
}
// 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); }
connect(AudioMotor::getInstance(), SIGNAL(toTerminal(QString)),
this, SLOT(toTerminal(QString)));
if (args.contains("-log"))
{
textEdit->append("Logging to file");
}
// Iniciamos Pure Data
connect(AudioMotor::getInstance(), SIGNAL(loadbang()),
this, SLOT (loadbang()));
AudioMotor::getInstance()->init();
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(ola, SIGNAL( dmxOutput(int, int, int) ),
this, SLOT( dmxInput(int, int, int) ) );
connect(ola, SIGNAL(universeReceived(uint)),
amw, SLOT(updateWatchDMX())); amw, SLOT(updateWatchDMX()));
// Inicia la media Library
MediaLibrary::getInstance()->initMediaLibrary();
// Inicia la lectura de datos DMX
ola->start(QThread::TimeCriticalPriority );
ola->blockSignals(false); ola->blockSignals(false);
connect(ola, SIGNAL( dmxOutput(int, int, int) ),
this, SLOT( dmxInput(int, int, int) ) );
ola->resendDmx();
qDebug("Init Complete");
} }
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
@ -128,14 +104,9 @@ libreMediaServerAudio::libreMediaServerAudio(QStringList args, QWidget *parent)
libreMediaServerAudio::~libreMediaServerAudio() libreMediaServerAudio::~libreMediaServerAudio()
{ {
// save_finish();
// delete MediaLibrary::getInstance();
ola->stop(); ola->stop();
AudioMotor::getInstance()->close(); // qDebug() << QDate::currentDate() << QTime::currentTime();
// qDebug() << "PD Audio restarts: " << m_startaudio; // qDebug() << "********************************************************************************";
qDebug() << QDate::currentDate() << QTime::currentTime();
qDebug() << "********************************************************************************";
// return;
} }
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
@ -175,9 +146,9 @@ void libreMediaServerAudio::ChangeMediaPath()
return; return;
fileNames = dialog.selectedFiles(); fileNames = dialog.selectedFiles();
QString file = fileNames.at(0); QString file = fileNames.at(0);
MediaLibrary::getInstance()->setPath(file); Settings::getInstance()->setPathMedia(file);
QString desc = tr("Media Path Changed to: %1").arg(m_pathmedia); QString desc = tr("Media Path Changed to: %1").arg(file);
textEdit->append(desc.toAscii()); qDebug(desc.toLatin1().constData());
} }
@ -199,57 +170,51 @@ 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 // 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; // qDebug() << tr("olaInterface|") << "newdmx layer" << layer << "channel" << channel << "value" << value;
if (layer > LAYER_CHANNELS)
return;
QString mediaFile = NULL; QString mediaFile = NULL;
int aux; int aux;
float f; qreal f;
switch(channel){ switch(channel){
case DMX_FOLDER:// Folder case DMX_FOLDER:// Folder
aux = ola->getValue(layer, DMX_FILE); aux = ola->getValue(layer, DMX_FILE);
mediaFile = MediaLibrary::getInstance()->requestNewFile(value, aux); mediaFile = MediaLibrary::getInstance()->requestNewFile(value, aux);
if (QFile::exists(mediaFile)) if (QFile::exists(mediaFile))
AudioMotor::getInstance()->load(layer, mediaFile); AudioWidget::getInstance()->mediaLoaded(layer, mediaFile);
break; break;
case DMX_FILE:// File case DMX_FILE:// File
aux = ola->getValue(layer, DMX_FOLDER); aux = ola->getValue(layer, DMX_FOLDER);
mediaFile = MediaLibrary::getInstance()->requestNewFile(aux, value); mediaFile = MediaLibrary::getInstance()->requestNewFile(aux, value);
if (QFile::exists(mediaFile)) if (QFile::exists(mediaFile))
AudioMotor::getInstance()->load(layer, mediaFile); AudioWidget::getInstance()->mediaLoaded(layer, mediaFile);
break; break;
case VOLUME_COARSE: case VOLUME_COARSE:
f = ( value * 0x100 ) + ola->getValue(layer, VOLUME_FINE); f = ( value * 0x100 ) + ola->getValue(layer, VOLUME_FINE);
AudioMotor::getInstance()->setLayerVolume(layer, f/655.35); AudioWidget::getInstance()->volChanged(layer, f / 655.35);
break; break;
case VOLUME_FINE: case VOLUME_FINE:
f = ( ola->getValue(layer, VOLUME_COARSE) * 0x100 ) + value; f = ( ola->getValue(layer, VOLUME_COARSE) * 0x100 ) + value;
AudioMotor::getInstance()->setLayerVolume(layer, f/655.35); AudioWidget::getInstance()->volChanged(layer, f / 655.35);
break; break;
case PAN: case PAN:
f = (float)value / 255; f = (float)value / 255;
AudioMotor::getInstance()->setLayerPan(layer, f );
break; break;
case PLAYBACK: case PLAYBACK:
if (value == 0)
break;
aux = value / 25; aux = value / 25;
switch (aux) { switch (aux) {
case 0 : case 0 :
AudioMotor::getInstance()->play(layer); AudioWidget::getInstance()->playbackChanged(layer, Playing);
break; break;
case 1 : case 1 :
AudioMotor::getInstance()->stop(layer); AudioWidget::getInstance()->playbackChanged(layer, Stopped);
break; break;
case 2 : case 2 :
AudioMotor::getInstance()->pause(layer); AudioWidget::getInstance()->playbackChanged(layer, Paused);
break; break;
} }
default: default:
// emit dmxInput(layer, channel, value);
break; break;
} }
} }
/**
* Send the DMX info to Pure Data in init
*
*/
void libreMediaServerAudio::loadbang() {
ola->resendDmx();
}

View file

@ -16,36 +16,30 @@
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef LIBREMEDIASERVER_H #ifndef LIBREMEDIASERVERAUDIO_H
#define LIBREMEDIASERVER_H #define LIBREMEDIASERVERAUDIO_H
#include <QMainWindow> #include <QMainWindow>
//#include <QApplication> #include <QDockWidget>
#include <QObject>
#include <QDesktopWidget>
#include <QtGui>
#include <QFile> #include <QFile>
#include <QFileInfo> #include <QFileInfo>
#include <QFileDialog> #include <QFileDialog>
#include <QTextStream> #include <QTextStream>
#include <QWebView> #include <QWebView>
#include <QUrl> //#include <QUrl>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QTextEdit> #include <QTextEdit>
#include "settings.h" #include "medialibrary.h"
#include "audiomotor.h"
#include "olathread.h"
#include "audiolayerwidget.h"
#include "audiomasterwidget.h"
#include "audiowidget.h" #include "audiowidget.h"
#include "settings.h"
#include "olathread.h"
#include "audiomasterwidget.h"
#include "defines.h" #include "defines.h"
#include "ui_libremediaserver-audio.h" #include "ui_libremediaserver-audio.h"
class QMenu; class QMenu;
//class QProcess;
class libreMediaServerAudio : public QMainWindow class libreMediaServerAudio : public QMainWindow
{ {
@ -58,20 +52,15 @@ public:
Ui::LibreMediaServerAudio ui; Ui::LibreMediaServerAudio ui;
// static QTextEdit *textEdit; // Terminal de feedback
protected: protected:
QString m_pathmedia; // Path to Medias
QProcess *m_ola; // OLA daemon process
bool m_gui;
private: private:
QTextEdit *textEdit; // Terminal de feedback // void MessageHandler(QtMsgType type, const QMessageLogContext &logcontext, const QString &msg);
AudioMasterWidget *amw; AudioMasterWidget *amw;
// AudioWidget *aw;
AudioWidget *aw;
olaThread *ola; olaThread *ola;
void open_start(); void open_start();
@ -79,32 +68,19 @@ private:
void open(QFile *file); void open(QFile *file);
void save(QFile *file); void save(QFile *file);
// void MessageHandler(QtMsgType type, const char *msg);
public slots: public slots:
// inline void toTerminal(QString msg) { textEdit->append(msg); }
inline void toTerminal (QString message)
{
textEdit->append(message);
}
private slots: private slots:
/** // void loadbang();
* @brief loadbang The audio motor engine is setup. Resend the dmx info to maintain aupdated to the current state
*/
void loadbang();
void olasetup(); void olasetup();
void dmxInput(int layer, int channel, int value); void dmxInput(int layer, int channel, int value);
// Menu File // Menu File
void openFile(); void openFile();
void saveFile(); void saveFile();
void ChangeMediaPath();// Change the path to medias void ChangeMediaPath();// Change the path to medias
}; };
#endif // LIBREMEDIASERVER_H #endif // LIBREMEDIASERVERAUDIO_H

View file

@ -1,29 +1,31 @@
TEMPLATE = app TEMPLATE = app
TARGET = libremediaserver-audio TARGET = libremediaserver-audio
QT += network script webkit
QT += webkitwidgets widgets
#CONFIG += release #CONFIG += release
DESTDIR = ./debug DESTDIR = ./debug
HEADERS += libremediaserver-audio.h \ HEADERS += libremediaserver-audio.h \
medialibrary.h \ medialibrary.h \
audiomotor.h \
olathread.h \ olathread.h \
audiolayerwidget.h \ audiolayerwidget.h \
dmxPersonality.h \ dmxPersonality.h \
audiowidget.h \ audiowidget.h \
audiomasterwidget.h \ audiomasterwidget.h \
defines.h \ defines.h \
settings.h settings.h \
settingsdialog.h
SOURCES += main.cpp \ SOURCES += main.cpp \
libremediaserver-audio.cpp \ libremediaserver-audio.cpp \
medialibrary.cpp \ medialibrary.cpp \
audiomotor.cpp \
olathread.cpp \ olathread.cpp \
audiolayerwidget.cpp \ audiolayerwidget.cpp \
audiowidget.cpp \ audiowidget.cpp \
audiomasterwidget.cpp \ audiomasterwidget.cpp \
settings.cpp settings.cpp \
settingsdialog.cpp
FORMS += \ FORMS += \
libremediaserver-audio.ui libremediaserver-audio.ui
@ -39,8 +41,9 @@ LIBS += -lola -lolacommon
#INCLUDEPATH += $$PWD/../debug #INCLUDEPATH += $$PWD/../debug
#DEPENDPATH += $$PWD/../debug #DEPENDPATH += $$PWD/../debug
RESOURCES = LIBS += -lola -lolacommon
RESOURCES =
OTHER_FILES += \ OTHER_FILES += \
../LICENSE.txt \ ../LICENSE.txt \
@ -49,3 +52,12 @@ OTHER_FILES += \
../compiling.txt \ ../compiling.txt \
../changelog.txt \ ../changelog.txt \
../lms-audio.xlm ../lms-audio.xlm
#win32:CONFIG(release, debug|release): LIBS += -L$$PWD/SFML/lib/release/ -lsfml-audio
#else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/SFML/lib/debug/ -lsfml-audio
#else:symbian: LIBS += -lsfml-audio
LIBS += -L$$PWD/SFML/lib/ -lsfml-audio -lsfml-system
INCLUDEPATH += $$PWD/SFML/include
DEPENDPATH += $$PWD/SFML/include

View file

@ -7,8 +7,8 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>148</width> <width>126</width>
<height>95</height> <height>89</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -20,7 +20,7 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>148</width> <width>126</width>
<height>29</height> <height>29</height>
</rect> </rect>
</property> </property>

View file

@ -19,38 +19,25 @@
*/ */
#include <QApplication> #include <QApplication>
//#include <QMutex>
//#include <QMutexLocker>
#include "libremediaserver-audio.h" #include "libremediaserver-audio.h"
// Handler for pipe the stderr to a log file // Handler for pipe the stderr to a log file and texEdit
//bool initMessageHandler = false;
bool initMessageHandler = false; //QFile outFile;
QFile outFile; //QMutex mutex;
//QMutexLocker mutexLocker(mutex);
void MessageHandler(QtMsgType type, const char *msg) /*
void MessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{ {
QString txt; Q_UNUSED(context);
switch (type) { // mutex.lock();
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 // Create the log dir and log file
if (!initMessageHandler) if (!initMessageHandler) {
{
QDir dir; QDir dir;
if (!dir.exists("log")) if (!dir.exists("log")) {
{ if (!dir.mkdir("log")) {
if (!dir.mkdir("log"))
{
qDebug()<<"MessageHandler: Can not create log folder"; qDebug()<<"MessageHandler: Can not create log folder";
return; return;
} }
@ -62,57 +49,127 @@ void MessageHandler(QtMsgType type, const char *msg)
filename.append(date.toString("ddMMyy-")); filename.append(date.toString("ddMMyy-"));
filename.append(time.toString("hhmmss.txt")); filename.append(time.toString("hhmmss.txt"));
outFile.setFileName(filename); outFile.setFileName(filename);
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append)) if (!outFile.open(QIODevice::WriteOnly | QIODevice::Append)) {
{ qWarning("main/MessageHandler/Qfile::open: can not open log file");
qDebug()<<"main/MessageHandler/Qfile::open: can not open log file";
return; return;
} }
initMessageHandler = true; initMessageHandler = true;
} }
QTextStream ts(&outFile); QTextStream ts(&outFile);*/
ts << txt << endl; /* if (libreMediaServerAudio::textEdit == 0)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
} }
}
else
{
QString txt;
switch (type) {
case QtDebugMsg:
txt.append("Debug from File: ");
txt.append(context.file);
txt.append(" Line: ");
txt.append(QString::number(context.line));
// txt.append(" Function: ");
// txt.append(context.function);
txt.append(" Message: ");
txt.append(msg);
// libreMediaServerAudio::textEdit->append(msg);, context.file, context.line, context.function);
libreMediaServerAudio::textEdit->append(txt);
break;
case QtWarningMsg:
txt.append("Warning from File: ");
txt.append(context.file);
txt.append(" Line: ");
txt.append(QString::number(context.line));
txt.append(" Function: ");
txt.append(context.function);
txt.append(" Message: ");
txt.append(msg);
// libreMediaServerAudio::textEdit->append(msg);, context.file, context.line, context.function);
libreMediaServerAudio::textEdit->append(txt);
abort();
break;
case QtCriticalMsg:
// txt.append("Critical from File: ");
txt.append(context.file);
txt.append(" Line: ");
txt.append(QString::number(context.line));
txt.append(" Function: ");
txt.append(context.function);
txt.append(" Message ");
txt.append(msg);
// libreMediaServerAudio::textEdit->append(msg);, context.file, context.line, context.function);
libreMediaServerAudio::textEdit->append(txt);
abort();
break;
case QtFatalMsg:
// txt.append("Fatal from File: ");
txt.append(context.file);
txt.append(" Line: ");
txt.append(QString::number(context.line));
txt.append(" Function: ");
txt.append(context.function);
txt.append(" Message: ");
txt.append(msg);
// libreMediaServerAudio::textEdit->append(msg);, context.file, context.line, context.function);
libreMediaServerAudio::textEdit->append(txt);// ts << txt << endl;
abort();
}
// outFile.write(txt.toLatin1().constData(), txt.size());
// ts << txt << endl;
// libreMediaServerAudio::textEdit->append(txt);
}
// mutex.unlock();
}*/
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
// ToDo: discriminar niveles de log y log a fichero segúna argumentos
/*
if (args.contains("-log"))
{
qInstallMessageHandler(MessageHandler);
}*/
// qInstallMessageHandler(MessageHandler);
QApplication app(argc, argv); QApplication app(argc, argv);
QStringList args = app.arguments(); QStringList args = app.arguments();
// parse the command line // parse the command line
if (args.size() > 1) if (args.size() > 1)
{ {
if (args.contains("-v") > 0) if (args.contains("-v"))
{ {
qDebug() << VERSION; qDebug() << VERSION;
qDebug() << COPYRIGHT; qDebug() << COPYRIGHT;
qDebug() << LICENSE; qDebug() << LICENSE;
return 0; return 0;
} }
if (args.contains("-h") > 0) if (args.contains("-h"))
{ {
qDebug() << VERSION; qDebug() << VERSION;
qDebug() << COPYRIGHT; qDebug() << COPYRIGHT;
qDebug() << LICENSE; qDebug() << LICENSE;
qDebug() << "Help for command line options:"; qDebug() << "Help for command line options:";
qDebug() << "-v show the version and exits"; 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() << "-log write the debug information to a log file instead stderr";
qDebug() << "-h this help"; qDebug() << "-h this help";
return 0; 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 libreMediaServerAudio(args);
libreMediaServerAudio.show(); libreMediaServerAudio.show();

View file

@ -1,5 +1,6 @@
#include "medialibrary.h" #include "medialibrary.h"
#include <QDebug>
MediaLibrary *MediaLibrary::_instance = 0; MediaLibrary *MediaLibrary::_instance = 0;
@ -15,10 +16,9 @@ MediaLibrary *MediaLibrary::getInstance() {
MediaLibrary::MediaLibrary(QObject *parent) : MediaLibrary::MediaLibrary(QObject *parent) :
QObject(parent) QObject(parent)
// ,m_media(new QList<MediaFolder>) // ,m_media(new QList<MediaFolder>)
, m_pathmedia()
{ {
// initMediaLibrary(); initMediaLibrary();
qDebug("Init MediaLibrary"); // qDebug("Init MediaLibrary");
} }
/** Initializes the media library and the media information /** Initializes the media library and the media information
@ -26,10 +26,10 @@ MediaLibrary::MediaLibrary(QObject *parent) :
*/ */
void MediaLibrary::initMediaLibrary() { void MediaLibrary::initMediaLibrary() {
qDebug("starting the media library");
QDir dir; QDir dir;
if (!dir.cd(m_pathmedia)) { if (!dir.cd(Settings::getInstance()->getPathMedia())) {
qWarning("initMediaLibrary| Can not cd to the path: "); qWarning("Can not cd to the path: %s", Settings::getInstance()->getPathMedia().toLatin1().constData());
qWarning(m_pathmedia.toAscii().constData());
return; return;
} }
m_media = new QList<MediaFolder>; m_media = new QList<MediaFolder>;
@ -77,15 +77,12 @@ QList<MediaFile> MediaLibrary::getMediaInformation(QDir dir)
*/ */
QString MediaLibrary::requestNewFile(int folder, int file){ QString MediaLibrary::requestNewFile(int folder, int file){
// Select one mediafile from the media library
if (!m_media) {
qWarning("Media Library not init. Set a correct path to medias library");
return NULL;
}
QString newfile; QString newfile;
if (m_pathmedia.isNull()) {
qWarning("Path not set yet");
return newfile;
}
if (m_media == NULL) {
qWarning("media not setup");
return newfile;
}
if (folder < m_media->size()) { if (folder < m_media->size()) {
if (file < m_media->at(folder).m_MediaInformation.size()) { if (file < m_media->at(folder).m_MediaInformation.size()) {
newfile = m_media->at(folder).m_MediaInformation.at(file).MediaName; newfile = m_media->at(folder).m_MediaInformation.at(file).MediaName;
@ -97,5 +94,3 @@ QString MediaLibrary::requestNewFile(int folder, int file){
} }
return newfile; return newfile;
} }

View file

@ -5,43 +5,58 @@
#include <QDir> #include <QDir>
#include "defines.h" #include "defines.h"
#include "settings.h"
class MediaLibrary : public QObject class MediaLibrary : public QObject
{ {
Q_OBJECT Q_OBJECT
friend class libreMediaserverAudio; // Not working... WHY?
friend class Settings; // working...
public: public:
static MediaLibrary *getInstance(); static MediaLibrary *getInstance();
inline void setPath(QString path) { m_pathmedia = path; rescanMediaLibrary();} /**
* @brief request a new file from the media library
* @param int folder - the folder required
* @param int layer - file required
* @return QString the file required with full path
*/
QString requestNewFile(int folder, int layer); QString requestNewFile(int folder, int layer);
/**
* @brief Inicia la biblioteca de medios
*/
void initMediaLibrary();
protected:
/**
* @brief Reload the media library on change of path or change the media files
*/
inline void rescanMediaLibrary() {
if (m_media != NULL)
delete m_media;
initMediaLibrary();
}
private: private:
explicit MediaLibrary(QObject *parent = 0); explicit MediaLibrary(QObject *parent = 0);
static MediaLibrary *_instance; 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();
}
// Wich structure is more efficient for us?
// QList, QMap, QSet, QVector?
QList<MediaFolder> *m_media; // Library to save the folders/media libraries and index each media file inside 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 * @brief Returns a list withe the medias contained in a folder
* this is called. Creates a new source. * @param QDir - the directory when are the media
* @return QList<MediaFile> The list with the medias in a folder
*/ */
QList<MediaFile> getMediaInformation(QDir dir); // Get all the information of each media file in a dir QList<MediaFile> getMediaInformation(QDir dir); // Get all the information of each media file in a dir
signals: signals:

View file

@ -1,41 +1,21 @@
#include "olathread.h" #include "olathread.h"
#include <ola/Callback.h>
olaThread::olaThread(QObject *parent) olaThread::olaThread(QObject *parent)
// : QObject(parent)
{ {
Q_UNUSED(parent); Q_UNUSED(parent);
m_universe = new QList<int>();
m_counter = 0; m_counter = 0;
gettimeofday(&m_last_data, NULL); gettimeofday(&m_last_data, NULL);
dmxSetting newsetting; // Init the dmx buffer to 0
newsetting.address = -1;
newsetting.universe = -1;
newsetting.updated = false;
m_layersNumber = LAYERS_NUMBER;
for (int i=0; i < LAYERS_NUMBER; i++) for (int i=0; i < LAYERS_NUMBER; i++)
{ {
newsetting.layer = i;
m_settings.append(newsetting);
for (int j=0; j < LAYER_CHANNELS; j++) for (int j=0; j < LAYER_CHANNELS; j++)
{ {
m_dmx[i][j] = 0; m_dmx[i][j] = 0;
} }
} }
/* int argc = 1; init(); // start the ola connection
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 --- // --- DECONSTRUCTOR ---
@ -43,17 +23,25 @@ olaThread::~olaThread() {
stop(); stop();
} }
/** Open the connection with olad and start processing data. void olaThread::init()
*/ {
if (ola::InitLogging(ola::OLA_LOG_INFO , ola::OLA_LOG_STDERR)) {
qDebug() << "ola logging debug working";
} else {
qWarning() << "Can not init ola logging";
}
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();
m_client->SetDMXCallback(ola::NewCallback(this, &olaThread::NewDmx));
m_clientWrapper->GetSelectServer()->RegisterRepeatingTimeout(4000, ola::NewCallback(this, &olaThread::CheckDataLoss));
m_client->SetCloseHandler(ola::NewSingleCallback(this, &olaThread::socketClosed));
}
void olaThread::run() { void olaThread::run()
{
/* register the universe emit toTerminal("Start reading DMX");
if (!m_client->RegisterUniverse(m_universe, ola::REGISTER,ola::NewSingleCallback(&RegisterComplete))) {
qDebug() << "Can not register universe %1".arg(m_universe);
}*/
qDebug() << tr("olaThread| Running");
emit toTerminal("Reading DMX");
m_clientWrapper->GetSelectServer()->Run(); m_clientWrapper->GetSelectServer()->Run();
} }
@ -61,40 +49,31 @@ void olaThread::stop()
{ {
if (m_clientWrapper != NULL) if (m_clientWrapper != NULL)
{ {
for (int i = 0; i < m_universe->size(); i++) { QSet<int> temp = Settings::getInstance()->getUniverses();
m_client->RegisterUniverse(m_universe->at(i), ola::client::UNREGISTER, ola::NewSingleCallback(this, &olaThread::RegisterComplete)); foreach (const int &i, temp) {
m_client->RegisterUniverse(i, ola::client::UNREGISTER, ola::NewSingleCallback(this, &olaThread::RegisterComplete));
} }
m_clientWrapper->GetSelectServer()->Terminate(); m_clientWrapper->GetSelectServer()->Terminate();
m_client = NULL;
m_clientWrapper = NULL; m_clientWrapper = NULL;
m_client = 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 // 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, void olaThread::NewDmx(const ola::client::DMXMetadata &data,
const ola::DmxBuffer &buffer) const ola::DmxBuffer &buffer)
{ {
m_counter++; m_counter++;
gettimeofday(&m_last_data, NULL); gettimeofday(&m_last_data, NULL);
uint universe = data.universe; uint universe = data.universe;
emit universeReceived(universe); emit layerReceived();
for (int i = 0; i < m_layersNumber; i++) { // loop for reading the channels by layer. foreach (const dmxSetting &i, Settings::getInstance()->getDmxSettings()) { // loop for reading the channels by layer.
if((m_settings.at(i).universe == universe) if(i.universe == universe && i.address > -1) { // Compare if the layer is from this universe AND if the DMX address is 0 or greater, process this layer.
&& ( 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++){ for (int j = 0; j < LAYER_CHANNELS; j++){
int value = buffer.Get((m_settings.at(i).address) + j); // Get the value for this channel. int value = buffer.Get((i.address) + j); // Get the value for this channel.
if (m_dmx[i][j] != value) { // Compare the new value with the old value. if (m_dmx[i.layer][j] != value) { // Compare the new value with the old value.
emit dmxOutput(i,j,value); // Connected with dmx slot in olaInterface. emit dmxOutput(i.layer,j,value);
m_dmx[i][j] = value; m_dmx[i.layer][j] = value;
} }
} }
} }
@ -113,25 +92,48 @@ bool olaThread::CheckDataLoss() {
if (diff.tv_sec > 4 || (diff.tv_sec == 4 && diff.tv_usec > 4000000)) { if (diff.tv_sec > 4 || (diff.tv_sec == 4 && diff.tv_usec > 4000000)) {
// loss of data // loss of data
qDebug()<< "olaThread| Can not read one or several universes"; qDebug()<< "olaThread| Can not read one or several universes";
emit toTerminal("Can not read one universe"); emit toTerminal("olaThread: Can not read one universe");
// return false; // Retorna false para deshabilitar el callback // return false; // Retorna false para deshabilitar el callback
} }
} }
return true; return true;
} }
void olaThread::setLayersNumber(int layersNumber) { m_layersNumber = layersNumber; }
void olaThread::resendDmx() void olaThread::resendDmx()
{ {
emit toTerminal("Resending DMX info"); // qDebug() << "Resending DMX info";
for (int i = 0; i < m_layersNumber; i++) { // loop for reading the channels by layer. for (int i = 0; i < Settings::getInstance()->getLayersNumber(); i++) { // loop for reading the channels by layer.
for (int j = 0; j < LAYER_CHANNELS; j++){ for (int j = 0; j < LAYER_CHANNELS; j++){
emit dmxOutput(i, j, m_dmx[i][j]); // Connected with dmx slot in olaInterface. emit dmxOutput(i, j, m_dmx[i][j]); // Connected with dmx slot in olaInterface.
} }
} }
} }
void olaThread::socketClosed()
{
qWarning("ola close the connection. Trying reopening it... ");
emit toTerminal("OLA closed the connection. Tryin reopening it... ");
// Qúe limpiamos? todo? el thread?
if (!m_client->Stop())
{
qWarning("Can not stop the ola client");
}
m_clientWrapper->GetSelectServer()->Terminate();
delete m_client;
m_client = NULL;
delete m_clientWrapper;
m_clientWrapper = NULL;
// set up ola connection
init();
// register all universes
registerUniverse();
// start the thread????
run();
}
//////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -16,6 +16,7 @@
#include "defines.h" #include "defines.h"
#include "dmxPersonality.h" #include "dmxPersonality.h"
#include "settings.h"
class olaThread : public QThread class olaThread : public QThread
{ {
@ -31,7 +32,6 @@ public:
*@param int channel the channel for the value wanted *@param int channel the channel for the value wanted
*@return int the value *@return int the value
*/ */
inline int getValue(int layer, int channel) { inline int getValue(int layer, int channel) {
return m_dmx[layer][channel]; return m_dmx[layer][channel];
} }
@ -39,70 +39,91 @@ public:
/** /**
* @brief resendDMX emite todo el buffer DMX * @brief resendDMX emite todo el buffer DMX
*/ */
void resendDmx(); void resendDmx();
private: private:
void run (); void run ();
ola::client::OlaClientWrapper *m_clientWrapper; ola::client::OlaClientWrapper *m_clientWrapper;
ola::client::OlaClient *m_client; ola::client::OlaClient *m_client;
unsigned int m_counter; unsigned int m_counter;
struct timeval m_last_data; // Last DMX frame received 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 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 * @brief Callback from ola. Control de errores en el registro de Universos en OLA
* typedef SingleUseCallback1<void, const Result&> ola::client::SetCallback
* @param ola::client::Result &error
* @return void
*
*
*/ */
// typedef SingleUseCallback1<void, const Result&> ola::client::SetCallback
inline void RegisterComplete(const ola::client::Result &error) { inline void RegisterComplete(const ola::client::Result &error) {
if (error.Success()) { if (error.Success()) {
qDebug() << "Register Universe success"; qDebug("Register Universe success");
emit toTerminal("Register Universe success"); emit toTerminal("Register Universe success");
} else { } else {
qWarning() << "olaThread|" << "Register command failed" << QString::fromStdString(error.Error()); qWarning("Register command failed: %s", error.Error().c_str());
emit toTerminal("olaThread| Register command failed " + QString::fromStdString(error.Error())); emit toTerminal("olaThread| Register command failed " + QString::fromStdString(error.Error()));
} }
} }
/**
* @brief Check if the dmx info is arriving each 4 seconds
* @return bool
*/
bool CheckDataLoss(); 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 * @brief RepeteableDMXCallBack from ola called when arrives a new dmx frame
* typedef Callback2<void, const DMXMetadata&, const DmxBuffer&> ola::client::RepeatableDMXCallback
* 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.
*
*
*/
void NewDmx(const ola::client::DMXMetadata &dmx_meta, const ola::DmxBuffer &buffer); //
/**
* @brief Sometimes the ola server closes the connection. This is a callback to handle this event an reconect to ola
*
*
*/
void socketClosed();
/**
* @brief Open the connection with olad and start processing data.
*
*
*/
void init();
public slots: public slots:
void stop(); // Close the connection with olad. void stop(); // Close the connection with olad.
void setLayersNumber(int layersNumber);
inline void setDMXConf(dmxSetting set) /**
{ * @brief register one Universe
if (set.layer >= m_layersNumber) { return; } * void ola::client::OlaClient::RegisterUniverse(unsigned int universe,RegisterAction register_action,SetCallback * callback
* @param universe
*/
inline void registerUniverse(int universe) {
qDebug("Registering universe %d", universe);
m_client->RegisterUniverse(universe,
ola::client::REGISTER,
ola::NewSingleCallback
(this, &olaThread::RegisterComplete));
}
m_settings.replace(set.layer, set); /**
* @brief Register all the universes again
// ToDo: registro del nuevo universo si no está registrado ya *
if (!m_universe->contains(set.universe)) { */
registerUniverse(set.universe); inline void registerUniverse() {
m_universe->append(set.universe); QSet<int> unis = Settings::getInstance()->getUniverses();
foreach (const int &universe, unis) {
registerUniverse(universe);
} }
} }
@ -114,6 +135,9 @@ signals:
void dmxOutput(int layer, int channel, int value); // Signal when a channel has changed void dmxOutput(int layer, int channel, int value); // Signal when a channel has changed
void toTerminal(QString message); void toTerminal(QString message);
void universeReceived(uint universe); void universeReceived(uint universe);
void layerReceived();
}; };
using namespace ola;
#endif // OLATHREAD_H #endif // OLATHREAD_H

View file

@ -1,9 +1,26 @@
#include "settings.h" #include "settings.h"
Settings *Settings::_instance = 0;
Settings *Settings::getInstance() {
if (_instance == 0) {
_instance = new Settings();
Q_CHECK_PTR(_instance);
}
return _instance;
}
Settings::Settings(QObject *parent) : Settings::Settings(QObject *parent) :
QObject(parent) QObject(parent)
{ {
// readDefaultFile(); m_layersNumber = 0;
}
void Settings::setPathMedia(QString path)
{
m_pathmedia = path;
MediaLibrary::getInstance()->rescanMediaLibrary();
} }
// Read the dmx settings for dmx.xml At the moment we need: // Read the dmx settings for dmx.xml At the moment we need:
@ -11,21 +28,21 @@ Settings::Settings(QObject *parent) :
// - The number of sources/layers controlled by DMX // - The number of sources/layers controlled by DMX
// - The first DMX channel of each source/layer // - The first DMX channel of each source/layer
// - The universe to bind in OLA // - The universe to bind in OLA
// All this is being moved to settingsDialog Class
bool Settings::readFromFile(QString file) {
void Settings::readFromFile(QString file) {
QFile* xmlFile = new QFile(file); QFile* xmlFile = new QFile(file);
if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) { if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::critical(NULL,"Load XML File Problem", QMessageBox::critical(NULL,"Load XML File Problem",
QString("Couldn't open %1 to load settings").arg(file), QString("Couldn't open %1 to load settings").arg(file),
QMessageBox::Ok); QMessageBox::Ok);
return false; // Instead exit give the oportunity to load another file or define the settings
qCritical("Load XML File Problem");
exit(1);
} }
QXmlStreamReader* xmlReader = new QXmlStreamReader(xmlFile); QXmlStreamReader* xmlReader = new QXmlStreamReader(xmlFile);
int counter = 0; int counter = 0;
//Parse the XML until we reach end of it //Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) { while(!xmlReader->atEnd() && !xmlReader->hasError() && counter < LAYERS_NUMBER) {
// Read next element // Read next element
QXmlStreamReader::TokenType token = xmlReader->readNext(); QXmlStreamReader::TokenType token = xmlReader->readNext();
//If token is just StartDocument - go to next //If token is just StartDocument - go to next
@ -37,15 +54,11 @@ bool Settings::readFromFile(QString file) {
if(xmlReader->name() == "dmxSettings") { if(xmlReader->name() == "dmxSettings") {
int version = xmlReader->attributes().value("fileVersion").toLocal8Bit().toInt(); int version = xmlReader->attributes().value("fileVersion").toLocal8Bit().toInt();
if(version == 1) { if(version == 1) {
int layers = xmlReader->attributes().value("layersNumber").toLocal8Bit().toInt(); m_layersNumber = xmlReader->attributes().value("layersNumber").toLocal8Bit().toInt();
emit layersNumber(layers); m_pathmedia = xmlReader->attributes().value("path").toLocal8Bit();
MediaLibrary::getInstance()->setPath (xmlReader->attributes().value("path").toLocal8Bit());
continue; continue;
} }
} }
/* if (worker->m_layersNumber > MAX_SOURCE_DMX) {
worker->m_layersNumber = MAX_SOURCE_DMX;
}*/
QString add = "layer"; QString add = "layer";
add.append(QString("%1").arg(counter)); add.append(QString("%1").arg(counter));
if((xmlReader->name() == add)) { if((xmlReader->name() == add)) {
@ -53,19 +66,20 @@ bool Settings::readFromFile(QString file) {
temp.address = xmlReader->attributes().value("dmx").toLocal8Bit().toInt() - 1; temp.address = xmlReader->attributes().value("dmx").toLocal8Bit().toInt() - 1;
temp.universe = xmlReader->attributes().value("universe").toLocal8Bit().toInt(); temp.universe = xmlReader->attributes().value("universe").toLocal8Bit().toInt();
temp.layer = counter; temp.layer = counter;
emit DMXConf(temp); m_settings.append(temp);
// If the universe is not in the list, append it. if (!m_universe.contains(temp.universe)) {
// if(!worker->m_universe.contains(temp.universe)) { m_universe.insert(temp.universe);
// worker->m_universe.append(temp.universe); // emit registerUniverse(temp.universe);
// } }
} }
counter++; counter++;
} }
} }
if(xmlReader->hasError()) { if(xmlReader->hasError()) {
QMessageBox::critical(NULL,"File xml Parse Error ", xmlReader->errorString(), QMessageBox::Ok); QMessageBox::critical(NULL,"File xml Parse Error ", xmlReader->errorString(), QMessageBox::Ok);
qWarning("File xml Parse Error %s", xmlReader->errorString().toLatin1().constData()); qWarning("File xml Parse Error %s", xmlReader->errorString().toLatin1().constData());
return false; return;
} }
//close reader and flush file //close reader and flush file
xmlReader->clear(); xmlReader->clear();
@ -73,16 +87,42 @@ bool Settings::readFromFile(QString file) {
delete xmlReader; delete xmlReader;
delete xmlFile; delete xmlFile;
return true;
} }
/** Read the default file /** Read the default file
* *
*/ */
bool Settings::readDefaultFile() { void Settings::readFile() {
if (readFromFile(DEFAULT_FILE)) { readFromFile(DEFAULT_FILE);
return true;
} else {
return false;
} }
/*
void Settings::writeFile(QString filename)
{
QFile* xmlFile = new QFile(filename);
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;
} }
QXmlStreamWriter* xmlWriter = new QXmlStreamWriter(xmlFile);
QXmlStreamWriter stream(&output);
stream.setAutoFormatting(true);
stream.writeStartDocument();
stream.writeStartElement("dmxSettings");
stream.writeAttribute("href", "http://qt.nokia.com/");
stream.writeTextElement("title", "Qt Home");
stream.writeEndElement();
stream.writeEndDocument();
}
void Settings::writeFile()
{
writeFile(DEFAULT_FILE);
}
*/

View file

@ -5,25 +5,132 @@
#include <QXmlStreamReader> #include <QXmlStreamReader>
#include <QFile> #include <QFile>
#include <QMessageBox> #include <QMessageBox>
#include <QSet>
#include "olathread.h" //#include "olathread.h"
#include "audiomotor.h"
#include "medialibrary.h" #include "medialibrary.h"
#include "defines.h"
/**
* This class stores the settings on lms.
* Is a singleton with set and get methods to manage the settings
* Also writes and reads the settings files.
*/
class Settings : public QObject class Settings : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
static Settings *getInstance(); //Singleton
/**
* @brief getUniverses
* @return
*/
inline QSet<int> getUniverses() { return m_universe; }
/**
* @brief getPathMedia
* @return
*/
inline QString getPathMedia() { return m_pathmedia; }
/**
* @brief setPathMedia
* @param path
*/
void setPathMedia(QString path);
/**
* @brief getDmxSettings
* @return
*/
inline QList<dmxSetting> getDmxSettings() { return m_settings; }
/**
* @brief getlayersNumber
* @return
*/
inline int getLayersNumber() { return m_layersNumber; }
inline int getUniverseNumber() { return m_universe.size(); }
/**
* @brief readDefaultFile
*/
void readFile();
private:
static Settings *_instance;
/** Constructor
*
*/
explicit Settings(QObject *parent = 0); explicit Settings(QObject *parent = 0);
bool readFromFile(QString file);
bool readDefaultFile(); QSet<int> m_universe; // Registered universes.
int m_layersNumber; // Number of layers in wich divide the dmx frame. Each layer, one source.
/**
* @brief olaThread::setLayersNumber
* @param layersNumber
*
*/
inline void setLayersNumber(int layersNumber)
{
if (layersNumber <= LAYERS_NUMBER)
m_layersNumber = layersNumber;
else
m_layersNumber = LAYERS_NUMBER;
}
// The list where we store the settings by layer
QList<dmxSetting> m_settings;
// The path to media library
QString m_pathmedia;
/**
* @brief readFromFile
* @param file
*/
void readFromFile(QString file);
/**
* @brief writeFile
* @param filename
*/
// void writeFile(QString filename); // Not implemented yet
/**
* @brief writeFile
* overload
*/
// void writeFile(); // Not implemented yet
signals: signals:
/**
* @brief pathChanged
* @param path
*/
void pathChanged(QString path); void pathChanged(QString path);
/**
* @brief layersNumber
* @param number
*/
void layersNumber(int number); void layersNumber(int number);
void DMXConf(dmxSetting universe);
/**
* @brief DMXConf
* @param universe
*/
void registerUniverse(int universe);
public slots: public slots:

41
src/settingsdialog.cpp Normal file
View file

@ -0,0 +1,41 @@
#include "settingsdialog.h"
SettingsDialog::SettingsDialog(QWidget *parent) :
QWidget(parent)
{
QHBoxLayout *layout = new QHBoxLayout();
for (int i= 0; i < LAYERS_NUMBER; i++ ) {
layout->insertWidget(i, new SettingsLayerWidget(this, tr("Layer %1").arg(i)));
}
setLayout(layout);
}
// Change Media path
void SettingsDialog::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(file);
qDebug(desc.toLatin1().constData());
}
void SettingsDialog::olasetup()
{
QWebView *view = new QWebView();
view->load(QUrl("http://localhost:9090/ola.html"));
view->show();
}
SettingsLayerWidget::SettingsLayerWidget(QWidget *parent, QString title)
{
}

46
src/settingsdialog.h Normal file
View file

@ -0,0 +1,46 @@
#ifndef SETTINGSDIALOG_H
#define SETTINGSDIALOG_H
#include <QWidget>
#include "defines.h"
#include <QHBoxLayout>
#include <QComboBox>
#include <QLabel>
#include <QPushButton>
#include <QCheckBox>
#include <QWebView>
#include <QFileDialog>
#include "medialibrary.h"
class SettingsDialog : public QWidget
{
Q_OBJECT
public:
explicit SettingsDialog(QWidget *parent = 0);
void ChangeMediaPath();
void olasetup();
signals:
public slots:
private:
QLabel m_path;
QPushButton m_changePathToMedias;
QPushButton m_olaSetup;
};
class SettingsLayerWidget : public QWidget
{
Q_OBJECT
public:
explicit SettingsLayerWidget(QWidget *parent = 0, QString title = "layer");
private:
QComboBox m_universe;
QComboBox m_address;
signals:
};
#endif // SETTINGSDIALOG_H