| 1 |
# Python-SoXR |
| 2 |
# https://github.com/dofuuz/python-soxr |
| 3 |
|
| 4 |
# SPDX-FileCopyrightText: (c) 2021 Myungchul Keum |
| 5 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 6 |
|
| 7 |
# High quality, one-dimensional sample-rate conversion library for Python. |
| 8 |
# Python-SoXR is a Python wrapper of libsoxr. |
| 9 |
|
| 10 |
import numpy as np |
| 11 |
from numpy.typing import ArrayLike |
| 12 |
|
| 13 |
from . import soxr_ext |
| 14 |
from .soxr_ext import QQ, LQ, MQ, HQ, VHQ |
| 15 |
from ._version import version as __version__ |
| 16 |
|
| 17 |
|
| 18 |
__libsoxr_version__ = soxr_ext.libsoxr_version() |
| 19 |
|
| 20 |
# libsoxr locates memory per each channel. |
| 21 |
# Too much channels will cause memory error. |
| 22 |
_CH_LIMIT = 65536 |
| 23 |
|
| 24 |
_DTYPE_UNMATCH_ERR_STR = 'Input should be a `np.ndarray` with matching dtype for ResampleStream({}).' |
| 25 |
_CH_EXEED_ERR_STR = 'Channel num({}) out of limit. Should be in [1, %d]' % _CH_LIMIT |
| 26 |
_DTYPE_ERR_STR = 'Data type must be one of [float32, float64, int16, int32], not {}' |
| 27 |
_QUALITY_ERR_STR = "Quality must be one of [QQ, LQ, MQ, HQ, VHQ]" |
| 28 |
|
| 29 |
_QUALITY_ENUM_DICT = { |
| 30 |
VHQ: VHQ, 'vhq': VHQ, 'soxr_vhq': VHQ, |
| 31 |
HQ: HQ, 'hq': HQ, 'soxr_hq': HQ, |
| 32 |
MQ: MQ, 'mq': MQ, 'soxr_mq': MQ, |
| 33 |
LQ: LQ, 'lq': LQ, 'soxr_lq': LQ, |
| 34 |
QQ: QQ, 'qq': QQ, 'soxr_qq': QQ, |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
def _quality_to_enum(q): |
| 39 |
if isinstance(q, str): |
| 40 |
q = q.lower() |
| 41 |
|
| 42 |
try: |
| 43 |
return _QUALITY_ENUM_DICT[q] |
| 44 |
except (KeyError, TypeError): |
| 45 |
raise ValueError(_QUALITY_ERR_STR) |
| 46 |
|
| 47 |
|
| 48 |
def _to_soxr_datatype(ntype): |
| 49 |
if ntype == np.float32: |
| 50 |
return soxr_ext.SOXR_FLOAT32_I |
| 51 |
elif ntype == np.float64: |
| 52 |
return soxr_ext.SOXR_FLOAT64_I |
| 53 |
elif ntype == np.int32: |
| 54 |
return soxr_ext.SOXR_INT32_I |
| 55 |
elif ntype == np.int16: |
| 56 |
return soxr_ext.SOXR_INT16_I |
| 57 |
else: |
| 58 |
raise TypeError(_DTYPE_ERR_STR.format(ntype)) |
| 59 |
|
| 60 |
|
| 61 |
class ResampleStream: |
| 62 |
""" Streaming resampler |
| 63 |
|
| 64 |
Use `ResampleStream` for real-time processing or very long signal. |
| 65 |
|
| 66 |
Parameters |
| 67 |
---------- |
| 68 |
in_rate : float |
| 69 |
Input sample-rate. |
| 70 |
out_rate : float |
| 71 |
Output sample-rate. |
| 72 |
num_channels : int |
| 73 |
Number of channels. |
| 74 |
dtype : type or str, optional |
| 75 |
Internal data type processed with. |
| 76 |
Should be one of float32, float64, int16, int32. |
| 77 |
quality : int or str, optional |
| 78 |
Quality setting. |
| 79 |
One of `QQ`, `LQ`, `MQ`, `HQ`, `VHQ`. |
| 80 |
""" |
| 81 |
|
| 82 |
def __init__(self, |
| 83 |
in_rate: float, out_rate: float, num_channels: int, |
| 84 |
dtype='float32', quality='HQ'): |
| 85 |
if in_rate <= 0 or out_rate <= 0: |
| 86 |
raise ValueError('Sample rate should be over 0') |
| 87 |
|
| 88 |
if num_channels < 1 or _CH_LIMIT < num_channels: |
| 89 |
raise ValueError(_CH_EXEED_ERR_STR.format(num_channels)) |
| 90 |
|
| 91 |
self._type = np.dtype(dtype) |
| 92 |
stype = _to_soxr_datatype(self._type) |
| 93 |
|
| 94 |
q = _quality_to_enum(quality) |
| 95 |
|
| 96 |
self._csoxr = soxr_ext.CSoxr(in_rate, out_rate, num_channels, stype, q) |
| 97 |
self._process = getattr(self._csoxr, f'process_{self._type}') |
| 98 |
|
| 99 |
def resample_chunk(self, x: np.ndarray, last=False) -> np.ndarray: |
| 100 |
""" Resample chunk with streaming resampler |
| 101 |
|
| 102 |
Parameters |
| 103 |
---------- |
| 104 |
x : np.ndarray |
| 105 |
Input array. Input can be mono(1D) or multi-channel(2D of [frame, channel]). |
| 106 |
dtype should match with constructor. |
| 107 |
|
| 108 |
last : bool, optional |
| 109 |
Set True at final chunk to flush last outputs. |
| 110 |
It should be `True` only once at the end of a continuous sequence. |
| 111 |
|
| 112 |
Returns |
| 113 |
------- |
| 114 |
np.ndarray |
| 115 |
Resampled data. |
| 116 |
Output is np.ndarray with same ndim with input. |
| 117 |
|
| 118 |
""" |
| 119 |
if type(x) != np.ndarray or x.dtype != self._type: |
| 120 |
raise TypeError(_DTYPE_UNMATCH_ERR_STR.format(self._type)) |
| 121 |
|
| 122 |
if x.ndim == 1: |
| 123 |
y = self._process(x[:, np.newaxis], last) |
| 124 |
return np.squeeze(y, axis=1) |
| 125 |
elif x.ndim == 2: |
| 126 |
return self._process(x, last) |
| 127 |
else: |
| 128 |
raise ValueError('Input must be 1-D or 2-D array') |
| 129 |
|
| 130 |
def num_clips(self) -> int: |
| 131 |
""" Clip counter. (for int I/O) |
| 132 |
|
| 133 |
Returns |
| 134 |
------- |
| 135 |
int |
| 136 |
Count of clipped samples. |
| 137 |
""" |
| 138 |
return self._csoxr.num_clips() |
| 139 |
|
| 140 |
def delay(self) -> float: |
| 141 |
""" Get current delay. |
| 142 |
|
| 143 |
SoXR output has an algorithmic delay. This function returns the length of current pending output. |
| 144 |
|
| 145 |
Returns |
| 146 |
------- |
| 147 |
float |
| 148 |
Current delay in output samples. |
| 149 |
""" |
| 150 |
return self._csoxr.delay() |
| 151 |
|
| 152 |
def clear(self) -> None: |
| 153 |
""" Reset resampler. Ready for fresh signal, same config. |
| 154 |
|
| 155 |
This can be used to save initialization time. |
| 156 |
""" |
| 157 |
self._csoxr.clear() |
| 158 |
|
| 159 |
|
| 160 |
def resample(x: ArrayLike, in_rate: float, out_rate: float, quality='HQ') -> np.ndarray: |
| 161 |
""" Resample signal |
| 162 |
|
| 163 |
Parameters |
| 164 |
---------- |
| 165 |
x : array_like |
| 166 |
Input array. Input can be mono(1D) or multi-channel(2D of [frame, channel]). |
| 167 |
If input is not `np.ndarray`, it will be converted to `np.ndarray(dtype='float32')`. |
| 168 |
Its dtype should be one of float32, float64, int16, int32. |
| 169 |
in_rate : float |
| 170 |
Input sample-rate. |
| 171 |
out_rate : float |
| 172 |
Output sample-rate. |
| 173 |
quality : int or str, optional |
| 174 |
Quality setting. |
| 175 |
One of `QQ`, `LQ`, `MQ`, `HQ`, `VHQ`. |
| 176 |
|
| 177 |
Returns |
| 178 |
------- |
| 179 |
np.ndarray |
| 180 |
Resampled data. |
| 181 |
Output is `np.ndarray` with same ndim and dtype with input. |
| 182 |
""" |
| 183 |
if in_rate <= 0 or out_rate <= 0: |
| 184 |
raise ValueError('Sample rate should be over 0') |
| 185 |
|
| 186 |
if type(x) != np.ndarray: |
| 187 |
x = np.asarray(x, dtype=np.float32) |
| 188 |
|
| 189 |
try: |
| 190 |
if x.strides[0] == x.itemsize: # split channel memory layout |
| 191 |
divide_proc = getattr(soxr_ext, f'csoxr_split_ch_{x.dtype}') |
| 192 |
else: |
| 193 |
divide_proc = getattr(soxr_ext, f'csoxr_divide_proc_{x.dtype}') |
| 194 |
except AttributeError: |
| 195 |
raise TypeError(_DTYPE_ERR_STR.format(x.dtype)) |
| 196 |
|
| 197 |
q = _quality_to_enum(quality) |
| 198 |
|
| 199 |
if x.ndim == 1: |
| 200 |
y = divide_proc(in_rate, out_rate, x[:, np.newaxis], q) |
| 201 |
return np.squeeze(y, axis=1) |
| 202 |
elif x.ndim == 2: |
| 203 |
num_channels = x.shape[1] |
| 204 |
if num_channels < 1 or _CH_LIMIT < num_channels: |
| 205 |
raise ValueError(_CH_EXEED_ERR_STR.format(num_channels)) |
| 206 |
|
| 207 |
return divide_proc(in_rate, out_rate, x, q) |
| 208 |
else: |
| 209 |
raise ValueError('Input must be 1-D or 2-D array') |
| 210 |
|
| 211 |
|
| 212 |
def _resample_oneshot(x: np.ndarray, in_rate: float, out_rate: float, quality='HQ') -> np.ndarray: |
| 213 |
""" |
| 214 |
Resample using libsoxr's `soxr_oneshot()`. Use `resample()` for general use. |
| 215 |
`soxr_oneshot()` becomes slow with long input. |
| 216 |
This function exists for test purpose. |
| 217 |
""" |
| 218 |
try: |
| 219 |
oneshot = getattr(soxr_ext, f'csoxr_oneshot_{x.dtype}') |
| 220 |
except AttributeError: |
| 221 |
raise TypeError(_DTYPE_ERR_STR.format(x.dtype)) |
| 222 |
|
| 223 |
if x.ndim == 1: |
| 224 |
y = oneshot(in_rate, out_rate, x[:, np.newaxis], _quality_to_enum(quality)) |
| 225 |
return np.squeeze(y, axis=1) |
| 226 |
|
| 227 |
return oneshot(in_rate, out_rate, x, _quality_to_enum(quality)) |