pedalboard.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. import argparse
  5. import base64
  6. import json
  7. import os
  8. import shutil
  9. import sys
  10. import time
  11. from enum import Enum
  12. from PIL import Image
  13. from modtools.utils import (
  14. init as lv2_init,
  15. cleanup as lv2_cleanup,
  16. get_pedalboard_info,
  17. get_plugin_info,
  18. get_plugin_gui,
  19. )
  20. MAX_THUMB_HEIGHT = 640
  21. MAX_THUMB_WIDTH = 640
  22. # The screenshot is only ever shown scaled down (the 640 px thumbnail here, the pedalboard page on the cloud), so
  23. # it is rendered at most this wide: a 3840 px canvas becomes 1920, four times fewer pixels to composite and encode.
  24. MAX_SCREENSHOT_WIDTH = 1920
  25. # Pause between the heavy image steps. A nice'd process still streams memory at full speed, and on the device that
  26. # is what starves the audio threads (xruns while the screenshot is made); short pauses spread the traffic out.
  27. PACE_SECONDS = 0.01
  28. __version__ = '1.0.1'
  29. def pace():
  30. time.sleep(PACE_SECONDS)
  31. def resize_image(img):
  32. width, height = img.size
  33. if width > MAX_THUMB_WIDTH:
  34. height = height * MAX_THUMB_WIDTH / width
  35. width = MAX_THUMB_WIDTH
  36. if height > MAX_THUMB_HEIGHT:
  37. width = width * MAX_THUMB_HEIGHT / height
  38. height = MAX_THUMB_HEIGHT
  39. if hasattr(Image, 'LANCZOS'):
  40. img.thumbnail((width, height), Image.LANCZOS)
  41. else:
  42. img.thumbnail((width, height), Image.ANTIALIAS)
  43. class Anchor(Enum):
  44. LEFT_CENTER = 1
  45. RIGHT_CENTER = 2
  46. def rint(x):
  47. return int(round(x))
  48. def anchor(size, x, y, align: Anchor):
  49. if align == Anchor.LEFT_CENTER:
  50. y = rint(y - size[1] / 2)
  51. elif align == Anchor.RIGHT_CENTER:
  52. y = rint(y - size[1] / 2)
  53. x = x - size[0]
  54. return x, y
  55. def rgbtoi(r, g, b):
  56. return (r << 16) + (g << 8) + b
  57. def detect_first_column(uri, img, scan, num_ports, rtol=False):
  58. if num_ports == 0:
  59. return []
  60. # these are non-typical modguis, our detection fails spetacularly for them :/
  61. # force hardcoded positions for now, nasty but works
  62. if uri == 'http://moddevices.com/plugins/mod-devel/cabsim-bass':
  63. return [(400, 107) if rtol else (2, 107)]
  64. if uri == 'http://moddevices.com/plugins/mod-devel/cabsim-modern':
  65. return [(416, 102) if rtol else (12, 102)]
  66. if uri == 'http://moddevices.com/plugins/forward-audio/marsh-1960-cabsim':
  67. return [(455, 89) if rtol else (20, 89)]
  68. if uri == 'http://moddevices.com/plugins/forward-audio/mega-california-rectifier':
  69. return [(455, 89) if rtol else (20, 89)]
  70. if uri == 'http://VeJaPlugins.com/plugins/Release/Rambler':
  71. return [(625, 216) if rtol else (8, 216)]
  72. if uri == 'https://falktx.com/plugins/portal#sink':
  73. return [(204, 183), (0, 0), (204, 264)]
  74. if uri == 'https://falktx.com/plugins/portal#source':
  75. return [(207, 183), (0, 0), (207, 264)]
  76. was_transparent = True
  77. found = False
  78. ret = []
  79. for _i in range(0, scan):
  80. i = img.size[0] - _i - 1 if rtol else _i
  81. for j in range(0, img.size[1]):
  82. pixel = img.getpixel((i, j))
  83. is_transparent = pixel[3] < 255
  84. if was_transparent != is_transparent:
  85. ret.append((i, j))
  86. was_transparent = is_transparent
  87. found = True
  88. if found:
  89. break
  90. else:
  91. # if we failed and this is a single port, use the default position
  92. if num_ports == 1:
  93. return [(img.size[0]-4, 100) if rtol else (0, 100)]
  94. return []
  95. # in case pixel detection failed and we need more ports, add them at the top
  96. for i in range(len(ret), num_ports*2):
  97. ret.insert(0, (ret[0][0], 100))
  98. return ret
  99. def chunks(l, n):
  100. o = l if isinstance(l, tuple) else tuple(l)
  101. for i in range(0, len(o), n):
  102. yield o[i:i + n]
  103. def take_screenshot(bundle_path, html_dir, cache_dir, size, job=None):
  104. os.makedirs(cache_dir, exist_ok=True)
  105. if job is None:
  106. # standalone use: load the LV2 world ourselves (slow, several seconds on a device)
  107. lv2_init()
  108. pb = get_pedalboard_info(bundle_path)
  109. plugin_info = get_plugin_info
  110. plugin_gui = get_plugin_gui
  111. else:
  112. # job made by mod-ui (mod/screenshot.py), whose LV2 world is already loaded: nothing to scan here
  113. pb = job['pedalboard']
  114. plugin_info = lambda uri: job['plugins'][uri]['info']
  115. plugin_gui = lambda uri: job['plugins'][uri]['gui']
  116. fixed_size = bool(size)
  117. if size:
  118. w, h = size.split('x')
  119. width, height = int(w), int(h)
  120. else:
  121. width, height = pb['width'], pb['height']
  122. if (width, height) == (0, 0):
  123. width, height = 3840, 2160
  124. img_dir = os.path.join(html_dir, 'img')
  125. # preload images
  126. audio_input_img = Image.open(os.path.join(img_dir, 'audio-input.png'))
  127. audio_output_img = Image.open(os.path.join(img_dir, 'audio-output.png'))
  128. audio_input_connected = Image.open(os.path.join(img_dir, 'audio-input-connected.png'))
  129. audio_output_connected = Image.open(os.path.join(img_dir, 'audio-output-connected.png'))
  130. midi_input_img = Image.open(os.path.join(img_dir, 'midi-input.png'))
  131. midi_output_img = Image.open(os.path.join(img_dir, 'midi-output.png'))
  132. midi_input_connected = Image.open(os.path.join(img_dir, 'midi-input-connected.png'))
  133. midi_output_connected = Image.open(os.path.join(img_dir, 'midi-output-connected.png'))
  134. cv_input_img = Image.open(os.path.join(img_dir, 'cv-input.png'))
  135. cv_output_img = Image.open(os.path.join(img_dir, 'cv-output.png'))
  136. cv_input_connected = Image.open(os.path.join(img_dir, 'cv-input-connected.png'))
  137. cv_output_connected = Image.open(os.path.join(img_dir, 'cv-output-connected.png'))
  138. default_screenshot = Image.open(os.path.join(html_dir, 'resources', 'pedals', 'default.png'))
  139. right_padding = audio_input_connected.size[0] * 2
  140. bottom_padding = right_padding
  141. # create capture/playback connectors
  142. device_capture = []
  143. for ix in range(0, pb['hardware']['audio_ins']):
  144. device_capture.append({
  145. 'symbol': 'capture_{0}'.format(ix + 1),
  146. 'img': audio_output_img,
  147. 'connected_img': audio_output_connected,
  148. 'type': 'audio',
  149. })
  150. if not pb.get('midi_separated_mode', False):
  151. device_capture.append({
  152. 'symbol': 'midi_merger_out',
  153. 'img': midi_output_img,
  154. 'connected_img': midi_output_connected,
  155. 'type': 'midi',
  156. })
  157. elif pb['hardware'].get('serial_midi_in', False):
  158. device_capture.append({
  159. 'symbol': 'serial_midi_in',
  160. 'img': midi_output_img,
  161. 'connected_img': midi_output_connected,
  162. 'type': 'midi',
  163. })
  164. for midi_in in pb['hardware']['midi_ins']:
  165. device_capture.append({
  166. 'symbol': midi_in['symbol'],
  167. 'img': midi_output_img,
  168. 'connected_img': midi_output_connected,
  169. 'type': 'midi',
  170. })
  171. for ix in range(0, pb['hardware']['cv_ins']):
  172. device_capture.append({
  173. 'symbol': 'cv_capture_{0}'.format(ix + 1),
  174. 'img': cv_output_img,
  175. 'connected_img': cv_output_connected,
  176. 'type': 'cv',
  177. })
  178. device_playback = []
  179. for ix in range(0, pb['hardware']['audio_outs']):
  180. device_playback.append({
  181. 'symbol': 'playback_{0}'.format(ix + 1),
  182. 'img': audio_input_img,
  183. 'connected_img': audio_input_connected,
  184. 'type': 'audio',
  185. })
  186. if not pb.get('midi_separated_mode', False):
  187. device_playback.append({
  188. 'symbol': 'midi_broadcaster_in',
  189. 'img': midi_input_img,
  190. 'connected_img': midi_input_connected,
  191. 'type': 'midi',
  192. })
  193. elif pb['hardware'].get('serial_midi_out', False):
  194. device_playback.append({
  195. 'symbol': 'serial_midi_out',
  196. 'img': midi_input_img,
  197. 'connected_img': midi_input_connected,
  198. 'type': 'midi',
  199. })
  200. for midi_out in pb['hardware']['midi_outs']:
  201. device_playback.append({
  202. 'symbol': midi_out['symbol'],
  203. 'img': midi_input_img,
  204. 'connected_img': midi_input_connected,
  205. 'type': 'midi',
  206. })
  207. if pb.get('midi_loopback', False):
  208. device_capture.append({
  209. 'symbol': 'midi_loopback',
  210. 'img': midi_input_img,
  211. 'connected_img': midi_input_connected,
  212. 'type': 'midi',
  213. })
  214. for ix in range(0, pb['hardware']['cv_outs']):
  215. device_playback.append({
  216. 'symbol': 'cv_playback_{0}'.format(ix + 1),
  217. 'img': cv_input_img,
  218. 'connected_img': cv_input_connected,
  219. 'type': 'cv',
  220. })
  221. # create plugins
  222. plugins = pb['plugins']
  223. plugins = [p for p in plugins if p['uri'] != 'http://drobilla.net/ns/ingen#GraphPrototype']
  224. plugin_map = {}
  225. for p in plugins:
  226. # read plugin data
  227. data = plugin_info(p['uri'])
  228. p['data'] = data
  229. # read plugin image
  230. gui = plugin_gui(p['uri'])
  231. screenshot_path = gui.get('screenshot', None)
  232. if screenshot_path is not None and os.path.isfile(screenshot_path):
  233. try:
  234. pimg = Image.open(screenshot_path).convert('RGBA')
  235. except:
  236. screenshot_path = None
  237. else:
  238. screenshot_path = None
  239. if screenshot_path is None:
  240. pimg = default_screenshot
  241. p['img'] = pimg
  242. in_ports = data['ports']['audio']['input'] + data['ports']['midi']['input'] + data['ports']['cv']['input']
  243. out_ports = data['ports']['audio']['output'] + data['ports']['midi']['output'] + data['ports']['cv']['output']
  244. if screenshot_path:
  245. # detect ports and save/read
  246. version = '{0}.{1}'.format(data['version'], data.get('release', 0)).replace('.', '_')
  247. encoded_uri = base64.b64encode(p['uri'].encode()).decode()
  248. filename = os.path.join(cache_dir, '{0}_{1}_{2}_v2'.format(__version__.replace('.', '_'), encoded_uri, version))
  249. validcache = False
  250. if os.path.isfile(filename):
  251. with open(filename, 'r') as fh:
  252. try:
  253. columns = json.loads(fh.read())
  254. except:
  255. pass
  256. else:
  257. validcache = 'in_ports' in columns and 'out_ports' in columns
  258. if not validcache:
  259. columns = {
  260. 'in_ports': tuple(tuple(c) for c in detect_first_column(p['uri'], pimg, pimg.size[0], len(in_ports))),
  261. 'out_ports': tuple(tuple(c) for c in detect_first_column(p['uri'], pimg, pimg.size[0], len(out_ports), rtol=True)),
  262. }
  263. with open(filename, 'w') as fh:
  264. fh.write(json.dumps(columns))
  265. else: # tuna can, we have to guess the position of the connectors
  266. columns = {
  267. # 8 inputs, 16 outputs; plugins don't usually have more than this
  268. 'in_ports': ((-9, 121), (-9, 146), (-9, 190), (-9, 215), (-9, 259), (-9, 284), (-9, 328), (-9, 353),
  269. (-9, 397), (-9, 422), (-9, 466), (-9, 491), (-9, 535), (-9, 560), (-9, 604), (-9, 629)),
  270. 'out_ports': ((259, 121), (259, 146), (259, 190), (259, 215), (259, 259), (259, 284), (259, 328), (259, 353),
  271. (259, 397), (259, 422), (259, 466), (259, 491), (259, 535), (259, 560), (259, 604), (259, 629),
  272. (259, 673), (259, 698), (259, 742), (259, 767), (259, 811), (259, 836), (259, 880), (259, 949),
  273. (259, 974), (259, 1018), (259, 1043), (259, 1087), (259, 1112), (259, 1156), (259, 1181), (259, 1225))
  274. }
  275. # detect connectors
  276. if len(in_ports) > 0:
  277. audio_in_ix = len(data['ports']['audio']['input'])
  278. cv_in_ix = len(data['ports']['cv']['input']) + audio_in_ix
  279. for ix, conn in enumerate(chunks(columns['in_ports'], 2)):
  280. if ix < len(in_ports):
  281. in_ports[ix]['connector'] = conn
  282. if ix < audio_in_ix:
  283. in_ports[ix]['connected_img'] = audio_input_connected
  284. in_ports[ix]['offset'] = (79, 15)
  285. in_ports[ix]['type'] = 'audio'
  286. elif ix < cv_in_ix:
  287. in_ports[ix]['connected_img'] = cv_input_connected
  288. in_ports[ix]['offset'] = (67, 15)
  289. in_ports[ix]['type'] = 'cv'
  290. else:
  291. in_ports[ix]['connected_img'] = midi_input_connected
  292. in_ports[ix]['offset'] = (67, 9)
  293. in_ports[ix]['type'] = 'midi'
  294. if not all('connector' in p for p in in_ports):
  295. raise Exception('Connector detection for input ports of plugin {0} failed'.format(p['uri']))
  296. if len(out_ports) > 0:
  297. audio_out_ix = len(data['ports']['audio']['output'])
  298. cv_out_ix = len(data['ports']['cv']['output']) + audio_out_ix
  299. for ix, conn in enumerate(chunks(columns['out_ports'], 2)):
  300. if ix < len(out_ports):
  301. out_ports[ix]['connector'] = conn
  302. if ix < audio_out_ix:
  303. out_ports[ix]['connected_img'] = audio_output_connected
  304. out_ports[ix]['offset'] = (8, 15)
  305. out_ports[ix]['type'] = 'audio'
  306. elif ix < cv_out_ix:
  307. out_ports[ix]['connected_img'] = cv_output_connected
  308. out_ports[ix]['offset'] = (11, 22)
  309. out_ports[ix]['type'] = 'cv'
  310. else:
  311. out_ports[ix]['connected_img'] = midi_output_connected
  312. out_ports[ix]['offset'] = (8, 9)
  313. out_ports[ix]['type'] = 'midi'
  314. if not all('connector' in p for p in out_ports):
  315. raise Exception('Connector detection for output ports of plugin {0} failed'.format(p['uri']))
  316. plugin_map[p['instance']] = p
  317. # we care more about speed than correctly cleaning up after ourselves
  318. # lv2_cleanup()
  319. # calculate image size
  320. height = 0
  321. for p in plugins:
  322. if p['x'] + p['img'].size[0] + right_padding > width:
  323. width = p['x'] + p['img'].size[0] + right_padding
  324. if p['y'] + p['img'].size[1] + bottom_padding > height:
  325. height = p['y'] + p['img'].size[1] + bottom_padding
  326. width = rint(width)
  327. height = rint(height) or rint(1112)
  328. # layout stays in canvas coordinates, the scale is applied when drawing
  329. scale = 1.0 if fixed_size else min(1.0, float(MAX_SCREENSHOT_WIDTH) / width)
  330. scaled_images = {}
  331. def sc(v):
  332. return rint(v * scale)
  333. def scaled(image):
  334. if scale == 1.0:
  335. return image
  336. key = id(image)
  337. if key not in scaled_images:
  338. scaled_images[key] = image.resize((max(1, sc(image.size[0])), max(1, sc(image.size[1]))), Image.BILINEAR)
  339. return scaled_images[key]
  340. # calculate device connectors positions
  341. used_symbols = tuple(c['source'] for c in pb['connections']) + tuple(c['target'] for c in pb['connections'])
  342. used_types = ('audio', 'cv')
  343. device_capture = tuple(
  344. d for d in device_capture
  345. if d['type'] in used_types or d['symbol'] in ('serial_midi_in', 'midi_merger_out') or d['symbol'] in used_symbols
  346. )
  347. device_playback = tuple(
  348. d for d in device_playback
  349. if d['type'] in used_types or d['symbol'] in ('serial_midi_out', 'midi_broadcaster_in') or d['symbol'] in used_symbols
  350. )
  351. step = rint(height / (len(device_capture) + 1))
  352. h = step
  353. for d in device_capture:
  354. d.update({'x': 0, 'y': h})
  355. h = h + step
  356. h = step
  357. for d in device_playback:
  358. d.update({'x': width, 'y': h})
  359. h = h + step
  360. del used_symbols
  361. del used_types
  362. # draw plugin cables and calculate connectors
  363. connectors = []
  364. paths = []
  365. for ix, c in enumerate(pb['connections']):
  366. # source
  367. source = next((s for s in device_capture if s['symbol'] == c['source']), None)
  368. if source:
  369. source_connected_img = source['connected_img']
  370. source_pos = anchor(source_connected_img.size, source['x'], source['y'], Anchor.LEFT_CENTER)
  371. source_x = source['x'] + source_connected_img.size[0]
  372. source_y = source['y']
  373. source_type = source['type']
  374. else:
  375. if '/' not in c['source']:
  376. continue
  377. source_i, source_s = c['source'].split('/')
  378. try:
  379. source = plugin_map[source_i]
  380. except KeyError:
  381. print("WARNING: invalid port source instance", source_i)
  382. continue
  383. all_ports = source['data']['ports']['audio']['output'] + source['data']['ports']['midi']['output'] + source['data']['ports']['cv']['output']
  384. try:
  385. port = next(p for p in all_ports if p['symbol'] == source_s)
  386. except StopIteration:
  387. print("WARNING: broken plugin port source", c['source'])
  388. continue
  389. conn = port['connector']
  390. source_connected_img = port['connected_img']
  391. source_pos = (source['x'] + conn[0][0] - port['offset'][0], source['y'] + conn[0][1] - port['offset'][1])
  392. source_x = source_pos[0] + source_connected_img.size[0]
  393. source_y = source_pos[1] + source_connected_img.size[1] / 2
  394. source_type = port['type']
  395. # target
  396. target = next((t for t in device_playback if t['symbol'] == c['target']), None)
  397. if target:
  398. target_connected_img = target['connected_img']
  399. target_pos = anchor(target_connected_img.size, target['x'], target['y'], Anchor.RIGHT_CENTER)
  400. target_x = target['x'] - target_connected_img.size[0]
  401. target_y = target['y']
  402. target_type = target['type']
  403. else:
  404. if '/' not in c['target']:
  405. continue
  406. target_i, target_s = c['target'].split('/')
  407. target = plugin_map[target_i]
  408. all_ports = target['data']['ports']['audio']['input'] + target['data']['ports']['midi']['input'] + target['data']['ports']['cv']['input']
  409. try:
  410. port = next(p for p in all_ports if p['symbol'] == target_s)
  411. except StopIteration:
  412. print("WARNING: broken plugin port target", c['target'])
  413. continue
  414. conn = port['connector']
  415. target_connected_img = port['connected_img']
  416. target_pos = (target['x'] + conn[0][0] - port['offset'][0], target['y'] + conn[0][1] - port['offset'][1])
  417. target_x = target_pos[0]
  418. target_y = target_pos[1] + target_connected_img.size[1] / 2
  419. target_type = port['type']
  420. delta_x = target_x - source_x - 50
  421. if delta_x < 0:
  422. delta_x = 8.5 * (delta_x / 6)
  423. else:
  424. delta_x /= 1.5
  425. path = 'm{0},{1} c{2},{3},{4},{5},{6},{7}'.format(
  426. sc(source_x),
  427. sc(source_y),
  428. sc(target_x - delta_x - source_x),
  429. 0,
  430. sc(delta_x),
  431. sc(target_y - source_y),
  432. sc(target_x - source_x),
  433. sc(target_y - source_y)
  434. )
  435. paths.append((path, source_type, target_type))
  436. connectors.append((source_connected_img, (rint(source_pos[0]), rint(source_pos[1])), source_connected_img))
  437. connectors.append((target_connected_img, (rint(target_pos[0]), rint(target_pos[1])), target_connected_img))
  438. del pb
  439. del plugin_map
  440. # create image
  441. img = Image.new('RGBA', (sc(width), sc(height)), (0, 0, 0, 0))
  442. # draw plugins
  443. for p in plugins:
  444. pimg = scaled(p['img'])
  445. img.paste(pimg, (sc(p['x']), sc(p['y'])), pimg)
  446. pace()
  447. del plugins
  448. # draw device connectors
  449. for d in device_capture:
  450. x, y = anchor(d['img'].size, d['x'], d['y'], Anchor.LEFT_CENTER)
  451. img.paste(scaled(d['img']), (sc(x), sc(y)))
  452. for d in device_playback:
  453. x, y = anchor(d['img'].size, d['x'], d['y'], Anchor.RIGHT_CENTER)
  454. img.paste(scaled(d['img']), (sc(x), sc(y)))
  455. audio_input_img.close()
  456. audio_output_img.close()
  457. midi_input_img.close()
  458. midi_output_img.close()
  459. cv_input_img.close()
  460. cv_output_img.close()
  461. del audio_input_img
  462. del audio_output_img
  463. del midi_input_img
  464. del midi_output_img
  465. del cv_input_img
  466. del cv_output_img
  467. # draw all paths
  468. try:
  469. from aggdraw import Draw, Pen, Symbol
  470. draw = Draw(img)
  471. pen_width = max(1.0, 7 * scale)
  472. audio_pen = Pen('#81009A', pen_width)
  473. midi_pen = Pen('#00546C', pen_width)
  474. cv_pen = Pen('#BB6736', pen_width)
  475. for path, source_type, target_type in paths:
  476. symbol = Symbol(path)
  477. if source_type == 'midi' or target_type == 'midi':
  478. pen = midi_pen
  479. elif source_type == 'cv' or target_type == 'cv':
  480. pen = cv_pen
  481. else:
  482. pen = audio_pen
  483. draw.symbol((0, 0), symbol, pen)
  484. draw.flush()
  485. pace()
  486. del draw
  487. del audio_pen
  488. del midi_pen
  489. del cv_pen
  490. except:
  491. print('Aggdraw failed')
  492. del paths
  493. # draw all connectors
  494. for cimg, (x, y), cmask in connectors:
  495. img.paste(scaled(cimg), (sc(x), sc(y)), scaled(cmask))
  496. pace()
  497. audio_input_connected.close()
  498. audio_output_connected.close()
  499. midi_input_connected.close()
  500. midi_output_connected.close()
  501. cv_input_connected.close()
  502. cv_output_connected.close()
  503. del device_capture
  504. del device_playback
  505. del audio_input_connected
  506. del audio_output_connected
  507. del midi_input_connected
  508. del midi_output_connected
  509. del cv_input_connected
  510. del cv_output_connected
  511. del connectors
  512. default_screenshot.close()
  513. del default_screenshot
  514. # zlib level 1: the fastest encode that still compresses the flat colours well, size is not a concern here
  515. img.save(os.path.join(bundle_path, 'screenshot.png'), compress_level=1)
  516. pace()
  517. resize_image(img)
  518. img.save(os.path.join(bundle_path, 'thumbnail.png'))
  519. img.close()
  520. del scaled_images
  521. def main():
  522. parser = argparse.ArgumentParser(description='Pedalboard tools')
  523. subparsers = parser.add_subparsers()
  524. # take screenshot bundle_path, html_dir, cache_dir
  525. def _take_screenshot(args):
  526. job = None
  527. if args.job:
  528. with open(args.job, 'r') as fh:
  529. job = json.load(fh)
  530. try:
  531. take_screenshot(args.pedalboard_path, args.html_path, args.cache_path, args.size, job)
  532. except:
  533. print("caught exception, retrying without cache...", file=sys.stderr, flush=True)
  534. # if we get exceptions thrown during screenshot generation, try invalidating cache
  535. shutil.rmtree(args.cache_path)
  536. take_screenshot(args.pedalboard_path, args.html_path, args.cache_path, args.size, job)
  537. subparser = subparsers.add_parser('take_screenshot', help='Take a screenshot of a given pedalboard')
  538. subparser.add_argument('pedalboard_path', help='Path to pedalboard bundle folder')
  539. subparser.add_argument('html_path', help='Path to mod-ui HTML folder')
  540. subparser.add_argument('cache_path', help='Path to cache folder')
  541. subparser.add_argument('-s', '--size', help='Screenshot width and height (i.e. 800x600)')
  542. subparser.add_argument('-j', '--job', help='JSON file with the pedalboard and plugin data, made by mod-ui; '
  543. 'skips loading the LV2 world')
  544. subparser.set_defaults(func=_take_screenshot)
  545. args = parser.parse_args()
  546. if hasattr(args, 'func'):
  547. args.func(args)
  548. sys.exit(0)
  549. else:
  550. parser.print_usage()
  551. if __name__ == '__main__':
  552. main()