lpm.py 6.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env python3
  2. """lpm.py - the LYNX Model parameter table file (.lpm, version 1; round 190ni). Read by src/core/physmod/LynxModel.cpp.
  3. Little endian. Fitted parameters only: no audio, no recorded attack (owner decision: synthesised excitation only).
  4. header (40 bytes)
  5. char[4] 'LPM1' · u16 version (1) · u16 model (0 marimba, 1 vibraphone, 2 xylophone, 3 glockenspiel, 4 tubular bells,
  6. 5 kalimba) · u16 anchors · u16 modes (all anchors) · u8 beam (0 free-free bar or tube, 1 clamped-free tine) · u8 noise
  7. order (round 190nl: 2 = the strike noise through two band-pass sections, -12 dB / octave skirts; 0 or 1 = one) · u8 onset
  8. (round 190nm: 1 = an anchor's riseMs is the whole note's onset, the voice's output rising as 1 - e^(-t / rise); 0 = the
  9. resonated modes' build-up twins, as before; round 190nn: 2 = the S-shaped onset (1 - e^(-t / rise))^2) · u8 fade (round 190nm: between two recorded keys a mode only one of
  10. them has fades by 1 = its power (equal power), 0 = its amplitude, as before)
  11. f32 posRef (the position knob's value the recordings were struck at) · f32 posU0, posU1 (the strike point along the
  12. bar, 0..1, at position 0 and 1) · f32 gainOffsetDb (instrument level) · u8[8] first bytes of the SHA-256 of the
  13. provenance record (resources/physmod/<name>.provenance.json)
  14. anchor (32 bytes each; one recorded note at one velocity layer, sorted by key, then velocity)
  15. f32 key (sounding MIDI key the ratios refer to) · f32 velocity (0..1, the layer) · f32 gainDb (the main mode's level)
  16. f32 contact (s, the time constant tau of the contact force t e^(-t / tau) that reproduces the recorded attack)
  17. f16 noiseDb (strike noise level re the main mode) · f16 noiseHz · f16 noiseQ · f16 noiseMs (decay time constant)
  18. u16 firstMode · u16 modeCount · f32 riseMs (the resonated modes' build-up time constant, 0 = none: the marimba's
  19. and vibraphone's tubes re-radiate the fundamental, which grows as e^(-t/T) - e^(-t/rise))
  20. mode (10 bytes each)
  21. f32 ratio (frequency / the anchor key's equal-tempered frequency) · f16 ampDb (re the main mode) · f16 t60 (s)
  22. u8 shape (0: no strike-position law, k >= 1: the k-th bending mode of the beam; round 190nm: bit 7 set = the mode
  23. starts in antiphase, the second component of a doublet - a tube's or a tine's near-degenerate pair - fitted so;
  24. never set before 190nm) · u8 family (round 190nl: the same
  25. physical mode in the neighbouring anchors of a layer carries the same id 1-255, tools/physmod/keyfit.py; 0 = none:
  26. the engine then pairs modes by ratio within 4 %, as version 1 tables written before 190nl always do; 255 = a line at
  27. its own pitch, another tine ringing along: played at another key it keeps its frequency in Hz)
  28. """
  29. import hashlib
  30. import struct
  31. import numpy as np
  32. MAGIC = b'LPM1'
  33. ABSOLUTE = 255 # the mode family byte of a line at its own pitch (another tine ringing along; kept in Hz across keys)
  34. VERSION = 1
  35. MODELS = ['marimba', 'vibraphone', 'xylophone', 'glockenspiel', 'tubularbells', 'kalimba']
  36. def f16(v):
  37. return np.float16(v).tobytes()
  38. def write(path, model, beam, pos_ref, pos_u0, pos_u1, gain_offset_db, anchors, provenance_bytes, noise_order=0, onset=0, fade=0):
  39. """anchors: list of dicts {key, velocity, gainDb, contact, noiseDb, noiseHz, noiseQ, noiseMs, modes: [{ratio, ampDb,
  40. t60, shape}]}; returns the file's bytes (also written to path)"""
  41. anchors = sorted(anchors, key=lambda a: (a['key'], a['velocity']))
  42. total = sum(len(a['modes']) for a in anchors)
  43. head = MAGIC + struct.pack('<HHHHBBBB', VERSION, MODELS.index(model), len(anchors), total, beam, noise_order, onset, fade)
  44. head += struct.pack('<4f', pos_ref, pos_u0, pos_u1, gain_offset_db) + hashlib.sha256(provenance_bytes).digest()[:8]
  45. assert len(head) == 40
  46. body, modes, first = b'', b'', 0
  47. for a in anchors:
  48. body += struct.pack('<4f', a['key'], a['velocity'], a['gainDb'], a['contact'])
  49. body += f16(a['noiseDb']) + f16(a['noiseHz']) + f16(a['noiseQ']) + f16(a['noiseMs'])
  50. body += struct.pack('<HHf', first, len(a['modes']), a.get('riseMs', 0.0))
  51. for m in a['modes']:
  52. modes += struct.pack('<f', m['ratio']) + f16(m['ampDb']) + f16(m['t60']) + struct.pack(
  53. '<BB', (m['shape'] & 0x7f) | (0x80 if m.get('invert') else 0), m.get('fam', 0))
  54. first += len(a['modes'])
  55. data = head + body + modes
  56. if path:
  57. open(path, 'wb').write(data)
  58. return data
  59. def read(data):
  60. """the file's content as a dict (the C++ reader's mirror; used by the tests and the reports)"""
  61. if data[:4] != MAGIC:
  62. raise ValueError('not an LPM1 file')
  63. ver, model, na, nm, beam = struct.unpack('<HHHHB', data[4:13])
  64. pos_ref, u0, u1, gain = struct.unpack('<4f', data[16:32])
  65. out = {'version': ver, 'model': MODELS[model], 'beam': beam, 'noiseOrder': data[13], 'onset': data[14], 'fade': data[15], 'posRef': pos_ref, 'posU0': u0, 'posU1': u1,
  66. 'gainOffsetDb': gain, 'provenance_sha256_8': data[32:40].hex(), 'anchors': []}
  67. o = 40
  68. mo = 40 + 32 * na
  69. for _ in range(na):
  70. key, vel, g, sig = struct.unpack('<4f', data[o:o + 16])
  71. nd, nh, nq, nms = np.frombuffer(data[o + 16:o + 24], '<f2').astype(float)
  72. first, count, rise = struct.unpack('<HHf', data[o + 24:o + 32])
  73. modes = []
  74. for k in range(count):
  75. p = mo + 10 * (first + k)
  76. r = struct.unpack('<f', data[p:p + 4])[0]
  77. a, t = np.frombuffer(data[p + 4:p + 8], '<f2').astype(float)
  78. modes.append({'ratio': r, 'ampDb': float(a), 't60': float(t), 'shape': data[p + 8] & 0x7f, 'fam': data[p + 9],
  79. **({'invert': True} if data[p + 8] & 0x80 else {})})
  80. out['anchors'].append({'key': key, 'velocity': vel, 'gainDb': g, 'contact': sig, 'noiseDb': float(nd), 'noiseHz': float(nh),
  81. 'noiseQ': float(nq), 'noiseMs': float(nms), 'riseMs': rise, 'modes': modes})
  82. o += 32
  83. if mo + 10 * nm != len(data):
  84. raise ValueError('size mismatch')
  85. return out