1:- module(mididcg, [ midi//3
2 , noteon//3, noteoff//2
3 , note//4, note//5
4 , prog//2, prog//3 , prog//4
5 , pan//2, volume//2
6 , tempo//1, keysig//2, timesig//1
7 , instr//2
8 ]). 9
10:- use_module(library(clpfd)). 11:- use_module(library(dcg_pair)). 12:- use_module(library(dcg_core), [get//1, set//1]). 13:- use_module(library(genmidi), [gm/4]). 14
15midi(Msg,Arg1,Arg2) --> get(T) <\> [msg(T,M,Arg1,Arg2)], {M #= Msg}.
16midi(Msg,Arg1) --> get(T) <\> [msg(T,M,Arg1)], {M #= Msg}.
17meta(Msg,Bytes) --> get(T) <\> [meta(T,M,N,Bytes)], {M #= Msg, length(Bytes,N)}.
18text(Type,Text) --> get(T) <\> [text(T,M,Text)], {text_type_code(M, Type)}.
19
20text_type_code(0x01, text).
21text_type_code(0x02, copyright).
22text_type_code(0x03, track_name).
23text_type_code(0x04, instrument).
24text_type_code(0x05, lyric).
25text_type_code(0x06, marker).
26text_type_code(0x07, cue).
27
28tempo(T) --> meta(0x51, [B2, B1, B0]), {divmod(T,256,Z,B0), divmod(Z,256,B2,B1)}.
29keysig(Sharps,major) --> meta(0x59, [Sharps, 0]).
30keysig(Sharps,minor) --> meta(0x59, [Sharps, 1]).
31timesig(Num/Denom) --> meta(0x58, [Num, DenomPower, 24, 8]), { Denom #= 2^DenomPower }.
32
33holding_time(P) --> \< get(T), call_dcg(P), \< set(T).
34
35noteon(Ch, NN, V) --> midi(144+Ch ,NN, V).
36noteoff(Ch, NN) --> midi(128+Ch, NN, 0).
37
38note(Ch, Vel, Dur, NN) --> note(adv_z, Ch,Vel, Dur, NN).
39
40:- meta_predicate note(3,?,?,?,?,?,?). 41note(Adv,Ch,Vel,Dur,NN) -->
42 {N1 #= NN, V1 #= Vel},
43 noteon(Ch,N1,V1), \< call(Adv, Dur),
44 noteoff(Ch,N1).
45
46prog(Ch,Prog) -->
47 midi(192+Ch,Prog).
48
49prog(Ch,Prog,Bank) -->
50 { MSB #= Bank // 128,
51 LSB #= Bank mod 128
52 },
53 midi(176+Ch,0,MSB),
54 midi(176+Ch,32,LSB),
55 prog(Ch,Prog).
56
57prog(Ch,Prog,MSB,LSB) -->
58 midi(176+Ch,0,MSB),
59 midi(176+Ch,32,LSB),
60 prog(Ch,Prog).
61
62instr(Ch,Instr) -->
63 {gm(Instr,Prog,MSB,LSB)},
64 prog(Ch,Prog,MSB,LSB).
65
66pan(Ch,Pan) --> midi(176+Ch,10,Pan).
67
68volume(Ch,Vol) --> midi(176+Ch,7,Vol).
69
70adv_z(Dur,T1,T2) :- T2