196 lines
6.5 KiB
Python
196 lines
6.5 KiB
Python
"""Generate C header from Opus files — extracts Opus frames from OGG container.
|
|
|
|
Usage: python gen_audio_prompts.py <opus_dir> <output.h>
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import struct
|
|
import random
|
|
|
|
|
|
def parse_ogg_opus(filepath):
|
|
"""Extract raw Opus frames from OGG/Opus file.
|
|
|
|
Validates that page 0 carries OpusHead — refuses OGG/FLAC, OGG/Vorbis
|
|
or any other non-Opus container that would otherwise be silently
|
|
misinterpreted as Opus packets and break the firmware decoder.
|
|
"""
|
|
frames = []
|
|
with open(filepath, "rb") as f:
|
|
data = f.read()
|
|
|
|
pos = 0
|
|
page_num = 0
|
|
while pos < len(data):
|
|
# OGG page header
|
|
if data[pos:pos+4] != b"OggS":
|
|
break
|
|
num_segments = data[pos+26]
|
|
segment_table = data[pos+27:pos+27+num_segments]
|
|
data_start = pos + 27 + num_segments
|
|
|
|
# Reconstruct packets from segments
|
|
packet_data = bytearray()
|
|
data_offset = data_start
|
|
for seg_size in segment_table:
|
|
packet_data.extend(data[data_offset:data_offset+seg_size])
|
|
data_offset += seg_size
|
|
if seg_size < 255:
|
|
# Packet complete
|
|
if page_num == 0:
|
|
# First packet must be OpusHead — reject anything else
|
|
# (FLAC marker is "fLaC", Vorbis is b"\x01vorbis", etc.)
|
|
if not bytes(packet_data).startswith(b"OpusHead"):
|
|
actual = bytes(packet_data[:8]).decode("ascii", errors="replace")
|
|
raise ValueError(
|
|
f"{filepath}: not OGG/Opus (page-0 packet starts "
|
|
f"with {actual!r}). Re-encode the source to Opus "
|
|
f"with: ffmpeg -i <src> -c:a libopus -ar 24000 -b:a 24k <out>.opus"
|
|
)
|
|
if page_num >= 2 and len(packet_data) > 0:
|
|
# Skip pages 0 (OpusHead) and 1 (OpusTags)
|
|
frames.append(bytes(packet_data))
|
|
packet_data = bytearray()
|
|
|
|
# If packet spans pages (all segments = 255)
|
|
if len(packet_data) > 0 and page_num >= 2:
|
|
frames.append(bytes(packet_data))
|
|
packet_data = bytearray()
|
|
|
|
pos = data_offset
|
|
page_num += 1
|
|
|
|
return frames
|
|
|
|
|
|
GROUPS = [
|
|
"activation_device",
|
|
"device_already_bound",
|
|
"server_error",
|
|
"alarm_wake",
|
|
"alarm_set",
|
|
"no_network",
|
|
"wifi_config",
|
|
"wake_response",
|
|
"story_expired",
|
|
"idle_check",
|
|
"idle_goodbye",
|
|
"wifi_success",
|
|
"welcome",
|
|
"shutdown",
|
|
"boot",
|
|
"error",
|
|
"low_battery_20",
|
|
"low_battery_10",
|
|
] + [f"digit_{d}" for d in range(10)]
|
|
|
|
|
|
def classify_file(filename):
|
|
"""Map filename → group.
|
|
|
|
File naming rule: <group>.ogg or <group>_<n>.ogg, lowercase, ASCII only.
|
|
Single-file groups (e.g. boot, shutdown) match by exact stem; multi-file
|
|
groups (e.g. welcome_1, error_3) match by `<group>_` prefix.
|
|
Match priority follows GROUPS order (longer-prefix groups first to avoid
|
|
`server_error_1` falsely matching `server`-style entries; current GROUPS
|
|
list has no prefix overlap, but the order is preserved as a safety rail).
|
|
"""
|
|
stem = os.path.splitext(filename)[0]
|
|
for g in GROUPS:
|
|
if stem == g or stem.startswith(g + "_"):
|
|
return g
|
|
return None
|
|
|
|
|
|
def frames_to_c_array(frames, var_name):
|
|
"""Convert Opus frames to C byte array with simple format:
|
|
[num_frames:u16][frame_size:u16, frame_data:bytes]...
|
|
"""
|
|
buf = bytearray()
|
|
buf.extend(struct.pack("<H", len(frames)))
|
|
for frame in frames:
|
|
buf.extend(struct.pack("<H", len(frame)))
|
|
buf.extend(frame)
|
|
|
|
lines = [f"static const uint8_t {var_name}[] = {{"]
|
|
for i in range(0, len(buf), 16):
|
|
chunk = buf[i:i+16]
|
|
hex_str = ", ".join(f"0x{b:02x}" for b in chunk)
|
|
lines.append(f" {hex_str},")
|
|
lines.append("};")
|
|
return "\n".join(lines), len(buf)
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 3:
|
|
print(f"Usage: {sys.argv[0]} <opus_dir> <output.h>")
|
|
sys.exit(1)
|
|
|
|
opus_dir = sys.argv[1]
|
|
output_h = sys.argv[2]
|
|
|
|
groups = {g: [] for g in GROUPS}
|
|
total_size = 0
|
|
|
|
# Scan directory
|
|
files = []
|
|
for f in sorted(os.listdir(opus_dir)):
|
|
if f.lower().endswith((".opus", ".ogg")):
|
|
filepath = os.path.join(opus_dir, f)
|
|
group = classify_file(f)
|
|
if group:
|
|
files.append((f, filepath, group))
|
|
|
|
print(f"Found {len(files)} audio files")
|
|
|
|
# Generate header
|
|
header_lines = [
|
|
"#pragma once",
|
|
"",
|
|
"// Auto-generated by gen_audio_prompts.py — DO NOT EDIT",
|
|
"",
|
|
"#include <cstdint>",
|
|
"#include <cstddef>",
|
|
"",
|
|
]
|
|
|
|
array_names = {g: [] for g in GROUPS}
|
|
|
|
for idx, (filename, filepath, group) in enumerate(files):
|
|
frames = parse_ogg_opus(filepath)
|
|
var_name = f"audio_{group}_{idx}"
|
|
c_array, size = frames_to_c_array(frames, var_name)
|
|
header_lines.append(f"// {filename} ({len(frames)} frames, {size} bytes)")
|
|
header_lines.append(c_array)
|
|
header_lines.append("")
|
|
array_names[group].append(var_name)
|
|
total_size += size
|
|
sys.stdout.buffer.write(f" [{group}] {filename}: {len(frames)} frames, {size} bytes\n".encode("utf-8", errors="replace"))
|
|
|
|
# Generate group index tables. Always emit the symbols even for empty
|
|
# groups so audio_prompt.cc's static references compile — count=0 makes
|
|
# HasPrompts() return false and the caller falls back gracefully.
|
|
for group, names in array_names.items():
|
|
if names:
|
|
ptrs = ", ".join(names)
|
|
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ {ptrs} }};")
|
|
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ {', '.join(f'sizeof({n})' for n in names)} }};")
|
|
header_lines.append(f"static const int audio_{group}_count = {len(names)};")
|
|
else:
|
|
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ nullptr }};")
|
|
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ 0 }};")
|
|
header_lines.append(f"static const int audio_{group}_count = 0;")
|
|
header_lines.append("")
|
|
|
|
# Write header file
|
|
os.makedirs(os.path.dirname(output_h), exist_ok=True)
|
|
with open(output_h, "w", encoding="utf-8") as f:
|
|
f.write("\n".join(header_lines))
|
|
|
|
print(f"\nGenerated {output_h}: {total_size} bytes total ({total_size/1024:.1f} KB)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|