msadpcm 0.1.1__tar.gz

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.
msadpcm-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Y-Dr. Now
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.
msadpcm-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.4
2
+ Name: msadpcm
3
+ Version: 0.1.1
4
+ Summary: Microsoft ADPCM (WAVE_FORMAT_ADPCM) encoder and decoder in pure Python + NumPy
5
+ Author: Y-Dr. Now
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Eyef/msadpcm
8
+ Keywords: adpcm,ms-adpcm,microsoft-adpcm,wav,audio,codec,encoder,decoder
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Conversion
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.21
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == "test"
20
+ Dynamic: license-file
21
+
22
+ # msadpcm
23
+
24
+ Microsoft ADPCM (`WAVE_FORMAT_ADPCM`, tag `0x0002`) **encoder and decoder** in pure
25
+ Python + NumPy. No FFmpeg, no compiled extensions, no multiprocessing.
26
+
27
+ * any block size (`block_align` in bytes, or `samples_per_block`), mono and stereo
28
+ * decoder output is **bit-exact with FFmpeg's `adpcm_ms`** (checked in the test suite, both directions)
29
+ * encoder searches all 7 standard predictors and a grid of initial step sizes for every block, with
30
+ the same arithmetic as the decoder, so the quality it measures is the quality you get
31
+ * reads and writes complete WAV files (`fact` chunk included), or works on raw blocks in memory
32
+ * optional custom coefficient tables
33
+ * command line tool and a small tkinter demo (`examples/gui_demo.py`)
34
+
35
+ ```
36
+ pip install msadpcm # once published; until then: pip install .
37
+ ```
38
+
39
+ ## Quick start
40
+
41
+ ```python
42
+ import numpy as np
43
+ import msadpcm
44
+
45
+ # whole files
46
+ msadpcm.write_wav("out.wav", pcm, 22050) # pcm: int16 (frames,) or (frames, 2)
47
+ pcm, rate = msadpcm.read_wav("out.wav") # ADPCM or PCM in, int16 (frames, channels) out
48
+
49
+ # raw blocks
50
+ blocks = msadpcm.encode(pcm, block_align=512) # quality="normal" by default
51
+ pcm = msadpcm.decode(blocks, channels=1, block_align=512, n_samples=len(pcm))
52
+ ```
53
+
54
+ Inputs may be `int16` arrays, floats in [-1, 1], plain lists of ints, or little-endian `bytes`
55
+ (then pass `channels=`). Wider integer arrays are rejected on purpose: a 24-bit file stored in
56
+ `int32` would be silently clipped otherwise; convert it explicitly.
57
+
58
+ ### Block size
59
+
60
+ ```python
61
+ msadpcm.write_wav("a.wav", pcm, 44100, block_align=2048) # bytes per block
62
+ msadpcm.write_wav("b.wav", pcm, 22050, samples_per_block=128) # 70-byte mono / 140-byte stereo blocks
63
+ msadpcm.samples_per_block(512, 2) # -> 500
64
+ msadpcm.block_align_for(128, 1) # -> 70
65
+ ```
66
+
67
+ Without an explicit size `write_wav` uses what Windows' ACM codec does
68
+ (`256 * channels * max(1, rate // 11025)` bytes). A larger block means a smaller file
69
+ (less header overhead) but slower adaptation after a transient.
70
+
71
+ ### Quality presets
72
+
73
+ `quality="fast" | "normal" (default) | "high" | "max"`: how many candidate step sizes are tried per
74
+ block. All presets try all seven predictors. `normal` is within a few hundredths of a dB of `high` at
75
+ about half the encoding time; use `high` or `max` when you want the last bit of quality and don't mind
76
+ waiting, `fast` for quick previews or batch jobs.
77
+
78
+ ### Command line
79
+
80
+ ```
81
+ python -m msadpcm encode in.wav -o out.wav --samples-per-block 128 --quality normal
82
+ python -m msadpcm decode out.wav -o back.wav
83
+ python -m msadpcm info *.wav
84
+ ```
85
+
86
+ `encode` shows a progress line on a terminal (nothing is printed when the output is redirected) and
87
+ reports the SNR of the result (it decodes the file again) unless `--no-verify` is given.
88
+
89
+ ## Quality and speed
90
+
91
+ SNR in dB (higher is better), 6 s of mono audio at 22.05 kHz, run with
92
+ `python benchmarks/compare_ffmpeg.py` (ffmpeg 6.1). All files were decoded with msadpcm's decoder,
93
+ which is bit-exact with FFmpeg's, so the differences come from the encoders only.
94
+
95
+ | signal | block | ffmpeg `adpcm_ms` | fast | normal | high | max |
96
+ |---|---|---|---|---|---|---|
97
+ | voice-like | 256 | 30.40 | 39.20 | 39.76 | 39.88 | 40.04 |
98
+ | music-like | 256 | 34.54 | 42.14 | 42.53 | 42.59 | 42.76 |
99
+ | white noise | 256 | 14.12 | 16.59 | 16.71 | 16.72 | 16.77 |
100
+ | voice-like | 1024 | 30.87 | 38.60 | 38.84 | 38.86 | 38.97 |
101
+ | music-like | 1024 | 34.54 | 39.19 | 39.32 | 39.38 | 39.46 |
102
+ | white noise | 1024 | 14.13 | 16.52 | 16.56 | 16.57 | 16.59 |
103
+
104
+ Caveats: the signals are synthetic (the test suite needs no audio assets), and harmonic signals
105
+ reward good predictor choice more than typical recordings do, so expect smaller gains on real
106
+ material. Run the script on your own files before relying on these numbers.
107
+
108
+ Speed depends on the CPU (NumPy uses SIMD instructions where available). Measured on a 2012 Core
109
+ i7-3770, 184 s of mono 48 kHz music with 1024-byte blocks: `fast` 7.1 s (26x real time, SNR 34.08 dB),
110
+ `normal` 15.8 s (12x, 34.26 dB), `high` 32.7 s (5.6x, 34.30 dB). Newer processors are several times
111
+ faster. Stereo takes twice as long as mono. Memory use stays bounded regardless of block size.
112
+
113
+ ## Format notes
114
+
115
+ Blocks are `predictor, delta, sample1, sample2` followed by 4-bit codes (high nibble first); stereo
116
+ stores both channels' header fields interleaved by field and both channels' codes in one byte (left in the
117
+ high nibble). The decoder uses `(s1*c1 + s2*c2) / 256` **truncated toward zero** and
118
+ `delta = max(16, (table[nibble] * delta) >> 8)`, exactly like FFmpeg and the Microsoft codec.
119
+
120
+ Details worth knowing:
121
+
122
+ * The first two samples of every block are stored verbatim, so each block starts exact.
123
+ * The last block is padded by repeating the final sample; the real length is written to the `fact`
124
+ chunk and honoured by `read_wav`/`decode(n_samples=...)`.
125
+ * The header stores the initial delta as a signed 16-bit value; the encoder never writes more than 32767
126
+ and avoids candidates whose delta would later exceed 32767, for decoders that keep it in 16 bits.
127
+ * Only 1 or 2 channels exist in this format.
128
+
129
+ ### Game audio with fixed block sizes
130
+
131
+ Some games expect a particular block geometry. `samples_per_block=128` produces the 70/140-byte blocks
132
+ and the 32-byte extra data (`wSamplesPerBlock=128, wNumCoef=7` + the standard coefficients) that Doom 3 BFG
133
+ Edition uses, which is the standard layout, nothing proprietary:
134
+
135
+ ```python
136
+ fmt = msadpcm.format_chunk(22050, 1, msadpcm.block_align_for(128, 1)) # 50 bytes, extra data included
137
+ raw = msadpcm.encode(pcm, samples_per_block=128) # blocks without any container
138
+ ```
139
+
140
+ ## API summary
141
+
142
+ | | |
143
+ |---|---|
144
+ | `encode(pcm, *, channels=None, block_align=None, samples_per_block=None, quality="normal", coeffs=None, progress=None) -> bytes` | raw blocks |
145
+ | `decode(data, *, channels, block_align, n_samples=None, coeffs=None) -> int16[frames, channels]` | raw blocks |
146
+ | `write_wav(path, pcm, rate, *, adpcm=True, block_align=None, samples_per_block=None, quality="normal", coeffs=None, progress=None)` | `adpcm=False` writes 16-bit PCM |
147
+ | `read_wav(path) -> (int16[frames, channels], rate)` | PCM 8/16/24/32, float, extensible, MS ADPCM |
148
+ | `wav_info(path) -> WavInfo`, `read_adpcm_raw(path)` | header / undecoded blocks |
149
+ | `format_chunk(rate, channels, block_align, coeffs=None)` | `fmt ` chunk body |
150
+ | `samples_per_block`, `block_align_for`, `default_block_align`, `snr_db` | helpers |
151
+
152
+ `progress` is `callback(done_blocks, total_blocks)`; encoding is vectorised over all blocks, so the
153
+ callback fires once per processed chunk of blocks (a few hundred blocks), not per block.
154
+
155
+ ## Development
156
+
157
+ ```
158
+ pip install -e .[test]
159
+ pytest
160
+ python benchmarks/compare_ffmpeg.py
161
+ ```
162
+
163
+ The ffmpeg interoperability tests are skipped automatically when `ffmpeg` is not installed. The decoder is
164
+ also tested against an independent scalar re-implementation (`tests/helpers.py`).
165
+
166
+ MIT licensed.
@@ -0,0 +1,145 @@
1
+ # msadpcm
2
+
3
+ Microsoft ADPCM (`WAVE_FORMAT_ADPCM`, tag `0x0002`) **encoder and decoder** in pure
4
+ Python + NumPy. No FFmpeg, no compiled extensions, no multiprocessing.
5
+
6
+ * any block size (`block_align` in bytes, or `samples_per_block`), mono and stereo
7
+ * decoder output is **bit-exact with FFmpeg's `adpcm_ms`** (checked in the test suite, both directions)
8
+ * encoder searches all 7 standard predictors and a grid of initial step sizes for every block, with
9
+ the same arithmetic as the decoder, so the quality it measures is the quality you get
10
+ * reads and writes complete WAV files (`fact` chunk included), or works on raw blocks in memory
11
+ * optional custom coefficient tables
12
+ * command line tool and a small tkinter demo (`examples/gui_demo.py`)
13
+
14
+ ```
15
+ pip install msadpcm # once published; until then: pip install .
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ ```python
21
+ import numpy as np
22
+ import msadpcm
23
+
24
+ # whole files
25
+ msadpcm.write_wav("out.wav", pcm, 22050) # pcm: int16 (frames,) or (frames, 2)
26
+ pcm, rate = msadpcm.read_wav("out.wav") # ADPCM or PCM in, int16 (frames, channels) out
27
+
28
+ # raw blocks
29
+ blocks = msadpcm.encode(pcm, block_align=512) # quality="normal" by default
30
+ pcm = msadpcm.decode(blocks, channels=1, block_align=512, n_samples=len(pcm))
31
+ ```
32
+
33
+ Inputs may be `int16` arrays, floats in [-1, 1], plain lists of ints, or little-endian `bytes`
34
+ (then pass `channels=`). Wider integer arrays are rejected on purpose: a 24-bit file stored in
35
+ `int32` would be silently clipped otherwise; convert it explicitly.
36
+
37
+ ### Block size
38
+
39
+ ```python
40
+ msadpcm.write_wav("a.wav", pcm, 44100, block_align=2048) # bytes per block
41
+ msadpcm.write_wav("b.wav", pcm, 22050, samples_per_block=128) # 70-byte mono / 140-byte stereo blocks
42
+ msadpcm.samples_per_block(512, 2) # -> 500
43
+ msadpcm.block_align_for(128, 1) # -> 70
44
+ ```
45
+
46
+ Without an explicit size `write_wav` uses what Windows' ACM codec does
47
+ (`256 * channels * max(1, rate // 11025)` bytes). A larger block means a smaller file
48
+ (less header overhead) but slower adaptation after a transient.
49
+
50
+ ### Quality presets
51
+
52
+ `quality="fast" | "normal" (default) | "high" | "max"`: how many candidate step sizes are tried per
53
+ block. All presets try all seven predictors. `normal` is within a few hundredths of a dB of `high` at
54
+ about half the encoding time; use `high` or `max` when you want the last bit of quality and don't mind
55
+ waiting, `fast` for quick previews or batch jobs.
56
+
57
+ ### Command line
58
+
59
+ ```
60
+ python -m msadpcm encode in.wav -o out.wav --samples-per-block 128 --quality normal
61
+ python -m msadpcm decode out.wav -o back.wav
62
+ python -m msadpcm info *.wav
63
+ ```
64
+
65
+ `encode` shows a progress line on a terminal (nothing is printed when the output is redirected) and
66
+ reports the SNR of the result (it decodes the file again) unless `--no-verify` is given.
67
+
68
+ ## Quality and speed
69
+
70
+ SNR in dB (higher is better), 6 s of mono audio at 22.05 kHz, run with
71
+ `python benchmarks/compare_ffmpeg.py` (ffmpeg 6.1). All files were decoded with msadpcm's decoder,
72
+ which is bit-exact with FFmpeg's, so the differences come from the encoders only.
73
+
74
+ | signal | block | ffmpeg `adpcm_ms` | fast | normal | high | max |
75
+ |---|---|---|---|---|---|---|
76
+ | voice-like | 256 | 30.40 | 39.20 | 39.76 | 39.88 | 40.04 |
77
+ | music-like | 256 | 34.54 | 42.14 | 42.53 | 42.59 | 42.76 |
78
+ | white noise | 256 | 14.12 | 16.59 | 16.71 | 16.72 | 16.77 |
79
+ | voice-like | 1024 | 30.87 | 38.60 | 38.84 | 38.86 | 38.97 |
80
+ | music-like | 1024 | 34.54 | 39.19 | 39.32 | 39.38 | 39.46 |
81
+ | white noise | 1024 | 14.13 | 16.52 | 16.56 | 16.57 | 16.59 |
82
+
83
+ Caveats: the signals are synthetic (the test suite needs no audio assets), and harmonic signals
84
+ reward good predictor choice more than typical recordings do, so expect smaller gains on real
85
+ material. Run the script on your own files before relying on these numbers.
86
+
87
+ Speed depends on the CPU (NumPy uses SIMD instructions where available). Measured on a 2012 Core
88
+ i7-3770, 184 s of mono 48 kHz music with 1024-byte blocks: `fast` 7.1 s (26x real time, SNR 34.08 dB),
89
+ `normal` 15.8 s (12x, 34.26 dB), `high` 32.7 s (5.6x, 34.30 dB). Newer processors are several times
90
+ faster. Stereo takes twice as long as mono. Memory use stays bounded regardless of block size.
91
+
92
+ ## Format notes
93
+
94
+ Blocks are `predictor, delta, sample1, sample2` followed by 4-bit codes (high nibble first); stereo
95
+ stores both channels' header fields interleaved by field and both channels' codes in one byte (left in the
96
+ high nibble). The decoder uses `(s1*c1 + s2*c2) / 256` **truncated toward zero** and
97
+ `delta = max(16, (table[nibble] * delta) >> 8)`, exactly like FFmpeg and the Microsoft codec.
98
+
99
+ Details worth knowing:
100
+
101
+ * The first two samples of every block are stored verbatim, so each block starts exact.
102
+ * The last block is padded by repeating the final sample; the real length is written to the `fact`
103
+ chunk and honoured by `read_wav`/`decode(n_samples=...)`.
104
+ * The header stores the initial delta as a signed 16-bit value; the encoder never writes more than 32767
105
+ and avoids candidates whose delta would later exceed 32767, for decoders that keep it in 16 bits.
106
+ * Only 1 or 2 channels exist in this format.
107
+
108
+ ### Game audio with fixed block sizes
109
+
110
+ Some games expect a particular block geometry. `samples_per_block=128` produces the 70/140-byte blocks
111
+ and the 32-byte extra data (`wSamplesPerBlock=128, wNumCoef=7` + the standard coefficients) that Doom 3 BFG
112
+ Edition uses, which is the standard layout, nothing proprietary:
113
+
114
+ ```python
115
+ fmt = msadpcm.format_chunk(22050, 1, msadpcm.block_align_for(128, 1)) # 50 bytes, extra data included
116
+ raw = msadpcm.encode(pcm, samples_per_block=128) # blocks without any container
117
+ ```
118
+
119
+ ## API summary
120
+
121
+ | | |
122
+ |---|---|
123
+ | `encode(pcm, *, channels=None, block_align=None, samples_per_block=None, quality="normal", coeffs=None, progress=None) -> bytes` | raw blocks |
124
+ | `decode(data, *, channels, block_align, n_samples=None, coeffs=None) -> int16[frames, channels]` | raw blocks |
125
+ | `write_wav(path, pcm, rate, *, adpcm=True, block_align=None, samples_per_block=None, quality="normal", coeffs=None, progress=None)` | `adpcm=False` writes 16-bit PCM |
126
+ | `read_wav(path) -> (int16[frames, channels], rate)` | PCM 8/16/24/32, float, extensible, MS ADPCM |
127
+ | `wav_info(path) -> WavInfo`, `read_adpcm_raw(path)` | header / undecoded blocks |
128
+ | `format_chunk(rate, channels, block_align, coeffs=None)` | `fmt ` chunk body |
129
+ | `samples_per_block`, `block_align_for`, `default_block_align`, `snr_db` | helpers |
130
+
131
+ `progress` is `callback(done_blocks, total_blocks)`; encoding is vectorised over all blocks, so the
132
+ callback fires once per processed chunk of blocks (a few hundred blocks), not per block.
133
+
134
+ ## Development
135
+
136
+ ```
137
+ pip install -e .[test]
138
+ pytest
139
+ python benchmarks/compare_ffmpeg.py
140
+ ```
141
+
142
+ The ffmpeg interoperability tests are skipped automatically when `ffmpeg` is not installed. The decoder is
143
+ also tested against an independent scalar re-implementation (`tests/helpers.py`).
144
+
145
+ MIT licensed.
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "msadpcm"
7
+ version = "0.1.1"
8
+ description = "Microsoft ADPCM (WAVE_FORMAT_ADPCM) encoder and decoder in pure Python + NumPy"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Y-Dr. Now" }]
14
+ keywords = ["adpcm", "ms-adpcm", "microsoft-adpcm", "wav", "audio", "codec", "encoder", "decoder"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Multimedia :: Sound/Audio",
20
+ "Topic :: Multimedia :: Sound/Audio :: Conversion",
21
+ ]
22
+ dependencies = ["numpy>=1.21"]
23
+
24
+ [project.optional-dependencies]
25
+ test = ["pytest"]
26
+
27
+ [project.scripts]
28
+ msadpcm = "msadpcm.cli:main"
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/Eyef/msadpcm"
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ """msadpcm - Microsoft ADPCM encoder/decoder in pure Python + NumPy."""
2
+ from .codec import (
3
+ ADAPTATION_TABLE,
4
+ QUALITY_LEVELS,
5
+ STANDARD_COEFFS,
6
+ block_align_for,
7
+ decode,
8
+ default_block_align,
9
+ encode,
10
+ samples_per_block,
11
+ snr_db,
12
+ )
13
+ from .wav import WavInfo, format_chunk, read_adpcm_raw, read_wav, wav_info, write_wav
14
+
15
+ __version__ = "0.1.1"
16
+
17
+ __all__ = [
18
+ "ADAPTATION_TABLE",
19
+ "QUALITY_LEVELS",
20
+ "STANDARD_COEFFS",
21
+ "WavInfo",
22
+ "block_align_for",
23
+ "decode",
24
+ "default_block_align",
25
+ "encode",
26
+ "format_chunk",
27
+ "read_adpcm_raw",
28
+ "read_wav",
29
+ "samples_per_block",
30
+ "snr_db",
31
+ "wav_info",
32
+ "write_wav",
33
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,220 @@
1
+ """Command line interface and the file-conversion helper shared with the GUI demo."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ import time
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Callable, List, Optional, Sequence
10
+
11
+ from . import codec, wav
12
+
13
+ __all__ = ["ConversionResult", "convert_file", "main"]
14
+
15
+
16
+ @dataclass
17
+ class ConversionResult:
18
+ """What :func:`convert_file` did."""
19
+
20
+ src: Path
21
+ dst: Path
22
+ mode: str # "encode" or "decode"
23
+ frames: int
24
+ sample_rate: int
25
+ channels: int
26
+ src_bytes: int
27
+ dst_bytes: int
28
+ seconds: float
29
+ block_align: Optional[int] = None
30
+ samples_per_block: Optional[int] = None
31
+ snr_db: Optional[float] = None # encode only: ADPCM output vs. the input
32
+
33
+ @property
34
+ def ratio(self) -> float:
35
+ return self.src_bytes / self.dst_bytes if self.dst_bytes else float("inf")
36
+
37
+
38
+ def convert_file(
39
+ src,
40
+ dst=None,
41
+ *,
42
+ mode: str = "encode",
43
+ block_align: Optional[int] = None,
44
+ samples_per_block: Optional[int] = None,
45
+ quality: str = "normal",
46
+ verify: bool = True,
47
+ progress: Optional[Callable[[int, int], None]] = None,
48
+ ) -> ConversionResult:
49
+ """Convert one WAV file.
50
+
51
+ ``mode="encode"`` writes MS ADPCM, ``mode="decode"`` writes 16-bit PCM.
52
+ With ``verify`` the encoded file is decoded again to report the SNR.
53
+ """
54
+ if mode not in ("encode", "decode"):
55
+ raise ValueError("mode must be 'encode' or 'decode'")
56
+ src = Path(src)
57
+ if dst is None:
58
+ dst = src.with_name(src.stem + (".adpcm.wav" if mode == "encode" else ".pcm.wav"))
59
+ dst = Path(dst)
60
+
61
+ t0 = time.perf_counter()
62
+ pcm, rate = wav.read_wav(src)
63
+ frames, ch = pcm.shape
64
+
65
+ if mode == "decode":
66
+ written = wav.write_wav(dst, pcm, rate, adpcm=False)
67
+ return ConversionResult(src, dst, mode, frames, rate, ch, src.stat().st_size,
68
+ written, time.perf_counter() - t0)
69
+
70
+ if block_align is None and samples_per_block is None:
71
+ block_align = codec.default_block_align(rate, ch)
72
+ ba, spb = codec._resolve_geometry(ch, block_align, samples_per_block)
73
+ written = wav.write_wav(dst, pcm, rate, block_align=ba, quality=quality, progress=progress)
74
+ snr = None
75
+ if verify:
76
+ decoded, _ = wav.read_wav(dst)
77
+ snr = codec.snr_db(pcm, decoded)
78
+ return ConversionResult(src, dst, mode, frames, rate, ch, src.stat().st_size, written,
79
+ time.perf_counter() - t0, ba, spb, snr)
80
+
81
+
82
+ class _ProgressLine:
83
+ """Single updating status line on stderr (``name: encoding 45%``).
84
+
85
+ Shown only on an interactive terminal, so redirected output and logs stay
86
+ clean. Call the instance as the ``progress`` callback; call :meth:`clear`
87
+ before printing anything else.
88
+ """
89
+
90
+ def __init__(self, label: str, stream=None) -> None:
91
+ self.label = label
92
+ self.stream = sys.stderr if stream is None else stream
93
+ self.enabled = bool(getattr(self.stream, "isatty", lambda: False)())
94
+ self._shown = 0
95
+ self._last = -1
96
+ self._t0 = time.perf_counter()
97
+
98
+ def __call__(self, done: int, total: int) -> None:
99
+ if not self.enabled or total <= 0:
100
+ return
101
+ percent = 100 * done // total
102
+ if percent == self._last:
103
+ return
104
+ self._last = percent
105
+ elapsed = time.perf_counter() - self._t0
106
+ text = "%s: encoding %d%%" % (self.label, percent)
107
+ if 0 < done < total and elapsed >= 2.0:
108
+ text += " (%ds left)" % round(elapsed * (total - done) / done)
109
+ self._write(text)
110
+
111
+ def _write(self, text: str) -> None:
112
+ pad = " " * max(0, self._shown - len(text))
113
+ self.stream.write("\r" + text + pad)
114
+ self.stream.flush()
115
+ self._shown = len(text)
116
+
117
+ def clear(self) -> None:
118
+ if self.enabled and self._shown:
119
+ self.stream.write("\r" + " " * self._shown + "\r")
120
+ self.stream.flush()
121
+ self._shown = 0
122
+
123
+
124
+ def _describe(r: ConversionResult) -> str:
125
+ text = "%s -> %s %.1fs audio, %s, %.2fs" % (
126
+ r.src.name, r.dst.name, r.frames / r.sample_rate,
127
+ "stereo" if r.channels == 2 else "mono", r.seconds)
128
+ text += " [%d -> %d bytes, x%.2f]" % (r.src_bytes, r.dst_bytes, r.ratio)
129
+ if r.mode == "encode":
130
+ text += " block %d bytes (%d samples)" % (r.block_align, r.samples_per_block)
131
+ if r.snr_db is not None:
132
+ text += " SNR %.2f dB" % r.snr_db
133
+ return text
134
+
135
+
136
+ def _targets(inputs: Sequence[str], out: Optional[str], outdir: Optional[str], mode: str):
137
+ if out and len(inputs) != 1:
138
+ raise SystemExit("-o/--output works with exactly one input file; use -d/--outdir")
139
+ suffix = ".adpcm.wav" if mode == "encode" else ".pcm.wav"
140
+ for item in inputs:
141
+ src = Path(item)
142
+ if out:
143
+ dst = Path(out)
144
+ elif outdir:
145
+ dst = Path(outdir) / (src.stem + suffix)
146
+ else:
147
+ dst = src.with_name(src.stem + suffix)
148
+ yield src, dst
149
+
150
+
151
+ def _build_parser() -> argparse.ArgumentParser:
152
+ p = argparse.ArgumentParser(
153
+ prog="msadpcm", description="Microsoft ADPCM WAV encoder/decoder.")
154
+ sub = p.add_subparsers(dest="cmd", required=True)
155
+
156
+ enc = sub.add_parser("encode", help="PCM WAV -> MS ADPCM WAV")
157
+ enc.add_argument("inputs", nargs="+")
158
+ g = enc.add_mutually_exclusive_group()
159
+ g.add_argument("--block-align", type=int, help="bytes per block (default: like Windows ACM)")
160
+ g.add_argument("--samples-per-block", type=int, help="sample frames per block, e.g. 128")
161
+ enc.add_argument("--quality", choices=list(codec.QUALITY_LEVELS), default="normal")
162
+ enc.add_argument("-o", "--output")
163
+ enc.add_argument("-d", "--outdir")
164
+ enc.add_argument("--no-verify", action="store_true", help="skip the SNR check")
165
+
166
+ dec = sub.add_parser("decode", help="MS ADPCM WAV -> 16-bit PCM WAV")
167
+ dec.add_argument("inputs", nargs="+")
168
+ dec.add_argument("-o", "--output")
169
+ dec.add_argument("-d", "--outdir")
170
+
171
+ info = sub.add_parser("info", help="show WAV header information")
172
+ info.add_argument("inputs", nargs="+")
173
+ return p
174
+
175
+
176
+ def main(argv: Optional[List[str]] = None) -> int:
177
+ args = _build_parser().parse_args(argv)
178
+
179
+ if args.cmd == "info":
180
+ for item in args.inputs:
181
+ i = wav.wav_info(item)
182
+ kind = {1: "PCM", 2: "MS ADPCM", 3: "float", 0xFFFE: "extensible"}.get(
183
+ i.format_tag, "0x%04X" % i.format_tag)
184
+ line = "%s: %s, %d ch, %d Hz, %d-bit" % (
185
+ item, kind, i.channels, i.sample_rate, i.bits_per_sample)
186
+ if i.is_adpcm:
187
+ line += ", block %d bytes (%d samples)" % (
188
+ i.block_align, codec.samples_per_block(i.block_align, i.channels))
189
+ if i.n_frames is not None:
190
+ line += ", %d frames (%.2fs)" % (i.n_frames, i.duration)
191
+ print(line)
192
+ return 0
193
+
194
+ failures = 0
195
+ for src, dst in _targets(args.inputs, args.output, args.outdir, args.cmd):
196
+ try:
197
+ if args.outdir:
198
+ Path(args.outdir).mkdir(parents=True, exist_ok=True)
199
+ kwargs = {}
200
+ line = None
201
+ if args.cmd == "encode":
202
+ line = _ProgressLine(src.name)
203
+ kwargs = dict(block_align=args.block_align,
204
+ samples_per_block=args.samples_per_block,
205
+ quality=args.quality, verify=not args.no_verify,
206
+ progress=line)
207
+ try:
208
+ result = convert_file(src, dst, mode=args.cmd, **kwargs)
209
+ finally:
210
+ if line is not None:
211
+ line.clear()
212
+ print(_describe(result))
213
+ except Exception as exc: # report and continue with the next file
214
+ failures += 1
215
+ print("%s: error: %s" % (src, exc), file=sys.stderr)
216
+ return 1 if failures else 0
217
+
218
+
219
+ if __name__ == "__main__":
220
+ sys.exit(main())