"""Pack long MODs to two ticks per row, within the 128-pattern limit.
Melody attacks stay on their exact tick. Only intermediate volume automation
is decimated. Panning is retained on a spare row; speed and tempo stay explicit.
"""
def pack(events,rows,mapping):
    if rows<=8192:return events,rows,mapping,1
    assert rows%128==0 and rows<=16384
    out={}; pans={}; tempos=[]
    for (r,ch),e in sorted(events.items()):
        sid,pitch,fx,value=e
        if fx==8:pans[ch]=value;continue
        if fx==15:
            if value>=32:tempos.append((r//2,value))
            if not sid:continue
            e=[sid,pitch,0,0]
        pos=(r//2,ch);old=out.get(pos)
        if sid:
            assert not old or not old[0],('two attacks in one packed row',r,ch)
            out[pos]=e.copy()
        elif not old or not old[0]:out[pos]=e.copy()
    for ch,pan in pans.items():
        r=1
        while out.get((r,ch),[0])[0]:r+=1
        out[r,ch]=[0,0,8,pan]
    def command(r,value):
        for ch in range(7,-1,-1):
            e=out.get((r,ch),[0,0,0,0])
            if e[2] in (0,12) and not e[0]:out[r,ch]=[0,0,15,value];return
        for ch in range(7,-1,-1):
            e=out[r,ch]
            if e[2] in (0,12):out[r,ch]=[e[0],e[1],15,value];return
        raise AssertionError('No tempo slot')
    command(0,2)
    for r,value in tempos:command(r,value)
    packed=mapping[::2];clock=[];ms=0.;bpm=125
    for r,(_,cs) in enumerate(packed[:-1]):
        for ch in range(8):
            e=out.get((r,ch),[0,0,0,0])
            if e[2]==15 and e[3]>=32:bpm=e[3]
        clock.append((round(ms),cs));ms+=5000/bpm
    clock.append((round(ms),-1))
    return out,rows//2,clock,2

def metadata(meta,speed):
    meta['speed']=speed;meta['rows_per_quarter']=24//speed
    if speed==1:return meta
    for key in ('intro_rows','body_rows','kick_pulse_rows'):
        if key in meta:meta[key]//=2
    for key in ('primary','sections','bars','rhythm'):
        for item in meta.get(key,[]):
            for field in ('start_row','end_row','row','start','end','length','pulse'):
                if field in item:item[field]//=2
    for key in ('phrase_rows',):
        if key in meta:meta[key]=[r//2 for r in meta[key]]
    meta['tempo_changes']=[[r//2,t] for r,t in meta['tempo_changes']]
    return meta
