als_skeleton.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #!/usr/bin/env python3
  2. """Generates src/core/AlsSkeleton.h: the element skeletons LYNX's .als export (round 175a, N2) fills in.
  3. Live's loader needs complete objects: every member, in Live's own order (docs/analise/ALS_FORMAT.md §9). A skeleton is
  4. one element kind's member names and default values. Lists are emptied, user content (names, paths, plugin states)
  5. is removed, and the kind's own Id is set to 0 (the export numbers it). It is made from sets saved by Live on this machine.
  6. Those sets are local only: none is committed, and the generated header holds no song content.
  7. usage: tools/als_skeleton.py --live12 <folder of decompressed Live 12 sets> --probe12 <folder with gainprobe.xml and
  8. warpref.als (Live-saved plugin probes)> --live11 <a Live 11 set .als> [--live11-extra <more Live 11 sets>]
  9. [--drum12 <folder with sample-on-drum-pad.xml: Live's default pad Simpler, decompressed>] [--out src/core/AlsSkeleton.h]
  10. round 175a used --live11 XRJAM.als (11.0.12) --live11-extra abletoolz 11.0.12.als (GroupTrack, AudioClip, VST3)
  11. WithPlugins.als (11.3.3, Locator); all public sets, kept local. Round 183c added the rack kinds (the Live 12 demo
  12. and template sets, gainprobe's plugin parameter) with the same arguments. Round 190ec added the Drum Rack kinds
  13. (DrumGroupDevice, DrumBranch, ReturnBranch, AudioBranchSendInfo from Quick_Start_Song; OriginalSimpler from Live's
  14. default pad Simpler, Core Library/Defaults/Dropping Samples/On Drum Rack, given by --drum12; MultiSamplePart from
  15. Quick_Start_Song): the earlier kinds come out byte for byte the same.
  16. """
  17. import argparse, copy, gzip, os, re, xml.etree.ElementTree as ET, zlib
  18. # containers whose children are items (emptied); "Notes" only inside a KeyTrack (MidiClip/Notes holds KeyTracks)
  19. LISTS = {'Tracks', 'Scenes', 'SendsPre', 'Events', 'KeyTracks', 'WarpMarkers', 'Devices', 'Envelopes', 'ClipSlotList', 'Sends',
  20. 'Grooves', 'ParameterList', 'AutomationLanes', 'EventLists', 'NoteProbabilityGroups', 'Locators', 'TakeLanes',
  21. 'MarkerList', 'ExpressionGrid', 'Branches', 'ReturnBranches', 'MacroSnapshots'}
  22. USER_VALUES = {'EffectiveName', 'UserName', 'Annotation', 'MemorizedFirstClipName', 'Name', 'Path', 'RelativePath',
  23. 'OriginalFileRef', 'BrowserContentPath', 'BranchDeviceId', 'PlugName', 'SnapshotName', 'ParameterName'}
  24. BLOBS = {'ProcessorState', 'ControllerState', 'Buffer', 'Data'}
  25. def strip(e, top=True, scale=False):
  26. # (ScaleInformation/Name is the scale, not user text: an index in Live 12, a name such as "Major" in Live 11)
  27. if not top and e.tag in LISTS and not (e.tag == 'Locators' and e.find('Locators') is not None) \
  28. and not (e.tag == 'TakeLanes' and e.find('TakeLanes') is not None) and not (e.tag == 'AutomationLanes' and e.find('AutomationLanes') is not None):
  29. for c in list(e):
  30. e.remove(c)
  31. if e.tag == 'Notes' and e.find('KeyTracks') is None:
  32. for c in list(e):
  33. if c.tag == 'MidiNoteEvent':
  34. e.remove(c)
  35. if e.tag in BLOBS:
  36. e.text = None
  37. for c in list(e):
  38. e.remove(c)
  39. # (a number is a setting, not user text: ScaleInformation/Name is the scale's index, and Live wants an int there)
  40. if e.tag in USER_VALUES and 'Value' in e.attrib and not re.fullmatch(r'-?\d+', e.get('Value')) and not scale:
  41. e.set('Value', '')
  42. if e.tag in ('LivePackName', 'LivePackId') and 'Value' in e.attrib:
  43. e.set('Value', '')
  44. # a rack's macro names, info texts and stored values are the preset's, not format (round 183c): Live's defaults
  45. if e.tag.startswith('MacroDisplayNames.') and 'Value' in e.attrib:
  46. e.set('Value', 'Macro ' + str(int(e.tag.split('.')[1]) + 1))
  47. if (e.tag.startswith('MacroAnnotations.') or e.tag == 'Annotation') and 'Value' in e.attrib:
  48. e.set('Value', '')
  49. if e.tag.startswith('MacroValues.') and 'Value' in e.attrib:
  50. e.set('Value', '-1')
  51. if e.tag.startswith('MacroHasValue.') and 'Value' in e.attrib:
  52. e.set('Value', 'false')
  53. if e.tag == 'ViewData' and 'Value' in e.attrib:
  54. e.set('Value', '{}')
  55. if e.tag == 'MidiInputRouting': # the sample's own MIDI device → Live's default "all inputs"
  56. for k, v in (('Target', 'MidiIn/External.All/-1'), ('UpperDisplayString', 'Ext: All Ins'), ('LowerDisplayString', '')):
  57. c = e.find(k)
  58. if c is not None:
  59. c.set('Value', v)
  60. # the kind's own Id is the export's to set; ids inside stay as Live wrote them, unique within each list
  61. # ("Non-unique list ids" otherwise) [LIVE]. Pointee/target ids are renumbered by the export anyway.
  62. if 'Id' in e.attrib and top:
  63. e.set('Id', '0')
  64. # a macro mapping onto an outer rack (KeyMidi on channel 16 [DATA]) is the export's to write (round 183c)
  65. for c in list(e):
  66. if c.tag == 'KeyMidi' and c.find('Channel') is not None and c.find('Channel').get('Value') == '16' and not top:
  67. e.remove(c)
  68. if e.text is not None and not e.text.strip():
  69. e.text = None
  70. e.tail = None
  71. for c in list(e):
  72. strip(c, False, e.tag == 'ScaleInformation')
  73. return e
  74. def text(e):
  75. return ET.tostring(e, encoding='unicode', short_empty_elements=True)
  76. def find(root, path):
  77. e = root.find(path)
  78. if e is None:
  79. raise SystemExit(f'missing {path}')
  80. return copy.deepcopy(e)
  81. # Live 12 → Live 11: names Live 12 renamed, members it added [DATA: a Live 11.0.12 set vs Live 12.4's]
  82. RENAME_11 = {'MainTrack': 'MasterTrack', 'ViewStateSessionTrackWidth': 'ViewStateSesstionTrackWidth',
  83. 'AutoColorPickerForReturnAndMainTracks': 'AutoColorPickerForReturnAndMasterTracks', 'MidiEditorLaneModel': 'ExpressionLane'}
  84. DROP_11 = {'MpeSettings', 'BreakoutIsExpanded', 'ComplexProEnvelopeModulationTarget', 'ComplexProFormantsModulationTarget',
  85. 'KeepRecordMonitoringLatency', 'TransientEnvelopeModulationTarget', 'ControllerLayoutCustomization', 'ControllerLayoutRemoteable',
  86. 'AccidentalSpellingPreference', 'AutomationEnvelopesListWrapper', 'NoteProbabilityGroups', 'ProbabilityGroupIdGenerator'}
  87. def to11(e):
  88. """A Live 12 skeleton for a kind no Live 11 sample holds, downgraded by the rules above (unverified in Live 11)."""
  89. for c in list(e):
  90. if c.tag in DROP_11:
  91. e.remove(c)
  92. continue
  93. to11(c)
  94. e.tag = RENAME_11.get(e.tag, e.tag)
  95. if e.tag == 'ScaleInformation':
  96. r = e.find('Root')
  97. if r is not None:
  98. r.tag = 'RootNote'
  99. return e
  100. # Drum Rack kinds (round 190ec): their own lists are emptied too (sends, sample parts, slice points), only in these kinds
  101. DRUM_KINDS = {'DrumGroupDevice': './/DrumGroupDevice', 'DrumBranch': './/DrumGroupDevice/Branches/DrumBranch',
  102. 'ReturnBranch': './/DrumGroupDevice/ReturnBranches/ReturnBranch', 'AudioBranchSendInfo': './/AudioBranchSendInfo',
  103. 'OriginalSimpler': './/OriginalSimpler', 'MultiSamplePart': './/OriginalSimpler//MultiSamplePart'}
  104. DRUM_LISTS = {'SendInfos', 'SampleParts', 'SlicePoints', 'ManualSlicePoints', 'BeatSlicePoints', 'RegionSlicePoints',
  105. 'InitialSlicePointsFromOnsets', 'UserOnsets', 'TimeSignatures'}
  106. def empty_lists(e, names):
  107. for c in e.iter():
  108. if c.tag in names:
  109. for x in list(c):
  110. c.remove(x)
  111. return e
  112. def drum_kinds(roots, default_simpler=None, required=True):
  113. out = {}
  114. for k, path in DRUM_KINDS.items():
  115. src = [default_simpler] if k == 'OriginalSimpler' and default_simpler is not None else roots
  116. e = next((r.find(path) for r in src if r is not None and r.find(path) is not None), None)
  117. if e is None:
  118. if required:
  119. raise SystemExit(f'missing {path}')
  120. continue
  121. e = empty_lists(copy.deepcopy(e), DRUM_LISTS)
  122. if k in ('DrumBranch', 'ReturnBranch'): # (the sample's routing into its own set's tracks: the export sets it)
  123. t = e.find('MixerDevice/RoutingHelper/Routable/Target')
  124. if t is not None:
  125. t.set('Value', 'AudioOut/None')
  126. out[k] = e
  127. return out
  128. def kinds12(a):
  129. x = lambda f: ET.parse(os.path.join(a.live12, f)).getroot()
  130. base, beat, demo, pod = x('DefaultLiveSet.xml'), x('Quick_Start_Beat.xml'), x('Chuck_Sutton_-_Patience__Live_12_Suite_Demo_.xml'), x('Podcast___Radio.xml')
  131. gain = ET.parse(os.path.join(a.probe12, 'gainprobe.xml')).getroot()
  132. vst2 = ET.fromstring(gzip.open(os.path.join(a.probe12, 'warpref.als')).read())
  133. return {
  134. 'Root': ET.Element('Ableton', base.attrib),
  135. 'LiveSet': find(base, 'LiveSet'),
  136. 'MidiTrack': find(base, './/Tracks/MidiTrack'), 'AudioTrack': find(base, './/Tracks/AudioTrack'),
  137. 'ReturnTrack': find(base, './/Tracks/ReturnTrack'), 'GroupTrack': find(pod, './/Tracks/GroupTrack'),
  138. 'MidiClip': find(beat, './/MidiClip'), 'KeyTrack': find(beat, './/KeyTrack'), 'AudioClip': find(demo, './/AudioClip'),
  139. 'Scene': find(base, './/Scenes/Scene'), 'ClipSlot': find(base, './/ClipSlotList/ClipSlot'),
  140. 'TrackSendHolder': find(base, './/Sends/TrackSendHolder'), 'Locator': find(demo, './/Locators/Locators/Locator'),
  141. 'AutomationEnvelope': find(beat, './/AutomationEnvelope'),
  142. 'PluginDeviceVst3': find(gain, './/PluginDevice'), 'PluginDeviceVst2': find(vst2, './/PluginDevice'),
  143. # racks (round 183c): the rack devices, a chain of each kind, a macro variation, a macro mapping, a plugin parameter
  144. **rack_kinds([demo, x('Guitar_Recording.xml'), x('Quick_Start_Song.xml')], gain),
  145. # Drum Racks (round 190ec)
  146. **(drum_kinds([x('Quick_Start_Song.xml')], ET.parse(os.path.join(a.drum12, 'sample-on-drum-pad.xml')).getroot()) if a.drum12 else {}),
  147. }
  148. RACK_KINDS = {'AudioEffectGroupDevice': './/AudioEffectGroupDevice', 'AudioEffectBranch': './/AudioEffectBranch',
  149. 'InstrumentGroupDevice': './/InstrumentGroupDevice', 'InstrumentBranch': './/InstrumentBranch',
  150. 'MidiEffectGroupDevice': './/MidiEffectGroupDevice', 'MidiEffectBranch': './/MidiEffectBranch',
  151. 'MacroSnapshot': './/MacroSnapshot'}
  152. def mapping_key(roots):
  153. """A KeyMidi that maps a parameter onto a macro (channel 16) [DATA], as a kind of its own"""
  154. for r in roots:
  155. for k in r.iter('KeyMidi'):
  156. c = k.find('Channel')
  157. if c is not None and c.get('Value') == '16':
  158. return copy.deepcopy(k)
  159. return None
  160. def rack_kinds(roots, plugin_probe, required=True):
  161. out = {}
  162. for k, path in RACK_KINDS.items():
  163. e = next((r.find(path) for r in roots if r.find(path) is not None), None)
  164. if e is None:
  165. if required:
  166. raise SystemExit(f'missing {path}')
  167. continue
  168. out[k] = copy.deepcopy(e)
  169. key = mapping_key(roots)
  170. if key is not None:
  171. out['MacroKeyMidi'] = key
  172. elif required:
  173. raise SystemExit('missing a macro KeyMidi')
  174. p = plugin_probe.find('.//PluginFloatParameter') if plugin_probe is not None else None
  175. if p is not None:
  176. out['PluginFloatParameter'] = copy.deepcopy(p)
  177. elif required:
  178. raise SystemExit('missing PluginFloatParameter')
  179. return out
  180. def kinds11(a, k12):
  181. r = ET.fromstring(gzip.open(a.live11).read())
  182. out = {
  183. 'Root': ET.Element('Ableton', r.attrib),
  184. 'LiveSet': find(r, 'LiveSet'),
  185. 'MidiTrack': find(r, './/Tracks/MidiTrack'), 'AudioTrack': find(r, './/Tracks/AudioTrack'),
  186. 'ReturnTrack': find(r, './/Tracks/ReturnTrack'),
  187. 'MidiClip': find(r, './/MidiClip'), 'KeyTrack': find(r, './/KeyTrack'),
  188. 'Scene': find(r, './/Scenes/Scene'), 'ClipSlot': find(r, './/ClipSlotList/ClipSlot'),
  189. 'TrackSendHolder': find(r, './/Sends/TrackSendHolder'), 'AutomationEnvelope': find(r, './/AutomationEnvelope'),
  190. 'PluginDeviceVst2': find(r, './/PluginDevice'),
  191. }
  192. # kinds the main sample lacks: from further Live 11 sets, else downgraded from Live 12 (to11, unverified)
  193. extra = [ET.fromstring(gzip.open(f).read()) for f in a.live11_extra]
  194. paths = {'GroupTrack': './/Tracks/GroupTrack', 'AudioClip': './/AudioClip', 'Locator': './/Locators/Locators/Locator'}
  195. for k in ('GroupTrack', 'AudioClip', 'Locator', 'PluginDeviceVst3'):
  196. for x in extra:
  197. if k == 'PluginDeviceVst3':
  198. e = next((d for d in x.iter('PluginDevice') if d.find('.//Vst3PluginInfo') is not None), None)
  199. else:
  200. e = x.find(paths[k])
  201. if e is not None:
  202. out[k] = copy.deepcopy(e)
  203. break
  204. else:
  205. print(f'Live 11: {k} downgraded from Live 12 (no Live 11 sample has one)')
  206. out[k] = to11(copy.deepcopy(k12[k]))
  207. # racks (round 183c): from the Live 11 sets that hold them, else downgraded from Live 12
  208. found = rack_kinds([r] + extra, next((x for x in [r] + extra if x.find('.//PluginFloatParameter') is not None), None), required=False)
  209. for k in list(RACK_KINDS) + ['MacroKeyMidi', 'PluginFloatParameter']:
  210. if k in found:
  211. out[k] = found[k]
  212. else:
  213. print(f'Live 11: {k} downgraded from Live 12 (no Live 11 sample has one)')
  214. out[k] = to11(copy.deepcopy(k12[k]))
  215. # Drum Racks (round 190ec): from the Live 11 sets that hold them, else downgraded from Live 12 (the pad Simpler is
  216. # always Live 12's default, downgraded)
  217. if 'DrumGroupDevice' in k12:
  218. found = drum_kinds([r] + extra, None, required=False)
  219. for k in DRUM_KINDS:
  220. if k in found and k != 'OriginalSimpler':
  221. out[k] = found[k]
  222. else:
  223. print(f'Live 11: {k} downgraded from Live 12')
  224. out[k] = to11(copy.deepcopy(k12[k]))
  225. return out
  226. def main():
  227. p = argparse.ArgumentParser()
  228. p.add_argument('--live12', required=True)
  229. p.add_argument('--probe12', required=True)
  230. p.add_argument('--live11', required=True)
  231. p.add_argument('--live11-extra', nargs='*', default=[], help='more Live 11 sets, for the kinds the first one lacks (first match wins)')
  232. p.add_argument('--drum12', default=None, help="folder with sample-on-drum-pad.xml (Live 12's default pad Simpler, decompressed)")
  233. p.add_argument('--out', default='src/core/AlsSkeleton.h')
  234. a = p.parse_args()
  235. k12 = kinds12(a)
  236. k11 = kinds11(a, k12)
  237. lines = ['#pragma once', '',
  238. '// Generated by tools/als_skeleton.py (rounds 175a, 183c, 190ec): the element skeletons of Live 12 and Live 11 sets that the .als',
  239. '// export fills in (member names and default values in Live\'s order; lists empty; no song content). One zlib',
  240. '// stream per version: <Skeletons><Kind name="MidiTrack">…</Kind>…</Skeletons>. Do not edit by hand.', '',
  241. '#include <cstddef>', '#include <cstdint>', '', 'namespace lynx::alsskeleton', '{']
  242. for ver, kinds in (('12', k12), ('11', k11)):
  243. body = '<Skeletons>' + ''.join(f'<Kind name="{k}">{text(strip(v))}</Kind>' for k, v in kinds.items()) + '</Skeletons>'
  244. body = re.sub(r'>\s+<', '><', body)
  245. z = zlib.compress(body.encode('utf-8'), 9)
  246. lines.append(f'inline constexpr std::size_t live{ver}Size = {len(body.encode("utf-8"))};')
  247. lines.append(f'inline constexpr std::uint8_t live{ver}[{len(z)}] = {{')
  248. for i in range(0, len(z), 24):
  249. lines.append(' ' + ', '.join(f'0x{b:02x}' for b in z[i:i + 24]) + ',')
  250. lines.append('};')
  251. print(f'Live {ver}: {len(kinds)} kinds, {len(body)} bytes of XML, {len(z)} compressed')
  252. lines += ['} // namespace lynx::alsskeleton', '']
  253. open(a.out, 'w').write('\n'.join(lines))
  254. if __name__ == '__main__':
  255. main()