Source file MIDI.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
open Mm_base
open Mm_audio
type division = Ticks_per_quarter of int | SMPTE of int * int
type event =
| Note_off of Audio.Note.t * float
| Note_on of Audio.Note.t * float
| Aftertouch of int * float
| Control_change of int * int
| Patch of int
| Channel_aftertouch of int
| Pitch of int
| Sequence_number of int
| Text of string
| Copyright of string
| Track_name of string
| Instrument_name of string
| Lyric of string
| Marker of string
| Cue of string
| End_of_track
| Tempo of int
| Time_signature of int * int * int * int
| Key_signature of int * bool
| Custom of string
let samples_of_delta samplerate division tempo delta =
match division with
| Ticks_per_quarter tpq ->
let tpq = Int64.of_int tpq in
let tempo = Int64.of_int tempo in
let tps = Int64.of_int samplerate in
let ten = Int64.of_int 1000000 in
let delta = Int64.of_int delta in
let ( * ) = Int64.mul in
let ( / ) = Int64.div in
Int64.to_int (delta * tempo / tpq * tps / ten)
| SMPTE (fps, res) -> samplerate * delta / (fps * res)
let byte_of_float x =
let clip x = max 0 (min 127 x) in
char_of_int (clip (int_of_float (x *. 127.)))
let encode_event chan e =
let s = Bytes.create 3 in
let coi = char_of_int in
let bof = byte_of_float in
(match e with
| Note_off (n, v) ->
Bytes.set s 0 (coi ((0x8 lsl 4) + chan));
Bytes.set s 1 (coi n);
Bytes.set s 2 (bof v)
| Note_on (n, v) ->
Bytes.set s 0 (coi ((0x9 lsl 4) + chan));
Bytes.set s 1 (coi n);
Bytes.set s 2 (bof v)
| _ ->
assert false);
Bytes.to_string s
type buffer = {
mutable data : (int * event) list;
duration : int;
}
let create duration = { data = []; duration }
let duration buf = buf.duration
let copy b =
let ans = create (duration b) in
ans.data <- b.data;
ans
let clear_all buf = buf.data <- []
let clear buf ofs len =
if ofs = 0 && len = duration buf then clear_all buf
else
buf.data <- List.filter (fun (t, _) -> t < ofs || t >= ofs + len) buf.data
let buf ofs len =
if not (ofs = 0 && len = duration buf) then
buf.data <- List.filter (fun (t, _) -> ofs <= t && t < ofs + len) buf.data
let cmp te1 te2 = fst te1 - fst te2
let merge b1 b2 = b1.data <- List.merge cmp b1.data b2.data
let translate b d = b.data <- List.map (fun (t, e) -> (t + d, e)) b.data
let add b1 o1 b2 o2 len =
let b2 = copy b2 in
extract b2 o2 len;
translate b2 (o1 - o2);
merge b1 b2
let blit_all b1 b2 = b2.data <- b1.data
let blit b1 o1 b2 o2 len =
if o1 = 0 && o2 = 0 && duration b1 = len && duration b2 = len then
blit_all b1 b2
else (
let b1 = copy b1 in
clear b2 o2 len;
extract b1 o1 len;
translate b1 (o2 - o1);
merge b2 b1)
let insert b te =
assert (fst te < duration b);
b.data <- List.merge cmp b.data [te]
let data buf = buf.data
module Multitrack = struct
type t = buffer array
type buffer = t
let channels buf = Array.length buf
let duration buf = duration buf.(0)
let create chans duration = Array.init chans (fun _ -> create duration)
let clear ?channel buf ofs len =
match channel with
| None -> Array.iter (fun buf -> clear buf ofs len) buf
| Some c -> clear buf.(c) ofs len
end
module IO = struct
exception Invalid_data
module Reader = struct
class type t =
object
method read : int -> Multitrack.buffer -> int -> int -> int
method close : unit
end
class virtual base =
object (self)
inherit IO.helper
val mutable tracks = 0
val mutable division = Ticks_per_quarter 0
method private input_id = self#really_input 4
method! private input_int = self#input_int_be
method! private input_short = self#input_short_be
(** Read midi header. *)
method private read_header =
let id = self#input_id in
let len = self#input_int in
let fmt = self#input_short in
let track_nb = self#input_short in
let div = self#input_short in
let div =
if div land 0x8000 = 0 then
Ticks_per_quarter div
else (
let frames = (div lsr 8) land 0x7f in
let ticks = div land 0xff in
SMPTE (frames, ticks))
in
if id <> "MThd" || len <> 6 || (fmt <> 0 && fmt <> 1 && fmt <> 2) then
raise Invalid_header;
tracks <- track_nb;
division <- div
(** Read a midi track. *)
method private decode_track_data data =
let len = String.length data in
let data = Array.init len (fun i -> int_of_char data.[i]) in
let pos = ref 0 in
let read_delta () =
let ans = ref 0 in
while data.(!pos) land 0x80 <> 0 do
ans := (!ans lsl 7) + (data.(!pos) land 0x7f);
incr pos;
if !pos >= Array.length data then raise Invalid_data
done;
ans := (!ans lsl 7) + data.(!pos);
incr pos;
!ans
in
let status = ref 0 in
let read_event () =
let get_byte () =
if !pos >= Array.length data then raise Invalid_data;
incr pos;
data.(!pos - 1)
in
let get_text len =
let ans = Bytes.create len in
if !pos + len >= Array.length data then raise Invalid_data;
for i = 0 to len - 1 do
Bytes.set ans i (char_of_int data.(!pos + i))
done;
pos := !pos + len;
Bytes.to_string ans
in
let advance len = pos := !pos + len in
let command =
if !pos >= Array.length data then raise Invalid_data;
data.(!pos)
in
incr pos;
let command =
if command land 0x80 <> 0 then (
status := command;
command)
else (
decr pos;
!status)
in
let cmd = (command lsr 4) land 0xf in
let chan = command land 0xf in
match cmd with
| 8 ->
let n = get_byte () in
let v = get_byte () in
(Some chan, Note_off (n, float v /. 127.))
| 9 ->
let n = get_byte () in
let v = get_byte () in
( Some chan,
if v = 0 then
Note_off (n, 0.)
else Note_on (n, float v /. 127.) )
| 0xa ->
let n = get_byte () in
let v = get_byte () in
(Some chan, Aftertouch (n, float v /. 127.))
| 0xb ->
let c = get_byte () in
let v = get_byte () in
(Some chan, Control_change (c, v))
| 0xc ->
let p = get_byte () in
(Some chan, Patch p)
| 0xd ->
let c = get_byte () in
(Some chan, Channel_aftertouch c)
| 0xe ->
let l = get_byte () land 0x7f in
let h = get_byte () land 0x7f in
(Some chan, Pitch ((h lsl 7) + l))
| _ -> (
match command with
| 0xf0 | 0xf7 ->
let len = read_delta () in
advance len;
raise Not_found
| 0xff -> (
let cmd = get_byte () in
let len = read_delta () in
match cmd with
| 0 ->
if len <> 2 then raise Invalid_data;
let h = get_byte () in
let l = get_byte () in
(None, Sequence_number ((h lsl 8) + l))
| 1 -> (None, Text (get_text len))
| 2 -> (None, Copyright (get_text len))
| 3 -> (None, Track_name (get_text len))
| 4 -> (None, Instrument_name (get_text len))
| 5 -> (None, Lyric (get_text len))
| 6 -> (None, Marker (get_text len))
| 7 -> (None, Cue (get_text len))
| 0x2f ->
if len <> 0 then raise Invalid_data;
raise Not_found
| 0x51 ->
if len <> 3 then raise Invalid_data;
let t1 = get_byte () in
let t2 = get_byte () in
let t3 = get_byte () in
let t = (t1 lsl 16) + (t2 lsl 8) + t3 in
(None, Tempo t)
| 0x58 ->
if len <> 4 then raise Invalid_data;
let n = get_byte () in
let d = get_byte () in
let c = get_byte () in
let b = get_byte () in
(None, Time_signature (n, d, c, b))
| 0x59 ->
if len <> 2 then raise Invalid_data;
let sf = get_byte () in
let m = get_byte () in
(None, Key_signature (sf, m <> 0))
| 0x54
| 0x7f ->
advance len;
raise Not_found
| _ ->
advance len;
Printf.printf "MIDI: unknown meta-event %x.\n%!"
cmd;
raise Not_found)
| _ ->
advance 1;
Printf.printf "MIDI: unknown command %x (pos: %d)\n%!"
command !pos;
raise Not_found)
in
let ans = ref [] in
while !pos < len do
try
let d = read_delta () in
let e = read_event () in
ans := (d, e) :: !ans
with Not_found -> ()
done;
List.rev !ans
method private read_track =
let id = self#input_id in
let len = self#input_int in
if id <> "MTrk" then raise Invalid_header;
let data = self#really_input len in
self#decode_track_data data
end
class of_file fname =
object (self)
inherit IO.Unix.rw ~read:true fname
inherit IO.helper
inherit! base
val mutable track = []
val mutable tempo = 500000
initializer
self#read_header;
let tracks = Array.init tracks (fun _ -> self#read_track) in
let trk =
let find_min () =
let ans = ref None in
for c = 0 to Array.length tracks - 1 do
match tracks.(c) with
| [] -> ()
| (d, _) :: _ -> (
match !ans with
| None -> ans := Some (d, c)
| Some (d', _) -> if d < d' then ans := Some (d, c))
done;
match !ans with Some (d, c) -> (d, c) | None -> raise Not_found
in
let ans = ref [] in
try
while true do
let d, c = find_min () in
ans := List.hd tracks.(c) :: !ans;
tracks.(c) <- List.tl tracks.(c);
Array.iteri
(fun n t ->
if n <> c && t <> [] then (
let d', e = List.hd t in
tracks.(n) <- (d' - d, e) :: List.tl t))
tracks
done;
assert false
with Not_found -> List.rev !ans
in
track <- trk
val mutable track_samples = []
val mutable track_samples_computed = false
method private read_add sr buf ofs len =
if not track_samples_computed then (
let t = tempo in
track_samples <-
List.map
(fun (d, (c, e)) ->
let d = samples_of_delta sr division tempo d in
(match e with Tempo t -> tempo <- t | _ -> ());
(d, (c, e)))
track;
tempo <- t;
track_samples_computed <- true);
let offset_in_buf = ref 0 in
while track_samples <> [] && !offset_in_buf < len do
let d, (c, e) = List.hd track_samples in
offset_in_buf := !offset_in_buf + d;
(match e with Tempo t -> tempo <- t | _ -> ());
if !offset_in_buf < len then (
track_samples <- List.tl track_samples;
match c with
| Some c -> (
match e with
| Note_on _ | Note_off _ | Control_change _ ->
if c < Array.length buf then
insert buf.(c) (!offset_in_buf + ofs, e)
| _ -> () )
| None -> ()
)
else
track_samples <-
(!offset_in_buf - len, (c, e)) :: List.tl track_samples
done;
if track_samples <> [] then len else !offset_in_buf
method read sr buf ofs len =
Multitrack.clear buf ofs len;
self#read_add sr buf ofs len
method close = self#stream_close
end
end
module Writer = struct
class type t =
object
method put : int -> event -> unit
method note_off : int -> int -> float -> unit
method note_on : int -> int -> float -> unit
method advance : int -> unit
method close : unit
end
class to_file samplerate fname =
let fps = 25 in
let tpf = 40 in
let rec delta d =
if d = 0 then ""
else delta (d lsr 7) ^ String.make 1 (char_of_int (128 + (d land 127)))
in
let delta d =
delta (d lsr 7) ^ String.make 1 (char_of_int (d land 127))
in
let delta d = delta (d * fps * tpf / samplerate) in
object (self)
inherit IO.Unix.rw ~write:true fname
inherit IO.helper
val mutable curdelta = 0
val mutable datalen = 0
method! private output_int = self#output_int_be
method! private output_short = self#output_short_be
initializer
self#output "MThd";
self#output_int 6;
self#output_short 0;
self#output_short 1;
self#output_short ((((fps - 1) lxor 0xff) lsl 8) + tpf);
self#output "MTrk";
self#output_int 0
method put chan e =
let d = delta curdelta in
let e = encode_event chan e in
self#output d;
self#output e;
datalen <- datalen + String.length d + String.length e;
curdelta <- 0
method note_off chan n v = self#put chan (Note_off (n, v))
method note_on chan n v = self#put chan (Note_on (n, v))
method advance n = curdelta <- curdelta + n
method close =
self#stream_seek 18;
self#output_int datalen;
self#stream_close
end
end
end