Controller.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /*
  2. This file is part of QTau
  3. Copyright (C) 2013-2018 Tobias "Tomoko" Platen <tplaten@posteo.de>
  4. Copyright (C) 2013 digited <https://github.com/digited>
  5. Copyright (C) 2010-2013 HAL@ShurabaP <https://github.com/haruneko>
  6. QTau is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. SPDX-License-Identifier: GPL-3.0+
  17. */
  18. #include "mainwindow.h"
  19. #include "Session.h"
  20. #include "Controller.h"
  21. #include "PluginInterfaces.h"
  22. #include "Utils.h"
  23. #include <QJsonDocument>
  24. #include "audio/jackaudio.h"
  25. #include "audio/audioengine.h"
  26. #include <QApplication>
  27. #include <QPluginLoader>
  28. #include <QDebug>
  29. #include <QTimer>
  30. #include <qsettings.h>
  31. #include <tempomap.h>
  32. #include <score.h>
  33. #define __devloglevel__ 4
  34. qtauController::qtauController(QString dir,QObject *parent) :
  35. QObject(parent), _jack(nullptr), _mainWindow(nullptr), _activeSession(nullptr)
  36. {
  37. QDir diru(dir);
  38. diru.cdUp();
  39. _prefix = diru.absolutePath();
  40. QSettings settings;
  41. bool autoconnect = settings.value("jack_auto_connect").toBool();
  42. QString startup_script = settings.value("startup_script").toString();
  43. if(startup_script.length())
  44. system(startup_script.toUtf8().data());
  45. //DO once
  46. //settings.setValue("startup_script","/home/isengaara/Hacking/Audio/Ongakunix/scripts/connect_qtau &");
  47. //settings.setValue("jack_auto_connect",false);
  48. //settings.sync();
  49. _jack = new JackAudio(autoconnect);
  50. _audio = new AudioEngine(_jack,this);
  51. _audio->setUseJackTransport(true);
  52. _outbuf = new OutputBuffer(_jack);
  53. _audio->setOutputBuffer(_outbuf);
  54. _jackSampleRate=_jack->getSamplerate();
  55. connect(_outbuf,&OutputBuffer::startPlayback,this,&qtauController::outbuf_startPlayback);
  56. connect(_outbuf,&OutputBuffer::stopPlayback,this,&qtauController::outbuf_stopPlayback);
  57. QTimer *timer = new QTimer(this);
  58. connect(timer, SIGNAL(timeout()), this, SLOT(jackTimer()));
  59. timer->start(10);
  60. _activeSynth = nullptr;
  61. _selectedSynth = nullptr;
  62. setupTranslations();
  63. setupPlugins();
  64. }
  65. int qtauController::sampleRate()
  66. {
  67. return _jack->sampleRate();
  68. }
  69. void qtauController::startOfflinePlayback(const QString &fileName)
  70. {
  71. _outbuf->openReadFile(fileName);
  72. _lastPlay = fileName;
  73. startPlayback(0);
  74. }
  75. void qtauController::jackTimer()
  76. {
  77. char midi[1024];
  78. if(_jack->readMidiData(midi,1024))
  79. {
  80. int event_type = midi[0] & 0xF0;
  81. int note_num = midi[1];
  82. if(event_type==144)
  83. {
  84. pianoKeyPressed(note_num);
  85. }
  86. else if(event_type==128)
  87. {
  88. pianoKeyReleased(note_num);
  89. }
  90. }
  91. if(_jack->stateChanged())
  92. {
  93. switch(_jack->transportState())
  94. {
  95. case JackTransportStopped:
  96. DEVLOG_DEBUG("state_changed to JackTransportStopped");
  97. //XXX if(_activeSynth) _activeSynth->stopThread();
  98. transportPositionChanged(-1);
  99. break;
  100. case JackTransportStarting:
  101. DEVLOG_DEBUG("state_changed to JackTransportStarting");
  102. break;
  103. case JackTransportLooping:
  104. DEVLOG_DEBUG("not supported JackTransportLooping");
  105. break;
  106. case JackTransportNetStarting:
  107. DEVLOG_DEBUG("not supported JackTransportNetStarting");
  108. default:
  109. break;
  110. }
  111. }
  112. int pos = _jack->positionChange();
  113. if(_nonzeroStart>0) {
  114. pos = -1;
  115. _nonzeroStart--;
  116. DEVLOG_DEBUG("NONZERO START "+STR(_nonzeroStart));
  117. }
  118. if(pos!=-1 && _audio->transportPosition()!=pos)
  119. {
  120. _audio->setTransportPosition(pos);
  121. //XXX if(_activeSynth) _activeSynth->stopThread();
  122. _localRequestStartPlayback = false;
  123. }
  124. //FIXME: if(_jack->isRolling() || (_audio->useJackTransport()==false && _audio->localTransportRolling())) transportPositionChanged(_samplesToMeasures*_audio->transportPosition());
  125. }
  126. void qtauController::outbuf_startPlayback()
  127. {
  128. // startPlayback(0);
  129. DEVLOG_DEBUG("playback is stable");
  130. }
  131. void qtauController::outbuf_stopPlayback()
  132. {
  133. stopPlayback();
  134. }
  135. qtauController::~qtauController()
  136. {
  137. delete _jack;
  138. //TODO --> shutdown audio -> crash here
  139. delete _audio;
  140. delete _mainWindow;
  141. }
  142. //------------------------------------------
  143. static qtauController* singleton=0;
  144. void qtauController::shutdown(int rc)
  145. {
  146. (void) rc;
  147. _jack->shutdown();
  148. _audio->shutdown();//kind of CopyEngine
  149. }
  150. bool qtauController::run()
  151. {
  152. _mainWindow = new MainWindow();
  153. _mainWindow->show();
  154. newEmptySession();
  155. _mainWindow->setController(*this, *this->_activeSession);
  156. singleton = this;
  157. return true;
  158. }
  159. qtauController* qtauController::instance()
  160. {
  161. return singleton;
  162. }
  163. bool qtauController::setupTranslations()
  164. {
  165. //FIXME: english only
  166. return false;
  167. }
  168. bool qtauController::setupPlugins()
  169. {
  170. //FIXME plugins dir, should not be hardcoded
  171. _pluginsDir = QDir(qApp->applicationDirPath());
  172. if(_pluginsDir.cd("plugins")==false) {
  173. _pluginsDir = QDir(_prefix+"/lib/qtau/");
  174. if(_pluginsDir.cd("plugins")==false) return false;
  175. }
  176. foreach (QString fileName, _pluginsDir.entryList(QDir::Files))
  177. {
  178. QPluginLoader loader(_pluginsDir.absoluteFilePath(fileName));
  179. QObject *plugin = loader.instance();
  180. if (plugin)
  181. {
  182. ISynth* s = qobject_cast<ISynth*>(plugin);
  183. if (s)
  184. initSynth(s);
  185. else
  186. {
  187. IPreviewSynth* ps = qobject_cast<IPreviewSynth*>(plugin);
  188. if(ps)
  189. {
  190. initPreviewSynth(ps);
  191. }
  192. }
  193. }
  194. else DEVLOG_INFO("Incompatible plugin: " + fileName+ "reason: "+loader.errorString());
  195. }
  196. return false;
  197. }
  198. void qtauController::initPreviewSynth(IPreviewSynth *ps)
  199. {
  200. ps->setup(this);
  201. _audio->setPreviewSynth(ps);
  202. _preview=ps;
  203. }
  204. void qtauController::initSynth(ISynth *s)
  205. {
  206. if (!_synths.contains(s->name()))
  207. {
  208. s->setup(this);
  209. DEVLOG_INFO("Adding synthesizer " + s->name());
  210. _synths[s->name()] = s;
  211. _voices.append(s->listVoices());
  212. }
  213. else DEVLOG_INFO("Synthesizer " + s->name() + " is already registered!");
  214. }
  215. void qtauController::selectSinger(QString singerName)
  216. {
  217. foreach (QString synthName, _synths.keys()) {
  218. if(_synths[synthName]->setVoice(singerName))
  219. {
  220. // DEVLOG_DEBUG("setSynth: "+synthName)
  221. _selectedSynth = _synths[synthName];
  222. }
  223. }
  224. }
  225. void qtauController::newEmptySession()
  226. {
  227. _activeSession = new qtauSession(this);
  228. }
  229. //------------------------------------------
  230. void qtauController::addFileToRecentFiles(QString fileName)
  231. {
  232. DEVLOG_DEBUG("addFileToRecentFiles: "+fileName);
  233. QSettings settings;
  234. QStringList files = settings.value("recentFileList").toStringList();
  235. files.removeAll(fileName);
  236. files.prepend(fileName);
  237. while (files.size() > MAXRECENTFILES)
  238. files.removeLast();
  239. foreach(QString file, files)
  240. DEVLOG_DEBUG("recent: "+file);
  241. settings.setValue("recentFileList", files);
  242. _mainWindow->updateRecentFileActions();
  243. }
  244. void qtauController::onLoadUST(QString fileName)
  245. {
  246. if (!fileName.isEmpty())
  247. {
  248. if (!_activeSession)
  249. newEmptySession();
  250. _activeSession->loadUST(fileName);
  251. addFileToRecentFiles(fileName);
  252. }
  253. else DEVLOG_WARNING("empty UST file name");
  254. }
  255. void qtauController::onSaveUST(QString fileName, bool rewrite)
  256. {
  257. if (_activeSession && !_activeSession->isSessionEmpty())
  258. {
  259. QFile uf(fileName);
  260. if (uf.open(QFile::WriteOnly))
  261. {
  262. addFileToRecentFiles(fileName);
  263. if (uf.size() == 0 || rewrite)
  264. {
  265. uf.reset(); // maybe it's redundant?..
  266. QJsonArray array;
  267. _activeSession->ustJson(array);
  268. QJsonDocument doc(array);
  269. uf.write(doc.toJson());
  270. uf.close();
  271. _activeSession->setFilePath(fileName);
  272. _activeSession->setSaved();
  273. DEVLOG_DEBUG("UST saved to " + fileName);
  274. }
  275. else DEVLOG_ERROR("File " + fileName + " is not empty, rewriting cancelled");
  276. }
  277. else DEVLOG_ERROR("Could not open file " + fileName + " to save UST");
  278. }
  279. else DEVLOG_ERROR("Trying to save ust from empty session!");
  280. }
  281. //new synth api required (madde)
  282. void qtauController::pianoKeyPressed(int keyNum)
  283. {
  284. _previewRunning=true;
  285. if(_preview) _preview->start(keyNum);
  286. }
  287. void qtauController::pianoKeyReleased(int keyNum)
  288. {
  289. DEVLOG_DEBUG("piano key released "+STR(keyNum));
  290. _previewRunning=false;
  291. if(_preview) _preview->stop();
  292. }
  293. #if 0
  294. bool qtauController::validateScore(const QJsonArray& ust)
  295. {
  296. // struct selectionRange sel = _mainWindow->getSelectionRange();
  297. //XXX if(_activeSynth) _activeSynth->setPlaybackSelection(sel);
  298. int tempo = 0;
  299. int lastNoteEnd=0;
  300. int noteCount = 0;
  301. for (int i = 0; i < ust.count(); ++i)
  302. {
  303. auto o = ust[i].toObject();
  304. if(!o.contains(NOTE_KEY_NUMBER)) {
  305. QJsonDocument doc(o);
  306. tempo=o[TEMPO].toInt();
  307. continue;
  308. }
  309. noteCount++;
  310. int noteOffset = o[NOTE_PULSE_OFFSET].toInt();
  311. int noteLength = o[NOTE_PULSE_LENGTH].toInt();
  312. int notenum = o[NOTE_KEY_NUMBER].toInt();
  313. QString lyric = o[NOTE_LYRIC].toString();
  314. int rest = noteOffset-lastNoteEnd;
  315. if(rest<0)
  316. {
  317. DEVLOG_ERROR("overlapping notes "+STR(i)+" "+STR(i-1));
  318. //SET color to red
  319. auto o = ust[i].toObject();
  320. auto o2 = ust[i-1].toObject();
  321. _mainWindow->markOverlappingNotes(_activeSession->getNote(o),_activeSession->getNote(o2));
  322. return false;
  323. }
  324. if(notenum<0 && notenum>127) return false;
  325. lastNoteEnd = noteOffset+noteLength;
  326. }
  327. if(noteCount==0) return false; //empty score
  328. if(tempo==0) return false;
  329. _mainWindow->updateNoteColors();
  330. return true;
  331. }
  332. #endif
  333. void qtauController::onRequestStartPlayback()
  334. {
  335. _localRequestStartPlayback=true;
  336. QJsonArray ust;
  337. _activeSession->ustJson(ust);
  338. if(_activeSynth!=_selectedSynth)
  339. {
  340. //XXX if(_activeSynth) _activeSynth->stopThread();
  341. _activeSynth = _selectedSynth;
  342. DEVLOG_DEBUG("synth selection");
  343. }
  344. DEVLOG_DEBUG("create score");
  345. TempoMap* tempoMap= _mainWindow->getTempoMap();
  346. QtauScore* score = new QtauScore(ust,tempoMap);
  347. if(score->getNoteCount()==0)
  348. {
  349. _mainWindow->onLog("empty session - nothing to do",ELog::error);
  350. _jack->changeTranportState(TRANSPORT_STOP);
  351. return;
  352. }
  353. bool result = _activeSynth->synthesize(score);
  354. if(result)
  355. {
  356. #if 0
  357. QString tmp = _activeSession->documentFile();
  358. tmp.replace(".ustj",".cache");
  359. if(tmp.length()==0) tmp="/tmp";
  360. _activeSynth->setCacheDir(tmp);
  361. if(_audio->useJackTransport()) _jack->changeTranportState(TRANSPORT_STOP);
  362. else _audio->setLocalTransportRolling(false);
  363. #endif
  364. if(_activeSynth->synthIsRealtime())
  365. {
  366. DEVLOG_DEBUG("schedule synth");
  367. _outbuf->scheduleSynth(_activeSynth);
  368. startPlayback(0);
  369. }
  370. else
  371. {
  372. DEVLOG_DEBUG("TODO:: synth must start playback");
  373. //_mainWindow->onLog("synth running offline",ELog::info);
  374. }
  375. }
  376. }
  377. void qtauController::onRequestStopPlayback()
  378. {
  379. _localRequestStartPlayback = false;
  380. if(_audio->useJackTransport()) _jack->changeTranportState(TRANSPORT_STOP);
  381. else {
  382. _audio->setLocalTransportRolling(false);
  383. //XXX if(_activeSynth) _activeSynth->stopThread();
  384. }
  385. }
  386. void qtauController::onRequestResetPlayback()
  387. {
  388. _localRequestStartPlayback = false;
  389. // XXX if(_activeSynth) _activeSynth->stopThread();
  390. _audio->setTransportPosition(0);
  391. if(_audio->useJackTransport())
  392. {
  393. _jack->changeTranportState(TRANSPORT_ZERO);
  394. }
  395. }
  396. //from synth plugin
  397. void qtauController::startPlayback(float startPos)
  398. {
  399. //_synthrunning = true;
  400. // _mainWindow->onLog("start playback",ELog::info);
  401. if(_audio->useJackTransport()==false)
  402. {
  403. _audio->setLocalTransportRolling(true);
  404. float _sampleRate_ = _jack->sampleRate(); //FIXXME
  405. if(startPos) _audio->setTransportPosition(_sampleRate_*startPos);
  406. }
  407. else
  408. {
  409. if(startPos==0)
  410. {
  411. _nonzeroStart=0;
  412. _jack->changeTranportState(TRANSPORT_START);
  413. }
  414. else
  415. {
  416. _nonzeroStart=30;
  417. float _sampleRate_ = _jack->sampleRate();
  418. _audio->setTransportPosition(_sampleRate_*startPos);
  419. _jack->transportStartPos(startPos);
  420. }
  421. }
  422. }
  423. void qtauController::stopPlayback()
  424. {
  425. _localRequestStartPlayback=false;
  426. //_synthrunning = false;
  427. //_mainWindow->onLog("stop playback",ELog::info);
  428. if(_audio->useJackTransport()==false)
  429. {
  430. _audio->setLocalTransportRolling(false);
  431. transportPositionChanged(-1);
  432. }
  433. else
  434. _jack->changeTranportState(TRANSPORT_STOP);
  435. }
  436. void qtauController::setJackTranportEnabled(bool enabled)
  437. {
  438. if(enabled==false)
  439. _jack->changeTranportState(TRANSPORT_STOP);
  440. _audio->setLocalTransportRolling(false);
  441. _jack->setUseTransport(enabled);
  442. _audio->setUseJackTransport(enabled);
  443. }
  444. void qtauController::updateTempoTimeSignature(int tempo)
  445. {
  446. (void) tempo;//FIXME
  447. //float bpm=tempo;
  448. //_samplesToMeasures = bpm/(_jackSampleRate*60);
  449. }
  450. void qtauController::logError(const QString &error)
  451. {
  452. _mainWindow->onLog(error,ELog::error);
  453. }
  454. void qtauController::logDebug(const QString &debug)
  455. {
  456. _mainWindow->onLog(debug,ELog::debug);
  457. }
  458. void qtauController::logSuccess(const QString &success)
  459. {
  460. _mainWindow->onLog(success,ELog::success);
  461. }
  462. void qtauController::addPluginAction(QAction *action)
  463. {
  464. _mainWindow->addPluginAction(action);
  465. }
  466. #if 0
  467. void qtauController::startThread(IThreaded *threaded)
  468. {
  469. WorkerThread *workerThread = new WorkerThread(threaded);
  470. workerThread->start();
  471. connect(workerThread,&WorkerThread::resultReady,workerThread,&WorkerThread::threadEnd);
  472. connect(workerThread,&WorkerThread::finished,workerThread,&WorkerThread::threadEnd2);
  473. }
  474. #endif