Controller.cpp 16 KB

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