-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsd_audio_split.py
More file actions
501 lines (425 loc) · 18 KB
/
sd_audio_split.py
File metadata and controls
501 lines (425 loc) · 18 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#!/usr/bin/env python3
import struct
from tempfile import NamedTemporaryFile
import os, glob, sys, subprocess, re
import wavinfo
def list_wav_files(directory):
os.chdir(directory)
return glob.glob('*.wav') + glob.glob('*.WAV')
def build_filename(wav_file, channel):
metadata = wavinfo.WavInfoReader(wav_file)
description = metadata.bext.description
track_names = list(iter_strk_values(description))
print(f"Track Names: {track_names}")
base, ext = os.path.splitext(wav_file)
return f"{base}_ch{channel}_{track_names[channel]}{ext}"
def iter_strk_values(text, include_empty=True):
"""
Iterate sTRK values (e.g., sTRK1, sTRK2, ...) in ascending numeric order.
Set include_empty=True to yield empty values too.
"""
kv = {}
for line in text.splitlines():
line = line.strip()
if not line or "=" not in line:
continue
k, v = line.split("=", 1)
kv[k.strip()] = v.strip()
tracks = []
for k, v in kv.items():
m = re.fullmatch(r"sTRK(\d+)", k, flags=re.IGNORECASE)
if m:
idx = int(m.group(1))
if include_empty or v != "":
tracks.append((idx, v))
for _, val in sorted(tracks, key=lambda t: t[0]):
yield val
def convert_to_mono(wav_file, outpath):
print(f"Converting {wav_file} to mono...")
metadata = wavinfo.WavInfoReader(wav_file)
channel_count = metadata.fmt.channel_count
for channel in range(channel_count):
filename = build_filename(wav_file, channel)
full_output_path = outpath + "/" + filename
print(f"Output will be saved to: {full_output_path}")
subprocess.run([
"ffmpeg", "-i", wav_file,
"-c:a", "pcm_f32le",
"-af", f"pan=mono|c0=c{channel}",
# "-write_bext", "1",
"-bitexact",
"-map_metadata", "-1",
full_output_path,
"-hide_banner", "-loglevel", "error"
])
show_metadata(wav_file)
show_metadata(full_output_path)
bext = extract_bext(wav_file)
if bext is None:
print("No bext in source.wav")
else:
inject_bext(full_output_path, bext, replace=True)
ixml = extract_ixml(wav_file)
if ixml is None:
print("No iXML in source.wav")
else:
inject_ixml(full_output_path, ixml, replace=True)
def show_metadata(wav_file):
metadata = wavinfo.WavInfoReader(wav_file)
print(f"Metadata for {wav_file}:")
print(f" Sample Rate: {metadata.fmt.sample_rate}")
print(f" Bit Depth: {metadata.fmt.bits_per_sample}")
print(f" Channels: {metadata.fmt.channel_count}\n")
def truncate_fmt_to_16(wav_path):
"""
Truncate the first 'fmt ' chunk's data to 16 bytes, ripple-deleting any extra bytes,
and updating the RIFF size accordingly. (Backups disabled per request.)
"""
with open(wav_path, 'rb') as f:
header = f.read(12)
if len(header) != 12:
raise ValueError("File too small to be a valid RIFF/WAVE.")
riff, riff_size_le, wave = struct.unpack('<4sI4s', header)
if riff != b'RIFF' or wave != b'WAVE':
raise ValueError("Not a RIFF/WAVE file.")
original_riff_size = riff_size_le # size of file minus the 8-byte RIFF header
# We'll scan chunks to find the first 'fmt '.
# Each chunk: 4-byte id, 4-byte size (LE), <size> bytes data, optional pad if size is odd.
# We'll record positions to stream-copy later.
f.seek(12) # after 'RIFF'+size+'WAVE'
fmt_found = False
fmt_chunk_offset = None
fmt_chunk_size = None
# Scan for first 'fmt ' chunk
while True:
hdr = f.read(8)
if not hdr:
break
if len(hdr) < 8:
raise ValueError("Truncated chunk header encountered.")
cid, csize = struct.unpack('<4sI', hdr)
data_start = f.tell()
# Move to next chunk (skip data + pad if any)
next_pos = data_start + csize + (csize & 1)
if cid == b'fmt ' and not fmt_found:
fmt_found = True
fmt_chunk_offset = data_start - 8 # start of chunk header (id+size)
fmt_chunk_size = csize
# Found first fmt; we can stop scanning further
# But we need to finish the copy later, so we just break.
break
f.seek(next_pos, os.SEEK_SET)
if not fmt_found:
print("No 'fmt ' chunk found. No changes made.")
return False
if fmt_chunk_size <= 16:
# Nothing to truncate
if fmt_chunk_size == 16:
print("'fmt ' chunk already 16 bytes. No changes made.")
else:
print(f"'fmt ' chunk is {fmt_chunk_size} bytes (<16). Not expanding. No changes made.")
return False
# We will rebuild the file into a temp and then replace the original.
# Compute how many bytes we will remove:
# - Remove (fmt_chunk_size - 16) bytes from fmt data
# - Remove 1 padding byte if original fmt size was odd (since new size=16 is even)
original_pad = fmt_chunk_size & 1
bytes_removed = (fmt_chunk_size - 16) + original_pad
# Prepare temp output
f.seek(0)
with NamedTemporaryFile('wb', delete=False) as tmp:
tmp_path = tmp.name
# --- Write the RIFF header with adjusted size ---
new_riff_size = original_riff_size - bytes_removed
# Sanity
if new_riff_size < 4: # must at least have 'WAVE'
raise ValueError("Adjustment would make RIFF size invalid.")
tmp.write(struct.pack('<4sI4s', b'RIFF', new_riff_size, b'WAVE'))
# --- Stream-copy chunks, modifying only the first 'fmt ' ---
f.seek(12)
fmt_done = False
while True:
hdr = f.read(8)
if not hdr:
break
if len(hdr) < 8:
raise ValueError("Truncated chunk header during copy.")
cid, csize = struct.unpack('<4sI', hdr)
data_start = f.tell()
if cid == b'fmt ' and not fmt_done:
# Write 'fmt ' header with new size 16
tmp.write(struct.pack('<4sI', b'fmt ', 16))
# Copy only first 16 bytes of original fmt data
to_copy = min(16, csize)
if to_copy < 16:
# Shouldn't happen because we guarded above, but be safe
raise ValueError("Unexpected: fmt chunk smaller than 16 during copy.")
tmp.write(f.read(16))
# Skip the rest of original fmt data
skip = csize - 16
if skip > 0:
f.seek(skip, os.SEEK_CUR)
# Skip original padding if present
if csize & 1:
f.seek(1, os.SEEK_CUR)
fmt_done = True
else:
# Pass-through for other chunks: write header as-is, then data
tmp.write(struct.pack('<4sI', cid, csize))
# Copy data
remaining = csize
while remaining:
chunk = f.read(min(65536, remaining))
if not chunk:
raise ValueError("Unexpected EOF while copying chunk data.")
tmp.write(chunk)
remaining -= len(chunk)
# Copy padding if present
if csize & 1:
pad = f.read(1)
if len(pad) != 1:
raise ValueError("Unexpected EOF reading padding.")
tmp.write(pad)
# Done writing temp
# Make replacement without creating a backup
# backup_path = wav_path + '.bak'
# shutil.copy2(wav_path, backup_path)
os.replace(tmp_path, wav_path)
print(f"Success: Truncated 'fmt ' from {fmt_chunk_size} → 16 bytes.")
print(f"Removed {bytes_removed} byte(s). RIFF size updated to {new_riff_size}.")
# print(f"Backup saved at: {backup_path}")
return True
CHUNK_HDR = struct.Struct('<4sI')
def _iter_chunks(f):
"""Yield (cid, csize, data_pos, next_pos) scanning from current file position."""
while True:
hdr = f.read(8)
if not hdr:
return
if len(hdr) < 8:
raise ValueError("Truncated chunk header.")
cid, csize = CHUNK_HDR.unpack(hdr)
data_pos = f.tell()
next_pos = data_pos + csize + (csize & 1)
yield cid, csize, data_pos, next_pos
f.seek(next_pos, os.SEEK_SET)
def _read_exact(f, pos, n):
f.seek(pos)
b = f.read(n)
if len(b) != n:
raise ValueError("Unexpected EOF.")
return b
def _read_riff_header(f):
f.seek(0)
h = f.read(12)
if len(h) != 12:
raise ValueError("Not a valid RIFF/WAVE file (too small).")
riff, riff_size, wave = struct.unpack('<4sI4s', h)
if riff != b'RIFF' or wave != b'WAVE':
raise ValueError("Not a RIFF/WAVE file.")
return riff_size
def extract_bext(src_wav):
"""
Return the first 'bext' chunk as raw bytes including the 8-byte header (id+size) and payload (no padding).
Returns None if no bext exists.
"""
with open(src_wav, 'rb') as f:
_read_riff_header(f)
f.seek(12)
for cid, csize, data_pos, next_pos in _iter_chunks(f):
if cid == b'bext':
# Return header + payload (omit original pad; we'll re-pad on write).
header = CHUNK_HDR.pack(b'bext', csize)
payload = _read_exact(f, data_pos, csize)
return header + payload
return None
def inject_bext(dst_wav, bext_chunk, replace=True):
"""
Insert (or replace) a 'bext' chunk in dst_wav. (Backups disabled per request.)
"""
if bext_chunk is None:
raise ValueError("bext_chunk is None; nothing to inject.")
if len(bext_chunk) < 8:
raise ValueError("bext_chunk is too small.")
cid, csize = CHUNK_HDR.unpack(bext_chunk[:8])
if cid != b'bext' or csize != len(bext_chunk) - 8:
raise ValueError("bext_chunk header/size mismatch.")
with open(dst_wav, 'rb') as f_in, NamedTemporaryFile('wb', delete=False) as f_out:
tmp_path = f_out.name
orig_riff_size = _read_riff_header(f_in)
# We'll compute delta to RIFF size
removed_bytes = 0 # complete chunk bytes removed (payload + header + old pad)
added_bytes = 0 # complete chunk bytes added (payload + header + new pad)
# Precompute new bext total size including padding when written
bext_payload_size = len(bext_chunk) - 8
bext_pad = bext_payload_size & 1
bext_total = 8 + bext_payload_size + bext_pad
# We will stream-copy:
# - write new RIFF header now with placeholder size (we'll correct at end)
f_out.write(struct.pack('<4sI4s', b'RIFF', orig_riff_size, b'WAVE'))
# Flags for handling placement
inserted = False
skipped_existing_bext = False
f_in.seek(12)
while True:
hdr = f_in.read(8)
if not hdr:
break
if len(hdr) < 8:
raise ValueError("Truncated chunk header during copy.")
cid, csize = CHUNK_HDR.unpack(hdr)
data_pos = f_in.tell()
next_pos = data_pos + csize + (csize & 1)
if cid == b'data' and not inserted:
# Insert our bext before the data chunk
f_out.write(bext_chunk)
if bext_pad:
f_out.write(b'\x00')
added_bytes += bext_total
inserted = True
if cid == b'bext' and replace and not skipped_existing_bext:
# Skip existing bext (remove from dest)
removed_bytes += 8 + csize + (csize & 1)
f_in.seek(next_pos, os.SEEK_SET)
skipped_existing_bext = True
continue
# Normal pass-through for other chunks (or bext if not replacing)
f_out.write(CHUNK_HDR.pack(cid, csize))
# Copy data in chunks
remaining = csize
while remaining:
chunk = f_in.read(min(65536, remaining))
if not chunk:
raise ValueError("Unexpected EOF while copying chunk.")
f_out.write(chunk)
remaining -= len(chunk)
# Preserve padding
if csize & 1:
pad = f_in.read(1)
if len(pad) != 1:
raise ValueError("Unexpected EOF reading padding.")
f_out.write(pad)
# If no 'data' chunk encountered (rare), append at end
if not inserted:
f_out.write(bext_chunk)
if bext_pad:
f_out.write(b'\x00')
added_bytes += bext_total
# Fix RIFF size
new_riff_size = orig_riff_size - removed_bytes + added_bytes
# Seek and rewrite the RIFF size at offset 4
f_out.seek(4)
f_out.write(struct.pack('<I', new_riff_size))
# Replace original atomically without creating a backup
# backup = dst_wav + '.bak'
# shutil.copy2(dst_wav, backup)
os.replace(tmp_path, dst_wav)
action = "replaced" if replace else "inserted"
print(f"Success: {action} 'bext' chunk. "
f"Removed {removed_bytes} byte(s), added {added_bytes} byte(s). "
f"RIFF size: {orig_riff_size} → {new_riff_size}.")
def extract_ixml(src_wav):
"""
Return the first 'iXML' chunk as raw bytes (8-byte header + payload, no padding).
Returns None if no iXML chunk exists.
"""
with open(src_wav, 'rb') as f:
_read_riff_header(f)
for cid, csize, data_pos, _ in _iter_chunks(f):
if cid == b'iXML':
header = CHUNK_HDR.pack(b'iXML', csize)
payload = _read_exact(f, data_pos, csize)
return header + payload
return None
def inject_ixml(dst_wav, ixml_chunk, replace=True):
"""
Insert (or replace) an 'iXML' chunk in dst_wav.
- ixml_chunk must be 8-byte header ('iXML'+size) + payload (no pad).
- replace=True: removes existing iXML first; otherwise keeps it and adds another (not typical).
- Placement: immediately before 'data' if present; else appended at end.
Creates dst_wav+'.bak' and atomically replaces the original.
"""
if ixml_chunk is None:
raise ValueError("ixml_chunk is None; nothing to inject.")
if len(ixml_chunk) < 8:
raise ValueError("ixml_chunk too small.")
cid, csize = CHUNK_HDR.unpack(ixml_chunk[:8])
if cid != b'iXML' or csize != len(ixml_chunk) - 8:
raise ValueError("iXML header/size mismatch.")
with open(dst_wav, 'rb') as f_in, NamedTemporaryFile('wb', delete=False) as f_out:
tmp_path = f_out.name
orig_riff_size = _read_riff_header(f_in)
# Precompute sizes
ixml_payload = len(ixml_chunk) - 8
ixml_pad = ixml_payload & 1
ixml_total = 8 + ixml_payload + ixml_pad
removed = 0
added = 0
# Write header with placeholder size (fixed later)
f_out.write(struct.pack('<4sI4s', b'RIFF', orig_riff_size, b'WAVE'))
inserted = False
skipped_existing_ixml = False
f_in.seek(12)
while True:
hdr = f_in.read(8)
if not hdr:
break
if len(hdr) < 8:
raise ValueError("Truncated chunk header during copy.")
ccid, csize = CHUNK_HDR.unpack(hdr)
data_pos = f_in.tell()
next_pos = data_pos + csize + (csize & 1)
# Insert new iXML right before data
if ccid == b'data' and not inserted:
f_out.write(ixml_chunk)
if ixml_pad:
f_out.write(b'\x00')
added += ixml_total
inserted = True
# If replacing, skip existing iXML once
if ccid == b'iXML' and replace and not skipped_existing_ixml:
removed += 8 + csize + (csize & 1)
f_in.seek(next_pos, os.SEEK_SET)
skipped_existing_ixml = True
continue
# Pass-through other chunks
f_out.write(CHUNK_HDR.pack(ccid, csize))
# Copy chunk payload
remaining = csize
while remaining:
chunk = f_in.read(min(65536, remaining))
if not chunk:
raise ValueError("Unexpected EOF copying chunk.")
f_out.write(chunk)
remaining -= len(chunk)
# Copy padding if present
if csize & 1:
pad = f_in.read(1)
if len(pad) != 1:
raise ValueError("Unexpected EOF reading padding.")
f_out.write(pad)
# If no data chunk was found, append at end
if not inserted:
f_out.write(ixml_chunk)
if ixml_pad:
f_out.write(b'\x00')
added += ixml_total
# Fix RIFF size (at offset 4)
new_riff_size = orig_riff_size - removed + added
f_out.seek(4)
f_out.write(struct.pack('<I', new_riff_size))
# Backup & replace
# backup = dst_wav + '.bak'
# shutil.copy2(dst_wav, backup)
os.replace(tmp_path, dst_wav)
action = "replaced" if replace else "inserted"
print(f"Success: {action} 'iXML'. Removed {removed} byte(s), added {added} byte(s). "
f"RIFF size: {orig_riff_size} → {new_riff_size}.")
def main(inpath, outpath):
print(f"Processing input file: {inpath}")
print(f"Output will be saved to: {outpath}")
wav_files = list_wav_files(inpath)
for wav_file in wav_files:
convert_to_mono(wav_file, outpath)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])