2023-11-17 00:31:41 +05:30
|
|
|
#!/usr/bin/python3
|
|
|
|
|
2023-11-17 00:59:52 +05:30
|
|
|
from argparse import ArgumentParser
|
2024-01-09 21:05:28 +05:30
|
|
|
from os import system, environ, makedirs
|
|
|
|
from os.path import exists, join as path_join
|
2023-11-17 00:59:52 +05:30
|
|
|
from sys import stdin
|
2024-01-09 21:05:28 +05:30
|
|
|
from typing import Dict, Union
|
2023-11-17 00:59:52 +05:30
|
|
|
import subprocess
|
|
|
|
|
|
|
|
# Paths
|
|
|
|
PATHS = {
|
2024-01-02 20:43:28 +05:30
|
|
|
"src_dir": "src",
|
|
|
|
"build_dir": "build",
|
2023-11-17 00:59:52 +05:30
|
|
|
"template": "template.c",
|
|
|
|
"substitute": "substituted.c",
|
2023-12-30 18:01:11 +05:30
|
|
|
"output": "render_bytebeat",
|
|
|
|
"fwrite_le_header": "fwrite_le.h",
|
|
|
|
"fwrite_le": "fwrite_le.c"
|
2023-11-17 00:59:52 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
# Solve paths
|
|
|
|
PATHS["template"] = path_join(PATHS["src_dir"], PATHS["template"])
|
|
|
|
PATHS["substitute"] = path_join(PATHS["build_dir"], PATHS["substitute"])
|
|
|
|
PATHS["output"] = path_join(PATHS["build_dir"], PATHS["output"])
|
2024-01-02 20:43:28 +05:30
|
|
|
PATHS["fwrite_le_header"] = PATHS["src_dir"] + "/" + PATHS["fwrite_le_header"]
|
|
|
|
PATHS["fwrite_le"] = path_join(PATHS["src_dir"], PATHS["fwrite_le"])
|
2023-11-17 00:59:52 +05:30
|
|
|
|
2023-12-30 18:10:37 +05:30
|
|
|
# Add `.` directory before all paths for compilation
|
|
|
|
PATHS["template"] = path_join(".", PATHS["template"])
|
|
|
|
PATHS["substitute"] = path_join(".", PATHS["substitute"])
|
|
|
|
PATHS["output"] = path_join(".", PATHS["output"])
|
2023-12-30 18:14:50 +05:30
|
|
|
PATHS["fwrite_le"] = path_join(".", PATHS["fwrite_le"])
|
2023-12-30 18:10:37 +05:30
|
|
|
|
2023-11-17 00:59:52 +05:30
|
|
|
# Default parameters
|
2023-11-17 00:31:41 +05:30
|
|
|
DEFAULT_PARAMETERS = {
|
2024-04-14 04:08:48 +05:30
|
|
|
"CC": "cc",
|
2024-01-27 16:31:49 +05:30
|
|
|
"CFLAGS": "-Ofast -march=native -mtune=native -Wall -Wextra -Wpedantic -pedantic -Wno-unused-variable -Wno-unused-but-set-variable -Wno-dangling-else -Wno-parentheses -std=c99",
|
2023-11-17 00:59:52 +05:30
|
|
|
"INPUT_FILE": PATHS["substitute"],
|
|
|
|
"OUTPUT_FILE": PATHS["output"]
|
2023-11-17 00:31:41 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
def fetch(name: str):
|
2023-12-24 21:50:47 +05:30
|
|
|
if from_env := environ.get(name):
|
2024-01-07 04:50:34 +05:30
|
|
|
return from_env
|
2024-01-10 01:39:02 +05:30
|
|
|
elif name != "CFLAGS_EXTRA":
|
2024-01-07 04:50:34 +05:30
|
|
|
return DEFAULT_PARAMETERS[name]
|
2023-11-17 00:31:41 +05:30
|
|
|
|
|
|
|
def read_file(path: str) -> str:
|
|
|
|
return open(path, "r", encoding="utf-8-sig").read()
|
|
|
|
|
|
|
|
def rewrite_file(path: str, content: str):
|
2024-01-09 18:24:00 +05:30
|
|
|
return open(path, "w", encoding="utf-8").write(content)
|
2023-11-17 00:31:41 +05:30
|
|
|
|
|
|
|
def read_from_file_or_stdin(path: str) -> str:
|
|
|
|
if path == "-":
|
|
|
|
return "\n".join(stdin)
|
|
|
|
elif exists(path):
|
|
|
|
return read_file(path)
|
|
|
|
else:
|
|
|
|
print("The specified file doesn't exist")
|
|
|
|
raise SystemExit
|
|
|
|
|
2024-01-09 21:05:28 +05:30
|
|
|
def substitute_vars(replacements: Dict[str, Union[bool, str]], text: str,
|
|
|
|
verbose: bool) -> str:
|
2024-01-09 20:34:26 +05:30
|
|
|
if verbose:
|
|
|
|
print("Substituting values:")
|
2023-12-03 18:25:08 +05:30
|
|
|
for placeholder, replacement in replacements.items():
|
2024-01-09 21:04:12 +05:30
|
|
|
if isinstance(replacement, bool):
|
|
|
|
replacement = preprocessor_bool(replacement)
|
|
|
|
|
2024-01-09 20:34:26 +05:30
|
|
|
if verbose and placeholder != "bytebeat_contents":
|
|
|
|
print(placeholder, ": ", replacement, sep="")
|
2023-12-03 18:25:08 +05:30
|
|
|
text = text.replace(f"`{placeholder}`", str(replacement))
|
2024-01-09 20:50:06 +05:30
|
|
|
if verbose:
|
|
|
|
print()
|
2023-12-03 18:25:08 +05:30
|
|
|
return text
|
2023-11-17 00:31:41 +05:30
|
|
|
|
2024-01-09 20:50:27 +05:30
|
|
|
preprocessor_bool = lambda value: "1" if value else "0"
|
2024-01-09 22:34:33 +05:30
|
|
|
C_str_repr = lambda s: '"' + s.replace("\\", "\\\\").replace(r'"', r'\"') + '"'
|
2024-01-09 20:50:27 +05:30
|
|
|
|
2023-11-17 00:31:41 +05:30
|
|
|
CC = fetch("CC")
|
2023-12-30 17:27:32 +05:30
|
|
|
CFLAGS = fetch("CFLAGS")
|
2023-11-17 00:59:52 +05:30
|
|
|
INPUT_FILE = fetch("INPUT_FILE")
|
2023-11-17 00:31:41 +05:30
|
|
|
OUTPUT_FILE = fetch("OUTPUT_FILE")
|
2024-01-10 01:39:02 +05:30
|
|
|
if extra := fetch("CFLAGS_EXTRA"):
|
|
|
|
CFLAGS += " " + extra
|
2023-11-17 00:31:41 +05:30
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
parser = ArgumentParser(description=\
|
|
|
|
"Substitutes supplied C (non-JavaScript!) bytebeat into the template, "
|
2024-01-09 19:18:34 +05:30
|
|
|
"then attempts to compile the instance of the template. Accepts "
|
2024-01-10 01:39:02 +05:30
|
|
|
"environmental variables `CC`, `CFLAGS`, `INPUT_FILE`, `OUTPUT_FILE`. "
|
|
|
|
"`CFLAGS_EXTRA` can be used to add to default `CFLAGS`.")
|
2023-11-17 00:31:41 +05:30
|
|
|
parser.add_argument("file", type=str,
|
2023-12-03 18:14:52 +05:30
|
|
|
help="bytebeat formula file (use `-` to read from stdin)")
|
2024-01-09 22:34:33 +05:30
|
|
|
parser.add_argument("-o", "--output", default="output.wav", type=str,
|
|
|
|
help="specify output file path (default is `output.wav`")
|
2023-11-17 00:31:41 +05:30
|
|
|
parser.add_argument("-r", "--sample-rate", default=8000, type=int,
|
|
|
|
help="sample rate (Hz)")
|
2023-11-18 16:45:48 +05:30
|
|
|
parser.add_argument("-p", "--final-sample-rate", default=None, type=int,
|
|
|
|
help="convert the output to a different sample rate (usually one that "
|
|
|
|
"is set in the system, to improve sound quality) during generation "
|
|
|
|
"(not just reinterpretation)")
|
2023-11-17 00:31:41 +05:30
|
|
|
parser.add_argument("-b", "--bit-depth", default=8, type=int,
|
|
|
|
help="bit depth")
|
|
|
|
parser.add_argument("-s", "--signed", default=False, action="store_true",
|
|
|
|
help="is signed?")
|
2024-01-09 20:44:32 +05:30
|
|
|
parser.add_argument("-R", "--precalculate-ratio", default=False,
|
|
|
|
action="store_true",
|
|
|
|
help="precalculate sample ratio to speed up rendering (may produce "
|
|
|
|
"inaccurate results")
|
|
|
|
parser.add_argument("-m", "--faster-sample-ratio-math", default=False,
|
|
|
|
action="store_true",
|
|
|
|
help="faster sample ratio math (implies argument -R)")
|
2024-01-09 20:05:27 +05:30
|
|
|
parser.add_argument("-f", "--floating-point", default=False,
|
|
|
|
action="store_true", help="use floating point as the return type")
|
2023-11-17 00:31:41 +05:30
|
|
|
parser.add_argument("-c", "--channels", default=1, type=int,
|
|
|
|
help="amount of channels")
|
2023-12-03 18:13:40 +05:30
|
|
|
parser.add_argument("-t", "--seconds", default=None, type=int,
|
|
|
|
help="length in seconds (samples = sample rate * seconds) : "
|
2024-01-09 21:06:27 +05:30
|
|
|
"default = 30 seconds")
|
2023-12-03 18:13:40 +05:30
|
|
|
parser.add_argument("-l", "--samples", default=None, type=int,
|
|
|
|
help="length in samples (adds to `-t`; supports negative numbers) : "
|
|
|
|
"default = +0 samples")
|
2023-11-17 00:31:41 +05:30
|
|
|
parser.add_argument("-a", "--no-return", default=False, action="store_true",
|
|
|
|
help="do not insert return statement before the code")
|
2024-01-10 06:37:15 +05:30
|
|
|
parser.add_argument("-u", "--mode", default="sequential", type=str,
|
|
|
|
help="mode of writing: `sequential` or `instant` (the latter is not "
|
|
|
|
"recommended, since the whole result would be stored in RAM)")
|
|
|
|
parser.add_argument("-n", "--block-size", default=65536, type=int,
|
|
|
|
help="sequential mode only: block size of each sequence, bytes")
|
2023-11-25 23:04:11 +05:30
|
|
|
parser.add_argument("-q", "--silent", default=False, action="store_true",
|
|
|
|
help="do not output anything during generation")
|
2023-11-25 23:33:27 +05:30
|
|
|
parser.add_argument("-v", "--verbose", default=False, action="store_true",
|
2023-11-25 23:36:19 +05:30
|
|
|
help="show progress during generation")
|
2024-01-09 20:34:26 +05:30
|
|
|
parser.add_argument("-E", "--show-substituted-values", default=False,
|
|
|
|
action="store_true", help="show substituted values")
|
2023-11-17 00:31:41 +05:30
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
bytebeat_contents = read_from_file_or_stdin(args.file).strip()
|
|
|
|
|
|
|
|
if not bytebeat_contents:
|
|
|
|
print("No valid contents")
|
|
|
|
raise SystemExit
|
|
|
|
|
2023-11-17 00:59:52 +05:30
|
|
|
# - Compilation
|
|
|
|
makedirs(PATHS["build_dir"], exist_ok=True)
|
|
|
|
|
2023-11-17 00:31:41 +05:30
|
|
|
if not args.no_return: # Insert return statement
|
2023-11-25 19:58:22 +05:30
|
|
|
bytebeat_contents = f"return {bytebeat_contents}"
|
2023-11-17 00:31:41 +05:30
|
|
|
|
2024-01-09 20:44:32 +05:30
|
|
|
original_sample_rate = args.sample_rate
|
2023-11-18 16:45:48 +05:30
|
|
|
final_sample_rate_code = ""
|
2024-01-09 20:44:32 +05:30
|
|
|
if args.faster_sample_ratio_math:
|
|
|
|
args.precalculate_ratio = True
|
2024-01-10 01:49:38 +05:30
|
|
|
if args.precalculate_ratio and not args.final_sample_rate is None:
|
2024-01-09 20:44:32 +05:30
|
|
|
if args.faster_sample_ratio_math:
|
|
|
|
sample_rate_ratio = args.sample_rate / args.final_sample_rate
|
|
|
|
final_sample_rate_code = f"w *= {sample_rate_ratio}L;"
|
|
|
|
else:
|
|
|
|
sample_rate_ratio = args.final_sample_rate / args.sample_rate
|
|
|
|
final_sample_rate_code = f"w /= {sample_rate_ratio}L;"
|
2023-11-18 16:45:48 +05:30
|
|
|
args.sample_rate = args.final_sample_rate
|
|
|
|
|
2024-01-12 01:33:45 +05:30
|
|
|
final_sample_rate = \
|
|
|
|
value if (value := args.final_sample_rate) else original_sample_rate
|
2023-12-03 18:13:40 +05:30
|
|
|
samples = 0
|
|
|
|
while True:
|
|
|
|
no_seconds = args.seconds is None or args.seconds == 0
|
|
|
|
no_samples = args.samples is None or args.samples == 0
|
2024-01-12 23:22:12 +05:30
|
|
|
seconds_specified = not no_seconds
|
|
|
|
samples_specified = not no_samples
|
2023-12-03 18:13:40 +05:30
|
|
|
|
2024-01-12 23:22:12 +05:30
|
|
|
if seconds_specified and args.seconds < 0:
|
2023-12-03 18:13:40 +05:30
|
|
|
print("CLI: Count of seconds can't be less than zero.")
|
|
|
|
raise SystemExit
|
|
|
|
|
2024-01-12 23:22:12 +05:30
|
|
|
if no_seconds and samples_specified:
|
2023-12-03 18:13:40 +05:30
|
|
|
samples = args.samples
|
2024-01-12 23:22:12 +05:30
|
|
|
elif seconds_specified and samples_specified:
|
2024-01-12 01:33:45 +05:30
|
|
|
samples = args.seconds * final_sample_rate + args.samples
|
2024-01-12 23:22:12 +05:30
|
|
|
elif seconds_specified and no_samples:
|
2024-01-12 01:33:45 +05:30
|
|
|
samples = args.seconds * final_sample_rate
|
2023-12-03 18:13:40 +05:30
|
|
|
elif no_seconds and no_samples:
|
|
|
|
args.seconds = 30 # default
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
print("CLI: Incorrect seconds/samples length format.")
|
|
|
|
raise SystemExit
|
|
|
|
break
|
|
|
|
|
|
|
|
if samples <= 0:
|
|
|
|
print("CLI: Count of samples should be greater than zero.")
|
|
|
|
raise SystemExit
|
|
|
|
|
2024-01-10 06:37:15 +05:30
|
|
|
if args.mode != "sequential" and args.mode != "instant":
|
|
|
|
print("Invalid mode '%s'" % args.mode)
|
2024-01-12 23:23:19 +05:30
|
|
|
raise SystemExit
|
2024-01-10 06:37:15 +05:30
|
|
|
|
2023-12-03 18:25:08 +05:30
|
|
|
rewrite_file(PATHS["substitute"], substitute_vars({
|
|
|
|
"bytebeat_contents": bytebeat_contents,
|
2024-01-09 22:34:33 +05:30
|
|
|
"output_file": C_str_repr(args.output),
|
2024-01-10 06:38:05 +05:30
|
|
|
"sample_rate": \
|
|
|
|
value if (value := args.final_sample_rate) else args.sample_rate,
|
2024-01-09 20:44:32 +05:30
|
|
|
"original_sample_rate": original_sample_rate,
|
2023-12-03 18:25:08 +05:30
|
|
|
"final_sample_rate_code": final_sample_rate_code,
|
|
|
|
"bit_depth": args.bit_depth,
|
2024-01-09 21:04:12 +05:30
|
|
|
"is_signed": args.signed,
|
|
|
|
"precalculated_ratio": args.precalculate_ratio,
|
|
|
|
"faster_sample_ratio_math": args.precalculate_ratio,
|
|
|
|
"fp_return_type": args.floating_point,
|
2023-12-03 18:25:08 +05:30
|
|
|
"channels": args.channels,
|
|
|
|
"length": samples,
|
2024-04-14 14:17:51 +05:30
|
|
|
"wav_product": args.channels * samples,
|
2024-01-10 06:37:15 +05:30
|
|
|
"sequential_mode": args.mode == "sequential",
|
|
|
|
"block_size": args.block_size,
|
2024-01-09 21:04:12 +05:30
|
|
|
"silent_mode": args.silent,
|
|
|
|
"verbose_mode": args.verbose and not args.silent,
|
2023-12-30 18:14:50 +05:30
|
|
|
"fwrite_le": "../" + PATHS["fwrite_le_header"]
|
2024-01-09 20:34:26 +05:30
|
|
|
}, read_file(PATHS["template"]), args.show_substituted_values))
|
2023-11-17 00:31:41 +05:30
|
|
|
|
|
|
|
# Compile by invoking the shell script
|
|
|
|
print("Compiling")
|
|
|
|
|
2023-11-17 00:59:52 +05:30
|
|
|
# Let the system execute aliases by calling os.system
|
2023-12-30 18:14:50 +05:30
|
|
|
command = " ".join([CC, CFLAGS, INPUT_FILE, PATHS["fwrite_le"], "-o",
|
|
|
|
OUTPUT_FILE])
|
2024-01-02 20:44:04 +05:30
|
|
|
print(command, flush=True)
|
2023-12-30 18:02:41 +05:30
|
|
|
system(command)
|