MidiExport.cpp 8.7 KB

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