#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Check direct MCP PCM16 WAV captures for digital silence or a bounded effect.""" import argparse import array import json import sys import wave def measure(path, tail_ms=500): with wave.open(str(path), 'rb') as wav: if wav.getsampwidth() != 2 or wav.getcomptype() != 'NONE': raise ValueError('Expected uncompressed PCM16 WAV') channels = wav.getnchannels() rate = wav.getframerate() frames = wav.getnframes() samples = array.array('h', wav.readframes(frames)) if sys.byteorder != 'little': samples.byteswap() if not frames or channels < 1 or len(samples) != frames * channels: raise ValueError('Empty or incomplete WAV') separate = [samples[channel::channels] for channel in range(channels)] tail_frames = min(frames, max(1, rate * tail_ms // 1000)) return { 'sample_rate': rate, 'channels': channels, 'sample_frames': frames, 'peak_per_channel': [max(abs(n) for n in channel) for channel in separate], 'changing_edges_per_channel': [ sum(channel[i] != channel[i - 1] for i in range(1, frames)) for channel in separate ], 'nonzero_frames': sum( any(samples[i * channels + channel] for channel in range(channels)) for i in range(frames) ), 'tail_ms': tail_ms, 'tail_peak': max(abs(n) for n in samples[-tail_frames * channels:]), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('wav') parser.add_argument('--expect', choices=('silent', 'effect'), required=True) parser.add_argument('--tail-ms', type=int, default=500) args = parser.parse_args() if args.tail_ms <= 0: parser.error('--tail-ms must be positive') result = measure(args.wav, args.tail_ms) if args.expect == 'silent': passed = result['nonzero_frames'] == 0 else: passed = (result['nonzero_frames'] > 0 and max(result['changing_edges_per_channel']) >= 2 and result['tail_peak'] == 0) print(json.dumps({'passed': passed, 'expect': args.expect, **result})) return 0 if passed else 1 if __name__ == '__main__': sys.exit(main())