MidiImport.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. /*
  2. * MidiImport.cpp - support for importing MIDI files
  3. *
  4. * Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #include <QDomDocument>
  25. #include <QDir>
  26. #include <QApplication>
  27. #include <QFile>
  28. #include <QMessageBox>
  29. #include <QProgressDialog>
  30. #include <sstream>
  31. #include <unordered_map>
  32. #include "MidiImport.h"
  33. #include "TrackContainer.h"
  34. #include "InstrumentTrack.h"
  35. #include "AutomationTrack.h"
  36. #include "AutomationPattern.h"
  37. #include "ConfigManager.h"
  38. #include "Pattern.h"
  39. #include "Instrument.h"
  40. #include "GuiApplication.h"
  41. #include "MainWindow.h"
  42. #include "TimePos.h"
  43. #include "debug.h"
  44. #include "Song.h"
  45. #include "embed.h"
  46. #include "plugin_export.h"
  47. #include "portsmf/allegro.h"
  48. #define makeID(_c0, _c1, _c2, _c3) \
  49. ( 0 | \
  50. ( ( _c0 ) | ( ( _c1 ) << 8 ) | ( ( _c2 ) << 16 ) | ( ( _c3 ) << 24 ) ) )
  51. extern "C"
  52. {
  53. Plugin::Descriptor PLUGIN_EXPORT midiimport_plugin_descriptor =
  54. {
  55. STRINGIFY( PLUGIN_NAME ),
  56. "MIDI Import",
  57. QT_TRANSLATE_NOOP( "PluginBrowser",
  58. "Filter for importing MIDI-files into LMMS" ),
  59. "Tobias Doerffel <tobydox/at/users/dot/sf/dot/net>",
  60. 0x0100,
  61. Plugin::ImportFilter,
  62. NULL,
  63. NULL,
  64. NULL
  65. } ;
  66. }
  67. MidiImport::MidiImport( const QString & _file ) :
  68. ImportFilter( _file, &midiimport_plugin_descriptor ),
  69. m_events(),
  70. m_timingDivision( 0 )
  71. {
  72. }
  73. MidiImport::~MidiImport()
  74. {
  75. }
  76. bool MidiImport::tryImport( TrackContainer* tc )
  77. {
  78. if( openFile() == false )
  79. {
  80. return false;
  81. }
  82. #ifdef LMMS_HAVE_FLUIDSYNTH
  83. if( gui != NULL &&
  84. ConfigManager::inst()->sf2File().isEmpty() )
  85. {
  86. QMessageBox::information( gui->mainWindow(),
  87. tr( "Setup incomplete" ),
  88. tr( "You have not set up a default soundfont in "
  89. "the settings dialog (Edit->Settings). "
  90. "Therefore no sound will be played back after "
  91. "importing this MIDI file. You should download "
  92. "a General MIDI soundfont, specify it in "
  93. "settings dialog and try again." ) );
  94. }
  95. #else
  96. if( gui )
  97. {
  98. QMessageBox::information( gui->mainWindow(),
  99. tr( "Setup incomplete" ),
  100. tr( "You did not compile LMMS with support for "
  101. "SoundFont2 player, which is used to add default "
  102. "sound to imported MIDI files. "
  103. "Therefore no sound will be played back after "
  104. "importing this MIDI file." ) );
  105. }
  106. #endif
  107. switch( readID() )
  108. {
  109. case makeID( 'M', 'T', 'h', 'd' ):
  110. printf( "MidiImport::tryImport(): found MThd\n");
  111. return readSMF( tc );
  112. case makeID( 'R', 'I', 'F', 'F' ):
  113. printf( "MidiImport::tryImport(): found RIFF\n");
  114. return readRIFF( tc );
  115. default:
  116. printf( "MidiImport::tryImport(): not a Standard MIDI "
  117. "file\n" );
  118. return false;
  119. }
  120. }
  121. class smfMidiCC
  122. {
  123. public:
  124. smfMidiCC() :
  125. at( NULL ),
  126. ap( NULL ),
  127. lastPos( 0 )
  128. { }
  129. AutomationTrack * at;
  130. AutomationPattern * ap;
  131. TimePos lastPos;
  132. smfMidiCC & create( TrackContainer* tc, QString tn )
  133. {
  134. if( !at )
  135. {
  136. // Keep LMMS responsive, for now the import runs
  137. // in the main thread. This should probably be
  138. // removed if that ever changes.
  139. qApp->processEvents();
  140. at = dynamic_cast<AutomationTrack *>( Track::create( Track::AutomationTrack, tc ) );
  141. }
  142. if( tn != "") {
  143. at->setName( tn );
  144. }
  145. return *this;
  146. }
  147. void clear()
  148. {
  149. at = NULL;
  150. ap = NULL;
  151. lastPos = 0;
  152. }
  153. smfMidiCC & putValue( TimePos time, AutomatableModel * objModel, float value )
  154. {
  155. if( !ap || time > lastPos + DefaultTicksPerBar )
  156. {
  157. TimePos pPos = TimePos( time.getBar(), 0 );
  158. ap = dynamic_cast<AutomationPattern*>(
  159. at->createTCO(pPos));
  160. ap->addObject( objModel );
  161. }
  162. lastPos = time;
  163. time = time - ap->startPosition();
  164. ap->putValue( time, value, false );
  165. ap->changeLength( TimePos( time.getBar() + 1, 0 ) );
  166. return *this;
  167. }
  168. };
  169. class smfMidiChannel
  170. {
  171. public:
  172. smfMidiChannel() :
  173. it( NULL ),
  174. p( NULL ),
  175. it_inst( NULL ),
  176. isSF2( false ),
  177. hasNotes( false )
  178. { }
  179. InstrumentTrack * it;
  180. Pattern* p;
  181. Instrument * it_inst;
  182. bool isSF2;
  183. bool hasNotes;
  184. QString trackName;
  185. smfMidiChannel * create( TrackContainer* tc, QString tn )
  186. {
  187. if( !it ) {
  188. // Keep LMMS responsive
  189. qApp->processEvents();
  190. it = dynamic_cast<InstrumentTrack *>( Track::create( Track::InstrumentTrack, tc ) );
  191. #ifdef LMMS_HAVE_FLUIDSYNTH
  192. it_inst = it->loadInstrument( "sf2player" );
  193. if( it_inst )
  194. {
  195. isSF2 = true;
  196. it_inst->loadFile( ConfigManager::inst()->sf2File() );
  197. it_inst->childModel( "bank" )->setValue( 0 );
  198. it_inst->childModel( "patch" )->setValue( 0 );
  199. }
  200. else
  201. {
  202. it_inst = it->loadInstrument( "patman" );
  203. }
  204. #else
  205. it_inst = it->loadInstrument( "patman" );
  206. #endif
  207. trackName = tn;
  208. if( trackName != "") {
  209. it->setName( tn );
  210. }
  211. // General MIDI default
  212. it->pitchRangeModel()->setInitValue( 2 );
  213. // Create a default pattern
  214. p = dynamic_cast<Pattern*>(it->createTCO(0));
  215. }
  216. return this;
  217. }
  218. void addNote( Note & n )
  219. {
  220. if (!p)
  221. {
  222. p = dynamic_cast<Pattern*>(it->createTCO(0));
  223. }
  224. p->addNote(n, false);
  225. hasNotes = true;
  226. }
  227. void splitPatterns()
  228. {
  229. Pattern * newPattern = nullptr;
  230. TimePos lastEnd(0);
  231. p->rearrangeAllNotes();
  232. for (auto n : p->notes())
  233. {
  234. if (!newPattern || n->pos() > lastEnd + DefaultTicksPerBar)
  235. {
  236. TimePos pPos = TimePos(n->pos().getBar(), 0);
  237. newPattern = dynamic_cast<Pattern*>(it->createTCO(pPos));
  238. }
  239. lastEnd = n->pos() + n->length();
  240. Note newNote(*n);
  241. newNote.setPos(n->pos(newPattern->startPosition()));
  242. newPattern->addNote(newNote, false);
  243. }
  244. delete p;
  245. p = nullptr;
  246. }
  247. };
  248. bool MidiImport::readSMF( TrackContainer* tc )
  249. {
  250. const int MIDI_CC_COUNT = 128 + 1; // 0-127 (128) + pitch bend
  251. const int preTrackSteps = 2;
  252. QProgressDialog pd( TrackContainer::tr( "Importing MIDI-file..." ),
  253. TrackContainer::tr( "Cancel" ), 0, preTrackSteps, gui->mainWindow() );
  254. pd.setWindowTitle( TrackContainer::tr( "Please wait..." ) );
  255. pd.setWindowModality(Qt::WindowModal);
  256. pd.setMinimumDuration( 0 );
  257. pd.setValue( 0 );
  258. std::istringstream stream(readAllData().toStdString());
  259. Alg_seq_ptr seq = new Alg_seq(stream, true);
  260. seq->convert_to_beats();
  261. pd.setMaximum( seq->tracks() + preTrackSteps );
  262. pd.setValue( 1 );
  263. // 128 CC + Pitch Bend
  264. smfMidiCC ccs[MIDI_CC_COUNT];
  265. // channels can be set out of 256 range
  266. // using unordered_map should fix most invalid loads and crashes while loading
  267. std::unordered_map<long, smfMidiChannel> chs;
  268. // NOTE: unordered_map::operator[] creates a new element if none exists
  269. MeterModel & timeSigMM = Engine::getSong()->getTimeSigModel();
  270. AutomationTrack * nt = dynamic_cast<AutomationTrack*>(
  271. Track::create(Track::AutomationTrack, Engine::getSong()));
  272. nt->setName(tr("MIDI Time Signature Numerator"));
  273. AutomationTrack * dt = dynamic_cast<AutomationTrack*>(
  274. Track::create(Track::AutomationTrack, Engine::getSong()));
  275. dt->setName(tr("MIDI Time Signature Denominator"));
  276. AutomationPattern * timeSigNumeratorPat =
  277. new AutomationPattern(nt);
  278. timeSigNumeratorPat->setDisplayName(tr("Numerator"));
  279. timeSigNumeratorPat->addObject(&timeSigMM.numeratorModel());
  280. AutomationPattern * timeSigDenominatorPat =
  281. new AutomationPattern(dt);
  282. timeSigDenominatorPat->setDisplayName(tr("Denominator"));
  283. timeSigDenominatorPat->addObject(&timeSigMM.denominatorModel());
  284. // TODO: adjust these to Time.Sig changes
  285. double beatsPerBar = 4;
  286. double ticksPerBeat = DefaultTicksPerBar / beatsPerBar;
  287. // Time-sig changes
  288. Alg_time_sigs * timeSigs = &seq->time_sig;
  289. for( int s = 0; s < timeSigs->length(); ++s )
  290. {
  291. Alg_time_sig timeSig = (*timeSigs)[s];
  292. timeSigNumeratorPat->putValue(timeSig.beat * ticksPerBeat, timeSig.num);
  293. timeSigDenominatorPat->putValue(timeSig.beat * ticksPerBeat, timeSig.den);
  294. }
  295. // manually call otherwise the pattern shows being 1 bar
  296. timeSigNumeratorPat->updateLength();
  297. timeSigDenominatorPat->updateLength();
  298. pd.setValue( 2 );
  299. // Tempo stuff
  300. AutomationPattern * tap = tc->tempoAutomationPattern();
  301. if( tap )
  302. {
  303. tap->clear();
  304. Alg_time_map * timeMap = seq->get_time_map();
  305. Alg_beats & beats = timeMap->beats;
  306. for( int i = 0; i < beats.len - 1; i++ )
  307. {
  308. Alg_beat_ptr b = &(beats[i]);
  309. double tempo = ( beats[i + 1].beat - b->beat ) /
  310. ( beats[i + 1].time - beats[i].time );
  311. tap->putValue( b->beat * ticksPerBeat, tempo * 60.0 );
  312. }
  313. if( timeMap->last_tempo_flag )
  314. {
  315. Alg_beat_ptr b = &( beats[beats.len - 1] );
  316. tap->putValue( b->beat * ticksPerBeat, timeMap->last_tempo * 60.0 );
  317. }
  318. }
  319. // Update the tempo to avoid crash when playing a project imported
  320. // via the command line
  321. Engine::updateFramesPerTick();
  322. // Song events
  323. for( int e = 0; e < seq->length(); ++e )
  324. {
  325. Alg_event_ptr evt = (*seq)[e];
  326. if( evt->is_update() )
  327. {
  328. printf("Unhandled SONG update: %d %f %s\n",
  329. evt->get_type_code(), evt->time, evt->get_attribute() );
  330. }
  331. }
  332. // Tracks
  333. for( int t = 0; t < seq->tracks(); ++t )
  334. {
  335. QString trackName = QString( tr( "Track" ) + " %1" ).arg( t );
  336. Alg_track_ptr trk = seq->track( t );
  337. pd.setValue( t + preTrackSteps );
  338. for( int c = 0; c < MIDI_CC_COUNT; c++ )
  339. {
  340. ccs[c].clear();
  341. }
  342. // Now look at events
  343. for( int e = 0; e < trk->length(); ++e )
  344. {
  345. Alg_event_ptr evt = (*trk)[e];
  346. if( evt->chan == -1 )
  347. {
  348. bool handled = false;
  349. if( evt->is_update() )
  350. {
  351. QString attr = evt->get_attribute();
  352. // seqnames is a track0 identifier (see allegro code)
  353. if (attr == (t == 0 ? "seqnames" : "tracknames")
  354. && evt->get_update_type() == 's')
  355. {
  356. trackName = evt->get_string_value();
  357. handled = true;
  358. }
  359. }
  360. if( !handled ) {
  361. // Write debug output
  362. printf("MISSING GLOBAL HANDLER\n");
  363. printf(" Chn: %d, Type Code: %d, Time: %f", (int) evt->chan,
  364. evt->get_type_code(), evt->time );
  365. if ( evt->is_update() )
  366. {
  367. printf( ", Update Type: %s", evt->get_attribute() );
  368. if ( evt->get_update_type() == 'a' )
  369. {
  370. printf( ", Atom: %s", evt->get_atom_value() );
  371. }
  372. }
  373. printf( "\n" );
  374. }
  375. }
  376. else if (evt->is_note())
  377. {
  378. smfMidiChannel * ch = chs[evt->chan].create( tc, trackName );
  379. Alg_note_ptr noteEvt = dynamic_cast<Alg_note_ptr>( evt );
  380. int ticks = noteEvt->get_duration() * ticksPerBeat;
  381. Note n( (ticks < 1 ? 1 : ticks ),
  382. noteEvt->get_start_time() * ticksPerBeat,
  383. noteEvt->get_identifier() - 12,
  384. noteEvt->get_loud() * (200.f / 127.f)); // Map from MIDI velocity to LMMS volume
  385. ch->addNote( n );
  386. }
  387. else if( evt->is_update() )
  388. {
  389. smfMidiChannel * ch = chs[evt->chan].create( tc, trackName );
  390. double time = evt->time*ticksPerBeat;
  391. QString update( evt->get_attribute() );
  392. if( update == "programi" )
  393. {
  394. long prog = evt->get_integer_value();
  395. if( ch->isSF2 )
  396. {
  397. ch->it_inst->childModel( "bank" )->setValue( 0 );
  398. ch->it_inst->childModel( "patch" )->setValue( prog );
  399. }
  400. else {
  401. const QString num = QString::number( prog );
  402. const QString filter = QString().fill( '0', 3 - num.length() ) + num + "*.pat";
  403. const QString dir = "/usr/share/midi/"
  404. "freepats/Tone_000/";
  405. const QStringList files = QDir( dir ).
  406. entryList( QStringList( filter ) );
  407. if( ch->it_inst && !files.empty() )
  408. {
  409. ch->it_inst->loadFile( dir+files.front() );
  410. }
  411. }
  412. }
  413. else if( update.startsWith( "control" ) || update == "bendr" )
  414. {
  415. int ccid = update.mid( 7, update.length()-8 ).toInt();
  416. if( update == "bendr" )
  417. {
  418. ccid = 128;
  419. }
  420. if( ccid <= 128 )
  421. {
  422. double cc = evt->get_real_value();
  423. AutomatableModel * objModel = NULL;
  424. switch( ccid )
  425. {
  426. case 0:
  427. if( ch->isSF2 && ch->it_inst )
  428. {
  429. objModel = ch->it_inst->childModel( "bank" );
  430. printf("BANK SELECT %f %d\n", cc, (int)(cc*127.0));
  431. cc *= 127.0f;
  432. }
  433. break;
  434. case 7:
  435. objModel = ch->it->volumeModel();
  436. cc *= 100.0f;
  437. break;
  438. case 10:
  439. objModel = ch->it->panningModel();
  440. cc = cc * 200.f - 100.0f;
  441. break;
  442. case 128:
  443. objModel = ch->it->pitchModel();
  444. cc = cc * 100.0f;
  445. break;
  446. default:
  447. //TODO: something useful for other CCs
  448. break;
  449. }
  450. if( objModel )
  451. {
  452. if( time == 0 && objModel )
  453. {
  454. objModel->setInitValue( cc );
  455. }
  456. else
  457. {
  458. if( ccs[ccid].at == NULL ) {
  459. ccs[ccid].create( tc, trackName + " > " + (
  460. objModel != NULL ?
  461. objModel->displayName() :
  462. QString("CC %1").arg(ccid) ) );
  463. }
  464. ccs[ccid].putValue( time, objModel, cc );
  465. }
  466. }
  467. }
  468. }
  469. else {
  470. printf("Unhandled update: %d %d %f %s\n", (int) evt->chan,
  471. evt->get_type_code(), evt->time, evt->get_attribute() );
  472. }
  473. }
  474. }
  475. }
  476. delete seq;
  477. for( auto& c: chs )
  478. {
  479. if (c.second.hasNotes)
  480. {
  481. c.second.splitPatterns();
  482. }
  483. else if (c.second.it)
  484. {
  485. printf(" Should remove empty track\n");
  486. // must delete trackView first - but where is it?
  487. //tc->removeTrack( chs[c].it );
  488. //it->deleteLater();
  489. }
  490. // Set channel 10 to drums as per General MIDI's orders
  491. if (c.first % 16l == 9 /* channel 10 */
  492. && c.second.hasNotes && c.second.it_inst && c.second.isSF2)
  493. {
  494. c.second.it_inst->childModel("bank")->setValue(128);
  495. c.second.it_inst->childModel("patch")->setValue(0);
  496. }
  497. }
  498. return true;
  499. }
  500. bool MidiImport::readRIFF( TrackContainer* tc )
  501. {
  502. // skip file length
  503. skip( 4 );
  504. // check file type ("RMID" = RIFF MIDI)
  505. if( readID() != makeID( 'R', 'M', 'I', 'D' ) )
  506. {
  507. invalid_format:
  508. qWarning( "MidiImport::readRIFF(): invalid file format" );
  509. return false;
  510. }
  511. // search for "data" chunk
  512. while( 1 )
  513. {
  514. const int id = readID();
  515. const int len = read32LE();
  516. if( file().atEnd() )
  517. {
  518. data_not_found:
  519. qWarning( "MidiImport::readRIFF(): data chunk not found" );
  520. return false;
  521. }
  522. if( id == makeID( 'd', 'a', 't', 'a' ) )
  523. {
  524. break;
  525. }
  526. if( len < 0 )
  527. {
  528. goto data_not_found;
  529. }
  530. skip( ( len + 1 ) & ~1 );
  531. }
  532. // the "data" chunk must contain data in SMF format
  533. if( readID() != makeID( 'M', 'T', 'h', 'd' ) )
  534. {
  535. goto invalid_format;
  536. }
  537. return readSMF( tc );
  538. }
  539. void MidiImport::error()
  540. {
  541. printf( "MidiImport::readTrack(): invalid MIDI data (offset %#x)\n",
  542. (unsigned int) file().pos() );
  543. }
  544. extern "C"
  545. {
  546. // necessary for getting instance out of shared lib
  547. PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *, void * _data )
  548. {
  549. return new MidiImport( QString::fromUtf8(
  550. static_cast<const char *>( _data ) ) );
  551. }
  552. }