PageRenderTime 74ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/exult/tags/Release0_96Beta1/audio/xmidi.cc

#
C++ | 1517 lines | 1136 code | 249 blank | 132 comment | 262 complexity | a992811b8eb4523a41981238dabda38c MD5 | raw file
Possible License(s): GPL-2.0
  1. /*
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU General Public License
  5. * as published by the Free Software Foundation; either version 2
  6. * of the License, or (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  16. *
  17. */
  18. #ifdef HAVE_CONFIG_H
  19. # include <config.h>
  20. #endif
  21. #ifndef ALPHA_LINUX_CXX
  22. # include <unistd.h>
  23. # include <cstdio>
  24. # include <cmath>
  25. # include <iostream>
  26. # include <cmath>
  27. #endif
  28. #include "exult.h"
  29. #include "utils.h"
  30. #include "xmidi.h"
  31. #include "Configuration.h"
  32. using std::atof;
  33. using std::atoi;
  34. using std::cerr;
  35. using std::endl;
  36. using std::memcmp;
  37. using std::memcpy;
  38. using std::string;
  39. #include "gamma.h"
  40. // Here's a bit of joy: WIN32 isn't SMP safe if we use operator new and delete.
  41. // On the other hand, nothing else is thread-safe if we use malloc()/free().
  42. // So, we wrap the implementations and use malloc()/calloc()/free() for WIN32, and
  43. // the C++ thread-safe allocator for other platforms.
  44. template<class T>
  45. inline T* Malloc(size_t num=1)
  46. {
  47. #ifdef WIN32
  48. return static_cast<T*>(std::malloc(num));
  49. #else
  50. return static_cast<T*>(::operator new(num));
  51. #endif
  52. }
  53. template<class T>
  54. inline T* Calloc(size_t num=1,size_t sz=0)
  55. {
  56. if(!sz)
  57. sz=sizeof(T);
  58. #ifdef WIN32
  59. return static_cast<T*>(std::calloc(num,sz));
  60. #else
  61. size_t total=sz*num;
  62. T *tmp=Malloc<T>(total);
  63. std::memset(tmp,0,total);
  64. return tmp;
  65. #endif
  66. }
  67. inline void Free(void *ptr)
  68. {
  69. #ifdef WIN32
  70. std::free(ptr);
  71. #else
  72. ::operator delete(ptr);
  73. #endif
  74. }
  75. // This is used to correct incorrect patch, vol and pan changes in midi files
  76. // The bias is just a value to used to work out if a vol and pan belong with a
  77. // patch change. This is to ensure that the default state of a midi file is with
  78. // the tracks centred, unless the first patch change says otherwise.
  79. #define PATCH_VOL_PAN_BIAS 5
  80. // This is a default set of patches to convert from MT32 to GM
  81. // The index is the MT32 Patch nubmer and the value is the GM Patch
  82. // This is only suitable for music that doesn'tdo timbre changes
  83. // XMIDIs that contain Timbre changes will not convert properly
  84. const char XMIDI::mt32asgm[128] = {
  85. 0, // 0 Piano 1
  86. 1, // 1 Piano 2
  87. 2, // 2 Piano 3 (synth)
  88. 4, // 3 EPiano 1
  89. 4, // 4 EPiano 2
  90. 5, // 5 EPiano 3
  91. 5, // 6 EPiano 4
  92. 3, // 7 Honkytonk
  93. 16, // 8 Organ 1
  94. 17, // 9 Organ 2
  95. 18, // 10 Organ 3
  96. 16, // 11 Organ 4
  97. 19, // 12 Pipe Organ 1
  98. 19, // 13 Pipe Organ 2
  99. 19, // 14 Pipe Organ 3
  100. 21, // 15 Accordion
  101. 6, // 16 Harpsichord 1
  102. 6, // 17 Harpsichord 2
  103. 6, // 18 Harpsichord 3
  104. 7, // 19 Clavinet 1
  105. 7, // 20 Clavinet 2
  106. 7, // 21 Clavinet 3
  107. 8, // 22 Celesta 1
  108. 8, // 23 Celesta 2
  109. 62, // 24 Synthbrass 1 (62)
  110. 63, // 25 Synthbrass 2 (63)
  111. 62, // 26 Synthbrass 3 Bank 8
  112. 63, // 27 Synthbrass 4 Bank 8
  113. 38, // 28 Synthbass 1
  114. 39, // 29 Synthbass 2
  115. 38, // 30 Synthbass 3 Bank 8
  116. 39, // 31 Synthbass 4 Bank 8
  117. 88, // 32 Fantasy
  118. 90, // 33 Harmonic Pan - No equiv closest is polysynth(90) :(
  119. 52, // 34 Choral ?? Currently set to SynthVox(54). Should it be ChoirAhhs(52)???
  120. 92, // 35 Glass
  121. 97, // 36 Soundtrack
  122. 99, // 37 Atmosphere
  123. 14, // 38 Warmbell, sounds kind of like crystal(98) perhaps Tubular Bells(14) would be better. It is!
  124. 54, // 39 FunnyVox, sounds alot like Bagpipe(109) and Shania(111)
  125. 98, // 40 EchoBell, no real equiv, sounds like Crystal(98)
  126. 96, // 41 IceRain
  127. 68, // 42 Oboe 2001, no equiv, just patching it to normal oboe(68)
  128. 95, // 43 EchoPans, no equiv, setting to SweepPad
  129. 81, // 44 DoctorSolo Bank 8
  130. 87, // 45 SchoolDaze, no real equiv
  131. 112, // 46 Bell Singer
  132. 80, // 47 SquareWave
  133. 48, // 48 Strings 1
  134. 48, // 49 Strings 2 - should be 49
  135. 44, // 50 Strings 3 (Synth) - Experimental set to Tremollo Strings - should be 50
  136. 45, // 51 Pizzicato Strings
  137. 40, // 52 Violin 1
  138. 40, // 53 Violin 2 ? Viola
  139. 42, // 54 Cello 1
  140. 42, // 55 Cello 2
  141. 43, // 56 Contrabass
  142. 46, // 57 Harp 1
  143. 46, // 58 Harp 2
  144. 24, // 59 Guitar 1 (Nylon)
  145. 25, // 60 Guitar 2 (Steel)
  146. 26, // 61 Elec Guitar 1
  147. 27, // 62 Elec Guitar 2
  148. 104, // 63 Sitar
  149. 32, // 64 Acou Bass 1
  150. 32, // 65 Acou Bass 2
  151. 33, // 66 Elec Bass 1
  152. 34, // 67 Elec Bass 2
  153. 36, // 68 Slap Bass 1
  154. 37, // 69 Slap Bass 2
  155. 35, // 70 Fretless Bass 1
  156. 35, // 71 Fretless Bass 2
  157. 73, // 72 Flute 1
  158. 73, // 73 Flute 2
  159. 72, // 74 Piccolo 1
  160. 72, // 75 Piccolo 2
  161. 74, // 76 Recorder
  162. 75, // 77 Pan Pipes
  163. 64, // 78 Sax 1
  164. 65, // 79 Sax 2
  165. 66, // 80 Sax 3
  166. 67, // 81 Sax 4
  167. 71, // 82 Clarinet 1
  168. 71, // 83 Clarinet 2
  169. 68, // 84 Oboe
  170. 69, // 85 English Horn (Cor Anglais)
  171. 70, // 86 Bassoon
  172. 22, // 87 Harmonica
  173. 56, // 88 Trumpet 1
  174. 56, // 89 Trumpet 2
  175. 57, // 90 Trombone 1
  176. 57, // 91 Trombone 2
  177. 60, // 92 French Horn 1
  178. 60, // 93 French Horn 2
  179. 58, // 94 Tuba
  180. 61, // 95 Brass Section 1
  181. 61, // 96 Brass Section 2
  182. 11, // 97 Vibes 1
  183. 11, // 98 Vibes 2
  184. 99, // 99 Syn Mallet Bank 1
  185. 112, // 100 WindBell no real equiv Set to TinkleBell(112)
  186. 9, // 101 Glockenspiel
  187. 14, // 102 Tubular Bells
  188. 13, // 103 Xylophone
  189. 12, // 104 Marimba
  190. 107, // 105 Koto
  191. 111, // 106 Sho?? set to Shanai(111)
  192. 77, // 107 Shakauhachi
  193. 78, // 108 Whistle 1
  194. 78, // 109 Whistle 2
  195. 76, // 110 Bottle Blow
  196. 76, // 111 Breathpipe no real equiv set to bottle blow(76)
  197. 47, // 112 Timpani
  198. 117, // 113 Melodic Tom
  199. 116, // 114 Deap Snare no equiv, set to Taiko(116)
  200. 118, // 115 Electric Perc 1
  201. 118, // 116 Electric Perc 2
  202. 116, // 117 Taiko
  203. 115, // 118 Taiko Rim, no real equiv, set to Woodblock(115)
  204. 119, // 119 Cymbal, no real equiv, set to reverse cymbal(119)
  205. 115, // 120 Castanets, no real equiv, in GM set to Woodblock(115)
  206. 112, // 121 Triangle, no real equiv, set to TinkleBell(112)
  207. 55, // 122 Orchestral Hit
  208. 124, // 123 Telephone
  209. 123, // 124 BirdTweet
  210. 94, // 125 Big Notes Pad no equiv, set to halo pad (94)
  211. 98, // 126 Water Bell set to Crystal Pad(98)
  212. 121 // 127 Jungle Tune set to Breath Noise
  213. };
  214. // Same as above, except include patch changes
  215. // so GS instruments can be used
  216. const char XMIDI::mt32asgs[256] = {
  217. 0, 0, // 0 Piano 1
  218. 1, 0, // 1 Piano 2
  219. 2, 0, // 2 Piano 3 (synth)
  220. 4, 0, // 3 EPiano 1
  221. 4, 0, // 4 EPiano 2
  222. 5, 0, // 5 EPiano 3
  223. 5, 0, // 6 EPiano 4
  224. 3, 0, // 7 Honkytonk
  225. 16, 0, // 8 Organ 1
  226. 17, 0, // 9 Organ 2
  227. 18, 0, // 10 Organ 3
  228. 16, 0, // 11 Organ 4
  229. 19, 0, // 12 Pipe Organ 1
  230. 19, 0, // 13 Pipe Organ 2
  231. 19, 0, // 14 Pipe Organ 3
  232. 21, 0, // 15 Accordion
  233. 6, 0, // 16 Harpsichord 1
  234. 6, 0, // 17 Harpsichord 2
  235. 6, 0, // 18 Harpsichord 3
  236. 7, 0, // 19 Clavinet 1
  237. 7, 0, // 20 Clavinet 2
  238. 7, 0, // 21 Clavinet 3
  239. 8, 0, // 22 Celesta 1
  240. 8, 0, // 23 Celesta 2
  241. 62, 0, // 24 Synthbrass 1 (62)
  242. 63, 0, // 25 Synthbrass 2 (63)
  243. 62, 0, // 26 Synthbrass 3 Bank 8
  244. 63, 0, // 27 Synthbrass 4 Bank 8
  245. 38, 0, // 28 Synthbass 1
  246. 39, 0, // 29 Synthbass 2
  247. 38, 0, // 30 Synthbass 3 Bank 8
  248. 39, 0, // 31 Synthbass 4 Bank 8
  249. 88, 0, // 32 Fantasy
  250. 90, 0, // 33 Harmonic Pan - No equiv closest is polysynth(90) :(
  251. 52, 0, // 34 Choral ?? Currently set to SynthVox(54). Should it be ChoirAhhs(52)???
  252. 92, 0, // 35 Glass
  253. 97, 0, // 36 Soundtrack
  254. 99, 0, // 37 Atmosphere
  255. 14, 0, // 38 Warmbell, sounds kind of like crystal(98) perhaps Tubular Bells(14) would be better. It is!
  256. 54, 0, // 39 FunnyVox, sounds alot like Bagpipe(109) and Shania(111)
  257. 98, 0, // 40 EchoBell, no real equiv, sounds like Crystal(98)
  258. 96, 0, // 41 IceRain
  259. 68, 0, // 42 Oboe 2001, no equiv, just patching it to normal oboe(68)
  260. 95, 0, // 43 EchoPans, no equiv, setting to SweepPad
  261. 81, 0, // 44 DoctorSolo Bank 8
  262. 87, 0, // 45 SchoolDaze, no real equiv
  263. 112, 0, // 46 Bell Singer
  264. 80, 0, // 47 SquareWave
  265. 48, 0, // 48 Strings 1
  266. 48, 0, // 49 Strings 2 - should be 49
  267. 44, 0, // 50 Strings 3 (Synth) - Experimental set to Tremollo Strings - should be 50
  268. 45, 0, // 51 Pizzicato Strings
  269. 40, 0, // 52 Violin 1
  270. 40, 0, // 53 Violin 2 ? Viola
  271. 42, 0, // 54 Cello 1
  272. 42, 0, // 55 Cello 2
  273. 43, 0, // 56 Contrabass
  274. 46, 0, // 57 Harp 1
  275. 46, 0, // 58 Harp 2
  276. 24, 0, // 59 Guitar 1 (Nylon)
  277. 25, 0, // 60 Guitar 2 (Steel)
  278. 26, 0, // 61 Elec Guitar 1
  279. 27, 0, // 62 Elec Guitar 2
  280. 104, 0, // 63 Sitar
  281. 32, 0, // 64 Acou Bass 1
  282. 32, 0, // 65 Acou Bass 2
  283. 33, 0, // 66 Elec Bass 1
  284. 34, 0, // 67 Elec Bass 2
  285. 36, 0, // 68 Slap Bass 1
  286. 37, 0, // 69 Slap Bass 2
  287. 35, 0, // 70 Fretless Bass 1
  288. 35, 0, // 71 Fretless Bass 2
  289. 73, 0, // 72 Flute 1
  290. 73, 0, // 73 Flute 2
  291. 72, 0, // 74 Piccolo 1
  292. 72, 0, // 75 Piccolo 2
  293. 74, 0, // 76 Recorder
  294. 75, 0, // 77 Pan Pipes
  295. 64, 0, // 78 Sax 1
  296. 65, 0, // 79 Sax 2
  297. 66, 0, // 80 Sax 3
  298. 67, 0, // 81 Sax 4
  299. 71, 0, // 82 Clarinet 1
  300. 71, 0, // 83 Clarinet 2
  301. 68, 0, // 84 Oboe
  302. 69, 0, // 85 English Horn (Cor Anglais)
  303. 70, 0, // 86 Bassoon
  304. 22, 0, // 87 Harmonica
  305. 56, 0, // 88 Trumpet 1
  306. 56, 0, // 89 Trumpet 2
  307. 57, 0, // 90 Trombone 1
  308. 57, 0, // 91 Trombone 2
  309. 60, 0, // 92 French Horn 1
  310. 60, 0, // 93 French Horn 2
  311. 58, 0, // 94 Tuba
  312. 61, 0, // 95 Brass Section 1
  313. 61, 0, // 96 Brass Section 2
  314. 11, 0, // 97 Vibes 1
  315. 11, 0, // 98 Vibes 2
  316. 99, 0, // 99 Syn Mallet Bank 1
  317. 112, 0, // 100 WindBell no real equiv Set to TinkleBell(112)
  318. 9, 0, // 101 Glockenspiel
  319. 14, 0, // 102 Tubular Bells
  320. 13, 0, // 103 Xylophone
  321. 12, 0, // 104 Marimba
  322. 107, 0, // 105 Koto
  323. 111, 0, // 106 Sho?? set to Shanai(111)
  324. 77, 0, // 107 Shakauhachi
  325. 78, 0, // 108 Whistle 1
  326. 78, 0, // 109 Whistle 2
  327. 76, 0, // 110 Bottle Blow
  328. 76, 0, // 111 Breathpipe no real equiv set to bottle blow(76)
  329. 47, 0, // 112 Timpani
  330. 117, 0, // 113 Melodic Tom
  331. 116, 0, // 114 Deap Snare no equiv, set to Taiko(116)
  332. 118, 0, // 115 Electric Perc 1
  333. 118, 0, // 116 Electric Perc 2
  334. 116, 0, // 117 Taiko
  335. 115, 0, // 118 Taiko Rim, no real equiv, set to Woodblock(115)
  336. 119, 0, // 119 Cymbal, no real equiv, set to reverse cymbal(119)
  337. 115, 0, // 120 Castanets, no real equiv, in GM set to Woodblock(115)
  338. 112, 0, // 121 Triangle, no real equiv, set to TinkleBell(112)
  339. 55, 0, // 122 Orchestral Hit
  340. 124, 0, // 123 Telephone
  341. 123, 0, // 124 BirdTweet
  342. 94, 0, // 125 Big Notes Pad no equiv, set to halo pad (94)
  343. 98, 0, // 126 Water Bell set to Crystal Pad(98)
  344. 121, 0 // 127 Jungle Tune set to Breath Noise
  345. };
  346. GammaTable<unsigned char> XMIDI::VolumeCurve(128);
  347. // Constructor
  348. XMIDI::XMIDI(DataSource *source, int pconvert) : events(NULL),timing(NULL),
  349. convert_type(pconvert),fixed(NULL),
  350. do_reverb(false), do_chorus(false)
  351. {
  352. std::memset(bank127,0,sizeof(bank127));
  353. ExtractTracks (source);
  354. }
  355. XMIDI::~XMIDI()
  356. {
  357. if (events)
  358. {
  359. for (int i=0; i < info.tracks; i++)
  360. DeleteEventList (events[i]);
  361. //delete [] events;
  362. Free(events);
  363. }
  364. if (timing) delete [] timing;
  365. if (fixed) delete [] fixed;
  366. }
  367. int XMIDI::retrieve (uint32 track, DataSource *dest)
  368. {
  369. int len = 0;
  370. if (!events)
  371. {
  372. cerr << "No midi data in loaded." << endl;
  373. return 0;
  374. }
  375. // Convert type 1 midi's to type 0
  376. if (info.type == 1)
  377. {
  378. DuplicateAndMerge(-1);
  379. for (int i=0; i < info.tracks; i++)
  380. DeleteEventList (events[i]);
  381. //delete [] events;
  382. Free (events);
  383. //events = new midi_event *[1];
  384. events = Calloc<midi_event *>();
  385. events[0] = list;
  386. info.tracks = 1;
  387. info.type = 0;
  388. }
  389. if (track >= info.tracks)
  390. {
  391. cerr << "Can't retrieve MIDI data, track out of range" << endl;
  392. return 0;
  393. }
  394. // And fix the midis if they are broken
  395. if (!fixed[track])
  396. {
  397. list = events[track];
  398. MovePatchVolAndPan ();
  399. fixed[track] = true;
  400. events[track] = list;
  401. }
  402. // This is so if using buffer datasource, the caller can know how big to make the buffer
  403. if (!dest)
  404. {
  405. // Header is 14 bytes long and add the rest as well
  406. len = ConvertListToMTrk (NULL, events[track]);
  407. return 14 + len;
  408. }
  409. dest->write1 ('M');
  410. dest->write1 ('T');
  411. dest->write1 ('h');
  412. dest->write1 ('d');
  413. dest->write4high (6);
  414. dest->write2high (0);
  415. dest->write2high (1);
  416. dest->write2high (timing[track]);
  417. len = ConvertListToMTrk (dest, events[track]);
  418. return len + 14;
  419. }
  420. int XMIDI::retrieve (uint32 track, midi_event **dest, int &ppqn)
  421. {
  422. if (!events)
  423. {
  424. cerr << "No midi data in loaded." << endl;
  425. return 0;
  426. }
  427. if ((info.type == 1 && track != 0) || (track >= info.tracks))
  428. {
  429. cerr << "Can't retrieve MIDI data, track out of range" << endl;
  430. return 0;
  431. }
  432. DuplicateAndMerge(track);
  433. MovePatchVolAndPan ();
  434. *dest = list;
  435. ppqn = timing[track];
  436. return 1;
  437. }
  438. void XMIDI::DeleteEventList (midi_event *mlist)
  439. {
  440. midi_event *event;
  441. midi_event *next;
  442. next = mlist;
  443. event = mlist;
  444. while ((event = next))
  445. {
  446. next = event->next;
  447. if (event->buffer)
  448. //delete [] event->buffer;
  449. Free (event->buffer);
  450. //delete event;
  451. Free (event);
  452. }
  453. }
  454. // Sets current to the new event and updates list
  455. void XMIDI::CreateNewEvent (int time)
  456. {
  457. if (!list)
  458. {
  459. list = current = Calloc<midi_event>(); //new midi_event;
  460. if (time > 0)
  461. current->time = time;
  462. return;
  463. }
  464. if (time < 0)
  465. {
  466. midi_event *event = Calloc<midi_event>(); //new midi_event;
  467. event->next = list;
  468. list = current = event;
  469. return;
  470. }
  471. if (current->time > time)
  472. current = list;
  473. while (current->next)
  474. {
  475. if (current->next->time > time)
  476. {
  477. midi_event *event = Calloc<midi_event>(); //new midi_event;
  478. event->next = current->next;
  479. current->next = event;
  480. current = event;
  481. current->time = time;
  482. return;
  483. }
  484. current = current->next;
  485. }
  486. current->next = Calloc<midi_event>(); //new midi_event;
  487. current = current->next;
  488. current->time = time;
  489. }
  490. // Conventional Variable Length Quantity
  491. int XMIDI::GetVLQ (DataSource *source, uint32 &quant)
  492. {
  493. int i;
  494. quant = 0;
  495. unsigned int data;
  496. for (i = 0; i < 4; i++)
  497. {
  498. data = source->read1();
  499. quant <<= 7;
  500. quant |= data & 0x7F;
  501. if (!(data & 0x80))
  502. {
  503. i++;
  504. break;
  505. }
  506. }
  507. return i;
  508. }
  509. // XMIDI Delta Variable Length Quantity
  510. int XMIDI::GetVLQ2 (DataSource *source, uint32 &quant)
  511. {
  512. int i;
  513. quant = 0;
  514. int data = 0;
  515. for (i = 0; i < 4; i++)
  516. {
  517. data = source->read1();
  518. if (data & 0x80)
  519. {
  520. source->skip(-1);
  521. break;
  522. }
  523. quant += data;
  524. }
  525. return i;
  526. }
  527. int XMIDI::PutVLQ(DataSource *dest, uint32 value)
  528. {
  529. int buffer;
  530. int i = 1;
  531. buffer = value & 0x7F;
  532. while (value >>= 7)
  533. {
  534. buffer <<= 8;
  535. buffer |= ((value & 0x7F) | 0x80);
  536. i++;
  537. }
  538. if (!dest) return i;
  539. for (int j = 0; j < i; j++)
  540. {
  541. dest->write1(buffer & 0xFF);
  542. buffer >>= 8;
  543. }
  544. return i;
  545. }
  546. // MovePatchVolAndPan
  547. //
  548. // This little function attempts to correct errors in midi files
  549. // that relate to patch, volume and pan changing
  550. void XMIDI::MovePatchVolAndPan (int channel)
  551. {
  552. if (channel == -1)
  553. {
  554. for (int i = 0; i < 16; i++)
  555. MovePatchVolAndPan (i);
  556. return;
  557. }
  558. midi_event *patch = NULL;
  559. midi_event *vol = NULL;
  560. midi_event *pan = NULL;
  561. midi_event *bank = NULL;
  562. midi_event *reverb = NULL;
  563. midi_event *chorus = NULL;
  564. midi_event *temp;
  565. for (current = list; current; )
  566. {
  567. if (!patch && (current->status >> 4) == 0xC && (current->status & 0xF) == channel)
  568. patch = current;
  569. else if (!vol && (current->status >> 4) == 0xB && current->data[0] == 7 && (current->status & 0xF) == channel)
  570. vol = current;
  571. else if (!pan && (current->status >> 4) == 0xB && current->data[0] == 10 && (current->status & 0xF) == channel)
  572. pan = current;
  573. else if (!bank && (current->status >> 4) == 0xB && current->data[0] == 0 && (current->status & 0xF) == channel)
  574. bank = current;
  575. if (pan && vol && patch) break;
  576. if (current) current = current->next;
  577. else current = list;
  578. }
  579. // Got no patch change, return and don't try fixing it
  580. if (!patch) return;
  581. // Copy Patch Change Event
  582. temp = patch;
  583. patch = Calloc<midi_event>(); //new midi_event;
  584. patch->time = temp->time;
  585. patch->status = channel|(MIDI_STATUS_PROG_CHANGE << 4);
  586. patch->data[0] = temp->data[0];
  587. // Copy Volume
  588. if (vol && (vol->time > patch->time+PATCH_VOL_PAN_BIAS || vol->time < patch->time-PATCH_VOL_PAN_BIAS))
  589. vol = NULL;
  590. temp = vol;
  591. vol = Calloc<midi_event>(); //new midi_event;
  592. vol->status = channel|(MIDI_STATUS_CONTROLLER << 4);
  593. vol->data[0] = 7;
  594. if (!temp)
  595. {
  596. if (convert_type) vol->data[1] = VolumeCurve[90];
  597. else vol->data[1] = 90;
  598. }
  599. else
  600. vol->data[1] = temp->data[1];
  601. // Copy Bank
  602. if (bank && (bank->time > patch->time+PATCH_VOL_PAN_BIAS || bank->time < patch->time-PATCH_VOL_PAN_BIAS))
  603. bank = NULL;
  604. temp = bank;
  605. bank = Calloc<midi_event>(); //new midi_event;
  606. bank->status = channel|(MIDI_STATUS_CONTROLLER << 4);
  607. if (!temp)
  608. bank->data[1] = 0;
  609. else
  610. bank->data[1] = temp->data[1];
  611. // Copy Pan
  612. if (pan && (pan->time > patch->time+PATCH_VOL_PAN_BIAS || pan->time < patch->time-PATCH_VOL_PAN_BIAS))
  613. pan = NULL;
  614. temp = pan;
  615. pan = Calloc<midi_event>(); //new midi_event;
  616. pan->status = channel|(MIDI_STATUS_CONTROLLER << 4);
  617. pan->data[0] = 10;
  618. if (!temp)
  619. pan->data[1] = 64;
  620. else
  621. pan->data[1] = temp->data[1];
  622. if (do_reverb)
  623. {
  624. reverb = Calloc<midi_event>(); //new midi_event;
  625. reverb->status = channel|(MIDI_STATUS_CONTROLLER << 4);
  626. reverb->data[0] = 91;
  627. reverb->data[1] = reverb_value;
  628. }
  629. if (do_chorus)
  630. {
  631. chorus = Calloc<midi_event>(); //new midi_event;
  632. chorus->status = channel|(MIDI_STATUS_CONTROLLER << 4);
  633. chorus->data[0] = 93;
  634. chorus->data[1] = chorus_value;
  635. }
  636. vol->time = 0;
  637. pan->time = 0;
  638. patch->time = 0;
  639. bank->time = 0;
  640. if (do_reverb && do_chorus) reverb->next = chorus;
  641. else if (do_reverb) reverb->next = bank;
  642. if (do_chorus) chorus->next = bank;
  643. bank->next = vol;
  644. vol->next = pan;
  645. pan->next = patch;
  646. patch->next = list;
  647. if (do_reverb) list = reverb;
  648. else if (do_chorus) list = chorus;
  649. else list = bank;
  650. }
  651. // DuplicateAndMerge
  652. void XMIDI::DuplicateAndMerge (int num)
  653. {
  654. int i;
  655. midi_event **track;
  656. int time = 0;
  657. int start = 0;
  658. int end = 1;
  659. if (info.type == 1)
  660. {
  661. start = 0;
  662. end = info.tracks;
  663. }
  664. else if (num >= 0 && num < info.tracks)
  665. {
  666. start += num;
  667. end += num;
  668. }
  669. track = Malloc<midi_event*>(sizeof(midi_event *)*info.tracks); //new midi_event *[info.tracks];
  670. // NOTE: Not using Calloc here, since we're initializing each element below.
  671. for (i = 0; i < info.tracks; i++)
  672. track[i] = events[i];
  673. current = list = NULL;
  674. while (1)
  675. {
  676. int lowest = 1 << 30;
  677. int selected = -1;
  678. int num_na = end-start;
  679. // Firstly we find the track with the lowest time
  680. // for it's current event
  681. for (i = start; i < end; i++)
  682. {
  683. if (!track[i])
  684. {
  685. num_na--;
  686. continue;
  687. }
  688. if (track[i]->time < lowest)
  689. {
  690. selected = i;
  691. lowest = track[i]->time;
  692. }
  693. }
  694. // This is just so I don't have to type [selected] all the time
  695. i = selected;
  696. // None left to convert
  697. if (!num_na) break;
  698. // Only need 1 end of track
  699. // So take the last one and ignore the rest;
  700. if ((num_na != 1) && (track[i]->status == 0xff) && (track[i]->data[0] == 0x2f))
  701. {
  702. track[i] = NULL;
  703. continue;
  704. }
  705. if (current)
  706. {
  707. current->next = Calloc<midi_event>(); //new midi_event;
  708. current = current->next;
  709. }
  710. else
  711. list = current = Calloc<midi_event>(); //new midi_event;
  712. current->next = NULL;
  713. time = track[i]->time;
  714. current->time = time;
  715. current->status = track[i]->status;
  716. current->data[0] = track[i]->data[0];
  717. current->data[1] = track[i]->data[1];
  718. current->len = track[i]->len;
  719. if (current->len)
  720. {
  721. current->buffer = Malloc<unsigned char>(current->len);
  722. memcpy (current->buffer, track[i]->buffer, current->len);
  723. }
  724. else
  725. current->buffer = NULL;
  726. track[i] = track[i]->next;
  727. }
  728. }
  729. // Converts Events
  730. //
  731. // Source is at the first data byte
  732. // size 1 is single data byte
  733. // size 2 is dual data byte
  734. // size 3 is XMI Note on
  735. // Returns bytes converted
  736. int XMIDI::ConvertEvent (const int time, const unsigned char status, DataSource *source, const int size)
  737. {
  738. uint32 delta = 0;
  739. int data;
  740. data = source->read1();
  741. // Bank changes are handled here
  742. if ((status >> 4) == 0xB && data == 0)
  743. {
  744. data = source->read1();
  745. bank127[status&0xF] = false;
  746. if (convert_type == XMIDI_CONVERT_MT32_TO_GM || convert_type == XMIDI_CONVERT_MT32_TO_GS
  747. || convert_type == XMIDI_CONVERT_MT32_TO_GS127)
  748. return 2;
  749. CreateNewEvent (time);
  750. current->status = status;
  751. current->data[0] = 0;
  752. current->data[1] = data;
  753. if (convert_type == XMIDI_CONVERT_GS127_TO_GS && data == 127)
  754. bank127[status&0xF] = true;
  755. return 2;
  756. }
  757. // Handling for patch change mt32 conversion, probably should go elsewhere
  758. if ((status >> 4) == 0xC && (status&0xF) != 9 && convert_type != XMIDI_CONVERT_NOCONVERSION)
  759. {
  760. if (convert_type == XMIDI_CONVERT_MT32_TO_GM)
  761. {
  762. data = mt32asgm[data];
  763. }
  764. else if ((convert_type == XMIDI_CONVERT_GS127_TO_GS && bank127[status&0xF]) ||
  765. convert_type == XMIDI_CONVERT_MT32_TO_GS)
  766. {
  767. CreateNewEvent (time);
  768. current->status = 0xB0 | (status&0xF);
  769. current->data[0] = 0;
  770. current->data[1] = mt32asgs[data*2+1];
  771. data = mt32asgs[data*2];
  772. }
  773. else if (convert_type == XMIDI_CONVERT_MT32_TO_GS127)
  774. {
  775. CreateNewEvent (time);
  776. current->status = 0xB0 | (status&0xF);
  777. current->data[0] = 0;
  778. current->data[1] = 127;
  779. }
  780. }// Disable patch changes on Track 10 is doing a conversion
  781. else if ((status >> 4) == 0xC && (status&0xF) == 9 && convert_type != XMIDI_CONVERT_NOCONVERSION)
  782. {
  783. return size;
  784. }
  785. CreateNewEvent (time);
  786. current->status = status;
  787. current->data[0] = data;
  788. if (size == 1)
  789. return 1;
  790. current->data[1] = source->read1();
  791. // Volume modify the note on's, only if converting
  792. if (convert_type && (current->status >> 4) == MIDI_STATUS_NOTE_ON && current->data[1])
  793. current->data[1] = VolumeCurve[current->data[1]];
  794. // Volume modify the volume controller, only if converting
  795. if (convert_type && (current->status >> 4) == MIDI_STATUS_CONTROLLER && current->data[0] == 7)
  796. current->data[1] = VolumeCurve[current->data[1]];
  797. if (size == 2)
  798. return 2;
  799. // XMI Note On handling
  800. // This is an optimization
  801. midi_event *prev = current;
  802. int i = GetVLQ (source, delta);
  803. CreateNewEvent (time+delta*3);
  804. current->status = status;
  805. current->data[0] = data;
  806. current->data[1] = 0;
  807. // Optimization
  808. current = prev;
  809. return i + 2;
  810. }
  811. // Simple routine to convert system messages
  812. int XMIDI::ConvertSystemMessage (const int time, const unsigned char status, DataSource *source)
  813. {
  814. int i=0;
  815. CreateNewEvent (time);
  816. current->status = status;
  817. // Handling of Meta events
  818. if (status == 0xFF)
  819. {
  820. current->data[0] = source->read1();
  821. i++;
  822. }
  823. i += GetVLQ (source, current->len);
  824. if (!current->len)
  825. {
  826. current->buffer = NULL;
  827. return i;
  828. }
  829. current->buffer = Malloc<unsigned char>(current->len);
  830. source->read (reinterpret_cast<char *>(current->buffer), current->len);
  831. return i+current->len;
  832. }
  833. // XMIDI and Midi to List
  834. // Returns XMIDI PPQN
  835. int XMIDI::ConvertFiletoList (DataSource *source, const bool is_xmi)
  836. {
  837. int time = 0;
  838. uint32 data;
  839. int end = 0;
  840. int tempo = 500000;
  841. int tempo_set = 0;
  842. uint32 status = 0;
  843. int play_size = 2;
  844. int file_size = source->getSize();
  845. if (is_xmi) play_size = 3;
  846. while (!end && source->getPos() < file_size)
  847. {
  848. if (!is_xmi)
  849. {
  850. GetVLQ (source, data);
  851. time += data;
  852. data = source->read1();
  853. if (data >= 0x80)
  854. {
  855. status = data;
  856. }
  857. else
  858. source->skip (-1);
  859. }
  860. else
  861. {
  862. GetVLQ2 (source, data);
  863. time += data*3;
  864. status = source->read1();
  865. }
  866. switch (status >> 4)
  867. {
  868. case MIDI_STATUS_NOTE_ON:
  869. ConvertEvent (time, status, source, play_size);
  870. break;
  871. // 2 byte data
  872. case MIDI_STATUS_NOTE_OFF:
  873. case MIDI_STATUS_AFTERTOUCH:
  874. case MIDI_STATUS_CONTROLLER:
  875. case MIDI_STATUS_PITCH_WHEEL:
  876. ConvertEvent (time, status, source, 2);
  877. break;
  878. // 1 byte data
  879. case MIDI_STATUS_PROG_CHANGE:
  880. case MIDI_STATUS_PRESSURE:
  881. ConvertEvent (time, status, source, 1);
  882. break;
  883. case MIDI_STATUS_SYSEX:
  884. if (status == 0xFF)
  885. {
  886. int pos = source->getPos();
  887. uint32 data = source->read1();
  888. if (data == 0x2F) // End
  889. end = 1;
  890. else if (data == 0x51 && !tempo_set) // Tempo. Need it for PPQN
  891. {
  892. source->skip(1);
  893. tempo = source->read1() << 16;
  894. tempo += source->read1() << 8;
  895. tempo += source->read1();
  896. tempo *= 3;
  897. tempo_set = 1;
  898. }
  899. else if (data == 0x51 && tempo_set && is_xmi) // Skip any other tempo changes
  900. {
  901. GetVLQ (source, data);
  902. source->skip(data);
  903. break;
  904. }
  905. source->seek (pos);
  906. }
  907. ConvertSystemMessage (time, status, source);
  908. break;
  909. default:
  910. break;
  911. }
  912. }
  913. return (tempo*3)/25000;
  914. }
  915. // Converts and event list to a MTrk
  916. // Returns bytes of the array
  917. // buf can be NULL
  918. uint32 XMIDI::ConvertListToMTrk (DataSource *dest, midi_event *mlist)
  919. {
  920. int time = 0;
  921. midi_event *event;
  922. uint32 delta;
  923. unsigned char last_status = 0;
  924. uint32 i = 8;
  925. uint32 j;
  926. uint32 size_pos=0;
  927. bool end = false;
  928. if (dest)
  929. {
  930. dest->write1('M');
  931. dest->write1('T');
  932. dest->write1('r');
  933. dest->write1('k');
  934. size_pos = dest->getPos();
  935. dest->skip(4);
  936. }
  937. for (event = mlist; event && !end; event=event->next)
  938. {
  939. delta = (event->time - time);
  940. time = event->time;
  941. i += PutVLQ (dest, delta);
  942. if ((event->status != last_status) || (event->status >= 0xF0))
  943. {
  944. if (dest) dest->write1(event->status);
  945. i++;
  946. }
  947. last_status = event->status;
  948. switch (event->status >> 4)
  949. {
  950. // 2 bytes data
  951. // Note off, Note on, Aftertouch, Controller and Pitch Wheel
  952. case 0x8: case 0x9: case 0xA: case 0xB: case 0xE:
  953. if (dest)
  954. {
  955. dest->write1(event->data[0]);
  956. dest->write1(event->data[1]);
  957. }
  958. i += 2;
  959. break;
  960. // 1 bytes data
  961. // Program Change and Channel Pressure
  962. case 0xC: case 0xD:
  963. if (dest) dest->write1(event->data[0]);
  964. i++;
  965. break;
  966. // Variable length
  967. // SysEx
  968. case 0xF:
  969. if (event->status == 0xFF)
  970. {
  971. if (event->data[0] == 0x2f) end = true;
  972. if (dest) dest->write1(event->data[0]);
  973. i++;
  974. }
  975. i += PutVLQ (dest, event->len);
  976. if (event->len)
  977. {
  978. for (j = 0; j < event->len; j++)
  979. {
  980. if (dest) dest->write1(event->buffer[j]);
  981. i++;
  982. }
  983. }
  984. break;
  985. // Never occur
  986. default:
  987. cerr << "Not supposed to see this" << endl;
  988. break;
  989. }
  990. }
  991. if (dest)
  992. {
  993. int cur_pos = dest->getPos();
  994. dest->seek (size_pos);
  995. dest->write4high (i-8);
  996. dest->seek (cur_pos);
  997. }
  998. return i;
  999. }
  1000. // Assumes correct xmidi
  1001. int XMIDI::ExtractTracksFromXmi (DataSource *source)
  1002. {
  1003. int num = 0;
  1004. signed short ppqn;
  1005. uint32 len = 0;
  1006. char buf[32];
  1007. while (source->getPos() < source->getSize() && num != info.tracks)
  1008. {
  1009. // Read first 4 bytes of name
  1010. source->read (buf, 4);
  1011. len = source->read4high();
  1012. // Skip the FORM entries
  1013. if (!memcmp(buf,"FORM",4))
  1014. {
  1015. source->skip (4);
  1016. source->read (buf, 4);
  1017. len = source->read4high();
  1018. }
  1019. if (memcmp(buf,"EVNT",4))
  1020. {
  1021. source->skip ((len+1)&~1);
  1022. continue;
  1023. }
  1024. list = NULL;
  1025. int begin = source->getPos ();
  1026. // Convert it
  1027. if (!(ppqn = ConvertFiletoList (source, true)))
  1028. {
  1029. cerr << "Unable to convert data" << endl;
  1030. break;
  1031. }
  1032. timing[num] = ppqn;
  1033. events[num] = list;
  1034. // Increment Counter
  1035. num++;
  1036. // go to start of next track
  1037. source->seek (begin + ((len+1)&~1));
  1038. }
  1039. // Return how many were converted
  1040. return num;
  1041. }
  1042. int XMIDI::ExtractTracksFromMid (DataSource *source)
  1043. {
  1044. int num = 0;
  1045. uint32 len = 0;
  1046. char buf[32];
  1047. while (source->getPos() < source->getSize() && num != info.tracks)
  1048. {
  1049. // Read first 4 bytes of name
  1050. source->read (buf, 4);
  1051. len = source->read4high();
  1052. if (memcmp(buf,"MTrk",4))
  1053. {
  1054. source->skip (len);
  1055. continue;
  1056. }
  1057. list = NULL;
  1058. int begin = source->getPos ();
  1059. // Convert it
  1060. if (!ConvertFiletoList (source, false))
  1061. {
  1062. cerr << "Unable to convert data" << endl;
  1063. break;
  1064. }
  1065. events[num] = list;
  1066. // Increment Counter
  1067. num++;
  1068. source->seek (begin+len);
  1069. }
  1070. // Return how many were converted
  1071. return num;
  1072. }
  1073. int XMIDI::ExtractTracks (DataSource *source)
  1074. {
  1075. uint32 i = 0;
  1076. int start;
  1077. uint32 len;
  1078. uint32 chunk_len;
  1079. int count;
  1080. char buf[32];
  1081. string s;
  1082. config->value("config/audio/midi/reverb/enabled",s,"no");
  1083. if (s == "yes") do_reverb = true;
  1084. config->set("config/audio/midi/reverb/enabled",s,true);
  1085. config->value("config/audio/midi/reverb/level",s,"---");
  1086. if (s == "---") config->value("config/audio/midi/reverb",s,"64");
  1087. reverb_value = atoi(s.c_str());
  1088. if (reverb_value > 127) reverb_value = 127;
  1089. else if (reverb_value < 0) reverb_value = 0;
  1090. config->set("config/audio/midi/reverb/level",reverb_value,true);
  1091. config->value("config/audio/midi/chorus/enabled",s,"no");
  1092. if (s == "yes") do_chorus = true;
  1093. config->set("config/audio/midi/chorus/enabled",s,true);
  1094. config->value("config/audio/midi/chorus/level",s,"---");
  1095. if (s == "---") config->value("config/audio/midi/chorus",s,"16");
  1096. chorus_value = atoi(s.c_str());
  1097. if (chorus_value > 127) chorus_value = 127;
  1098. else if (chorus_value < 0) chorus_value = 0;
  1099. config->set("config/audio/midi/chorus/level",chorus_value,true);
  1100. config->value("config/audio/midi/volume_curve",s,"---");
  1101. if (s == "---") config->value("config/audio/midi/gamma",s,"1");
  1102. VolumeCurve.set_gamma (atof(s.c_str()));
  1103. std::snprintf (buf, 32, "%f", VolumeCurve.get_gamma ());
  1104. config->set("config/audio/midi/volume_curve",buf,true);
  1105. // Read first 4 bytes of header
  1106. source->read (buf, 4);
  1107. // Could be XMIDI
  1108. if (!memcmp (buf, "FORM", 4))
  1109. {
  1110. // Read length of
  1111. len = source->read4high();
  1112. start = source->getPos();
  1113. // Read 4 bytes of type
  1114. source->read (buf, 4);
  1115. // XDIRless XMIDI, we can handle them here.
  1116. if (!memcmp (buf, "XMID", 4))
  1117. {
  1118. cerr << "Warning: XMIDI doesn't have XDIR" << endl;
  1119. info.tracks = 1;
  1120. } // Not an XMIDI that we recognise
  1121. else if (memcmp (buf, "XDIR", 4))
  1122. {
  1123. cerr << "Not a recognised XMID" << endl;
  1124. return 0;
  1125. } // Seems Valid
  1126. else
  1127. {
  1128. info.tracks = 0;
  1129. for (i = 4; i < len; i++)
  1130. {
  1131. // Read 4 bytes of type
  1132. source->read (buf, 4);
  1133. // Read length of chunk
  1134. chunk_len = source->read4high();
  1135. // Add eight bytes
  1136. i+=8;
  1137. if (memcmp (buf, "INFO", 4))
  1138. {
  1139. // Must allign
  1140. source->skip((chunk_len+1)&~1);
  1141. i+= (chunk_len+1)&~1;
  1142. continue;
  1143. }
  1144. // Must be at least 2 bytes long
  1145. if (chunk_len < 2)
  1146. break;
  1147. info.tracks = source->read2();
  1148. break;
  1149. }
  1150. // Didn't get to fill the header
  1151. if (info.tracks == 0)
  1152. {
  1153. cerr << "Not a valid XMID" << endl;
  1154. return 0;
  1155. }
  1156. // Ok now to start part 2
  1157. // Goto the right place
  1158. source->seek (start+((len+1)&~1));
  1159. // Read 4 bytes of type
  1160. source->read (buf, 4);
  1161. // Not an XMID
  1162. if (memcmp (buf, "CAT ", 4))
  1163. {
  1164. cerr << "Not a recognised XMID (" << buf[0] << buf[1] << buf[2] << buf[3] << ") should be (CAT )" << endl;
  1165. return 0;
  1166. }
  1167. // Now read length of this track
  1168. len = source->read4high();
  1169. // Read 4 bytes of type
  1170. source->read (buf, 4);
  1171. // Not an XMID
  1172. if (memcmp (buf, "XMID", 4))
  1173. {
  1174. cerr << "Not a recognised XMID (" << buf[0] << buf[1] << buf[2] << buf[3] << ") should be (XMID)" << endl;
  1175. return 0;
  1176. }
  1177. }
  1178. // Ok it's an XMID, so pass it to the ExtractCode
  1179. events = Calloc<midi_event*>(info.tracks); //new midi_event *[info.tracks];
  1180. timing = new short[info.tracks];
  1181. fixed = new bool[info.tracks];
  1182. info.type = 0;
  1183. for (i = 0; i < info.tracks; i++)
  1184. {
  1185. // events[i] = NULL; // Not necessary if we Calloc'ed it
  1186. fixed[i] = false;
  1187. }
  1188. count = ExtractTracksFromXmi (source);
  1189. if (count != info.tracks)
  1190. {
  1191. cerr << "Error: unable to extract all (" << info.tracks << ") tracks specified from XMIDI. Only ("<< count << ")" << endl;
  1192. int i = 0;
  1193. for (i = 0; i < info.tracks; i++)
  1194. DeleteEventList (events[i]);
  1195. //delete [] events;
  1196. Free (events);
  1197. delete [] timing;
  1198. return 0;
  1199. }
  1200. return 1;
  1201. }// Definately a Midi
  1202. else if (!memcmp (buf, "MThd", 4))
  1203. {
  1204. // Simple read length of header
  1205. len = source->read4high();
  1206. if (len < 6)
  1207. {
  1208. cerr << "Not a valid MIDI" << endl;
  1209. return 0;
  1210. }
  1211. info.type = source->read2high();
  1212. info.tracks = source->read2high();
  1213. events = Calloc<midi_event*>(info.tracks); //new midi_event *[info.tracks];
  1214. timing = new short[info.tracks];
  1215. fixed = new bool[info.tracks];
  1216. timing[0] = source->read2high();
  1217. for (i = 0; i < info.tracks; i++)
  1218. {
  1219. timing[i] = timing[0];
  1220. // events[i] = NULL; // Not necessary. We Calloc'ed
  1221. fixed[i] = false;
  1222. }
  1223. count = ExtractTracksFromMid (source);
  1224. if (count != info.tracks)
  1225. {
  1226. cerr << "Error: unable to extract all (" << info.tracks << ") tracks specified from MIDI. Only ("<< count << ")" << endl;
  1227. for (i = 0; i < info.tracks; i++)
  1228. DeleteEventList (events[i]);
  1229. //delete [] events;
  1230. Free (events);
  1231. delete [] timing;
  1232. return 0;
  1233. }
  1234. return 1;
  1235. }// A RIFF Midi, just pass the source back to this function at the start of the midi file
  1236. else if (!memcmp (buf, "RIFF", 4))
  1237. {
  1238. // Read len
  1239. len = source->read4();
  1240. // Read 4 bytes of type
  1241. source->read (buf, 4);
  1242. // Not an RMID
  1243. if (memcmp (buf, "RMID", 4))
  1244. {
  1245. cerr << "Invalid RMID" << endl;
  1246. return 0;
  1247. }
  1248. // Is a RMID
  1249. for (i = 4; i < len; i++)
  1250. {
  1251. // Read 4 bytes of type
  1252. source->read (buf, 4);
  1253. chunk_len = source->read4();
  1254. i+=8;
  1255. if (memcmp (buf, "data", 4))
  1256. {
  1257. // Must allign
  1258. source->skip ((chunk_len+1)&~1);
  1259. i+= (chunk_len+1)&~1;
  1260. continue;
  1261. }
  1262. return ExtractTracks (source);
  1263. }
  1264. cerr << "Failed to find midi data in RIFF Midi" << endl;
  1265. return 0;
  1266. }
  1267. return 0;
  1268. }