resample_compare.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python3
  2. """Sound object files at other rates than the output, against OpenAL Soft 1.21.1.
  3. WE hands every sound file to OpenAL at its own rate and OpenAL resamples it in the mixer (linear, 12 bit fixed
  4. point step), mixing in 20 ms updates (960 frames at 48 kHz). This builds one "single" or "loop" sound object scene
  5. per case, renders it with the engine's SDL disk output and the same file with refstream (build.sh), and compares
  6. them from the first non-zero frame: start, length (the held last sample and the 64 sample stop fade) and samples.
  7. usage: resample_compare.py [--hrtf] [work dir] (default work dir ~/.cache/lwe-openal-1.21.1, build.sh's)
  8. The non-HRTF path differs by about one float ulp from OpenAL's (its panning goes through an ambisonic decode),
  9. HRTF is bit-identical except for files above 48 kHz, where OpenAL mixes an update in several passes.
  10. """
  11. import json, math, os, shutil, struct, subprocess, sys, wave
  12. import numpy as np
  13. REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
  14. ASSETS = os.environ.get('LWE_ASSETS_DIR', '/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets')
  15. STOP = """
  16. 'use strict';
  17. let frames = 0;
  18. export function update(value) {
  19. frames++;
  20. if (frames === 12) thisScene.getLayer('snd').stop();
  21. return value;
  22. }
  23. """
  24. # name: rate, channels, seconds, playback mode, stopped by a script
  25. CASES = {
  26. 'mono22050': (22050, 1, 0.7, 'single', False),
  27. 'stereo44100': (44100, 2, 0.7, 'single', False),
  28. 'mono16000': (16000, 1, 0.7, 'single', False),
  29. 'mono48000': (48000, 1, 0.7, 'single', False),
  30. 'odd96000': (96000, 2, 0.7013, 'single', False),
  31. 'stop22050': (22050, 1, 3.0, 'loop', True),
  32. 'loop22050': (22050, 1, 0.4321, 'loop', False),
  33. }
  34. def tone(path, rate, secs, channels, repeat=1):
  35. frames = bytearray()
  36. n = int(rate * secs)
  37. for i in range(n):
  38. t = i / rate
  39. # a sweep plus a level step, ending away from zero so the held last sample shows
  40. v = 0.4 * math.sin(2 * math.pi * (300 + 900 * t) * t) + (0.3 if i > n * 0.8 else 0.0)
  41. s = int(round(v * 32767))
  42. frames += struct.pack('<h', s) if channels == 1 else struct.pack('<hh', s, -s // 2)
  43. with wave.open(path, 'wb') as w:
  44. w.setnchannels(channels)
  45. w.setsampwidth(2)
  46. w.setframerate(rate)
  47. w.writeframes(bytes(frames) * repeat)
  48. def scene(d, mode, stop):
  49. objs = [{'id': 1, 'name': 'snd', 'origin': '960 540 0', 'sound': ['sounds/a.wav'], 'volume': 1.0,
  50. 'playbackmode': mode}]
  51. if stop:
  52. objs.append({'id': 2, 'name': 'stopper', 'origin': '0 0 0', 'visible': {'script': STOP, 'value': True}})
  53. json.dump({'file': 'scene.json', 'type': 'scene', 'title': os.path.basename(d), 'general': {'properties': {}}},
  54. open(d + '/project.json', 'w'))
  55. json.dump({'camera': {'center': '960 540 0', 'eye': '960 540 1', 'up': '0 1 0'},
  56. 'general': {'orthogonalprojection': {'width': 1920, 'height': 1080}, 'clearcolor': '0 0 0',
  57. 'bloom': False, 'cameraparallax': False},
  58. 'objects': objs, 'version': 3}, open(d + '/scene.json', 'w'))
  59. def onset_end(x):
  60. nz = np.any(x != 0, axis=1)
  61. return int(np.argmax(nz)), len(x) - int(np.argmax(nz[::-1]))
  62. def main():
  63. args = [a for a in sys.argv[1:] if a != '--hrtf']
  64. hrtf = '--hrtf' in sys.argv
  65. work = os.path.abspath(args[0] if args else os.path.expanduser('~/.cache/lwe-openal-1.21.1'))
  66. out = os.path.join(work, 'resample')
  67. os.makedirs(out, exist_ok=True)
  68. # never "linux-wallpaperengine" in a test process' command line, we_manager's shutdown pkill matches it
  69. binary = os.path.join(REPO, 'build/output/lwe-resample-bin')
  70. shutil.copy(os.path.join(REPO, 'build/output/linux-wallpaperengine'), binary)
  71. empty = os.path.join(work, 'empty')
  72. os.makedirs(empty, exist_ok=True)
  73. status = 0
  74. for name, (rate, channels, secs, mode, stop) in CASES.items():
  75. d = os.path.join(out, name)
  76. os.makedirs(d + '/sounds', exist_ok=True)
  77. tone(d + '/sounds/a.wav', rate, secs, channels)
  78. scene(d, mode, stop)
  79. ours = os.path.join(out, name + '.ours.f32')
  80. env = dict(os.environ, SDL_AUDIODRIVER='disk', SDL_DISKAUDIOFILE=ours, HEADLESS_RENDER_KEEP_RUNNING='1',
  81. HEADLESS_RENDER_TIMEOUT='4', HEADLESS_RENDER_SIZE='640x360')
  82. subprocess.run(['bash', os.path.join(REPO, 'tools/headless_render.sh'), binary, os.path.join(out, name + '.png'),
  83. '--assets-dir', ASSETS, '--volume', '128', '--hrtf', 'on' if hrtf else 'off', d],
  84. env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  85. b = np.fromfile(ours, np.float32).reshape(-1, 2)
  86. sb, eb = onset_end(b)
  87. # the script's stop lands on whatever update the frame it runs falls into, give refstream the same one
  88. stop_update = (eb - sb) // 960 if stop else -1
  89. src = d + '/sounds/a.wav'
  90. if mode == 'loop' and not stop:
  91. src = os.path.join(out, name + '.x8.wav')
  92. tone(src, rate, secs, channels, 8)
  93. ref = os.path.join(out, name + '.ref.f32')
  94. subprocess.run([os.path.join(work, 'refstream'), src, '1.0', '160', ref, str(stop_update), '960',
  95. '1' if hrtf else '0'],
  96. env={'HOME': empty, 'XDG_DATA_DIRS': empty, 'XDG_CONFIG_DIRS': empty}, check=True)
  97. a = np.fromfile(ref, np.float32).reshape(-1, 2)
  98. sa, ea = onset_end(a)
  99. a, b = a[sa:], b[sb:]
  100. n = min(len(a), len(b))
  101. diff = float(np.abs(a[:n] - b[:n]).max())
  102. lengths = (ea - sa, eb - sb) if mode == 'single' or stop else None
  103. ok = diff < 2e-7 and (lengths is None or lengths[0] == lengths[1])
  104. status |= not ok
  105. print(f'{name:12} max diff {diff:.3g}' + (f' length ref {lengths[0]} ours {lengths[1]}' if lengths else '')
  106. + ('' if ok else ' DIFFERENT'))
  107. sys.exit(status)
  108. if __name__ == '__main__':
  109. main()