MidiExport.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * MidiExport.cpp - support for Exporting MIDI files
  3. *
  4. * Copyright (c) 2015 Mohamed Abdel Maksoud <mohamed at amaksoud.com>
  5. * Copyright (c) 2017 Hyunjin Song <tteu.ingog/at/gmail.com>
  6. *
  7. * This file is part of LMMS - https://lmms.io
  8. *
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public
  20. * License along with this program (see COPYING); if not, write to the
  21. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301 USA.
  23. *
  24. */
  25. #include <QDomDocument>
  26. #include <QDir>
  27. #include <QApplication>
  28. #include <QMessageBox>
  29. #include <QProgressDialog>
  30. #include "MidiExport.h"
  31. #include "lmms_math.h"
  32. #include "TrackContainer.h"
  33. #include "BBTrack.h"
  34. #include "InstrumentTrack.h"
  35. #include "LocaleHelper.h"
  36. extern "C"
  37. {
  38. Plugin::Descriptor PLUGIN_EXPORT midiexport_plugin_descriptor =
  39. {
  40. STRINGIFY( PLUGIN_NAME ),
  41. "MIDI Export",
  42. QT_TRANSLATE_NOOP( "pluginBrowser",
  43. "Filter for exporting MIDI-files from LMMS" ),
  44. "Mohamed Abdel Maksoud <mohamed at amaksoud.com> and "
  45. "Hyunjin Song <tteu.ingog/at/gmail.com>",
  46. 0x0100,
  47. Plugin::ExportFilter,
  48. NULL,
  49. NULL,
  50. NULL
  51. } ;
  52. }
  53. MidiExport::MidiExport() : ExportFilter( &midiexport_plugin_descriptor)
  54. {
  55. }
  56. MidiExport::~MidiExport()
  57. {
  58. }
  59. bool MidiExport::tryExport(const TrackContainer::TrackList &tracks,
  60. const TrackContainer::TrackList &tracks_BB,
  61. int tempo, int masterPitch, const QString &filename)
  62. {
  63. QFile f(filename);
  64. f.open(QIODevice::WriteOnly);
  65. QDataStream midiout(&f);
  66. InstrumentTrack* instTrack;
  67. BBTrack* bbTrack;
  68. QDomElement element;
  69. int nTracks = 0;
  70. uint8_t buffer[BUFFER_SIZE];
  71. uint32_t size;
  72. for (const Track* track : tracks) if (track->type() == Track::InstrumentTrack) nTracks++;
  73. for (const Track* track : tracks_BB) if (track->type() == Track::InstrumentTrack) nTracks++;
  74. // midi header
  75. MidiFile::MIDIHeader header(nTracks);
  76. size = header.writeToBuffer(buffer);
  77. midiout.writeRawData((char *)buffer, size);
  78. std::vector<std::vector<std::pair<int,int>>> plists;
  79. // midi tracks
  80. for (Track* track : tracks)
  81. {
  82. DataFile dataFile(DataFile::SongProject);
  83. MTrack mtrack;
  84. if (track->type() == Track::InstrumentTrack)
  85. {
  86. mtrack.addName(track->name().toStdString(), 0);
  87. //mtrack.addProgramChange(0, 0);
  88. mtrack.addTempo(tempo, 0);
  89. instTrack = dynamic_cast<InstrumentTrack *>(track);
  90. element = instTrack->saveState(dataFile, dataFile.content());
  91. int base_pitch = 0;
  92. double base_volume = 1.0;
  93. int base_time = 0;
  94. MidiNoteVector pat;
  95. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  96. {
  97. if (n.nodeName() == "instrumenttrack")
  98. {
  99. QDomElement it = n.toElement();
  100. // transpose +12 semitones, workaround for #1857
  101. base_pitch = (69 - it.attribute("basenote", "57").toInt());
  102. if (it.attribute("usemasterpitch", "1").toInt())
  103. {
  104. base_pitch += masterPitch;
  105. }
  106. base_volume = LocaleHelper::toDouble(it.attribute("volume", "100"))/100.0;
  107. }
  108. if (n.nodeName() == "pattern")
  109. {
  110. base_time = n.toElement().attribute("pos", "0").toInt();
  111. writePattern(pat, n, base_pitch, base_volume, base_time);
  112. }
  113. }
  114. ProcessBBNotes(pat, INT_MAX);
  115. writePatternToTrack(mtrack, pat);
  116. size = mtrack.writeToBuffer(buffer);
  117. midiout.writeRawData((char *)buffer, size);
  118. }
  119. if (track->type() == Track::BBTrack)
  120. {
  121. bbTrack = dynamic_cast<BBTrack *>(track);
  122. element = bbTrack->saveState(dataFile, dataFile.content());
  123. std::vector<std::pair<int,int>> plist;
  124. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  125. {
  126. if (n.nodeName() == "bbtco")
  127. {
  128. QDomElement it = n.toElement();
  129. int pos = it.attribute("pos", "0").toInt();
  130. int len = it.attribute("len", "0").toInt();
  131. plist.push_back(std::pair<int,int>(pos, pos+len));
  132. }
  133. }
  134. std::sort(plist.begin(), plist.end());
  135. plists.push_back(plist);
  136. }
  137. } // for each track
  138. // midi tracks in BB tracks
  139. for (Track* track : tracks_BB)
  140. {
  141. DataFile dataFile(DataFile::SongProject);
  142. MTrack mtrack;
  143. auto itr = plists.begin();
  144. std::vector<std::pair<int,int>> st;
  145. if (track->type() != Track::InstrumentTrack) continue;
  146. mtrack.addName(track->name().toStdString(), 0);
  147. //mtrack.addProgramChange(0, 0);
  148. mtrack.addTempo(tempo, 0);
  149. instTrack = dynamic_cast<InstrumentTrack *>(track);
  150. element = instTrack->saveState(dataFile, dataFile.content());
  151. int base_pitch = 0;
  152. double base_volume = 1.0;
  153. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  154. {
  155. if (n.nodeName() == "instrumenttrack")
  156. {
  157. QDomElement it = n.toElement();
  158. // transpose +12 semitones, workaround for #1857
  159. base_pitch = (69 - it.attribute("basenote", "57").toInt());
  160. if (it.attribute("usemasterpitch", "1").toInt())
  161. {
  162. base_pitch += masterPitch;
  163. }
  164. base_volume = LocaleHelper::toDouble(it.attribute("volume", "100")) / 100.0;
  165. }
  166. if (n.nodeName() == "pattern")
  167. {
  168. std::vector<std::pair<int,int>> &plist = *itr;
  169. MidiNoteVector nv, pat;
  170. writePattern(pat, n, base_pitch, base_volume, 0);
  171. // workaround for nested BBTCOs
  172. int pos = 0;
  173. int len = n.toElement().attribute("steps", "1").toInt() * 12;
  174. for (auto it = plist.begin(); it != plist.end(); ++it)
  175. {
  176. while (!st.empty() && st.back().second <= it->first)
  177. {
  178. writeBBPattern(pat, nv, len, st.back().first, pos, st.back().second);
  179. pos = st.back().second;
  180. st.pop_back();
  181. }
  182. if (!st.empty() && st.back().second <= it->second)
  183. {
  184. writeBBPattern(pat, nv, len, st.back().first, pos, it->first);
  185. pos = it->first;
  186. while (!st.empty() && st.back().second <= it->second)
  187. {
  188. st.pop_back();
  189. }
  190. }
  191. st.push_back(*it);
  192. pos = it->first;
  193. }
  194. while (!st.empty())
  195. {
  196. writeBBPattern(pat, nv, len, st.back().first, pos, st.back().second);
  197. pos = st.back().second;
  198. st.pop_back();
  199. }
  200. ProcessBBNotes(nv, pos);
  201. writePatternToTrack(mtrack, nv);
  202. ++itr;
  203. }
  204. }
  205. size = mtrack.writeToBuffer(buffer);
  206. midiout.writeRawData((char *)buffer, size);
  207. }
  208. return true;
  209. }
  210. void MidiExport::writePattern(MidiNoteVector &pat, QDomNode n,
  211. int base_pitch, double base_volume, int base_time)
  212. {
  213. // TODO interpret steps="12" muted="0" type="1" name="Piano1" len="2592"
  214. for (QDomNode nn = n.firstChild(); !nn.isNull(); nn = nn.nextSibling())
  215. {
  216. QDomElement note = nn.toElement();
  217. if (note.attribute("len", "0") == "0") continue;
  218. // TODO interpret pan="0" fxch="0" pitchrange="1"
  219. MidiNote mnote;
  220. mnote.pitch = qMax(0, qMin(127, note.attribute("key", "0").toInt() + base_pitch));
  221. // Map from LMMS volume to MIDI velocity
  222. mnote.volume = qMin(qRound(base_volume * LocaleHelper::toDouble(note.attribute("vol", "100")) * (127.0 / 200.0)), 127);
  223. mnote.time = base_time + note.attribute("pos", "0").toInt();
  224. mnote.duration = note.attribute("len", "0").toInt();
  225. pat.push_back(mnote);
  226. }
  227. }
  228. void MidiExport::writePatternToTrack(MTrack &mtrack, MidiNoteVector &nv)
  229. {
  230. for (auto it = nv.begin(); it != nv.end(); ++it)
  231. {
  232. mtrack.addNote(it->pitch, it->volume, it->time / 48.0, it->duration / 48.0);
  233. }
  234. }
  235. void MidiExport::writeBBPattern(MidiNoteVector &src, MidiNoteVector &dst,
  236. int len, int base, int start, int end)
  237. {
  238. if (start >= end) { return; }
  239. start -= base;
  240. end -= base;
  241. std::sort(src.begin(), src.end());
  242. for (auto it = src.begin(); it != src.end(); ++it)
  243. {
  244. for (int time = it->time + ceil((start - it->time) / len)
  245. * len; time < end; time += len)
  246. {
  247. MidiNote note;
  248. note.duration = it->duration;
  249. note.pitch = it->pitch;
  250. note.time = base + time;
  251. note.volume = it->volume;
  252. dst.push_back(note);
  253. }
  254. }
  255. }
  256. void MidiExport::ProcessBBNotes(MidiNoteVector &nv, int cutPos)
  257. {
  258. std::sort(nv.begin(), nv.end());
  259. int cur = INT_MAX, next = INT_MAX;
  260. for (auto it = nv.rbegin(); it != nv.rend(); ++it)
  261. {
  262. if (it->time < cur)
  263. {
  264. next = cur;
  265. cur = it->time;
  266. }
  267. if (it->duration < 0)
  268. {
  269. it->duration = qMin(qMin(-it->duration, next - cur), cutPos - it->time);
  270. }
  271. }
  272. }
  273. void MidiExport::error()
  274. {
  275. //qDebug() << "MidiExport error: " << m_error ;
  276. }
  277. extern "C"
  278. {
  279. // necessary for getting instance out of shared lib
  280. Plugin * PLUGIN_EXPORT lmms_plugin_main( Model *, void * _data )
  281. {
  282. return new MidiExport();
  283. }
  284. }