1 /*
2  * XMIDI: Miles XMIDI to MID Library
3  *
4  * Copyright (C) 2001  Ryan Nunn
5  * Copyright (C) 2014  Bret Curtis
6  * Copyright (C) WildMIDI Developers 2015-2016
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA  02110-1301, USA.
22  */
23 
24 /* XMIDI Converter */
25 
26 #include "config.h"
27 
28 #include <stddef.h>
29 #include <stdint.h>
30 #include <string.h>
31 #include <stdlib.h>
32 
33 #include "xmi2mid.h"
34 #include "wm_error.h"
35 
36 /* Midi Status Bytes */
37 #define MIDI_STATUS_NOTE_OFF    0x8
38 #define MIDI_STATUS_NOTE_ON     0x9
39 #define MIDI_STATUS_AFTERTOUCH  0xA
40 #define MIDI_STATUS_CONTROLLER  0xB
41 #define MIDI_STATUS_PROG_CHANGE 0xC
42 #define MIDI_STATUS_PRESSURE    0xD
43 #define MIDI_STATUS_PITCH_WHEEL 0xE
44 #define MIDI_STATUS_SYSEX       0xF
45 
46 typedef struct _midi_event {
47     int32_t time;
48     uint8_t status;
49     uint8_t data[2];
50     uint32_t len;
51     uint8_t *buffer;
52     struct _midi_event *next;
53 } midi_event;
54 
55 typedef struct {
56     uint16_t type;
57     uint16_t tracks;
58 } midi_descriptor;
59 
60 struct xmi_ctx {
61     const uint8_t *src, *src_ptr;
62     uint32_t srcsize;
63     uint32_t datastart;
64     uint8_t *dst, *dst_ptr;
65     uint32_t dstsize, dstrem;
66     uint32_t convert_type;
67     midi_descriptor info;
68     int bank127[16];
69     midi_event **events;
70     signed short *timing;
71     midi_event *list;
72     midi_event *current;
73 };
74 
75 /* forward declarations of private functions */
76 static void DeleteEventList(midi_event *mlist);
77 static void CreateNewEvent(struct xmi_ctx *ctx, int32_t time); /* List manipulation */
78 static int GetVLQ(struct xmi_ctx *ctx, uint32_t *quant); /* Variable length quantity */
79 static int GetVLQ2(struct xmi_ctx *ctx, uint32_t *quant);/* Variable length quantity */
80 static int PutVLQ(struct xmi_ctx *ctx, uint32_t value);  /* Variable length quantity */
81 static int ConvertEvent(struct xmi_ctx *ctx,
82             const int32_t time, const uint8_t status, const int size);
83 static int32_t ConvertSystemMessage(struct xmi_ctx *ctx,
84                 const int32_t time, const uint8_t status);
85 static int32_t ConvertFiletoList(struct xmi_ctx *ctx);
86 static uint32_t ConvertListToMTrk(struct xmi_ctx *ctx, midi_event *mlist);
87 static int ParseXMI(struct xmi_ctx *ctx);
88 static int ExtractTracks(struct xmi_ctx *ctx);
89 static uint32_t ExtractTracksFromXmi(struct xmi_ctx *ctx);
90 
read1(struct xmi_ctx * ctx)91 static uint32_t read1(struct xmi_ctx *ctx)
92 {
93     uint8_t b0;
94     b0 = *ctx->src_ptr++;
95     return (b0);
96 }
97 
read2(struct xmi_ctx * ctx)98 static uint32_t read2(struct xmi_ctx *ctx)
99 {
100     uint8_t b0, b1;
101     b0 = *ctx->src_ptr++;
102     b1 = *ctx->src_ptr++;
103     return (b0 + (b1 << 8));
104 }
105 
read4(struct xmi_ctx * ctx)106 static uint32_t read4(struct xmi_ctx *ctx)
107 {
108     uint8_t b0, b1, b2, b3;
109     b3 = *ctx->src_ptr++;
110     b2 = *ctx->src_ptr++;
111     b1 = *ctx->src_ptr++;
112     b0 = *ctx->src_ptr++;
113     return (b0 + (b1<<8) + (b2<<16) + (b3<<24));
114 }
115 
copy(struct xmi_ctx * ctx,char * b,uint32_t len)116 static void copy(struct xmi_ctx *ctx, char *b, uint32_t len)
117 {
118     memcpy(b, ctx->src_ptr, len);
119     ctx->src_ptr += len;
120 }
121 
122 #define DST_CHUNK 8192
resize_dst(struct xmi_ctx * ctx)123 static void resize_dst(struct xmi_ctx *ctx) {
124     uint32_t pos = ctx->dst_ptr - ctx->dst;
125     ctx->dst = (uint8_t *) realloc(ctx->dst, ctx->dstsize + DST_CHUNK);
126     ctx->dstsize += DST_CHUNK;
127     ctx->dstrem += DST_CHUNK;
128     ctx->dst_ptr = ctx->dst + pos;
129 }
130 
write1(struct xmi_ctx * ctx,uint32_t val)131 static void write1(struct xmi_ctx *ctx, uint32_t val)
132 {
133     if (ctx->dstrem < 1)
134         resize_dst(ctx);
135     *ctx->dst_ptr++ = val & 0xff;
136     ctx->dstrem--;
137 }
138 
write2(struct xmi_ctx * ctx,uint32_t val)139 static void write2(struct xmi_ctx *ctx, uint32_t val)
140 {
141     if (ctx->dstrem < 2)
142         resize_dst(ctx);
143     *ctx->dst_ptr++ = (val>>8) & 0xff;
144     *ctx->dst_ptr++ = val & 0xff;
145     ctx->dstrem -= 2;
146 }
147 
write4(struct xmi_ctx * ctx,uint32_t val)148 static void write4(struct xmi_ctx *ctx, uint32_t val)
149 {
150     if (ctx->dstrem < 4)
151         resize_dst(ctx);
152     *ctx->dst_ptr++ = (val>>24)&0xff;
153     *ctx->dst_ptr++ = (val>>16)&0xff;
154     *ctx->dst_ptr++ = (val>>8) & 0xff;
155     *ctx->dst_ptr++ = val & 0xff;
156     ctx->dstrem -= 4;
157 }
158 
seeksrc(struct xmi_ctx * ctx,uint32_t pos)159 static void seeksrc(struct xmi_ctx *ctx, uint32_t pos) {
160     ctx->src_ptr = ctx->src + pos;
161 }
162 
seekdst(struct xmi_ctx * ctx,uint32_t pos)163 static void seekdst(struct xmi_ctx *ctx, uint32_t pos) {
164     ctx->dst_ptr = ctx->dst + pos;
165     while (ctx->dstsize < pos)
166         resize_dst(ctx);
167     ctx->dstrem = ctx->dstsize - pos;
168 }
169 
skipsrc(struct xmi_ctx * ctx,int32_t pos)170 static void skipsrc(struct xmi_ctx *ctx, int32_t pos) {
171     ctx->src_ptr += pos;
172 }
173 
skipdst(struct xmi_ctx * ctx,int32_t pos)174 static void skipdst(struct xmi_ctx *ctx, int32_t pos) {
175     size_t newpos;
176     ctx->dst_ptr += pos;
177     newpos = ctx->dst_ptr - ctx->dst;
178     while (ctx->dstsize < newpos)
179         resize_dst(ctx);
180     ctx->dstrem = ctx->dstsize - newpos;
181 }
182 
getsrcsize(struct xmi_ctx * ctx)183 static uint32_t getsrcsize(struct xmi_ctx *ctx) {
184     return (ctx->srcsize);
185 }
186 
getsrcpos(struct xmi_ctx * ctx)187 static uint32_t getsrcpos(struct xmi_ctx *ctx) {
188     return (ctx->src_ptr - ctx->src);
189 }
190 
getdstpos(struct xmi_ctx * ctx)191 static uint32_t getdstpos(struct xmi_ctx *ctx) {
192     return (ctx->dst_ptr - ctx->dst);
193 }
194 
195 /* This is a default set of patches to convert from MT32 to GM
196  * The index is the MT32 Patch number and the value is the GM Patch
197  * This is only suitable for music that doesn't do timbre changes
198  * XMIDIs that contain Timbre changes will not convert properly.
199  */
200 static const char mt32asgm[128] = {
201     0,  /* 0   Piano 1 */
202     1,  /* 1   Piano 2 */
203     2,  /* 2   Piano 3 (synth) */
204     4,  /* 3   EPiano 1 */
205     4,  /* 4   EPiano 2 */
206     5,  /* 5   EPiano 3 */
207     5,  /* 6   EPiano 4 */
208     3,  /* 7   Honkytonk */
209     16, /* 8   Organ 1 */
210     17, /* 9   Organ 2 */
211     18, /* 10  Organ 3 */
212     16, /* 11  Organ 4 */
213     19, /* 12  Pipe Organ 1 */
214     19, /* 13  Pipe Organ 2 */
215     19, /* 14  Pipe Organ 3 */
216     21, /* 15  Accordion */
217     6,  /* 16  Harpsichord 1 */
218     6,  /* 17  Harpsichord 2 */
219     6,  /* 18  Harpsichord 3 */
220     7,  /* 19  Clavinet 1 */
221     7,  /* 20  Clavinet 2 */
222     7,  /* 21  Clavinet 3 */
223     8,  /* 22  Celesta 1 */
224     8,  /* 23  Celesta 2 */
225     62, /* 24  Synthbrass 1 (62) */
226     63, /* 25  Synthbrass 2 (63) */
227     62, /* 26  Synthbrass 3 Bank 8 */
228     63, /* 27  Synthbrass 4 Bank 8 */
229     38, /* 28  Synthbass 1 */
230     39, /* 29  Synthbass 2 */
231     38, /* 30  Synthbass 3 Bank 8 */
232     39, /* 31  Synthbass 4 Bank 8 */
233     88, /* 32  Fantasy */
234     90, /* 33  Harmonic Pan - No equiv closest is polysynth(90) :( */
235     52, /* 34  Choral ?? Currently set to SynthVox(54). Should it be ChoirAhhs(52)??? */
236     92, /* 35  Glass */
237     97, /* 36  Soundtrack */
238     99, /* 37  Atmosphere */
239     14, /* 38  Warmbell, sounds kind of like crystal(98) perhaps Tubular Bells(14) would be better. It is! */
240     54, /* 39  FunnyVox, sounds alot like Bagpipe(109) and Shania(111) */
241     98, /* 40  EchoBell, no real equiv, sounds like Crystal(98) */
242     96, /* 41  IceRain */
243     68, /* 42  Oboe 2001, no equiv, just patching it to normal oboe(68) */
244     95, /* 43  EchoPans, no equiv, setting to SweepPad */
245     81, /* 44  DoctorSolo Bank 8 */
246     87, /* 45  SchoolDaze, no real equiv */
247     112,/* 46  Bell Singer */
248     80, /* 47  SquareWave */
249     48, /* 48  Strings 1 */
250     48, /* 49  Strings 2 - should be 49 */
251     44, /* 50  Strings 3 (Synth) - Experimental set to Tremollo Strings - should be 50 */
252     45, /* 51  Pizzicato Strings */
253     40, /* 52  Violin 1 */
254     40, /* 53  Violin 2 ? Viola */
255     42, /* 54  Cello 1 */
256     42, /* 55  Cello 2 */
257     43, /* 56  Contrabass */
258     46, /* 57  Harp 1 */
259     46, /* 58  Harp 2 */
260     24, /* 59  Guitar 1 (Nylon) */
261     25, /* 60  Guitar 2 (Steel) */
262     26, /* 61  Elec Guitar 1 */
263     27, /* 62  Elec Guitar 2 */
264     104,/* 63  Sitar */
265     32, /* 64  Acou Bass 1 */
266     32, /* 65  Acou Bass 2 */
267     33, /* 66  Elec Bass 1 */
268     34, /* 67  Elec Bass 2 */
269     36, /* 68  Slap Bass 1 */
270     37, /* 69  Slap Bass 2 */
271     35, /* 70  Fretless Bass 1 */
272     35, /* 71  Fretless Bass 2 */
273     73, /* 72  Flute 1 */
274     73, /* 73  Flute 2 */
275     72, /* 74  Piccolo 1 */
276     72, /* 75  Piccolo 2 */
277     74, /* 76  Recorder */
278     75, /* 77  Pan Pipes */
279     64, /* 78  Sax 1 */
280     65, /* 79  Sax 2 */
281     66, /* 80  Sax 3 */
282     67, /* 81  Sax 4 */
283     71, /* 82  Clarinet 1 */
284     71, /* 83  Clarinet 2 */
285     68, /* 84  Oboe */
286     69, /* 85  English Horn (Cor Anglais) */
287     70, /* 86  Bassoon */
288     22, /* 87  Harmonica */
289     56, /* 88  Trumpet 1 */
290     56, /* 89  Trumpet 2 */
291     57, /* 90  Trombone 1 */
292     57, /* 91  Trombone 2 */
293     60, /* 92  French Horn 1 */
294     60, /* 93  French Horn 2 */
295     58, /* 94  Tuba */
296     61, /* 95  Brass Section 1 */
297     61, /* 96  Brass Section 2 */
298     11, /* 97  Vibes 1 */
299     11, /* 98  Vibes 2 */
300     99, /* 99  Syn Mallet Bank 1 */
301     112,/* 100 WindBell no real equiv Set to TinkleBell(112) */
302     9,  /* 101 Glockenspiel */
303     14, /* 102 Tubular Bells */
304     13, /* 103 Xylophone */
305     12, /* 104 Marimba */
306     107,/* 105 Koto */
307     111,/* 106 Sho?? set to Shanai(111) */
308     77, /* 107 Shakauhachi */
309     78, /* 108 Whistle 1 */
310     78, /* 109 Whistle 2 */
311     76, /* 110 Bottle Blow */
312     76, /* 111 Breathpipe no real equiv set to bottle blow(76) */
313     47, /* 112 Timpani */
314     117,/* 113 Melodic Tom */
315     116,/* 114 Deap Snare no equiv, set to Taiko(116) */
316     118,/* 115 Electric Perc 1 */
317     118,/* 116 Electric Perc 2 */
318     116,/* 117 Taiko */
319     115,/* 118 Taiko Rim, no real equiv, set to Woodblock(115) */
320     119,/* 119 Cymbal, no real equiv, set to reverse cymbal(119) */
321     115,/* 120 Castanets, no real equiv, in GM set to Woodblock(115) */
322     112,/* 121 Triangle, no real equiv, set to TinkleBell(112) */
323     55, /* 122 Orchestral Hit */
324     124,/* 123 Telephone */
325     123,/* 124 BirdTweet */
326     94, /* 125 Big Notes Pad no equiv, set to halo pad (94) */
327     98, /* 126 Water Bell set to Crystal Pad(98) */
328     121 /* 127 Jungle Tune set to Breath Noise */
329 };
330 
331 /* Same as above, except include patch changes
332  * so GS instruments can be used */
333 static const char mt32asgs[256] = {
334     0, 0,   /* 0   Piano 1 */
335     1, 0,   /* 1   Piano 2 */
336     2, 0,   /* 2   Piano 3 (synth) */
337     4, 0,   /* 3   EPiano 1 */
338     4, 0,   /* 4   EPiano 2 */
339     5, 0,   /* 5   EPiano 3 */
340     5, 0,   /* 6   EPiano 4 */
341     3, 0,   /* 7   Honkytonk */
342     16, 0,  /* 8   Organ 1 */
343     17, 0,  /* 9   Organ 2 */
344     18, 0,  /* 10  Organ 3 */
345     16, 0,  /* 11  Organ 4 */
346     19, 0,  /* 12  Pipe Organ 1 */
347     19, 0,  /* 13  Pipe Organ 2 */
348     19, 0,  /* 14  Pipe Organ 3 */
349     21, 0,  /* 15  Accordion */
350     6, 0,   /* 16  Harpsichord 1 */
351     6, 0,   /* 17  Harpsichord 2 */
352     6, 0,   /* 18  Harpsichord 3 */
353     7, 0,   /* 19  Clavinet 1 */
354     7, 0,   /* 20  Clavinet 2 */
355     7, 0,   /* 21  Clavinet 3 */
356     8, 0,   /* 22  Celesta 1 */
357     8, 0,   /* 23  Celesta 2 */
358     62, 0,  /* 24  Synthbrass 1 (62) */
359     63, 0,  /* 25  Synthbrass 2 (63) */
360     62, 0,  /* 26  Synthbrass 3 Bank 8 */
361     63, 0,  /* 27  Synthbrass 4 Bank 8 */
362     38, 0,  /* 28  Synthbass 1 */
363     39, 0,  /* 29  Synthbass 2 */
364     38, 0,  /* 30  Synthbass 3 Bank 8 */
365     39, 0,  /* 31  Synthbass 4 Bank 8 */
366     88, 0,  /* 32  Fantasy */
367     90, 0,  /* 33  Harmonic Pan - No equiv closest is polysynth(90) :( */
368     52, 0,  /* 34  Choral ?? Currently set to SynthVox(54). Should it be ChoirAhhs(52)??? */
369     92, 0,  /* 35  Glass */
370     97, 0,  /* 36  Soundtrack */
371     99, 0,  /* 37  Atmosphere */
372     14, 0,  /* 38  Warmbell, sounds kind of like crystal(98) perhaps Tubular Bells(14) would be better. It is! */
373     54, 0,  /* 39  FunnyVox, sounds alot like Bagpipe(109) and Shania(111) */
374     98, 0,  /* 40  EchoBell, no real equiv, sounds like Crystal(98) */
375     96, 0,  /* 41  IceRain */
376     68, 0,  /* 42  Oboe 2001, no equiv, just patching it to normal oboe(68) */
377     95, 0,  /* 43  EchoPans, no equiv, setting to SweepPad */
378     81, 0,  /* 44  DoctorSolo Bank 8 */
379     87, 0,  /* 45  SchoolDaze, no real equiv */
380     112, 0, /* 46  Bell Singer */
381     80, 0,  /* 47  SquareWave */
382     48, 0,  /* 48  Strings 1 */
383     48, 0,  /* 49  Strings 2 - should be 49 */
384     44, 0,  /* 50  Strings 3 (Synth) - Experimental set to Tremollo Strings - should be 50 */
385     45, 0,  /* 51  Pizzicato Strings */
386     40, 0,  /* 52  Violin 1 */
387     40, 0,  /* 53  Violin 2 ? Viola */
388     42, 0,  /* 54  Cello 1 */
389     42, 0,  /* 55  Cello 2 */
390     43, 0,  /* 56  Contrabass */
391     46, 0,  /* 57  Harp 1 */
392     46, 0,  /* 58  Harp 2 */
393     24, 0,  /* 59  Guitar 1 (Nylon) */
394     25, 0,  /* 60  Guitar 2 (Steel) */
395     26, 0,  /* 61  Elec Guitar 1 */
396     27, 0,  /* 62  Elec Guitar 2 */
397     104, 0, /* 63  Sitar */
398     32, 0,  /* 64  Acou Bass 1 */
399     32, 0,  /* 65  Acou Bass 2 */
400     33, 0,  /* 66  Elec Bass 1 */
401     34, 0,  /* 67  Elec Bass 2 */
402     36, 0,  /* 68  Slap Bass 1 */
403     37, 0,  /* 69  Slap Bass 2 */
404     35, 0,  /* 70  Fretless Bass 1 */
405     35, 0,  /* 71  Fretless Bass 2 */
406     73, 0,  /* 72  Flute 1 */
407     73, 0,  /* 73  Flute 2 */
408     72, 0,  /* 74  Piccolo 1 */
409     72, 0,  /* 75  Piccolo 2 */
410     74, 0,  /* 76  Recorder */
411     75, 0,  /* 77  Pan Pipes */
412     64, 0,  /* 78  Sax 1 */
413     65, 0,  /* 79  Sax 2 */
414     66, 0,  /* 80  Sax 3 */
415     67, 0,  /* 81  Sax 4 */
416     71, 0,  /* 82  Clarinet 1 */
417     71, 0,  /* 83  Clarinet 2 */
418     68, 0,  /* 84  Oboe */
419     69, 0,  /* 85  English Horn (Cor Anglais) */
420     70, 0,  /* 86  Bassoon */
421     22, 0,  /* 87  Harmonica */
422     56, 0,  /* 88  Trumpet 1 */
423     56, 0,  /* 89  Trumpet 2 */
424     57, 0,  /* 90  Trombone 1 */
425     57, 0,  /* 91  Trombone 2 */
426     60, 0,  /* 92  French Horn 1 */
427     60, 0,  /* 93  French Horn 2 */
428     58, 0,  /* 94  Tuba */
429     61, 0,  /* 95  Brass Section 1 */
430     61, 0,  /* 96  Brass Section 2 */
431     11, 0,  /* 97  Vibes 1 */
432     11, 0,  /* 98  Vibes 2 */
433     99, 0,  /* 99  Syn Mallet Bank 1 */
434     112, 0, /* 100 WindBell no real equiv Set to TinkleBell(112) */
435     9, 0,   /* 101 Glockenspiel */
436     14, 0,  /* 102 Tubular Bells */
437     13, 0,  /* 103 Xylophone */
438     12, 0,  /* 104 Marimba */
439     107, 0, /* 105 Koto */
440     111, 0, /* 106 Sho?? set to Shanai(111) */
441     77, 0,  /* 107 Shakauhachi */
442     78, 0,  /* 108 Whistle 1 */
443     78, 0,  /* 109 Whistle 2 */
444     76, 0,  /* 110 Bottle Blow */
445     76, 0,  /* 111 Breathpipe no real equiv set to bottle blow(76) */
446     47, 0,  /* 112 Timpani */
447     117, 0, /* 113 Melodic Tom */
448     116, 0, /* 114 Deap Snare no equiv, set to Taiko(116) */
449     118, 0, /* 115 Electric Perc 1 */
450     118, 0, /* 116 Electric Perc 2 */
451     116, 0, /* 117 Taiko */
452     115, 0, /* 118 Taiko Rim, no real equiv, set to Woodblock(115) */
453     119, 0, /* 119 Cymbal, no real equiv, set to reverse cymbal(119) */
454     115, 0, /* 120 Castanets, no real equiv, in GM set to Woodblock(115) */
455     112, 0, /* 121 Triangle, no real equiv, set to TinkleBell(112) */
456     55, 0,  /* 122 Orchestral Hit */
457     124, 0, /* 123 Telephone */
458     123, 0, /* 124 BirdTweet */
459     94, 0,  /* 125 Big Notes Pad no equiv, set to halo pad (94) */
460     98, 0,  /* 126 Water Bell set to Crystal Pad(98) */
461     121, 0  /* 127 Jungle Tune set to Breath Noise */
462 };
463 
_WM_xmi2midi(const uint8_t * in,uint32_t insize,uint8_t ** out,uint32_t * outsize,uint32_t convert_type)464 int _WM_xmi2midi(const uint8_t *in, uint32_t insize,
465                  uint8_t **out, uint32_t *outsize,
466                  uint32_t convert_type) {
467     struct xmi_ctx ctx;
468     unsigned int i;
469     int ret = -1;
470 
471     if (convert_type > XMIDI_CONVERT_MT32_TO_GS) {
472         _WM_ERROR_NEW("%s:%i:  %d is an invalid conversion type.", __FUNCTION__, __LINE__, convert_type);
473         return (ret);
474     }
475 
476     memset(&ctx, 0, sizeof(struct xmi_ctx));
477     ctx.src = ctx.src_ptr = in;
478     ctx.srcsize = insize;
479     ctx.convert_type = convert_type;
480 
481     if (ParseXMI(&ctx) < 0) {
482         _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0);
483         goto _end;
484     }
485 
486     if (ExtractTracks(&ctx) < 0) {
487         _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MIDI, NULL, 0);
488         goto _end;
489     }
490 
491     ctx.dst = (uint8_t *) malloc(DST_CHUNK);
492     ctx.dst_ptr = ctx.dst;
493     ctx.dstsize = DST_CHUNK;
494     ctx.dstrem = DST_CHUNK;
495 
496     /* Header is 14 bytes long and add the rest as well */
497     write1(&ctx, 'M');
498     write1(&ctx, 'T');
499     write1(&ctx, 'h');
500     write1(&ctx, 'd');
501 
502     write4(&ctx, 6);
503 
504     write2(&ctx, ctx.info.type);
505     write2(&ctx, ctx.info.tracks);
506     write2(&ctx, ctx.timing[0]);/* write divisions from track0 */
507 
508     for (i = 0; i < ctx.info.tracks; i++)
509         ConvertListToMTrk(&ctx, ctx.events[i]);
510     *out = ctx.dst;
511     *outsize = ctx.dstsize - ctx.dstrem;
512     ret = 0;
513 
514 _end:   /* cleanup */
515     if (ret < 0) {
516         free(ctx.dst);
517         *out = NULL;
518         *outsize = 0;
519     }
520     if (ctx.events) {
521         for (i = 0; i < ctx.info.tracks; i++)
522             DeleteEventList(ctx.events[i]);
523         free(ctx.events);
524     }
525     free(ctx.timing);
526 
527     return (ret);
528 }
529 
DeleteEventList(midi_event * mlist)530 static void DeleteEventList(midi_event *mlist) {
531     midi_event *event;
532     midi_event *next;
533 
534     next = mlist;
535 
536     while ((event = next) != NULL) {
537         next = event->next;
538         free(event->buffer);
539         free(event);
540     }
541 }
542 
543 /* Sets current to the new event and updates list */
CreateNewEvent(struct xmi_ctx * ctx,int32_t time)544 static void CreateNewEvent(struct xmi_ctx *ctx, int32_t time) {
545     if (!ctx->list) {
546         ctx->list = ctx->current = (midi_event *) calloc(1, sizeof(midi_event));
547         ctx->current->time = (time < 0)? 0 : time;
548         return;
549     }
550 
551     if (time < 0) {
552         midi_event *event = (midi_event *) calloc(1, sizeof(midi_event));
553         event->next = ctx->list;
554         ctx->list = ctx->current = event;
555         return;
556     }
557 
558     if (ctx->current->time > time)
559         ctx->current = ctx->list;
560 
561     while (ctx->current->next) {
562         if (ctx->current->next->time > time) {
563             midi_event *event = (midi_event *) calloc(1, sizeof(midi_event));
564             event->next = ctx->current->next;
565             ctx->current->next = event;
566             ctx->current = event;
567             ctx->current->time = time;
568             return;
569         }
570 
571         ctx->current = ctx->current->next;
572     }
573 
574     ctx->current->next = (midi_event *) calloc(1, sizeof(midi_event));
575     ctx->current = ctx->current->next;
576     ctx->current->time = time;
577 }
578 
579 /* Conventional Variable Length Quantity */
GetVLQ(struct xmi_ctx * ctx,uint32_t * quant)580 static int GetVLQ(struct xmi_ctx *ctx, uint32_t *quant) {
581     int i;
582     uint32_t data;
583 
584     *quant = 0;
585     for (i = 0; i < 4; i++) {
586         data = read1(ctx);
587         *quant <<= 7;
588         *quant |= data & 0x7F;
589 
590         if (!(data & 0x80)) {
591             i++;
592             break;
593         }
594     }
595     return (i);
596 }
597 
598 /* XMIDI Delta Variable Length Quantity */
GetVLQ2(struct xmi_ctx * ctx,uint32_t * quant)599 static int GetVLQ2(struct xmi_ctx *ctx, uint32_t *quant) {
600     int i;
601     int32_t data;
602 
603     *quant = 0;
604     for (i = 0; i < 4; i++) {
605         data = read1(ctx);
606         if (data & 0x80) {
607             skipsrc(ctx, -1);
608             break;
609         }
610         *quant += data;
611     }
612     return (i);
613 }
614 
PutVLQ(struct xmi_ctx * ctx,uint32_t value)615 static int PutVLQ(struct xmi_ctx *ctx, uint32_t value) {
616     int32_t buffer;
617     int i = 1, j;
618     buffer = value & 0x7F;
619     while (value >>= 7) {
620         buffer <<= 8;
621         buffer |= ((value & 0x7F) | 0x80);
622         i++;
623     }
624     for (j = 0; j < i; j++) {
625         write1(ctx, buffer & 0xFF);
626         buffer >>= 8;
627     }
628 
629     return (i);
630 }
631 
632 /* Converts Events
633  *
634  * Source is at the first data byte
635  * size 1 is single data byte
636  * size 2 is dual data byte
637  * size 3 is XMI Note on
638  * Returns bytes converted  */
ConvertEvent(struct xmi_ctx * ctx,const int32_t time,const uint8_t status,const int size)639 static int ConvertEvent(struct xmi_ctx *ctx, const int32_t time,
640                         const uint8_t status, const int size) {
641     uint32_t delta = 0;
642     int32_t data;
643     midi_event *prev;
644     int i;
645 
646     data = read1(ctx);
647 
648     /* Bank changes are handled here */
649     if ((status >> 4) == 0xB && data == 0) {
650         data = read1(ctx);
651 
652         ctx->bank127[status & 0xF] = 0;
653 
654         if ( ctx->convert_type == XMIDI_CONVERT_MT32_TO_GM ||
655              ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS ||
656              ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127 ||
657             (ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127DRUM
658                     && (status & 0xF) == 9) )
659             return (2);
660 
661         CreateNewEvent(ctx, time);
662         ctx->current->status = status;
663         ctx->current->data[0] = 0;
664         ctx->current->data[1] = data;
665 
666         if (ctx->convert_type == XMIDI_CONVERT_GS127_TO_GS && data == 127)
667             ctx->bank127[status & 0xF] = 1;
668 
669         return (2);
670     }
671 
672     /* Handling for patch change mt32 conversion, probably should go elsewhere */
673     if ((status >> 4) == 0xC && (status&0xF) != 9
674             && ctx->convert_type != XMIDI_CONVERT_NOCONVERSION)
675     {
676         if (ctx->convert_type == XMIDI_CONVERT_MT32_TO_GM)
677         {
678             data = mt32asgm[data];
679         }
680         else if ((ctx->convert_type == XMIDI_CONVERT_GS127_TO_GS && ctx->bank127[status&0xF]) ||
681             ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS ||
682             ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127DRUM)
683         {
684             CreateNewEvent (ctx, time);
685             ctx->current->status = 0xB0 | (status&0xF);
686             ctx->current->data[0] = 0;
687             ctx->current->data[1] = mt32asgs[data*2+1];
688 
689             data = mt32asgs[data*2];
690         }
691         else if (ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127)
692         {
693             CreateNewEvent (ctx, time);
694             ctx->current->status = 0xB0 | (status&0xF);
695             ctx->current->data[0] = 0;
696             ctx->current->data[1] = 127;
697         }
698     }
699     /* Drum track handling */
700     else if ((status >> 4) == 0xC && (status&0xF) == 9 &&
701         (ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127DRUM || ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127))
702     {
703         CreateNewEvent (ctx, time);
704         ctx->current->status = 0xB9;
705         ctx->current->data[0] = 0;
706         ctx->current->data[1] = 127;
707     }
708 
709     CreateNewEvent(ctx, time);
710     ctx->current->status = status;
711 
712     ctx->current->data[0] = data;
713 
714     if (size == 1)
715         return (1);
716 
717     ctx->current->data[1] = read1(ctx);
718 
719     if (size == 2)
720         return (2);
721 
722     /* XMI Note On handling */
723     prev = ctx->current;
724     i = GetVLQ(ctx, &delta);
725     CreateNewEvent(ctx, time + delta * 3);
726 
727     ctx->current->status = status;
728     ctx->current->data[0] = data;
729     ctx->current->data[1] = 0;
730     ctx->current = prev;
731 
732     return (i + 2);
733 }
734 
735 /* Simple routine to convert system messages */
ConvertSystemMessage(struct xmi_ctx * ctx,const int32_t time,const uint8_t status)736 static int32_t ConvertSystemMessage(struct xmi_ctx *ctx, const int32_t time,
737                                     const uint8_t status) {
738     int32_t i = 0;
739 
740     CreateNewEvent(ctx, time);
741     ctx->current->status = status;
742 
743     /* Handling of Meta events */
744     if (status == 0xFF) {
745         ctx->current->data[0] = read1(ctx);
746         i++;
747     }
748 
749     i += GetVLQ(ctx, &ctx->current->len);
750 
751     if (!ctx->current->len)
752         return (i);
753 
754     ctx->current->buffer = (uint8_t *) malloc(sizeof(uint8_t)*ctx->current->len);
755     copy(ctx, (char *) ctx->current->buffer, ctx->current->len);
756 
757     return (i + ctx->current->len);
758 }
759 
760 /* XMIDI and Midi to List
761  * Returns XMIDI PPQN   */
ConvertFiletoList(struct xmi_ctx * ctx)762 static int32_t ConvertFiletoList(struct xmi_ctx *ctx) {
763     int32_t time = 0;
764     uint32_t data;
765     int32_t end = 0;
766     int32_t tempo = 500000;
767     int32_t tempo_set = 0;
768     uint32_t status = 0;
769     uint32_t file_size = getsrcsize(ctx);
770 
771     /* Set Drum track to correct setting if required */
772     if (ctx->convert_type == XMIDI_CONVERT_MT32_TO_GS127) {
773         CreateNewEvent(ctx, 0);
774         ctx->current->status = 0xB9;
775         ctx->current->data[0] = 0;
776         ctx->current->data[1] = 127;
777     }
778 
779     while (!end && getsrcpos(ctx) < file_size) {
780         GetVLQ2(ctx, &data);
781         time += data * 3;
782 
783         status = read1(ctx);
784 
785         switch (status >> 4) {
786         case MIDI_STATUS_NOTE_ON:
787             ConvertEvent(ctx, time, status, 3);
788             break;
789 
790         /* 2 byte data */
791         case MIDI_STATUS_NOTE_OFF:
792         case MIDI_STATUS_AFTERTOUCH:
793         case MIDI_STATUS_CONTROLLER:
794         case MIDI_STATUS_PITCH_WHEEL:
795             ConvertEvent(ctx, time, status, 2);
796             break;
797 
798         /* 1 byte data */
799         case MIDI_STATUS_PROG_CHANGE:
800         case MIDI_STATUS_PRESSURE:
801             ConvertEvent(ctx, time, status, 1);
802             break;
803 
804         case MIDI_STATUS_SYSEX:
805             if (status == 0xFF) {
806                 int32_t pos = getsrcpos(ctx);
807                 uint32_t dat = read1(ctx);
808 
809                 if (dat == 0x2F) /* End */
810                     end = 1;
811                 else if (dat == 0x51 && !tempo_set) /* Tempo. Need it for PPQN */
812                 {
813                     skipsrc(ctx, 1);
814                     tempo = read1(ctx) << 16;
815                     tempo += read1(ctx) << 8;
816                     tempo += read1(ctx);
817                     tempo *= 3;
818                     tempo_set = 1;
819                 } else if (dat == 0x51 && tempo_set) /* Skip any other tempo changes */
820                 {
821                     GetVLQ(ctx, &dat);
822                     skipsrc(ctx, dat);
823                     break;
824                 }
825 
826                 seeksrc(ctx, pos);
827             }
828             ConvertSystemMessage(ctx, time, status);
829             break;
830 
831         default:
832             break;
833         }
834     }
835     return ((tempo * 3) / 25000);
836 }
837 
838 /* Converts and event list to a MTrk
839  * Returns bytes of the array
840  * buf can be NULL */
ConvertListToMTrk(struct xmi_ctx * ctx,midi_event * mlist)841 static uint32_t ConvertListToMTrk(struct xmi_ctx *ctx, midi_event *mlist) {
842     int32_t time = 0;
843     midi_event *event;
844     uint32_t delta;
845     uint8_t last_status = 0;
846     uint32_t i = 8;
847     uint32_t j;
848     uint32_t size_pos, cur_pos;
849     int end = 0;
850 
851     write1(ctx, 'M');
852     write1(ctx, 'T');
853     write1(ctx, 'r');
854     write1(ctx, 'k');
855 
856     size_pos = getdstpos(ctx);
857     skipdst(ctx, 4);
858 
859     for (event = mlist; event && !end; event = event->next) {
860         delta = (event->time - time);
861         time = event->time;
862 
863         i += PutVLQ(ctx, delta);
864 
865         if ((event->status != last_status) || (event->status >= 0xF0)) {
866             write1(ctx, event->status);
867             i++;
868         }
869 
870         last_status = event->status;
871 
872         switch (event->status >> 4) {
873         /* 2 bytes data
874          * Note off, Note on, Aftertouch, Controller and Pitch Wheel */
875         case 0x8:
876         case 0x9:
877         case 0xA:
878         case 0xB:
879         case 0xE:
880             write1(ctx, event->data[0]);
881             write1(ctx, event->data[1]);
882             i += 2;
883             break;
884 
885         /* 1 bytes data
886          * Program Change and Channel Pressure */
887         case 0xC:
888         case 0xD:
889             write1(ctx, event->data[0]);
890             i++;
891             break;
892 
893         /* Variable length
894          * SysEx */
895         case 0xF:
896             if (event->status == 0xFF) {
897                 if (event->data[0] == 0x2f)
898                     end = 1;
899                 write1(ctx, event->data[0]);
900                 i++;
901             }
902             i += PutVLQ(ctx, event->len);
903             if (event->len) {
904                 for (j = 0; j < event->len; j++) {
905                     write1(ctx, event->buffer[j]);
906                     i++;
907                 }
908             }
909             break;
910 
911         /* Never occur */
912         default:
913             _WM_DEBUG_MSG("%s: unrecognized event", __FUNCTION__);
914             break;
915         }
916     }
917 
918     cur_pos = getdstpos(ctx);
919     seekdst(ctx, size_pos);
920     write4(ctx, i - 8);
921     seekdst(ctx, cur_pos);
922 
923     return (i);
924 }
925 
926 /* Assumes correct xmidi */
ExtractTracksFromXmi(struct xmi_ctx * ctx)927 static uint32_t ExtractTracksFromXmi(struct xmi_ctx *ctx) {
928     uint32_t num = 0;
929     signed short ppqn;
930     uint32_t len = 0;
931     int32_t begin;
932     char buf[32];
933 
934     while (getsrcpos(ctx) < getsrcsize(ctx) && num != ctx->info.tracks) {
935         /* Read first 4 bytes of name */
936         copy(ctx, buf, 4);
937         len = read4(ctx);
938 
939         /* Skip the FORM entries */
940         if (!memcmp(buf, "FORM", 4)) {
941             skipsrc(ctx, 4);
942             copy(ctx, buf, 4);
943             len = read4(ctx);
944         }
945 
946         if (memcmp(buf, "EVNT", 4)) {
947             skipsrc(ctx, (len + 1) & ~1);
948             continue;
949         }
950 
951         ctx->list = NULL;
952         begin = getsrcpos(ctx);
953 
954         /* Convert it */
955         if (!(ppqn = ConvertFiletoList(ctx))) {
956             _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, NULL, 0);
957             break;
958         }
959         ctx->timing[num] = ppqn;
960         ctx->events[num] = ctx->list;
961 
962         /* Increment Counter */
963         num++;
964 
965         /* go to start of next track */
966         seeksrc(ctx, begin + ((len + 1) & ~1));
967     }
968 
969     /* Return how many were converted */
970     return (num);
971 }
972 
ParseXMI(struct xmi_ctx * ctx)973 static int ParseXMI(struct xmi_ctx *ctx) {
974     uint32_t i;
975     uint32_t start;
976     uint32_t len;
977     uint32_t chunk_len;
978     uint32_t file_size;
979     char buf[32];
980 
981     file_size = getsrcsize(ctx);
982     if (getsrcpos(ctx) + 8 > file_size) {
983 badfile:    _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
984         return (-1);
985     }
986 
987     /* Read first 4 bytes of header */
988     copy(ctx, buf, 4);
989 
990     /* Could be XMIDI */
991     if (!memcmp(buf, "FORM", 4)) {
992         /* Read length of */
993         len = read4(ctx);
994 
995         start = getsrcpos(ctx);
996         if (start + 4 > file_size)
997             goto badfile;
998 
999         /* Read 4 bytes of type */
1000         copy(ctx, buf, 4);
1001 
1002         /* XDIRless XMIDI, we can handle them here. */
1003         if (!memcmp(buf, "XMID", 4)) {
1004             _WM_DEBUG_MSG("Warning: XMIDI without XDIR");
1005             ctx->info.tracks = 1;
1006         }
1007         /* Not an XMIDI that we recognise */
1008         else if (memcmp(buf, "XDIR", 4)) {
1009             goto badfile;
1010         }
1011         else { /* Seems Valid */
1012             ctx->info.tracks = 0;
1013 
1014             for (i = 4; i < len; i++) {
1015                 /* check too short files */
1016                 if (getsrcpos(ctx) + 10 > file_size)
1017                     break;
1018 
1019                 /* Read 4 bytes of type */
1020                 copy(ctx, buf, 4);
1021 
1022                 /* Read length of chunk */
1023                 chunk_len = read4(ctx);
1024 
1025                 /* Add eight bytes */
1026                 i += 8;
1027 
1028                 if (memcmp(buf, "INFO", 4)) {
1029                     /* Must align */
1030                     skipsrc(ctx, (chunk_len + 1) & ~1);
1031                     i += (chunk_len + 1) & ~1;
1032                     continue;
1033                 }
1034 
1035                 /* Must be at least 2 bytes long */
1036                 if (chunk_len < 2)
1037                     break;
1038 
1039                 ctx->info.tracks = read2(ctx);
1040                 break;
1041             }
1042 
1043             /* Didn't get to fill the header */
1044             if (ctx->info.tracks == 0) {
1045                 goto badfile;
1046             }
1047 
1048             /* Ok now to start part 2
1049              * Goto the right place */
1050             seeksrc(ctx, start + ((len + 1) & ~1));
1051             if (getsrcpos(ctx) + 12 > file_size)
1052                 goto badfile;
1053 
1054             /* Read 4 bytes of type */
1055             copy(ctx, buf, 4);
1056 
1057             if (memcmp(buf, "CAT ", 4)) {
1058                 _WM_ERROR_NEW("XMI error: expected \"CAT \", found \"%c%c%c%c\".",
1059                         buf[0], buf[1], buf[2], buf[3]);
1060                 return (-1);
1061             }
1062 
1063             /* Now read length of this track */
1064             read4(ctx);
1065 
1066             /* Read 4 bytes of type */
1067             copy(ctx, buf, 4);
1068 
1069             if (memcmp(buf, "XMID", 4)) {
1070                 _WM_ERROR_NEW("XMI error: expected \"XMID\", found \"%c%c%c%c\".",
1071                         buf[0], buf[1], buf[2], buf[3]);
1072                 return (-1);
1073             }
1074 
1075             /* Valid XMID */
1076             ctx->datastart = getsrcpos(ctx);
1077             return (0);
1078         }
1079     }
1080 
1081     return (-1);
1082 }
1083 
ExtractTracks(struct xmi_ctx * ctx)1084 static int ExtractTracks(struct xmi_ctx *ctx) {
1085     uint32_t i;
1086 
1087     ctx->events = (midi_event **) calloc(ctx->info.tracks, sizeof(midi_event*));
1088     ctx->timing = (int16_t *) calloc(ctx->info.tracks, sizeof(int16_t));
1089     /* type-2 for multi-tracks, type-0 otherwise */
1090     ctx->info.type = (ctx->info.tracks > 1)? 2 : 0;
1091 
1092     seeksrc(ctx, ctx->datastart);
1093     i = ExtractTracksFromXmi(ctx);
1094 
1095     if (i != ctx->info.tracks) {
1096         _WM_ERROR_NEW("XMI error: extracted only %u out of %u tracks from XMIDI",
1097                 ctx->info.tracks, i);
1098         return (-1);
1099     }
1100 
1101     return (0);
1102 }
1103 
1104