microbr-decode 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ import argparse
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from microbr_decode.br_format import (
6
+ decode_song_directory,
7
+ inspect_path,
8
+ write_wav_mono_16,
9
+ )
10
+
11
+
12
+ def _inspect(path: Path) -> int:
13
+ try:
14
+ card_root, songs = inspect_path(path)
15
+ except (OSError, ValueError) as error:
16
+ print(f"microbr-decode: {error}", file=sys.stderr)
17
+ return 2
18
+
19
+ print(f"Card directory: {card_root}")
20
+ print(f"Songs found: {len(songs)}")
21
+ for song in songs:
22
+ print(f"\n{song.directory.name}")
23
+ print(f" Song name: {song.song_name or 'unknown'}")
24
+ print(f" Recorder identifier: {song.recorder_model or 'unknown'}")
25
+ if song.audio_format and song.audio_format.hardware_id:
26
+ print(f" Hardware ID: {song.audio_format.hardware_id}")
27
+ if song.invalid_headers:
28
+ print(f" Invalid metadata headers: {', '.join(song.invalid_headers)}")
29
+ for name, size in song.files.items():
30
+ description = "missing" if size is None else f"{size} bytes"
31
+ print(f" {name}: {description}")
32
+
33
+ if song.audio_format:
34
+ fmt = song.audio_format
35
+ print(
36
+ f" Audio format: {fmt.mode_label}, {fmt.sample_rate} Hz, "
37
+ f"page={fmt.page_size}B ({fmt.blocks_per_page} blocks/page)"
38
+ )
39
+ else:
40
+ print(" Audio format: unparsed")
41
+
42
+ if song.active_events:
43
+ tracks: dict[tuple[int, int], list] = {}
44
+ max_blk = 0
45
+ for ev in song.active_events:
46
+ tracks.setdefault((ev.track, ev.vtrack), []).append(ev)
47
+ max_blk = max(max_blk, ev.timeline_start_block + ev.block_count)
48
+ sr = song.audio_format.sample_rate if song.audio_format else 44100
49
+ dur = (max_blk * 16) / sr
50
+ track_desc = ", ".join(
51
+ f"T{t}V{v}({len(evs)} ev)" for (t, v), evs in sorted(tracks.items())
52
+ )
53
+ print(f" Active tracks: {track_desc} (duration={dur:.2f}s)")
54
+ else:
55
+ print(" Active tracks: none")
56
+
57
+ return 0
58
+
59
+
60
+ def _decode(
61
+ path: Path,
62
+ output_dir: Path | None = None,
63
+ *,
64
+ split_tracks: bool = True,
65
+ ) -> int:
66
+ try:
67
+ card_root, songs = inspect_path(path)
68
+ except (OSError, ValueError) as error:
69
+ print(f"microbr-decode: {error}", file=sys.stderr)
70
+ return 2
71
+
72
+ out_root = output_dir if output_dir is not None else Path("decoded_wav")
73
+ decoded_count = 0
74
+ for song_info in songs:
75
+ try:
76
+ decoded = decode_song_directory(song_info.directory)
77
+ except (OSError, ValueError) as error:
78
+ print(f"microbr-decode: skipping {song_info.directory.name}: {error}", file=sys.stderr)
79
+ continue
80
+
81
+ stem = song_info.directory.stem
82
+ sr = decoded.audio_format.sample_rate
83
+ mix_path = out_root / f"{stem}.wav"
84
+ write_wav_mono_16(mix_path, decoded.mixdown, sr)
85
+ dur = len(decoded.mixdown) / sr
86
+ print(f"Decoded {stem} -> {mix_path} ({dur:.2f}s, {len(decoded.tracks)} track(s))")
87
+
88
+ if split_tracks and len(decoded.tracks) > 1:
89
+ for tr in decoded.tracks:
90
+ tr_path = out_root / f"{stem}_T{tr.track}_V{tr.vtrack}.wav"
91
+ write_wav_mono_16(tr_path, tr.samples, sr)
92
+ print(f" Track {tr.track} V{tr.vtrack} -> {tr_path}")
93
+ decoded_count += 1
94
+
95
+ if decoded_count == 0:
96
+ print("microbr-decode: no songs were decoded.", file=sys.stderr)
97
+ return 2
98
+ return 0
99
+
100
+
101
+ def main() -> None:
102
+ parser = argparse.ArgumentParser(
103
+ prog="microbr-decode",
104
+ description="Inspect and decode BOSS BR / Micro-BR song folders to WAV.",
105
+ )
106
+ subparsers = parser.add_subparsers(dest="command", required=True)
107
+ inspect_parser = subparsers.add_parser(
108
+ "inspect", help="inspect a card directory or one SONG*.BR0 folder"
109
+ )
110
+ inspect_parser.add_argument("path", type=Path)
111
+ decode_parser = subparsers.add_parser(
112
+ "decode", help="decode a song or card directory to 16-bit WAV"
113
+ )
114
+ decode_parser.add_argument("path", type=Path)
115
+ decode_parser.add_argument(
116
+ "-o",
117
+ "--output",
118
+ type=Path,
119
+ default=Path("decoded_wav"),
120
+ help="output directory for WAV files (default: decoded_wav)",
121
+ )
122
+ decode_parser.add_argument(
123
+ "--no-split-tracks",
124
+ action="store_true",
125
+ help="only write the mixed song WAV without separate per-track WAV files",
126
+ )
127
+ args = parser.parse_args()
128
+
129
+ if args.command == "inspect":
130
+ raise SystemExit(_inspect(args.path))
131
+
132
+ raise SystemExit(_decode(args.path, args.output, split_tracks=not args.no_split_tracks))
@@ -0,0 +1,434 @@
1
+ from __future__ import annotations
2
+
3
+ from array import array
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ import struct
7
+ import wave
8
+
9
+ from microbr_decode.rdac_brwc import BRWCRdacDecoder
10
+
11
+ SONG_FILE_NAMES = (
12
+ "SONGINF2.BR0",
13
+ "SONGPRM.BR1",
14
+ "ARRANGE3.BR1",
15
+ "EFFECTS3.BR1",
16
+ "TAKE_DAT.BR0",
17
+ "TAKE_DT1.BR0",
18
+ "TAKE_DT2.BR0",
19
+ "TAKE_EVT.BR0",
20
+ )
21
+
22
+ BR0_SIGNATURE = b"BOSS BR0 Format "
23
+ BS0_SIGNATURE = b"BOSS BS0 BFORMAT"
24
+
25
+ SAMPLE_RATES = {
26
+ 0: 48000,
27
+ 1: 44100,
28
+ 2: 32000,
29
+ }
30
+
31
+ MODE_WORDS_MAP = {
32
+ 0: 16, # Uncompressed 16-bit PCM (32 bytes / 16 samples)
33
+ 1: 8, # RDAC 16 bytes / 16 samples
34
+ 2: 6, # RDAC 12 bytes / 16 samples (Micro-BR Hi-Fi / MT2)
35
+ 3: 5, # RDAC 10 bytes / 16 samples
36
+ 4: 4, # RDAC 8 bytes / 16 samples
37
+ }
38
+
39
+ MODE_LABELS = {
40
+ 16: "PCM16 (32B/block)",
41
+ 8: "RDAC-8W (16B/block)",
42
+ 6: "RDAC-6W / MT2 (12B/block)",
43
+ 5: "RDAC-5W (10B/block)",
44
+ 4: "RDAC-4W (8B/block)",
45
+ }
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class SongAudioFormat:
50
+ sample_rate: int
51
+ mode_words: int
52
+ mode_label: str
53
+ block_bytes: int
54
+ tracks: int
55
+ vtracks: int
56
+ page_size: int
57
+ data_bytes_per_page: int
58
+ blocks_per_page: int
59
+ hardware_id: str | None
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class TakeEvent:
64
+ index: int
65
+ track: int
66
+ vtrack: int
67
+ take_id: int
68
+ flags: int
69
+ muted: bool
70
+ start_page: int
71
+ data_offset_blocks: int
72
+ timeline_start_block: int
73
+ block_count: int
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class SongInspection:
78
+ directory: Path
79
+ song_name: str | None
80
+ recorder_model: str | None
81
+ files: dict[str, int | None]
82
+ invalid_headers: tuple[str, ...]
83
+ audio_format: SongAudioFormat | None = None
84
+ active_events: tuple[TakeEvent, ...] = ()
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class DecodedTrack:
89
+ track: int
90
+ vtrack: int
91
+ samples: array
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class DecodedSong:
96
+ directory: Path
97
+ song_name: str
98
+ audio_format: SongAudioFormat
99
+ tracks: tuple[DecodedTrack, ...]
100
+ mixdown: array
101
+
102
+
103
+ def _read_fixed_text(data: bytes, start: int, length: int) -> str | None:
104
+ if len(data) < start + length:
105
+ return None
106
+ text = data[start : start + length].decode("ascii", errors="replace")
107
+ text = text.replace("\x00", "").strip()
108
+ return text or None
109
+
110
+
111
+ def _song_directory(path: Path) -> Path:
112
+ if not path.is_dir():
113
+ raise ValueError(f"Not a directory: {path}")
114
+
115
+ if path.name.upper().startswith("SONG") and path.name.upper().endswith(".BR0"):
116
+ return path
117
+
118
+ candidate = path / "BR0"
119
+ if candidate.is_dir():
120
+ path = candidate
121
+ if not list(path.glob("SONG*.BR0")):
122
+ raise ValueError(f"No SONG*.BR0 directories found in {path}")
123
+ return path
124
+
125
+
126
+ def _data_bytes_per_page(mode_words: int, page_size: int) -> int:
127
+ """Compute usable RDAC bytes per page (FUN_0041ce80)."""
128
+ if mode_words == 4:
129
+ return page_size & 0xFFF0
130
+ if mode_words == 5:
131
+ return ((page_size >> 1) // 10) * 0x14 & 0xFFFF
132
+ if mode_words == 6:
133
+ return ((page_size >> 1) // 0xC) * 0x18 & 0xFFFF
134
+ if mode_words == 8:
135
+ return page_size & 0xFFE0
136
+ if mode_words == 16:
137
+ return page_size & 0xFFC0
138
+ return 0x4000
139
+
140
+
141
+ def parse_song_format(directory: Path) -> SongAudioFormat | None:
142
+ """Parse sample rate, RDAC mode, page geometry, and hardware ID from BR files."""
143
+ info_path = directory / "SONGINF2.BR0"
144
+ evt_path = directory / "TAKE_EVT.BR0"
145
+ if not info_path.is_file() or not evt_path.is_file():
146
+ return None
147
+
148
+ info = info_path.read_bytes()
149
+ evt = evt_path.read_bytes()
150
+ if not info.startswith(BR0_SIGNATURE) or len(info) < 0x62:
151
+ return None
152
+ if not evt.startswith(BR0_SIGNATURE) or len(evt) < 0x40:
153
+ return None
154
+
155
+ model = _read_fixed_text(info, 32, 16)
156
+ if model == "BR-532":
157
+ sr_code = info[0x50]
158
+ mode_code = info[0x51]
159
+ else:
160
+ sr_code = info[0x60]
161
+ mode_code = info[0x61]
162
+
163
+ sample_rate = SAMPLE_RATES.get(sr_code)
164
+ mode_words = MODE_WORDS_MAP.get(mode_code)
165
+ if sample_rate is None or mode_words is None:
166
+ return None
167
+
168
+ tracks, vtracks, _num_ev, page_size, _unk1, _unk2 = struct.unpack_from("<BBHIII", evt, 0x30)
169
+ if page_size == 0 or tracks == 0 or vtracks == 0:
170
+ return None
171
+
172
+ block_bytes = mode_words * 2
173
+ data_bytes = _data_bytes_per_page(mode_words, page_size)
174
+ blocks_per_page = data_bytes // block_bytes if block_bytes else 0
175
+
176
+ hardware_id: str | None = None
177
+ prm_path = directory / "SONGPRM.BR1"
178
+ if prm_path.is_file():
179
+ prm = prm_path.read_bytes()
180
+ if prm.startswith(BS0_SIGNATURE) and len(prm) >= 0x40:
181
+ hardware_id = _read_fixed_text(prm, 0x34, 12)
182
+
183
+ return SongAudioFormat(
184
+ sample_rate=sample_rate,
185
+ mode_words=mode_words,
186
+ mode_label=MODE_LABELS.get(mode_words, f"RDAC-{mode_words}W"),
187
+ block_bytes=block_bytes,
188
+ tracks=tracks,
189
+ vtracks=vtracks,
190
+ page_size=page_size,
191
+ data_bytes_per_page=data_bytes,
192
+ blocks_per_page=blocks_per_page,
193
+ hardware_id=hardware_id,
194
+ )
195
+
196
+
197
+ def parse_take_events(directory: Path) -> list[TakeEvent]:
198
+ """Parse active (unmuted) take events from TAKE_EVT.BR0."""
199
+ evt_path = directory / "TAKE_EVT.BR0"
200
+ if not evt_path.is_file():
201
+ return []
202
+ evt = evt_path.read_bytes()
203
+ if not evt.startswith(BR0_SIGNATURE) or len(evt) < 0x60:
204
+ return []
205
+
206
+ tracks, vtracks, num_ev, _page_sz, _unk1, _unk2 = struct.unpack_from("<BBHIII", evt, 0x30)
207
+ list_table_end = 0x60 + tracks * vtracks * 8
208
+ if len(evt) < list_table_end + num_ev * 0x20:
209
+ return []
210
+
211
+ events: list[TakeEvent] = []
212
+ off = 0x60
213
+ for track_idx in range(tracks):
214
+ for vtrack_idx in range(vtracks):
215
+ head, _tail, cnt, _pad = struct.unpack_from("<HHHH", evt, off)
216
+ off += 8
217
+ if cnt == 0:
218
+ continue
219
+ idx = head
220
+ seen = 0
221
+ while idx != 0xFFFF and seen < cnt and idx < num_ev:
222
+ eoff = list_table_end + idx * 0x20
223
+ (
224
+ _b0,
225
+ _b1,
226
+ flags,
227
+ _b3,
228
+ take_id,
229
+ _prev,
230
+ nxt,
231
+ _u_a,
232
+ page_u32,
233
+ data_off,
234
+ tstart,
235
+ blen,
236
+ _u1c,
237
+ ) = struct.unpack_from("<BBBBHHHHIIIII", evt, eoff)
238
+ muted = bool(flags & 0x20)
239
+ if not muted and blen > 0:
240
+ events.append(
241
+ TakeEvent(
242
+ index=idx,
243
+ track=track_idx + 1,
244
+ vtrack=vtrack_idx + 1,
245
+ take_id=take_id,
246
+ flags=flags,
247
+ muted=muted,
248
+ start_page=page_u32 & 0xFFFF,
249
+ data_offset_blocks=data_off,
250
+ timeline_start_block=tstart,
251
+ block_count=blen,
252
+ )
253
+ )
254
+ idx = nxt
255
+ seen += 1
256
+ return events
257
+
258
+
259
+ def inspect_song_directory(directory: Path) -> SongInspection:
260
+ info_path = directory / "SONGINF2.BR0"
261
+ info = info_path.read_bytes() if info_path.is_file() else b""
262
+
263
+ invalid_headers: list[str] = []
264
+ if info and not info.startswith(BR0_SIGNATURE):
265
+ invalid_headers.append("SONGINF2.BR0")
266
+
267
+ model = _read_fixed_text(info, 32, 16) if info.startswith(BR0_SIGNATURE) else None
268
+ song_name = _read_fixed_text(info, 48, 16) if info.startswith(BR0_SIGNATURE) else None
269
+
270
+ for name in ("SONGPRM.BR1", "ARRANGE3.BR1", "EFFECTS3.BR1"):
271
+ file_path = directory / name
272
+ if file_path.is_file() and not file_path.read_bytes().startswith(BS0_SIGNATURE):
273
+ invalid_headers.append(name)
274
+
275
+ files = {
276
+ name: (directory / name).stat().st_size if (directory / name).is_file() else None
277
+ for name in SONG_FILE_NAMES
278
+ }
279
+
280
+ audio_format = parse_song_format(directory)
281
+ active_events = tuple(parse_take_events(directory))
282
+
283
+ return SongInspection(
284
+ directory=directory,
285
+ song_name=song_name,
286
+ recorder_model=model,
287
+ files=files,
288
+ invalid_headers=tuple(invalid_headers),
289
+ audio_format=audio_format,
290
+ active_events=active_events,
291
+ )
292
+
293
+
294
+ def inspect_path(path: Path) -> tuple[Path, list[SongInspection]]:
295
+ root = _song_directory(path)
296
+ if root.name.upper().startswith("SONG") and root.name.upper().endswith(".BR0"):
297
+ directories = [root]
298
+ card_root = root.parent
299
+ else:
300
+ directories = sorted(root.glob("SONG*.BR0"))
301
+ card_root = root
302
+
303
+ return card_root, [inspect_song_directory(directory) for directory in directories]
304
+
305
+
306
+ def _c_trunc_div(num: int, den: int) -> int:
307
+ if num >= 0:
308
+ return num // den
309
+ return -((-num) // den)
310
+
311
+
312
+ def decode_track_events(
313
+ dat: bytes | memoryview,
314
+ events: list[TakeEvent],
315
+ audio_format: SongAudioFormat,
316
+ total_blocks: int,
317
+ ) -> array:
318
+ """Decode one track/vtrack event chain into a mono 16-bit PCM array."""
319
+ samples = array("h", [0]) * (total_blocks * 16)
320
+ decoder = BRWCRdacDecoder(audio_format.mode_words)
321
+
322
+ page_size = audio_format.page_size
323
+ block_bytes = audio_format.block_bytes
324
+ blocks_per_page = audio_format.blocks_per_page
325
+ fade_blocks = int(audio_format.sample_rate * 0.005792 * 0.0625)
326
+ fade_samples = fade_blocks * 16
327
+ dat_mv = memoryview(dat)
328
+
329
+ prev_end = -1
330
+ for ev in sorted(events, key=lambda e: e.timeline_start_block):
331
+ if ev.timeline_start_block >= total_blocks:
332
+ continue
333
+ if ev.timeline_start_block != prev_end:
334
+ decoder.reset()
335
+
336
+ block_limit = min(ev.block_count, total_blocks - ev.timeline_start_block)
337
+ for rel in range(block_limit):
338
+ abs_blk = ev.data_offset_blocks + rel
339
+ page = ev.start_page + (abs_blk // blocks_per_page)
340
+ blk_in_page = abs_blk % blocks_per_page
341
+ byte_off = page * page_size + blk_in_page * block_bytes
342
+ if byte_off + block_bytes > len(dat_mv):
343
+ raise ValueError(
344
+ f"Event {ev.index} out of bounds in TAKE_DAT.BR0 "
345
+ f"(offset {byte_off + block_bytes} > {len(dat_mv)})"
346
+ )
347
+
348
+ pcm16 = decoder.decode_block(dat_mv[byte_off : byte_off + block_bytes])
349
+
350
+ if fade_blocks > 0:
351
+ if rel < fade_blocks:
352
+ base = rel * 16
353
+ pcm16 = [
354
+ _c_trunc_div(pcm16[j] * (base + j), fade_samples) for j in range(16)
355
+ ]
356
+ elif rel >= ev.block_count - fade_blocks:
357
+ rem = (ev.block_count - rel) * 16
358
+ pcm16 = [
359
+ _c_trunc_div(pcm16[j] * (rem - j), fade_samples) for j in range(16)
360
+ ]
361
+
362
+ out_off = (ev.timeline_start_block + rel) * 16
363
+ samples[out_off : out_off + 16] = array("h", pcm16)
364
+
365
+ prev_end = ev.timeline_start_block + ev.block_count
366
+
367
+ return samples
368
+
369
+
370
+ def mix_tracks(tracks: list[DecodedTrack], total_samples: int) -> array:
371
+ """Sum mono tracks into a clipped 16-bit PCM mixdown."""
372
+ if len(tracks) == 1:
373
+ return tracks[0].samples
374
+
375
+ mix = array("h", [0]) * total_samples
376
+ pcm_lists = [t.samples for t in tracks]
377
+ for i in range(total_samples):
378
+ val = 0
379
+ for pcm in pcm_lists:
380
+ val += pcm[i]
381
+ if val > 32767:
382
+ val = 32767
383
+ elif val < -32768:
384
+ val = -32768
385
+ mix[i] = val
386
+ return mix
387
+
388
+
389
+ def decode_song_directory(directory: Path) -> DecodedSong:
390
+ """Decode all active tracks of a SONG*.BR0 directory."""
391
+ inspection = inspect_song_directory(directory)
392
+ if inspection.audio_format is None:
393
+ raise ValueError(f"Missing or invalid SONGINF2.BR0 / TAKE_EVT.BR0 in {directory}")
394
+
395
+ dat_path = directory / "TAKE_DAT.BR0"
396
+ if not dat_path.is_file() or dat_path.stat().st_size == 0:
397
+ raise ValueError(f"Empty or missing TAKE_DAT.BR0 in {directory}")
398
+
399
+ if not inspection.active_events:
400
+ raise ValueError(f"No active (unmuted) take events found in {directory}")
401
+
402
+ dat = dat_path.read_bytes()
403
+ by_track: dict[tuple[int, int], list[TakeEvent]] = {}
404
+ max_block = 0
405
+ for ev in inspection.active_events:
406
+ by_track.setdefault((ev.track, ev.vtrack), []).append(ev)
407
+ end = ev.timeline_start_block + ev.block_count
408
+ if end > max_block:
409
+ max_block = end
410
+
411
+ decoded_tracks: list[DecodedTrack] = []
412
+ for (track_num, vtrack_num), evs in sorted(by_track.items()):
413
+ pcm = decode_track_events(dat, evs, inspection.audio_format, max_block)
414
+ decoded_tracks.append(DecodedTrack(track=track_num, vtrack=vtrack_num, samples=pcm))
415
+
416
+ mixdown = mix_tracks(decoded_tracks, max_block * 16)
417
+ song_name = inspection.song_name or directory.stem
418
+ return DecodedSong(
419
+ directory=directory,
420
+ song_name=song_name,
421
+ audio_format=inspection.audio_format,
422
+ tracks=tuple(decoded_tracks),
423
+ mixdown=mixdown,
424
+ )
425
+
426
+
427
+ def write_wav_mono_16(path: Path, samples: array, sample_rate: int) -> None:
428
+ """Write signed 16-bit mono PCM samples to a WAV file."""
429
+ path.parent.mkdir(parents=True, exist_ok=True)
430
+ with wave.open(str(path), "wb") as wav_file:
431
+ wav_file.setnchannels(1)
432
+ wav_file.setsampwidth(2)
433
+ wav_file.setframerate(sample_rate)
434
+ wav_file.writeframes(samples.tobytes())
@@ -0,0 +1,641 @@
1
+ """Roland BRWC RDAC block decoder.
2
+
3
+ Pure-Python implementation of the RDAC audio decompression algorithm
4
+ reverse-engineered from Roland BR Wave Converter (`BRWC.exe`,
5
+ ``FUN_0041a190`` and sub-decoders ``FUN_00418d90``..``FUN_00419ed0``, plus
6
+ uncompressed 16-bit PCM handling in ``FUN_00411dc0``).
7
+
8
+ Each compressed block has ``mode_words * 2`` bytes and decodes to 16 signed
9
+ 16-bit PCM samples, threading the final 32-bit anchor value ``d0`` across
10
+ consecutive blocks.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import struct
16
+ from typing import Callable
17
+
18
+
19
+ def _i32(x: int) -> int:
20
+ x &= 0xFFFFFFFF
21
+ return x - 0x100000000 if (x & 0x80000000) else x
22
+
23
+
24
+ def _u32(x: int) -> int:
25
+ return x & 0xFFFFFFFF
26
+
27
+
28
+ def _i16(x: int) -> int:
29
+ x &= 0xFFFF
30
+ return x - 0x10000 if (x & 0x8000) else x
31
+
32
+
33
+ def _clamp_s16(x: int) -> int:
34
+ x = _i32(x)
35
+ if x > 0x7FFF:
36
+ x = 0x7FFF
37
+ return _i16(x)
38
+
39
+
40
+ def _setup_mask_round(s_val: int, mode_words: int) -> tuple[int, int]:
41
+ """Compute dequantization mask and rounding bias (FUN_004198b0)."""
42
+ b = (s_val + 4) & 0x1F
43
+ mask = _i32(_u32((-1) << b)) >> (mode_words & 0x1F)
44
+ rnd = _i32(_u32(1 << b)) >> ((mode_words + 1) & 0x1F)
45
+ return mask, rnd
46
+
47
+
48
+ def _unpack_words(buf: bytes | bytearray | memoryview, off: int) -> tuple[int, int]:
49
+ w0 = _i32((buf[off] << 24) | (buf[off + 1] << 16) | (buf[off + 4] << 8) | buf[off + 5])
50
+ w1 = _u32((buf[off + 8] << 24) | (buf[off + 9] << 16) | (buf[off + 12] << 8) | buf[off + 13])
51
+ return w0, w1
52
+
53
+
54
+ def _dec_a(
55
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
56
+ ) -> tuple[list[int], int]:
57
+ """Family 'A' (FUN_00418d90)."""
58
+ w0, w1 = _unpack_words(buf, off)
59
+ if mode_words == 8:
60
+ local_4 = _i32(w0 << 4)
61
+ p1 = _i32(w1 * 4)
62
+ i6 = _i32(w0 << 0xC)
63
+ i7 = _i32(w0 << 0x13)
64
+ u5 = _i32(w1 << 0x11)
65
+ u4 = _i32((w1 >> 5) | _u32(w0 << 0x1B))
66
+ v0 = _i32(w1 << 0x19)
67
+ l8 = _i32(w1 << 10)
68
+ elif mode_words == 7:
69
+ local_4 = _i32(w0 << 4)
70
+ i6 = _i32(w0 << 0xB)
71
+ i7 = _i32(w0 << 0x11)
72
+ u4 = _i32(w0 << 0x18)
73
+ p1 = _i32((w1 >> 2) | _u32(w0 << 0x1E))
74
+ u5 = _i32(w1 << 0xB)
75
+ v0 = _i32(w1 << 0x12)
76
+ l8 = _i32(w1 << 5)
77
+ elif mode_words == 6:
78
+ local_4 = _i32(w0 << 4)
79
+ i6 = _i32(w0 << 10)
80
+ i7 = _i32(w0 << 0xF)
81
+ u4 = _i32(w0 << 0x15)
82
+ u5 = _i32(w1 << 5)
83
+ p1 = _i32(w0 << 0x1A)
84
+ v0 = _i32(w1 << 0xB)
85
+ l8 = _i32(w1)
86
+ elif mode_words == 5:
87
+ local_4 = _i32(w0 << 4)
88
+ i6 = _i32(w0 << 9)
89
+ i7 = _i32(w0 << 0xD)
90
+ u4 = _i32(w0 << 0x12)
91
+ p1 = _i32(w0 << 0x16)
92
+ l8 = _i32(w0 << 0x1B)
93
+ u5 = _i32((w1 >> 1) | _u32(w0 << 0x1F))
94
+ v0 = _i32(w1 << 4)
95
+ else:
96
+ local_4 = _i32(w0 * 8)
97
+ i6 = _i32(w0 << 7)
98
+ i7 = _i32(w0 * 0x800)
99
+ u4 = _i32(w0 * 0x4000)
100
+ p1 = _i32(w0 * 0x40000)
101
+ l8 = _i32(w0 * 0x200000)
102
+ u5 = _i32(w0 * 0x2000000)
103
+ v0 = _i32(w0 * 0x10000000)
104
+
105
+ sh = (0x1D - s_val) & 0x1F
106
+ hmask = mask >> 1
107
+ hrnd = rnd >> 1
108
+ out7 = ((local_4 >> sh) & hmask) | hrnd
109
+ if mode_words == 4:
110
+ out = [
111
+ _i16(((v0 >> sh) & hmask) | hrnd),
112
+ _i16(((u5 >> sh) & mask) | rnd),
113
+ _i16(((l8 >> sh) & hmask) | hrnd),
114
+ _i16(((p1 >> sh) & mask) | rnd),
115
+ _i16(((u4 >> sh) & hmask) | hrnd),
116
+ _i16(((i7 >> sh) & mask) | rnd),
117
+ _i16(((i6 >> sh) & hmask) | hrnd),
118
+ _i16(out7),
119
+ ]
120
+ else:
121
+ out = [
122
+ _i16(((v0 >> sh) & mask) | rnd),
123
+ _i16(((u5 >> sh) & hmask) | hrnd),
124
+ _i16(((l8 >> sh) & mask) | rnd),
125
+ _i16(((p1 >> sh) & hmask) | hrnd),
126
+ _i16(((u4 >> sh) & mask) | rnd),
127
+ _i16(((i7 >> sh) & hmask) | hrnd),
128
+ _i16(((i6 >> sh) & mask) | rnd),
129
+ _i16(out7),
130
+ ]
131
+ return out, _i32(out7)
132
+
133
+
134
+ def _dec_b(
135
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
136
+ ) -> tuple[list[int], int]:
137
+ """Family 'B' (FUN_004190e0)."""
138
+ w0, w1 = _unpack_words(buf, off)
139
+ if mode_words == 8:
140
+ p1 = _i32(w1 * 4)
141
+ i9 = _i32(w0 << 0xC)
142
+ i6 = _i32(w0 << 0x13)
143
+ p4 = _i32(w1 << 0x11)
144
+ u10 = _i32((w1 >> 5) | _u32(w0 << 0x1B))
145
+ i2 = _i32(w1 << 0x19)
146
+ u8 = _i32(w1 << 10)
147
+ elif mode_words == 7:
148
+ i9 = _i32(w0 << 0xB)
149
+ i6 = _i32(w0 << 0x11)
150
+ u10 = _i32(w0 << 0x18)
151
+ p1 = _i32((w1 >> 2) | _u32(w0 << 0x1E))
152
+ p4 = _i32(w1 << 0xB)
153
+ i2 = _i32(w1 << 0x12)
154
+ u8 = _i32(w1 << 5)
155
+ elif mode_words == 6:
156
+ i9 = _i32(w0 << 10)
157
+ i6 = _i32(w0 << 0xF)
158
+ u10 = _i32(w0 << 0x15)
159
+ p4 = _i32(w1 << 5)
160
+ p1 = _i32(w0 << 0x1A)
161
+ i2 = _i32(w1 << 0xB)
162
+ u8 = _i32(w1)
163
+ elif mode_words == 5:
164
+ i9 = _i32(w0 << 9)
165
+ i6 = _i32(w0 << 0xD)
166
+ u10 = _i32(w0 << 0x12)
167
+ p1 = _i32(w0 << 0x16)
168
+ u8 = _i32(w0 << 0x1B)
169
+ p4 = _i32((w1 >> 1) | _u32(w0 << 0x1F))
170
+ i2 = _i32(w1 << 4)
171
+ else:
172
+ i9 = _i32(w0 * 0x100)
173
+ i6 = _i32(w0 * 0x800)
174
+ u10 = _i32(w0 * 0x8000)
175
+ p1 = _i32(w0 * 0x40000)
176
+ u8 = _i32(w0 * 0x400000)
177
+ p4 = _i32(w0 * 0x2000000)
178
+ i2 = _i32(p4 << 4)
179
+
180
+ sh1c = (0x1C - s_val) & 0x1F
181
+ sh1d = (0x1D - s_val) & 0x1F
182
+ v7 = ((_i32(w0 << 4) >> sh1c) & mask) | rnd
183
+ v3 = ((p1 >> sh1c) & mask) | rnd
184
+ v1 = ((p4 >> sh1c) & mask) | rnd
185
+ v5 = ((i6 >> sh1c) & mask) | rnd
186
+ out = [
187
+ _i16((((i2 >> sh1d) & mask) | rnd) + ((v1 + d0) >> 1)),
188
+ _i16(v1),
189
+ _i16((((u8 >> sh1d) & mask) | rnd) + ((v1 + v3) >> 1)),
190
+ _i16(v3),
191
+ _i16((((u10 >> sh1d) & mask) | rnd) + ((v3 + v5) >> 1)),
192
+ _i16(v5),
193
+ _i16((((i9 >> sh1d) & mask) | rnd) + ((v5 + v7) >> 1)),
194
+ _i16(v7),
195
+ ]
196
+ return out, _i32(v7)
197
+
198
+
199
+ def _dec_c(
200
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
201
+ ) -> tuple[list[int], int]:
202
+ """Family 'C' (FUN_00419360)."""
203
+ w0, w1 = _unpack_words(buf, off)
204
+ if mode_words == 8:
205
+ p1 = _i32(w1 * 2)
206
+ i8 = _i32(w0 << 0xB)
207
+ i5 = _i32(w0 << 0x12)
208
+ u6 = _i32(w1 << 0x11)
209
+ u9 = _i32((w1 >> 6) | _u32(w0 << 0x1A))
210
+ i2 = _i32(w1 << 0x19)
211
+ lc = _i32(w1 << 10)
212
+ elif mode_words == 7:
213
+ i8 = _i32(w0 << 10)
214
+ i5 = _i32(w0 << 0x10)
215
+ u9 = _i32(w0 << 0x17)
216
+ p1 = _i32((w1 >> 3) | _u32(w0 << 0x1D))
217
+ u6 = _i32(w1 << 0xB)
218
+ i2 = _i32(w1 << 0x12)
219
+ lc = _i32(w1 << 5)
220
+ elif mode_words == 6:
221
+ i8 = _i32(w0 << 9)
222
+ i5 = _i32(w0 << 0xE)
223
+ u9 = _i32(w0 << 0x14)
224
+ u6 = _i32(w1 << 5)
225
+ p1 = _i32(w0 << 0x19)
226
+ i2 = _i32(w1 << 0xB)
227
+ lc = _i32(w1)
228
+ elif mode_words == 5:
229
+ i8 = _i32(w0 << 8)
230
+ i5 = _i32(w0 << 0xC)
231
+ u9 = _i32(w0 << 0x11)
232
+ p1 = _i32(w0 << 0x15)
233
+ lc = _i32(w0 << 0x1B)
234
+ u6 = _i32((w1 >> 1) | _u32(w0 << 0x1F))
235
+ i2 = _i32(w1 << 4)
236
+ else:
237
+ i8 = _i32(w0 * 0x80)
238
+ i5 = _i32(w0 * 0x400)
239
+ u9 = _i32(w0 * 0x4000)
240
+ p1 = _i32(w0 * 0x20000)
241
+ lc = _i32(w0 * 0x400000)
242
+ u6 = _i32(w0 * 0x2000000)
243
+ i2 = _i32(u6 << 4)
244
+
245
+ sh1b = (0x1B - s_val) & 0x1F
246
+ sh1c = (0x1C - s_val) & 0x1F
247
+ sh1d = (0x1D - s_val) & 0x1F
248
+ v7 = ((_i32(w0 * 4) >> sh1b) & mask) | rnd
249
+ v3 = ((p1 >> sh1b) & mask) | rnd
250
+ v1 = (((u6 >> sh1c) & mask) | rnd) + ((v3 + d0) >> 1)
251
+ v5 = (((i5 >> sh1c) & mask) | rnd) + ((v3 + v7) >> 1)
252
+ out = [
253
+ _i16((((i2 >> sh1d) & mask) | rnd) + ((v1 + d0) >> 1)),
254
+ _i16(v1),
255
+ _i16((((lc >> sh1d) & mask) | rnd) + ((v1 + v3) >> 1)),
256
+ _i16(v3),
257
+ _i16((((u9 >> sh1d) & mask) | rnd) + ((v3 + v5) >> 1)),
258
+ _i16(v5),
259
+ _i16((((i8 >> sh1d) & mask) | rnd) + ((v5 + v7) >> 1)),
260
+ _i16(v7),
261
+ ]
262
+ return out, _i32(v7)
263
+
264
+
265
+ def _dec_d(
266
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
267
+ ) -> tuple[list[int], int]:
268
+ """Family 'D' (FUN_004198f0)."""
269
+ w0, w1 = _unpack_words(buf, off)
270
+ if mode_words == 8:
271
+ i7 = _i32(w0 << 0xE)
272
+ i2 = _i32(w0 << 0x14)
273
+ p1 = _i32(w1 * 4)
274
+ u8 = _i32((w1 >> 4) | _u32(w0 << 0x1C))
275
+ lc = _i32(w1 << 0xC)
276
+ i4 = _i32(w1 << 0x1A)
277
+ vu3 = _i32(w1 << 0x12)
278
+ elif mode_words == 7:
279
+ i7 = _i32(w0 << 0xD)
280
+ i2 = _i32(w0 << 0x12)
281
+ u8 = _i32(w0 << 0x19)
282
+ p1 = _i32((w1 >> 2) | _u32(w0 << 0x1E))
283
+ lc = _i32(w1 << 7)
284
+ i4 = _i32(w1 << 0x13)
285
+ vu3 = _i32(w1 << 0xC)
286
+ elif mode_words == 6:
287
+ i7 = _i32(w0 << 0xC)
288
+ i2 = _i32(w0 << 0x10)
289
+ u8 = _i32(w0 << 0x16)
290
+ p1 = _i32((w1 >> 6) | _u32(w0 << 0x1A))
291
+ lc = _i32(w1 * 4)
292
+ i4 = _i32(w1 << 0xC)
293
+ vu3 = _i32(w1 << 6)
294
+ elif mode_words == 5:
295
+ i7 = _i32(w0 * 0x800)
296
+ i2 = _i32(w0 * 0x4000)
297
+ u8 = _i32(w0 * 0x80000)
298
+ p1 = _i32(w0 * 0x400000)
299
+ lc = _i32(w0 << 0x1D)
300
+ i4 = _i32(w1 << 5)
301
+ vu3 = _i32(w1)
302
+ else:
303
+ i7 = _i32(w0 * 0x400)
304
+ i2 = _i32(w0 * 0x1000)
305
+ u8 = _i32(w0 * 0x10000)
306
+ p1 = _i32(w0 * 0x40000)
307
+ lc = _i32(w0 * 0x1000000)
308
+ vu3 = _i32(w0 * 0x4000000)
309
+ i4 = _i32(w0 << 0x1E)
310
+
311
+ sh19 = (0x19 - s_val) & 0x1F
312
+ sh1a = (0x1A - s_val) & 0x1F
313
+ sh1c = (0x1C - s_val) & 0x1F
314
+ sh1e = (0x1E - s_val) & 0x1F
315
+ if s_val == 10:
316
+ l8 = ((_i32(w0 << 4) >> 0x10) & mask) | rnd
317
+ v3 = ((p1 >> 0x10) & mask) | rnd
318
+ else:
319
+ l8 = ((_i32(w0 * 8) >> sh19) & mask) | rnd
320
+ v3 = (((p1 >> sh1a) & mask) | rnd) + ((d0 + l8) >> 1)
321
+ v1 = (((vu3 >> sh1c) & mask) | rnd) + ((v3 + d0) >> 1)
322
+ v5 = (((i2 >> sh1c) & mask) | rnd) + ((v3 + l8) >> 1)
323
+ out = [
324
+ _i16((((i4 >> sh1e) & mask) | rnd) + ((d0 + v1) >> 1)),
325
+ _i16(v1),
326
+ _clamp_s16((((lc >> sh1e) & mask) | rnd) + ((v1 + v3) >> 1)),
327
+ _i16(v3),
328
+ _clamp_s16((((u8 >> sh1e) & mask) | rnd) + ((v3 + v5) >> 1)),
329
+ _i16(v5),
330
+ _i16((((i7 >> sh1e) & mask) | rnd) + ((v5 + l8) >> 1)),
331
+ _i16(l8),
332
+ ]
333
+ return out, _i32(l8)
334
+
335
+
336
+ def _dec_e(
337
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
338
+ ) -> tuple[list[int], int]:
339
+ """Family 'E' (FUN_00419be0)."""
340
+ w0, w1 = _unpack_words(buf, off)
341
+ if mode_words == 8:
342
+ i7 = _i32(w0 << 0xF)
343
+ i2 = _i32(w0 << 0x15)
344
+ p1 = _i32(w1 * 8)
345
+ u8 = _i32((w1 >> 3) | _u32(w0 << 0x1D))
346
+ lc = _i32(w1 << 0xC)
347
+ i4 = _i32(w1 << 0x1A)
348
+ vu3 = _i32(w1 << 0x12)
349
+ elif mode_words == 7:
350
+ i7 = _i32(w0 << 0xE)
351
+ i2 = _i32(w0 << 0x13)
352
+ u8 = _i32(w0 << 0x1A)
353
+ p1 = _i32((w1 >> 1) | _u32(w0 << 0x1F))
354
+ lc = _i32(w1 << 7)
355
+ i4 = _i32(w1 << 0x13)
356
+ vu3 = _i32(w1 << 0xC)
357
+ elif mode_words == 6:
358
+ i7 = _i32(w0 << 0xD)
359
+ i2 = _i32(w0 << 0x11)
360
+ u8 = _i32(w0 << 0x17)
361
+ p1 = _i32((w1 >> 5) | _u32(w0 << 0x1B))
362
+ lc = _i32(w1 * 4)
363
+ i4 = _i32(w1 << 0xC)
364
+ vu3 = _i32(w1 << 6)
365
+ elif mode_words == 5:
366
+ i7 = _i32(w0 * 0x1000)
367
+ i2 = _i32(w0 * 0x8000)
368
+ u8 = _i32(w0 * 0x100000)
369
+ p1 = _i32(w0 * 0x800000)
370
+ lc = _i32(w0 << 0x1D)
371
+ i4 = _i32(w1 << 5)
372
+ vu3 = _i32(w1)
373
+ else:
374
+ i7 = _i32(w0 * 0x800)
375
+ i2 = _i32(w0 * 0x2000)
376
+ u8 = _i32(w0 * 0x20000)
377
+ p1 = _i32(w0 * 0x80000)
378
+ lc = _i32(w0 * 0x1000000)
379
+ vu3 = _i32(w0 * 0x4000000)
380
+ i4 = _i32(w0 << 0x1E)
381
+
382
+ sh17 = (0x17 - s_val) & 0x1F
383
+ sh1b = (0x1B - s_val) & 0x1F
384
+ sh1c = (0x1C - s_val) & 0x1F
385
+ sh1e = (0x1E - s_val) & 0x1F
386
+ if s_val == 8:
387
+ l8 = ((_i32(w0 << 3) >> 0x10) & mask) | rnd
388
+ else:
389
+ l8 = ((_i32(w0 * 4) >> sh17) & mask) | rnd
390
+ v3 = (((p1 >> sh1b) & mask) | rnd) + ((d0 + l8) >> 1)
391
+ v1 = (((vu3 >> sh1c) & mask) | rnd) + ((v3 + d0) >> 1)
392
+ v5 = (((i2 >> sh1c) & mask) | rnd) + ((v3 + l8) >> 1)
393
+ out = [
394
+ _i16((((i4 >> sh1e) & mask) | rnd) + ((v1 + d0) >> 1)),
395
+ _i16(v1),
396
+ _clamp_s16((((lc >> sh1e) & mask) | rnd) + ((v1 + v3) >> 1)),
397
+ _i16(v3),
398
+ _clamp_s16((((u8 >> sh1e) & mask) | rnd) + ((v5 + v3) >> 1)),
399
+ _i16(v5),
400
+ _i16((((i7 >> sh1e) & mask) | rnd) + ((v5 + l8) >> 1)),
401
+ _i16(l8),
402
+ ]
403
+ return out, _i32(l8)
404
+
405
+
406
+ def _dec_f(
407
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
408
+ ) -> tuple[list[int], int]:
409
+ """Family 'F' (FUN_00419ed0)."""
410
+ w0, w1 = _unpack_words(buf, off)
411
+ if mode_words == 8:
412
+ i8 = _i32(w0 << 0x11)
413
+ i2 = _i32(w0 << 0x17)
414
+ u9 = _i32((w1 >> 2) | _u32(w0 << 0x1E))
415
+ lc = _i32(w1 << 0xD)
416
+ i6 = _i32(w1 << 0x13)
417
+ i4 = _i32(w1 << 0x1A)
418
+ p1 = _i32(w1 << 4)
419
+ elif mode_words == 7:
420
+ lc = _i32(w1 << 8)
421
+ i8 = _i32(w0 << 0x10)
422
+ i2 = _i32(w0 << 0x15)
423
+ i6 = _i32(w1 << 0xD)
424
+ u9 = _i32(w0 << 0x1B)
425
+ i4 = _i32(w1 << 0x13)
426
+ p1 = _i32(w1)
427
+ elif mode_words == 6:
428
+ i8 = _i32(w0 << 0xF)
429
+ i2 = _i32(w0 << 0x13)
430
+ u9 = _i32(w0 << 0x18)
431
+ p1 = _i32((w1 >> 4) | _u32(w0 << 0x1C))
432
+ lc = _i32(w1 * 8)
433
+ i6 = _i32(w1 << 7)
434
+ i4 = _i32(w1 << 0xC)
435
+ elif mode_words == 5:
436
+ i8 = _i32(w0 * 0x4000)
437
+ i2 = _i32(w0 * 0x20000)
438
+ u9 = _i32(w0 * 0x200000)
439
+ p1 = _i32(w0 * 0x1000000)
440
+ lc = _i32((w1 >> 2) | _u32(w0 << 0x1E))
441
+ i6 = _i32(w1 * 2)
442
+ i4 = _i32(w1 << 5)
443
+ else:
444
+ i8 = _i32(w0 * 0x2000)
445
+ i2 = _i32(w0 * 0x8000)
446
+ u9 = _i32(w0 * 0x40000)
447
+ p1 = _i32(w0 * 0x100000)
448
+ lc = _i32(w0 * 0x2000000)
449
+ i6 = _i32(w0 * 0x8000000)
450
+ i4 = _i32(w0 * 0x40000000)
451
+
452
+ sh16 = (0x16 - s_val) & 0x1F
453
+ sh1b = (0x1B - s_val) & 0x1F
454
+ sh1d = (0x1D - s_val) & 0x1F
455
+ sh1e = (0x1E - s_val) & 0x1F
456
+ u7 = ((_i32(w0 * 8) >> sh16) & mask) | rnd
457
+ v3 = (((p1 >> sh1b) & mask) | rnd) + ((d0 + u7) >> 1)
458
+ v1 = (((i6 >> sh1d) & mask) | rnd) + ((v3 + d0) >> 1)
459
+ v5 = (((i2 >> sh1d) & mask) | rnd) + ((v3 + u7) >> 1)
460
+ out = [
461
+ _i16((((i4 >> sh1e) & mask) | rnd) + ((v1 + d0) >> 1)),
462
+ _i16(v1),
463
+ _clamp_s16((((lc >> sh1e) & mask) | rnd) + ((v1 + v3) >> 1)),
464
+ _i16(v3),
465
+ _clamp_s16((((u9 >> sh1e) & mask) | rnd) + ((v5 + v3) >> 1)),
466
+ _i16(v5),
467
+ _i16((((i8 >> sh1e) & mask) | rnd) + ((v5 + u7) >> 1)),
468
+ _i16(u7),
469
+ ]
470
+ return out, _i32(u7)
471
+
472
+
473
+ def _dec_g(
474
+ s_val: int, mask: int, rnd: int, buf: bytearray, off: int, d0: int, mode_words: int
475
+ ) -> tuple[list[int], int]:
476
+ """Family 'G' (FUN_004195f0)."""
477
+ w0, w1 = _unpack_words(buf, off)
478
+ if mode_words == 8:
479
+ i8 = _i32(w0 << 0xF)
480
+ lc = _i32(w1 << 0xB)
481
+ i9 = _i32(w0 << 0x16)
482
+ u5 = _i32((w1 >> 3) | _u32(w0 << 0x1D))
483
+ i2 = _i32(w1 << 0x19)
484
+ p6 = _i32(w1 << 0x12)
485
+ p1 = _i32(w1 << 4)
486
+ elif mode_words == 7:
487
+ lc = _i32(w1 << 6)
488
+ i8 = _i32(w0 << 0xE)
489
+ i9 = _i32(w0 << 0x14)
490
+ u5 = _i32(w0 << 0x1A)
491
+ i2 = _i32(w1 << 0x12)
492
+ p6 = _i32(w1 << 0xC)
493
+ p1 = _i32(w1)
494
+ elif mode_words == 6:
495
+ i8 = _i32(w0 << 0xD)
496
+ i9 = _i32(w0 << 0x12)
497
+ u5 = _i32(w0 << 0x17)
498
+ p1 = _i32((w1 >> 4) | _u32(w0 << 0x1C))
499
+ lc = _i32(w1 * 2)
500
+ i2 = _i32(w1 << 0xB)
501
+ p6 = _i32(w1 << 6)
502
+ elif mode_words == 5:
503
+ i8 = _i32(w0 << 0xC)
504
+ i9 = _i32(w0 << 0x10)
505
+ u5 = _i32(w0 << 0x14)
506
+ p1 = _i32(w0 << 0x18)
507
+ lc = _i32(w0 << 0x1C)
508
+ i2 = _i32(w1 << 4)
509
+ p6 = _i32(w1)
510
+ else:
511
+ i8 = _i32(w0 * 0x800)
512
+ i9 = _i32(w0 * 0x4000)
513
+ u5 = _i32(w0 * 0x20000)
514
+ p1 = _i32(w0 * 0x100000)
515
+ lc = _i32(w0 * 0x800000)
516
+ p6 = _i32(w0 * 0x4000000)
517
+ i2 = _i32(w0 * 0x20000000)
518
+
519
+ sh19 = (0x19 - s_val) & 0x1F
520
+ sh1d = (0x1D - s_val) & 0x1F
521
+ u3 = ((_i32(w0 << 4) >> sh19) & mask) | rnd
522
+ v3 = (((p1 >> sh1d) & mask) | rnd) + ((u3 + d0) >> 1)
523
+ v1 = (((p6 >> sh1d) & mask) | rnd) + ((v3 + d0) >> 1)
524
+ v5 = (((i9 >> sh1d) & mask) | rnd) + ((v3 + u3) >> 1)
525
+ out = [
526
+ _i16((((i2 >> sh1d) & mask) | rnd) + ((v1 + d0) >> 1)),
527
+ _i16(v1),
528
+ _i16((((lc >> sh1d) & mask) | rnd) + ((v1 + v3) >> 1)),
529
+ _i16(v3),
530
+ _i16((((u5 >> sh1d) & mask) | rnd) + ((v3 + v5) >> 1)),
531
+ _i16(v5),
532
+ _i16((((i8 >> sh1d) & mask) | rnd) + ((v5 + u3) >> 1)),
533
+ _i16(u3),
534
+ ]
535
+ return out, _i32(u3)
536
+
537
+
538
+ _FamilyFn = Callable[[int, int, int, bytearray, int, int, int], tuple[list[int], int]]
539
+
540
+
541
+ def _build_dispatch_entry(pattern_byte: int, mode_words: int) -> tuple[_FamilyFn, int, int, int]:
542
+ """Precompute family function, scale parameter, mask, and round bias (FUN_0041a190)."""
543
+ b5 = pattern_byte & 0x0F
544
+ b0_hi = pattern_byte & 0xF0
545
+ b7 = pattern_byte & 0xCC
546
+ b6 = pattern_byte & 0xEE
547
+
548
+ if (b7 < 0x48) or (b6 == 0xCE and mode_words == 4) or (b6 == 0xCC and mode_words != 4):
549
+ if b7 < 0x48:
550
+ s_val = ((((pattern_byte >> 2) & 0x30) | (pattern_byte & 0x0C)) >> 2) + 2
551
+ else:
552
+ s_val = 8
553
+ fn: _FamilyFn = _dec_e
554
+ elif b7 < 0xC0:
555
+ s_val = (((b0_hi & 0xC0) >> 2) | (b5 & 0x0C)) >> 2
556
+ fn = _dec_c
557
+ elif (b6 < 0xCE and mode_words == 4) or (b6 < 0xCC and mode_words != 4):
558
+ s_val = ((((b0_hi & 0xE0) >> 1) | (b5 & 0x0E)) >> 1) + (1 if mode_words != 4 else 0) - 0x30
559
+ fn = _dec_f
560
+ elif (
561
+ ((0xEB < b6 and pattern_byte != 0xFE) or mode_words != 4)
562
+ and ((0xE9 < b6 and pattern_byte != 0xFA) or mode_words == 4)
563
+ ):
564
+ if (
565
+ ((0xFD < pattern_byte or b6 == 0xEC) or mode_words != 4)
566
+ and (pattern_byte < 0xFB or mode_words == 4)
567
+ ):
568
+ if pattern_byte != 0xFF and (pattern_byte == 0xEF or mode_words == 4):
569
+ s_val = 0xD
570
+ fn = _dec_a
571
+ else:
572
+ s_val = 0xC if mode_words == 4 else (pattern_byte - 0xE2)
573
+ fn = _dec_b
574
+ else:
575
+ if mode_words == 4:
576
+ s_val = pattern_byte - 0xEE
577
+ else:
578
+ s_val = (pattern_byte - 0xFB) if pattern_byte < 0xFD else (pattern_byte - 0x100)
579
+ fn = _dec_g
580
+ else:
581
+ if mode_words == 4:
582
+ if b6 < 0xEE:
583
+ s_val = ((((pattern_byte >> 1) & 0x70) | (pattern_byte & 0x0E)) >> 1) - 0x34
584
+ else:
585
+ s_val = 10
586
+ else:
587
+ if b6 < 0xEA:
588
+ s_val = ((((pattern_byte >> 1) & 0x70) | (pattern_byte & 0x0E)) >> 1) - 0x33
589
+ else:
590
+ s_val = 10
591
+ fn = _dec_d
592
+
593
+ s_val = _i16(s_val)
594
+ mask, rnd = _setup_mask_round(s_val, mode_words)
595
+ return fn, s_val, mask, rnd
596
+
597
+
598
+ _DISPATCH_TABLES: dict[int, list[tuple[_FamilyFn, int, int, int]]] = {
599
+ mw: [_build_dispatch_entry(p, mw) for p in range(256)]
600
+ for mw in (4, 5, 6, 7, 8)
601
+ }
602
+
603
+
604
+ class BRWCRdacDecoder:
605
+ """Stateful Roland BRWC RDAC block decoder."""
606
+
607
+ def __init__(self, mode_words: int = 6) -> None:
608
+ if mode_words not in (4, 5, 6, 7, 8, 16):
609
+ raise ValueError(f"Unsupported RDAC mode_words: {mode_words}")
610
+ self.mode_words = mode_words
611
+ self.block_bytes = mode_words * 2
612
+ self.d0 = 0
613
+ self._buf = bytearray(16)
614
+ self._table = None if mode_words == 16 else _DISPATCH_TABLES[mode_words]
615
+
616
+ def reset(self) -> None:
617
+ self.d0 = 0
618
+
619
+ def decode_block(self, block: bytes | bytearray | memoryview) -> list[int]:
620
+ """Decode one block (``mode_words * 2`` bytes) into 16 signed 16-bit PCM samples."""
621
+ size = self.block_bytes
622
+ if len(block) < size:
623
+ raise ValueError(f"Need {size} bytes for mode_words={self.mode_words}, got {len(block)}")
624
+
625
+ if self.mode_words == 16:
626
+ return list(struct.unpack_from("<16h", block))
627
+
628
+ buf = self._buf
629
+ buf[:size] = block[:size]
630
+ if self.mode_words == 4:
631
+ buf[4], buf[2] = buf[2], buf[4]
632
+ buf[3], buf[5] = buf[5], buf[3]
633
+ elif (self.mode_words & 1) != 0:
634
+ buf[size] = buf[size - 1]
635
+
636
+ pattern_byte = (buf[0] & 0xF0) | (buf[2] >> 4)
637
+ fn, s_val, mask, rnd = self._table[pattern_byte] # type: ignore[index]
638
+ out0, mid = fn(s_val, mask, rnd, buf, 0, self.d0, self.mode_words)
639
+ out1, end = fn(s_val, mask, rnd, buf, 2, mid, self.mode_words)
640
+ self.d0 = end
641
+ return out0 + out1
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: microbr-decode
3
+ Version: 0.1.0
4
+ Summary: Decode BOSS Micro-BR RDAC audio (.BR0 song folders) to WAV
5
+ Keywords: roland,boss,micro-br,rdac,audio,decoder,wav
6
+ Author: David Jackson
7
+ Author-email: David Jackson <pyguy411@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: End Users/Desktop
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Conversion
15
+ Requires-Python: >=3.10
16
+ Project-URL: Homepage, https://github.com/pyguy411/microbr-decode
17
+ Description-Content-Type: text/markdown
18
+
19
+ # microbr-decode
20
+
21
+ A pure-Python decoder for audio recorded on the **BOSS Micro-BR** digital
22
+ recorder. It reads a memory-card backup (the `BR0` folder containing
23
+ `SONG000X.BR0` folders and their `TAKE_DAT.BR0` / `TAKE_EVT.BR0` files),
24
+ decodes Roland's proprietary RDAC audio, and writes standard 16-bit 44.1 kHz
25
+ WAV files — a mixdown per song plus per-track stems.
26
+
27
+ Not affiliated with, endorsed by, or sponsored by Roland Corporation or BOSS.
28
+ Use it to decode your own recordings.
29
+
30
+ Tested with files recorded on the **BOSS Micro-BR**. The song headers on a
31
+ Micro-BR card identify themselves as `BR-900`, which suggests the two
32
+ recorders share the same file format, so it may also work on BR-900 card
33
+ backups — untested. Other BR-family or VS-family devices are also untested
34
+ and probably won't work as-is.
35
+
36
+ ## Status
37
+
38
+ WORKING. Verified against all 9 songs of a full Micro-BR card: 19 WAV files (mixdowns + stems), zero sample mismatches,
39
+ zero wraparound artifacts.
40
+
41
+ Supports RDAC `mode_words` 4–8 and 16 (including uncompressed 16-bit PCM),
42
+ with the 16 KB page framing, multi-track event mapping, and punch-in take
43
+ chains the Micro-BR uses. The format was reverse engineered for
44
+ interoperability with recordings made by the (discontinued) Micro-BR and,
45
+ likely, the related BR-900. Other devices are untested and probably won't
46
+ work as-is.
47
+
48
+ ## Installation
49
+
50
+ From PyPI:
51
+
52
+ ```bash
53
+ uv tool install microbr-decode
54
+ # or
55
+ pipx install microbr-decode
56
+ # or
57
+ pip install microbr-decode
58
+ ```
59
+
60
+ From source:
61
+
62
+ ```bash
63
+ uv sync
64
+ ```
65
+
66
+ All three make a `microbr-decode` script available on your PATH.
67
+
68
+ ## Usage
69
+
70
+ Inspect a card backup:
71
+
72
+ ```bash
73
+ microbr-decode inspect path/to/BR0
74
+ ```
75
+
76
+ Decode every song (mixdowns to `output_dir/SONG000X.wav`, stems to
77
+ `output_dir/SONG000X-track1.wav`, etc.):
78
+
79
+ ```bash
80
+ microbr-decode decode path/to/BR0 -o output_dir
81
+ ```
82
+
83
+ Decode a single song:
84
+
85
+ ```bash
86
+ microbr-decode decode path/to/BR0/SONG0000.BR0 -o output_dir
87
+ ```
88
+
89
+ Use `--no-split-tracks` to write only the mixdown per song.
90
+
91
+ No dependencies beyond Python 3.10+.
92
+
93
+ ## What's inside a Micro-BR card
94
+
95
+ ```
96
+ BR0/
97
+ ├── CARDPRM.BR1
98
+ ├── DISKINF2.BR0
99
+ ├── SONG0000.BR0/
100
+ │ ├── ARRANGE3.BR1
101
+ │ ├── EFFECTS3.BR1
102
+ │ ├── SONGINF2.BR0
103
+ │ ├── SONGPRM.BR1
104
+ │ ├── TAKE_DAT.BR0 <- RDAC audio (16 KB pages)
105
+ │ ├── TAKE_DT1.BR0
106
+ │ ├── TAKE_DT2.BR0
107
+ │ └── TAKE_EVT.BR0 <- track/take event map
108
+ ├── SONG0001.BR0/
109
+ ...
110
+ ```
111
+
112
+ ## Development
113
+
114
+ ```bash
115
+ uv sync
116
+ uv run python -m unittest discover -s tests -v
117
+ uv build
118
+ ```
119
+
120
+ ## License
121
+
122
+ MIT — see [LICENSE](LICENSE).
123
+
124
+ ## Background
125
+
126
+ The Micro-BR stores audio in Roland's proprietary RDAC compression inside a
127
+ 16 KB-paged container. Details of the reverse engineering are in
128
+ [docs/FORMAT_ANALYSIS.md](docs/FORMAT_ANALYSIS.md). Related prior art:
129
+ [randygordon/rdac](https://github.com/randygordon/rdac) (C/Go decoders for
130
+ Roland VS recorders).
@@ -0,0 +1,8 @@
1
+ microbr_decode/__init__.py,sha256=0V2V1WEt0vt-bS1062I9FMhJW_4-Nbq0fpIY6h_VtjU,4702
2
+ microbr_decode/br_format.py,sha256=SocOlX72ywoH468zjQHiPTz2F_9ZW1EG9wN2NPQIshY,13747
3
+ microbr_decode/rdac_brwc.py,sha256=J4YHKuNlTu-CRjUztdtpUhVte6umAb_dPy92YfGkaK8,20726
4
+ microbr_decode-0.1.0.dist-info/licenses/LICENSE,sha256=O3yVxM9FHhHaa0qfts-lWsekXWtUJ3-dQg56lwq1pAo,1070
5
+ microbr_decode-0.1.0.dist-info/WHEEL,sha256=si2p8vW03RnhyBnhWl4tj-ObJa78SpE-c9HsEtblGR0,80
6
+ microbr_decode-0.1.0.dist-info/entry_points.txt,sha256=xBUbs1G415HegvsrBMpTU-2s4gAtFiljhBtSgn6wyHM,56
7
+ microbr_decode-0.1.0.dist-info/METADATA,sha256=yoFgCvl9Zasgv0oAMGnn7WQdWzMoJBUAh22-_vn0FMQ,3611
8
+ microbr_decode-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.5
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ microbr-decode = microbr_decode:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 David Jackson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.