PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/exult/tags/Release0_991RC2/audio/xmidi.cc

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