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

/exult/tags/Release1_00/audio/xmidi.cc

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