MidiExport.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. #include "plugin_export.h"
  37. extern "C"
  38. {
  39. Plugin::Descriptor PLUGIN_EXPORT midiexport_plugin_descriptor =
  40. {
  41. STRINGIFY( PLUGIN_NAME ),
  42. "MIDI Export",
  43. QT_TRANSLATE_NOOP( "pluginBrowser",
  44. "Filter for exporting MIDI-files from LMMS" ),
  45. "Mohamed Abdel Maksoud <mohamed at amaksoud.com> and "
  46. "Hyunjin Song <tteu.ingog/at/gmail.com>",
  47. 0x0100,
  48. Plugin::ExportFilter,
  49. NULL,
  50. NULL,
  51. NULL
  52. } ;
  53. }
  54. MidiExport::MidiExport() : ExportFilter( &midiexport_plugin_descriptor)
  55. {
  56. }
  57. MidiExport::~MidiExport()
  58. {
  59. }
  60. bool MidiExport::tryExport(const TrackContainer::TrackList &tracks,
  61. const TrackContainer::TrackList &tracks_BB,
  62. int tempo, int masterPitch, const QString &filename)
  63. {
  64. QFile f(filename);
  65. f.open(QIODevice::WriteOnly);
  66. QDataStream midiout(&f);
  67. InstrumentTrack* instTrack;
  68. BBTrack* bbTrack;
  69. QDomElement element;
  70. int nTracks = 0;
  71. uint8_t buffer[BUFFER_SIZE];
  72. uint32_t size;
  73. for (const Track* track : tracks) if (track->type() == Track::InstrumentTrack) nTracks++;
  74. for (const Track* track : tracks_BB) if (track->type() == Track::InstrumentTrack) nTracks++;
  75. // midi header
  76. MidiFile::MIDIHeader header(nTracks);
  77. size = header.writeToBuffer(buffer);
  78. midiout.writeRawData((char *)buffer, size);
  79. std::vector<std::vector<std::pair<int,int>>> plists;
  80. // midi tracks
  81. for (Track* track : tracks)
  82. {
  83. DataFile dataFile(DataFile::SongProject);
  84. MTrack mtrack;
  85. if (track->type() == Track::InstrumentTrack)
  86. {
  87. mtrack.addName(track->name().toStdString(), 0);
  88. //mtrack.addProgramChange(0, 0);
  89. mtrack.addTempo(tempo, 0);
  90. instTrack = dynamic_cast<InstrumentTrack *>(track);
  91. element = instTrack->saveState(dataFile, dataFile.content());
  92. int base_pitch = 0;
  93. double base_volume = 1.0;
  94. int base_time = 0;
  95. MidiNoteVector pat;
  96. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  97. {
  98. if (n.nodeName() == "instrumenttrack")
  99. {
  100. QDomElement it = n.toElement();
  101. // transpose +12 semitones, workaround for #1857
  102. base_pitch = (69 - it.attribute("basenote", "57").toInt());
  103. if (it.attribute("usemasterpitch", "1").toInt())
  104. {
  105. base_pitch += masterPitch;
  106. }
  107. base_volume = LocaleHelper::toDouble(it.attribute("volume", "100"))/100.0;
  108. }
  109. if (n.nodeName() == "pattern")
  110. {
  111. base_time = n.toElement().attribute("pos", "0").toInt();
  112. writePattern(pat, n, base_pitch, base_volume, base_time);
  113. }
  114. }
  115. ProcessBBNotes(pat, INT_MAX);
  116. writePatternToTrack(mtrack, pat);
  117. size = mtrack.writeToBuffer(buffer);
  118. midiout.writeRawData((char *)buffer, size);
  119. }
  120. if (track->type() == Track::BBTrack)
  121. {
  122. bbTrack = dynamic_cast<BBTrack *>(track);
  123. element = bbTrack->saveState(dataFile, dataFile.content());
  124. std::vector<std::pair<int,int>> plist;
  125. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  126. {
  127. if (n.nodeName() == "bbtco")
  128. {
  129. QDomElement it = n.toElement();
  130. int pos = it.attribute("pos", "0").toInt();
  131. int len = it.attribute("len", "0").toInt();
  132. plist.push_back(std::pair<int,int>(pos, pos+len));
  133. }
  134. }
  135. std::sort(plist.begin(), plist.end());
  136. plists.push_back(plist);
  137. }
  138. } // for each track
  139. // midi tracks in BB tracks
  140. for (Track* track : tracks_BB)
  141. {
  142. DataFile dataFile(DataFile::SongProject);
  143. MTrack mtrack;
  144. auto itr = plists.begin();
  145. std::vector<std::pair<int,int>> st;
  146. if (track->type() != Track::InstrumentTrack) continue;
  147. mtrack.addName(track->name().toStdString(), 0);
  148. //mtrack.addProgramChange(0, 0);
  149. mtrack.addTempo(tempo, 0);
  150. instTrack = dynamic_cast<InstrumentTrack *>(track);
  151. element = instTrack->saveState(dataFile, dataFile.content());
  152. int base_pitch = 0;
  153. double base_volume = 1.0;
  154. for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
  155. {
  156. if (n.nodeName() == "instrumenttrack")
  157. {
  158. QDomElement it = n.toElement();
  159. // transpose +12 semitones, workaround for #1857
  160. base_pitch = (69 - it.attribute("basenote", "57").toInt());
  161. if (it.attribute("usemasterpitch", "1").toInt())
  162. {
  163. base_pitch += masterPitch;
  164. }
  165. base_volume = LocaleHelper::toDouble(it.attribute("volume", "100")) / 100.0;
  166. }
  167. if (n.nodeName() == "pattern")
  168. {
  169. std::vector<std::pair<int,int>> &plist = *itr;
  170. MidiNoteVector nv, pat;
  171. writePattern(pat, n, base_pitch, base_volume, 0);
  172. // workaround for nested BBTCOs
  173. int pos = 0;
  174. int len = n.toElement().attribute("steps", "1").toInt() * 12;
  175. for (auto it = plist.begin(); it != plist.end(); ++it)
  176. {
  177. while (!st.empty() && st.back().second <= it->first)
  178. {
  179. writeBBPattern(pat, nv, len, st.back().first, pos, st.back().second);
  180. pos = st.back().second;
  181. st.pop_back();
  182. }
  183. if (!st.empty() && st.back().second <= it->second)
  184. {
  185. writeBBPattern(pat, nv, len, st.back().first, pos, it->first);
  186. pos = it->first;
  187. while (!st.empty() && st.back().second <= it->second)
  188. {
  189. st.pop_back();
  190. }
  191. }
  192. st.push_back(*it);
  193. pos = it->first;
  194. }
  195. while (!st.empty())
  196. {
  197. writeBBPattern(pat, nv, len, st.back().first, pos, st.back().second);
  198. pos = st.back().second;
  199. st.pop_back();
  200. }
  201. ProcessBBNotes(nv, pos);
  202. writePatternToTrack(mtrack, nv);
  203. ++itr;
  204. }
  205. }
  206. size = mtrack.writeToBuffer(buffer);
  207. midiout.writeRawData((char *)buffer, size);
  208. }
  209. return true;
  210. }
  211. void MidiExport::writePattern(MidiNoteVector &pat, QDomNode n,
  212. int base_pitch, double base_volume, int base_time)
  213. {
  214. // TODO interpret steps="12" muted="0" type="1" name="Piano1" len="2592"
  215. for (QDomNode nn = n.firstChild(); !nn.isNull(); nn = nn.nextSibling())
  216. {
  217. QDomElement note = nn.toElement();
  218. if (note.attribute("len", "0") == "0") continue;
  219. // TODO interpret pan="0" fxch="0" pitchrange="1"
  220. MidiNote mnote;
  221. mnote.pitch = qMax(0, qMin(127, note.attribute("key", "0").toInt() + base_pitch));
  222. // Map from LMMS volume to MIDI velocity
  223. mnote.volume = qMin(qRound(base_volume * LocaleHelper::toDouble(note.attribute("vol", "100")) * (127.0 / 200.0)), 127);
  224. mnote.time = base_time + note.attribute("pos", "0").toInt();
  225. mnote.duration = note.attribute("len", "0").toInt();
  226. pat.push_back(mnote);
  227. }
  228. }
  229. void MidiExport::writePatternToTrack(MTrack &mtrack, MidiNoteVector &nv)
  230. {
  231. for (auto it = nv.begin(); it != nv.end(); ++it)
  232. {
  233. mtrack.addNote(it->pitch, it->volume, it->time / 48.0, it->duration / 48.0);
  234. }
  235. }
  236. void MidiExport::writeBBPattern(MidiNoteVector &src, MidiNoteVector &dst,
  237. int len, int base, int start, int end)
  238. {
  239. if (start >= end) { return; }
  240. start -= base;
  241. end -= base;
  242. std::sort(src.begin(), src.end());
  243. for (auto it = src.begin(); it != src.end(); ++it)
  244. {
  245. for (int time = it->time + ceil((start - it->time) / len)
  246. * len; time < end; time += len)
  247. {
  248. MidiNote note;
  249. note.duration = it->duration;
  250. note.pitch = it->pitch;
  251. note.time = base + time;
  252. note.volume = it->volume;
  253. dst.push_back(note);
  254. }
  255. }
  256. }
  257. void MidiExport::ProcessBBNotes(MidiNoteVector &nv, int cutPos)
  258. {
  259. std::sort(nv.begin(), nv.end());
  260. int cur = INT_MAX, next = INT_MAX;
  261. for (auto it = nv.rbegin(); it != nv.rend(); ++it)
  262. {
  263. if (it->time < cur)
  264. {
  265. next = cur;
  266. cur = it->time;
  267. }
  268. if (it->duration < 0)
  269. {
  270. it->duration = qMin(qMin(-it->duration, next - cur), cutPos - it->time);
  271. }
  272. }
  273. }
  274. void MidiExport::error()
  275. {
  276. //qDebug() << "MidiExport error: " << m_error ;
  277. }
  278. extern "C"
  279. {
  280. // necessary for getting instance out of shared lib
  281. PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *, void * _data )
  282. {
  283. return new MidiExport();
  284. }
  285. }