#!/usr/bin/env python3 """Validate a narrated story package, using standard Python plus ffmpeg.""" import argparse import hashlib import json import struct import subprocess import wave from pathlib import Path parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('package', type=Path) a = parser.parse_args() repo = Path(__file__).resolve().parents[1] package = a.package.resolve() read = lambda path: json.loads(path.read_text()) sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() campaign = read(package / 'campaign.json') notebook = read(package / 'notebook.json')['pages'] scripts = {s['pageId']: s for s in read(package / 'narration/scripts.json')} manifest = read(package / 'narration/manifest.json') tracks = read(package / 'audio/narration_manifest.json')['tracks'] assert tracks == manifest['tracks'], 'Runtime/provenance manifests differ' assert len({p['id'] for p in notebook}) == len(notebook), 'Duplicate page IDs' prose = {p['id'] for p in notebook if p['type'] != 'puzzle'} assert set(scripts) == prose == set(tracks), 'Every prose page must have exactly one recording' images = {package / 'artwork/cover-v1.png'} for level in campaign['levels']: images.add(repo / level['illustrationAsset']) for path in images: data = path.read_bytes() assert data[:8] == b'\x89PNG\r\n\x1a\n', path w, h, depth, colour = struct.unpack('>IIBB', data[16:26]) assert min(w, h) >= 512 and depth == 8 and colour == 6, f'Expected large RGBA PNG: {path}' for page in notebook: if page['type'] == 'puzzle': assert page['id'] not in tracks, 'Puzzle instructions should not autoplay' continue index = page.get('campaignIndex') source = page.get('textSource') text = campaign['levels'][index][source] if source in ('before', 'after') else page['text'] text = '\n\n'.join(s for s in [text, page.get('continuation', '')] if s) script, track = scripts[page['id']], tracks[page['id']] assert text == script['text'] == track['text'], f'Stale script: {page["id"]}' assert hashlib.sha256(text.encode()).hexdigest() == track['textSha256'] assert track.get('cueJoin','\n\n').join(c['text'] for c in track['cues']) == text, f'Incomplete cues: {page["id"]}' if script.get('segments'): cast = read(package / 'narration/cast.json') assert track['segments'] == script['segments'], 'Stale performance directions' assert ''.join(s['text'] for s in script['segments']) == text assert len(script['segments']) == len(track['cues']) for segment, cue in zip(script['segments'], track['cues']): assert segment['speaker'] == cue['speaker'] assert cast[segment['speaker']]['voice'] == cue['voice'] for event in track['events']: assert 0 <= event['startMs'] < event['endMs'] <= track['durationMs'] assert all(event['endMs'] <= c['startMs'] or event['startMs'] >= c['endMs'] for c in track['cues']), 'Foley must leave the spoken words clear' wav = repo / track['asset'] master = package / 'narration/wav' / track['file'] flac = package / 'narration/flac' / track['flacFile'] assert sha(wav) == sha(master) == track['wavSha256'], wav assert sha(flac) == track['flacSha256'], flac with wave.open(str(wav), 'rb') as audio: assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000) assert audio.getnframes() == track['frames'] pcm = audio.readframes(audio.getnframes()) samples = memoryview(pcm).cast('h') peak = max(abs(v) for v in samples) assert 1000 < peak < 32000, f'Silent/clipped recording: {wav}' assert abs(track['durationMs'] - round(track['frames'] / 24)) <= 1 last = 0 for cue in track['cues']: assert last <= cue['startMs'] < cue['endMs'] <= track['durationMs'] last = cue['endMs'] decoded = subprocess.check_output(['ffmpeg', '-v', 'error', '-i', str(flac), '-f', 's16le', '-acodec', 'pcm_s16le', '-']) assert decoded == pcm, f'Lossless master mismatch: {flac}' print(f'PASS {page["id"]}: script, cues, PCM and lossless archive ({track["durationMs"]/1000:.1f}s)') minutes = sum(t['durationMs'] for t in tracks.values()) / 60000 if (package / 'audio/atmosphere.json').exists(): atmosphere = read(package / 'audio/atmosphere.json') provenance = read(package / 'audio/atmosphere_provenance.json')['tracks'] for page_id, scene in atmosphere['pages'].items(): assert page_id in {p['id'] for p in notebook} assert scene in atmosphere['scenes'] for name, scene in atmosphere['scenes'].items(): path = repo / scene['asset'] assert sha(path) == provenance[name]['wavSha256'] with wave.open(str(path), 'rb') as audio: assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000) pcm = memoryview(audio.readframes(audio.getnframes())).cast('h') assert abs(pcm[-1] - pcm[0]) <= 1, 'Loop has a discontinuity' assert 1000 < max(abs(v) for v in pcm) < 24000 print(f'PASS atmosphere: {name}, bundled PCM and seamless loop') print(f'PASS package: {len(campaign["levels"])} puzzles, {len(notebook)} leaves, {len(images)} illustrations, {len(tracks)} recordings, {minutes:.1f} minutes')