comparison musiccutter.py @ 11:9faad813e39e

switch to PDF to avoid dealing with CorelDraw crashing
author Daniel O'Connor <darius@dons.net.au>
date Thu, 07 Apr 2016 23:35:44 +0930
parents e9760224e992
children 6e46ceee57a7
comparison
equal deleted inserted replaced
10:b9727813e029 11:9faad813e39e
2 2
3 import exceptions 3 import exceptions
4 import itertools 4 import itertools
5 import math 5 import math
6 import mido 6 import mido
7 import svgwrite 7 import os
8 import reportlab.lib.colors
9 from reportlab.lib.units import mm
8 import sys 10 import sys
9 11
12 CUT_COLOUR = reportlab.lib.colors.red
13 ENGRAVE_COLOUR = reportlab.lib.colors.black
14
15
16 ## XXX: PDF origin bottom left, SVG origin top left
10 def test(filename = None): 17 def test(filename = None):
11 if filename == None: 18 if filename == None:
12 filename = 'test.midi' 19 filename = 'test.midi'
13 # Card layout from http://www.orgues-de-barbarie.com/wp-content/uploads/2014/09/format-cartons.pdf 20 # Card layout from http://www.orgues-de-barbarie.com/wp-content/uploads/2014/09/format-cartons.pdf
14 m = Midi2SVG('notes', 20, 15.5, 0.55, 0.6, 1.0) 21 m = Midi2PDF('notes', 200, 155, 5.5, 6.0, 10, 'Helvetica', 12)
15 m.processMidi(filename, 'test%02d.svg') 22 base, ext = os.path.splitext(filename)
23 m.processMidi(filename, base + '-%02d.pdf')
16 24
17 class Midi2SVG(object): 25 class Midi2PDF(object):
18 def __init__(self, notefile, pagewidth, pageheight, pitch, offset, timescale): 26 def __init__(self, notefile, pagewidth, pageheight, pitch, offset, timescale, fontname, fontsize):
19 self.midi2note, self.note2midi = Midi2SVG.genmidi2note() 27 self.midi2note, self.note2midi = Midi2PDF.genmidi2note()
20 self.note2slot = Midi2SVG.loadnote2slot(notefile, self.note2midi) 28 self.note2slot = Midi2PDF.loadnote2slot(notefile, self.note2midi)
21 self.pagewidth = pagewidth 29 self.pagewidth = pagewidth # Dimensions are in millimetres
22 self.pageheight = pageheight 30 self.pageheight = pageheight
23 self.pitch = pitch 31 self.pitch = pitch
24 self.offset = offset 32 self.offset = offset
25 self.timescale = timescale 33 self.timescale = timescale
34 self.fontname = fontname
35 self.fontsize = fontsize
26 36
27 def processMidi(self, midifile, outpat): 37 def processMidi(self, midifile, outpat):
28 playablecount = 0 38 playablecount = 0
29 unplayablecount = 0 39 unplayablecount = 0
30 midi = mido.MidiFile(midifile) 40 midi = mido.MidiFile(midifile)
31 ctime = 0 41 ctime = 0
32 channels = [] 42 channels = []
33 for i in range(16): 43 for i in range(16):
34 channels.append({}) 44 channels.append({})
35 45
36 npages = int(math.ceil(midi.length / self.timescale / self.pagewidth)) 46 npages = int(math.ceil(midi.length * self.timescale / self.pagewidth))
37 print 'npages', npages 47 print 'npages', npages
38 svgs = [] 48 pdfs = []
39 for i in range(npages): 49 for i in range(npages):
40 svg = svgwrite.Drawing(outpat % i, profile = 'full', size = ('%.3fcm' % (self.pagewidth), '%.3fcm' % (self.pageheight))) 50 pdf = reportlab.pdfgen.canvas.Canvas(file(outpat % (i + 1), 'w'), pagesize = (self.pagewidth * mm, self.pageheight * mm))
41 svgs.append(svg) 51 pdfs.append(pdf)
42 52
53 title = midifile
43 for ev in midi: 54 for ev in midi:
55 if ev.type == 'text' and ctime == 0:
56 title = ev.text
57
44 ctime += ev.time 58 ctime += ev.time
45 if ev.type == 'note_on' or ev.type == 'note_off': 59 if ev.type == 'note_on' or ev.type == 'note_off':
46 note = self.midi2note[ev.note] 60 note = self.midi2note[ev.note]
47 print ctime, ev 61 #print ctime, ev
48 if ev.type == 'note_on' and ev.velocity > 0: 62 if ev.type == 'note_on' and ev.velocity > 0:
49 if ev.note in channels[ev.channel]: 63 if ev.note in channels[ev.channel]:
50 print 'Duplicate note_on message %d (%s)' % (ev.note, note) 64 print 'Duplicate note_on message %d (%s)' % (ev.note, note)
51 else: 65 else:
52 channels[ev.channel][ev.note] = ctime 66 channels[ev.channel][ev.note] = ctime
60 else: 74 else:
61 start = channels[ev.channel][ev.note] 75 start = channels[ev.channel][ev.note]
62 notelen = ctime - start 76 notelen = ctime - start
63 slot = self.note2slot[note] 77 slot = self.note2slot[note]
64 print 'Note %s (%d) at %.2f length %.2f' % (note, slot, start, notelen) 78 print 'Note %s (%d) at %.2f length %.2f' % (note, slot, start, notelen)
65 self.emitnote(svgs, slot, start, notelen) 79 self.emitnote(pdfs, slot, start, notelen)
66 playablecount += 1 80 playablecount += 1
67 del channels[ev.channel][ev.note] 81 del channels[ev.channel][ev.note]
68 elif ev.type == 'end_of_track': 82 elif ev.type == 'end_of_track':
69 print 'EOT, not flushing, check for missed notes' 83 print 'EOT, not flushing, check for missed notes'
70 for chan in channels: 84 for chan in channels:
72 print ev 86 print ev
73 87
74 print 'Playable count:', playablecount 88 print 'Playable count:', playablecount
75 print 'Unplayable count:', unplayablecount 89 print 'Unplayable count:', unplayablecount
76 90
77 for i in range(len(svgs)): 91 for i in range(len(pdfs)):
78 svg = svgs[i] 92 pdf = pdfs[i]
79 svg.add(svg.text('%s (%d / %d)' % (midifile, i + 1, npages), fill = 'black', stroke = 'black', 93 tobj = pdf.beginText()
80 insert = ('%.3fcm' % (0), '%.3fcm' % (self.pageheight)))) 94 tobj.setTextOrigin(2 * mm, 1 * mm)
81 svg.save() 95 tobj.setFont(self.fontname, self.fontsize)
96 tobj.setFillColor(ENGRAVE_COLOUR)
97 tobj.setStrokeColor(ENGRAVE_COLOUR)
98 tobj.textLine('%s (%d / %d)' % (title, i + 1, npages))
99 pdf.drawText(tobj)
100 pdf.save()
82 101
83 # http://www.electronics.dit.ie/staff/tscarff/Music_technology/midi/midi_note_numbers_for_octaves.htm 102 # http://www.electronics.dit.ie/staff/tscarff/Music_technology/midi/midi_note_numbers_for_octaves.htm
84 @staticmethod 103 @staticmethod
85 def genmidi2note(): 104 def genmidi2note():
86 '''Create forward & reverse tables for midi number to note name (assuming 69 == A440)''' 105 '''Create forward & reverse tables for midi number to note name (assuming 69 == A440)'''
110 note2slot[note] = index 129 note2slot[note] = index
111 index += 1 130 index += 1
112 131
113 return note2slot 132 return note2slot
114 133
115 def emitnote(self, svgs, slot, start, notelen): 134 def emitnote(self, pdfs, slot, start, notelen):
116 startx = start / self.timescale 135 x = start * self.timescale
117 startpageidx = int(startx / self.pagewidth) 136 pageidx = int(x / self.pagewidth)
118 endx = (start + notelen) / self.timescale 137 x = x % self.pagewidth
119 endpageidx = int(endx / self.pagewidth) 138 y = self.offset + slot * self.pitch
120 startx = startx % self.pagewidth 139 w = notelen * self.timescale
121 y = self.pageheight - (self.offset + slot * self.pitch)
122 w = notelen / self.timescale
123 h = self.pitch 140 h = self.pitch
124 141
125 if startpageidx != endpageidx: 142 print 'page = %d x = %.3f y = %.3f w = %.3f h = %.3f' % (pageidx, x, y, w, h)
126 print 'page crossed from %d to %d' % (startpageidx, endpageidx) 143 w1 = w
127 print 'page = %d x = %.3f y = %.3f w = %.3f h = %.3f' % (startpageidx, startx, y, w, h) 144 # Check if the note crosses a page
128 Midi2SVG._emitnote(svgs[startpageidx], startx, y, w, h) 145 if x + w > self.pagewidth:
146 w1 = x - self.pagewidth # Crop first note
147 w2 = w - w1
148 assert w1 <= self.pagewidth, 'note extends for more than a page'
149 # Emit second half of note
150 print 'split note, page %d w2 = %.3f' % (pageidx + 1, w2)
151 Midi2PDF._emitnote(pdfs[pageidx + 1], 0, y, w2, h)
152
153 Midi2PDF._emitnote(pdfs[pageidx], x, y, w1, h)
129 154
130 @staticmethod 155 @staticmethod
131 def _emitnote(svg, x, y, w, h): 156 def _emitnote(pdf, x, y, w, h):
132 svg.add(svgwrite.shapes.Rect(insert = ('%.3fcm' % (x), '%.3fcm' % (y)), 157 pdf.saveState()
133 size = ('%.3fcm' % (w), '%.3fcm' % (h)), 158 pdf.setStrokeColor(CUT_COLOUR)
134 stroke = 'red', stroke_width = '1px', fill = 'none')) 159 pdf.setLineWidth(0)
160 pdf.rect(x * mm, y * mm, w * mm, h * mm, fill = False, stroke = True)
161 pdf.restoreState()
135 162
136 if __name__ == '__main__': 163 if __name__ == '__main__':
137 main() 164 main()