view musiccutter.py @ 24:71b78f06ff03

Highest notes are at the bottom not the top. Rename margin to heel to match the builders nomenclature.
author Daniel O'Connor <darius@dons.net.au>
date Sat, 30 Apr 2016 16:37:14 +0930
parents 63d13efa040f
children ce367392806c
line wrap: on
line source

#!/usr/bin/env python

import exceptions
import itertools
import math
import mido
import os.path
import reportlab.lib.colors
import reportlab.pdfgen.canvas
from reportlab.lib.units import mm
import sys

CUT_COLOUR = reportlab.lib.colors.red
ENGRAVE_COLOUR = reportlab.lib.colors.black

def test(filename = None):
    if filename == None:
        filename = 'test.midi'
    # Card layout from http://www.orgues-de-barbarie.com/wp-content/uploads/2014/09/format-cartons.pdf
    # Notes are read from right to left
    # Highest note is at the bottom (closest to the crank)
    m = Midi2PDF('notes', 120, 155, 5.5, 3.3, 6.0, 50, False, False, False, False, 0, 10, 'Helvetica', 12)
    base, ext = os.path.splitext(filename)
    base = os.path.basename(base)
    m.processMidi(filename, base + '-%02d.pdf')

class Midi2PDF(object):
    def __init__(self, notefile, pagewidth, pageheight, pitch, slotsize, heel, leadin, timemarks, drawrect, notenames, notelines, noteoffset, timescale, fontname, fontsize):
        self.midi2note, self.note2midi = Midi2PDF.genmidi2note(noteoffset)
        self.note2slot, self.slot2note = Midi2PDF.loadnote2slot(notefile, self.note2midi)
        self.pagewidth = pagewidth # Dimensions are in millimetres
        self.pageheight = pageheight
        self.pitch = pitch # Distance between each slot
        self.slotsize = slotsize # Size of each slot cut out
        self.heel = heel # Bottom margin (from bottom of page to centre of slot)
        self.leadin = leadin # Extra at the start
        self.timemarks = timemarks # Draw vertical time lines
        self.drawrect = drawrect # Draw rectangle around each page
        self.notenames = notenames # Draw note names on the right edge
        self.notelines = notelines # Draw line rulers
        self.timescale = timescale # Width per second
        self.fontname = fontname
        self.fontsize = fontsize # Points

    def processMidi(self, midifile, outpat):
        playablecount = 0
        unplayablecount = 0
        midi = mido.MidiFile(midifile)
        ctime = 0
        channels = []
        for i in range(16):
            channels.append({})

        npages = int(math.ceil(((midi.length * self.timescale) + self.leadin) / self.pagewidth))
        print 'npages', npages
        pdfs = []
        for i in range(npages):
            pdf = reportlab.pdfgen.canvas.Canvas(file(outpat % (i + 1), 'w'), pagesize = (self.pagewidth * mm, self.pageheight * mm))
            pdfs.append(pdf)

        title = os.path.basename(midifile)
        title, ext = os.path.splitext(title)
        for ev in midi:
            if ev.type == 'text' and ctime == 0:
                title = ev.text

            ctime += ev.time
            if ev.type == 'note_on' or ev.type == 'note_off':
                note = self.midi2note[ev.note]
            #print ctime, ev
            if ev.type == 'note_on' and ev.velocity > 0:
                if ev.note in channels[ev.channel]:
                    print 'Duplicate note_on message %d (%s)' % (ev.note, note)
                else:
                    channels[ev.channel][ev.note] = ctime
            elif ev.type == 'note_off' or (ev.type == 'note_on' and ev.velocity == 0):
                    if ev.note not in channels[ev.channel]:
                        print 'note_off with no corresponding note_on for channel %d note %d' % (ev.channel, ev.note)
                    else:
                        if note not in self.note2slot:
                            print 'Skipping unplayable note %d (%s)' % (ev.note, note)
                            unplayablecount += 1
                        else:
                            start = channels[ev.channel][ev.note]
                            notelen = ctime - start
                            slot = self.note2slot[note]
                            print 'Note %s (%d) at %.2f length %.2f' % (note, slot, start, notelen)
                            self.emitnote(pdfs, slot, start, notelen)
                            playablecount += 1
                        del channels[ev.channel][ev.note]
            elif ev.type == 'end_of_track':
                print 'EOT, not flushing, check for missed notes'
                for chan in channels:
                    for ev in chan:
                        print ev

        print 'Playable count:', playablecount
        print 'Unplayable count:', unplayablecount

        for pindx in range(len(pdfs)):
            pdf = pdfs[pindx]
            # Add title and page number
            Midi2PDF.textHelper(pdf, 0 * mm, 1 * mm, ENGRAVE_COLOUR, True, self.fontname, self.fontsize, '%s (%d / %d)' % (title, pindx + 1, npages))

            pdf.saveState() # Not really necessary since this is last thing we do
            pdf.setLineWidth(0)

            # Draw time marks
            if self.timemarks:
                tstart = self.leadin / self.timescale
                tend = self.pagewidth / self.timescale
                if pindx > 0:
                    tsize = self.pagewidth / self.timescale
                    tstart = tend + tsize * pindx
                    tend = tend + tsize * (pindx + 1)
                for s in range(tstart, tend, 5):
                    x = self.pagewidth - (float(s * self.timescale + self.leadin) % self.pagewidth)
                    pdf.line(x * mm, self.heel, x * mm, self.pageheight * mm)
                    Midi2PDF.textHelper(pdf, x * mm, 1 * mm, ENGRAVE_COLOUR, False, self.fontname, self.fontsize, str(s) + 's')

            # Draw rectangle around page
            if self.drawrect:
                pdf.rect(0, 0, self.pagewidth * mm, self.pageheight * mm, fill = False, stroke = True)

            # Draw lines per note
            for slot in sorted(self.slot2note.keys()):
                ofs = (self.heel - self.slotsize / 2 + slot * self.pitch) * mm
                if self.notelines:
                    pdf.line(0, ofs, self.pagewidth * mm, ofs)
                # Note name
                if self.notenames:
                    Midi2PDF.textHelper(pdf, (self.pagewidth - 10) * mm, ofs + 1 * mm, ENGRAVE_COLOUR, False, self.fontname, self.fontsize, self.slot2note[slot])
                pdf.save()

    # http://newt.phys.unsw.edu.au/jw/notes.html
    @staticmethod
    def genmidi2note(offset):
        '''Create forward & reverse tables for midi number to note name (assuming 69 = A4 = A440)
offset is amount to shift notes (+12 = +1 octave)'''
        names = ['C%d', 'C%d#', 'D%d', 'D%d#', 'E%d', 'F%d', 'F%d#', 'G%d', 'G%d#', 'A%d', 'A%d#', 'B%d']
        midi2note = {}
        note2midi = {}
        for midi in range(21, 128):
            octave = midi / len(names) - 1
            index = midi % len(names)
            name = names[index] % (octave)
            midi2note[midi - offset] = name
            note2midi[name] = midi - offset

        return midi2note, note2midi

    @staticmethod
    def loadnote2slot(fname, note2midi):
        note2slot = {}
        slot2note = {}
        index = 0

        for note in file(fname):
            note = note.strip()
            if note[0] == '#':
                continue
            if note not in note2midi:
                raise exceptions.ValueError('Note \'%s\' not valid' % note)
            note2slot[note] = index
            slot2note[index] = note
            index += 1

        return note2slot, slot2note

    def emitnote(self, pdfs, slot, start, notelen):
        x = start * self.timescale + self.leadin # Convert start time to distance
        pageidx = int(x / self.pagewidth) # Determine which page
        x = x % self.pagewidth # and where on that page
        h = self.slotsize
        y = self.pageheight - (self.heel + slot * self.pitch - self.slotsize / 2) - self.slotsize
        w = notelen * self.timescale # Convert note length in time to distance

        print 'page = %d x = %.3f y = %.3f w = %.3f h = %.3f' % (pageidx, x, y, w, h)
        w1 = w
        # Check if the note crosses a page
        if x + w > self.pagewidth:
            w1 = self.pagewidth - x # Crop first note
            w2 = w - w1 # Calculate length of second note
            assert w2 <= self.pagewidth, 'note extends for more than a page'
            # Emit second half of note
            print 'split note, page %d w2 = %.3f' % (pageidx + 1, w2)
            Midi2PDF._emitnote(pdfs[pageidx + 1], self.pagewidth - w2, y, w2, h)

        Midi2PDF._emitnote(pdfs[pageidx], self.pagewidth - x - w1, y, w1, h)

    @staticmethod
    def _emitnote(pdf, x, y, w, h):
        pdf.saveState()
        pdf.setStrokeColor(CUT_COLOUR)
        pdf.setLineWidth(0)
        pdf.rect(x * mm, y * mm, w * mm, h * mm, fill = False, stroke = True)
        pdf.restoreState()

    @staticmethod
    def textHelper(pdf, x, y, colour, fill, fontname, fontsize, text):
        tobj = pdf.beginText()
        tobj.setTextOrigin(x, y)
        tobj.setFont(fontname, fontsize)
        tobj.setStrokeColor(colour)
        tobj.setFillColor(colour)
        if fill:
            tobj.setTextRenderMode(0)
        else:
            tobj.setTextRenderMode(1)
        tobj.textLine(text)
        pdf.drawText(tobj)

if __name__ == '__main__':
    main()