aboutsummaryrefslogtreecommitdiff
path: root/examples/sound/spustream/convert_stream.py
blob: 1b1696f84a9c9648cdfc9aceea3584ebee0de374 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python3
# Simple .VAG to STREAM.BIN interleaving tool
# (C) 2021 spicyjpeg - MPL licensed

import sys
from warnings  import warn
from struct    import Struct
from itertools import zip_longest
from argparse  import ArgumentParser, FileType

VAG_HEADER  = Struct("> 4s I 4x 2I 12x 16s")
VAG_MAGIC   = b"VAGp"
SAMPLE_RATE = 44100
BUFFER_SIZE = 26624 # (26624 / 16 * 28) / 44100 = 1.05 seconds
ALIGN_SIZE  = 2048

## Helpers

def align(data, size):
	chunks = (len(data) + size - 1) // size

	return data.ljust(chunks * size, b"\x00")

def set_loop_flag(data):
	last_block    = bytearray(data[-16:])
	last_block[1] = 0x03 # Jump to loop point + sustain

	return data[:-16] + last_block

## .VAG file reader

def read_vag(_file, chunk_size):
	with _file:
		header = _file.read(VAG_HEADER.size)
		(
			magic,
			version,
			size,
			sample_rate,
			name
		) = VAG_HEADER.unpack(header)

		#if magic != VAG_MAGIC:
			#raise RuntimeError(f"{_file.name} is not a valid .VAG file")
		if sample_rate != SAMPLE_RATE:
			warn(RuntimeWarning(f"{_file.name} sample rate is not {SAMPLE_RATE} Hz"))

		for i in range(0, size, chunk_size):
			chunk   = _file.read(chunk_size)

			if len(chunk) % 16:
				warn(RuntimeWarning(f"{_file.name} is not 16-byte aligned, trimming"))
				chunk = chunk[0:len(chunk) // 16 * 16]

			chunk = set_loop_flag(chunk)

			yield chunk.ljust(chunk_size, b"\x00")

## Main

def get_args():
	parser = ArgumentParser(
		description = "Generates interleaved stream data from one or more .VAG files."
	)
	parser.add_argument(
		"input_file",
		nargs = "+",
		type  = FileType("rb"),
		help  = f"mono input files for each channel (must be {SAMPLE_RATE} Hz .VAG)"
	)
	parser.add_argument(
		"-o", "--output",
		type    = FileType("wb"),
		default = "stream.bin",
		help    = "where to output converted stream data (stream.bin by default)",
		metavar = "file"
	)
	parser.add_argument(
		"-b", "--buffer-size",
		type    = int,
		default = BUFFER_SIZE,
		help    = f"size of each interleaved chunk (one per channel, default {BUFFER_SIZE})",
		metavar = "bytes"
	)
	parser.add_argument(
		"-a", "--align",
		type    = int,
		default = ALIGN_SIZE,
		help    = f"align each group of chunks to N bytes (default {ALIGN_SIZE})",
		metavar = "bytes"
	)

	return parser.parse_args()

def main():
	args = get_args()
	if args.buffer_size % 16:
		raise ValueError("buffer size must be a multiple of 16 bytes")

	interleave = zip_longest(
		*( read_vag(_file, args.buffer_size) for _file in args.input_file ),
		fillvalue = b"\x00" * args.buffer_size
	)

	with args.output as _file:
		for chunks in interleave:
			data = b"".join(chunks)

			_file.write(align(data, args.align))

if __name__ == "__main__":
	main()