kaldi.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. import math
  2. from typing import Tuple
  3. import torch
  4. import torchaudio
  5. from torch import Tensor
  6. __all__ = [
  7. "get_mel_banks",
  8. "inverse_mel_scale",
  9. "inverse_mel_scale_scalar",
  10. "mel_scale",
  11. "mel_scale_scalar",
  12. "spectrogram",
  13. "fbank",
  14. "mfcc",
  15. "vtln_warp_freq",
  16. "vtln_warp_mel_freq",
  17. ]
  18. # numeric_limits<float>::epsilon() 1.1920928955078125e-07
  19. EPSILON = torch.tensor(torch.finfo(torch.float).eps)
  20. # 1 milliseconds = 0.001 seconds
  21. MILLISECONDS_TO_SECONDS = 0.001
  22. # window types
  23. HAMMING = "hamming"
  24. HANNING = "hanning"
  25. POVEY = "povey"
  26. RECTANGULAR = "rectangular"
  27. BLACKMAN = "blackman"
  28. WINDOWS = [HAMMING, HANNING, POVEY, RECTANGULAR, BLACKMAN]
  29. def _get_epsilon(device, dtype):
  30. return EPSILON.to(device=device, dtype=dtype)
  31. def _next_power_of_2(x: int) -> int:
  32. r"""Returns the smallest power of 2 that is greater than x"""
  33. return 1 if x == 0 else 2 ** (x - 1).bit_length()
  34. def _get_strided(waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool) -> Tensor:
  35. r"""Given a waveform (1D tensor of size ``num_samples``), it returns a 2D tensor (m, ``window_size``)
  36. representing how the window is shifted along the waveform. Each row is a frame.
  37. Args:
  38. waveform (Tensor): Tensor of size ``num_samples``
  39. window_size (int): Frame length
  40. window_shift (int): Frame shift
  41. snip_edges (bool): If True, end effects will be handled by outputting only frames that completely fit
  42. in the file, and the number of frames depends on the frame_length. If False, the number of frames
  43. depends only on the frame_shift, and we reflect the data at the ends.
  44. Returns:
  45. Tensor: 2D tensor of size (m, ``window_size``) where each row is a frame
  46. """
  47. assert waveform.dim() == 1
  48. num_samples = waveform.size(0)
  49. strides = (window_shift * waveform.stride(0), waveform.stride(0))
  50. if snip_edges:
  51. if num_samples < window_size:
  52. return torch.empty((0, 0), dtype=waveform.dtype, device=waveform.device)
  53. else:
  54. m = 1 + (num_samples - window_size) // window_shift
  55. else:
  56. reversed_waveform = torch.flip(waveform, [0])
  57. m = (num_samples + (window_shift // 2)) // window_shift
  58. pad = window_size // 2 - window_shift // 2
  59. pad_right = reversed_waveform
  60. if pad > 0:
  61. # torch.nn.functional.pad returns [2,1,0,1,2] for 'reflect'
  62. # but we want [2, 1, 0, 0, 1, 2]
  63. pad_left = reversed_waveform[-pad:]
  64. waveform = torch.cat((pad_left, waveform, pad_right), dim=0)
  65. else:
  66. # pad is negative so we want to trim the waveform at the front
  67. waveform = torch.cat((waveform[-pad:], pad_right), dim=0)
  68. sizes = (m, window_size)
  69. return waveform.as_strided(sizes, strides)
  70. def _feature_window_function(
  71. window_type: str,
  72. window_size: int,
  73. blackman_coeff: float,
  74. device: torch.device,
  75. dtype: int,
  76. ) -> Tensor:
  77. r"""Returns a window function with the given type and size"""
  78. if window_type == HANNING:
  79. return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype)
  80. elif window_type == HAMMING:
  81. return torch.hamming_window(window_size, periodic=False, alpha=0.54, beta=0.46, device=device, dtype=dtype)
  82. elif window_type == POVEY:
  83. # like hanning but goes to zero at edges
  84. return torch.hann_window(window_size, periodic=False, device=device, dtype=dtype).pow(0.85)
  85. elif window_type == RECTANGULAR:
  86. return torch.ones(window_size, device=device, dtype=dtype)
  87. elif window_type == BLACKMAN:
  88. a = 2 * math.pi / (window_size - 1)
  89. window_function = torch.arange(window_size, device=device, dtype=dtype)
  90. # can't use torch.blackman_window as they use different coefficients
  91. return (
  92. blackman_coeff
  93. - 0.5 * torch.cos(a * window_function)
  94. + (0.5 - blackman_coeff) * torch.cos(2 * a * window_function)
  95. ).to(device=device, dtype=dtype)
  96. else:
  97. raise Exception("Invalid window type " + window_type)
  98. def _get_log_energy(strided_input: Tensor, epsilon: Tensor, energy_floor: float) -> Tensor:
  99. r"""Returns the log energy of size (m) for a strided_input (m,*)"""
  100. device, dtype = strided_input.device, strided_input.dtype
  101. log_energy = torch.max(strided_input.pow(2).sum(1), epsilon).log() # size (m)
  102. if energy_floor == 0.0:
  103. return log_energy
  104. return torch.max(log_energy, torch.tensor(math.log(energy_floor), device=device, dtype=dtype))
  105. def _get_waveform_and_window_properties(
  106. waveform: Tensor,
  107. channel: int,
  108. sample_frequency: float,
  109. frame_shift: float,
  110. frame_length: float,
  111. round_to_power_of_two: bool,
  112. preemphasis_coefficient: float,
  113. ) -> Tuple[Tensor, int, int, int]:
  114. r"""Gets the waveform and window properties"""
  115. channel = max(channel, 0)
  116. assert channel < waveform.size(0), "Invalid channel {} for size {}".format(channel, waveform.size(0))
  117. waveform = waveform[channel, :] # size (n)
  118. window_shift = int(sample_frequency * frame_shift * MILLISECONDS_TO_SECONDS)
  119. window_size = int(sample_frequency * frame_length * MILLISECONDS_TO_SECONDS)
  120. padded_window_size = _next_power_of_2(window_size) if round_to_power_of_two else window_size
  121. assert 2 <= window_size <= len(waveform), "choose a window size {} that is [2, {}]".format(
  122. window_size, len(waveform)
  123. )
  124. assert 0 < window_shift, "`window_shift` must be greater than 0"
  125. assert padded_window_size % 2 == 0, (
  126. "the padded `window_size` must be divisible by two." " use `round_to_power_of_two` or change `frame_length`"
  127. )
  128. assert 0.0 <= preemphasis_coefficient <= 1.0, "`preemphasis_coefficient` must be between [0,1]"
  129. assert sample_frequency > 0, "`sample_frequency` must be greater than zero"
  130. return waveform, window_shift, window_size, padded_window_size
  131. def _get_window(
  132. waveform: Tensor,
  133. padded_window_size: int,
  134. window_size: int,
  135. window_shift: int,
  136. window_type: str,
  137. blackman_coeff: float,
  138. snip_edges: bool,
  139. raw_energy: bool,
  140. energy_floor: float,
  141. dither: float,
  142. remove_dc_offset: bool,
  143. preemphasis_coefficient: float,
  144. ) -> Tuple[Tensor, Tensor]:
  145. r"""Gets a window and its log energy
  146. Returns:
  147. (Tensor, Tensor): strided_input of size (m, ``padded_window_size``) and signal_log_energy of size (m)
  148. """
  149. device, dtype = waveform.device, waveform.dtype
  150. epsilon = _get_epsilon(device, dtype)
  151. # size (m, window_size)
  152. strided_input = _get_strided(waveform, window_size, window_shift, snip_edges)
  153. if dither != 0.0:
  154. # Returns a random number strictly between 0 and 1
  155. x = torch.max(epsilon, torch.rand(strided_input.shape, device=device, dtype=dtype))
  156. rand_gauss = torch.sqrt(-2 * x.log()) * torch.cos(2 * math.pi * x)
  157. strided_input = strided_input + rand_gauss * dither
  158. if remove_dc_offset:
  159. # Subtract each row/frame by its mean
  160. row_means = torch.mean(strided_input, dim=1).unsqueeze(1) # size (m, 1)
  161. strided_input = strided_input - row_means
  162. if raw_energy:
  163. # Compute the log energy of each row/frame before applying preemphasis and
  164. # window function
  165. signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
  166. if preemphasis_coefficient != 0.0:
  167. # strided_input[i,j] -= preemphasis_coefficient * strided_input[i, max(0, j-1)] for all i,j
  168. offset_strided_input = torch.nn.functional.pad(strided_input.unsqueeze(0), (1, 0), mode="replicate").squeeze(
  169. 0
  170. ) # size (m, window_size + 1)
  171. strided_input = strided_input - preemphasis_coefficient * offset_strided_input[:, :-1]
  172. # Apply window_function to each row/frame
  173. window_function = _feature_window_function(window_type, window_size, blackman_coeff, device, dtype).unsqueeze(
  174. 0
  175. ) # size (1, window_size)
  176. strided_input = strided_input * window_function # size (m, window_size)
  177. # Pad columns with zero until we reach size (m, padded_window_size)
  178. if padded_window_size != window_size:
  179. padding_right = padded_window_size - window_size
  180. strided_input = torch.nn.functional.pad(
  181. strided_input.unsqueeze(0), (0, padding_right), mode="constant", value=0
  182. ).squeeze(0)
  183. # Compute energy after window function (not the raw one)
  184. if not raw_energy:
  185. signal_log_energy = _get_log_energy(strided_input, epsilon, energy_floor) # size (m)
  186. return strided_input, signal_log_energy
  187. def _subtract_column_mean(tensor: Tensor, subtract_mean: bool) -> Tensor:
  188. # subtracts the column mean of the tensor size (m, n) if subtract_mean=True
  189. # it returns size (m, n)
  190. if subtract_mean:
  191. col_means = torch.mean(tensor, dim=0).unsqueeze(0)
  192. tensor = tensor - col_means
  193. return tensor
  194. def spectrogram(
  195. waveform: Tensor,
  196. blackman_coeff: float = 0.42,
  197. channel: int = -1,
  198. dither: float = 0.0,
  199. energy_floor: float = 1.0,
  200. frame_length: float = 25.0,
  201. frame_shift: float = 10.0,
  202. min_duration: float = 0.0,
  203. preemphasis_coefficient: float = 0.97,
  204. raw_energy: bool = True,
  205. remove_dc_offset: bool = True,
  206. round_to_power_of_two: bool = True,
  207. sample_frequency: float = 16000.0,
  208. snip_edges: bool = True,
  209. subtract_mean: bool = False,
  210. window_type: str = POVEY,
  211. ) -> Tensor:
  212. r"""Create a spectrogram from a raw audio signal. This matches the input/output of Kaldi's
  213. compute-spectrogram-feats.
  214. Args:
  215. waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
  216. blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
  217. channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
  218. dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
  219. the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
  220. energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
  221. this floor is applied to the zeroth component, representing the total signal energy. The floor on the
  222. individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
  223. frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
  224. frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
  225. min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
  226. preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
  227. raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
  228. remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
  229. round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
  230. to FFT. (Default: ``True``)
  231. sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
  232. specified there) (Default: ``16000.0``)
  233. snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
  234. in the file, and the number of frames depends on the frame_length. If False, the number of frames
  235. depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
  236. subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
  237. it this way. (Default: ``False``)
  238. window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
  239. (Default: ``'povey'``)
  240. Returns:
  241. Tensor: A spectrogram identical to what Kaldi would output. The shape is
  242. (m, ``padded_window_size // 2 + 1``) where m is calculated in _get_strided
  243. """
  244. device, dtype = waveform.device, waveform.dtype
  245. epsilon = _get_epsilon(device, dtype)
  246. waveform, window_shift, window_size, padded_window_size = _get_waveform_and_window_properties(
  247. waveform, channel, sample_frequency, frame_shift, frame_length, round_to_power_of_two, preemphasis_coefficient
  248. )
  249. if len(waveform) < min_duration * sample_frequency:
  250. # signal is too short
  251. return torch.empty(0)
  252. strided_input, signal_log_energy = _get_window(
  253. waveform,
  254. padded_window_size,
  255. window_size,
  256. window_shift,
  257. window_type,
  258. blackman_coeff,
  259. snip_edges,
  260. raw_energy,
  261. energy_floor,
  262. dither,
  263. remove_dc_offset,
  264. preemphasis_coefficient,
  265. )
  266. # size (m, padded_window_size // 2 + 1, 2)
  267. fft = torch.fft.rfft(strided_input)
  268. # Convert the FFT into a power spectrum
  269. power_spectrum = torch.max(fft.abs().pow(2.0), epsilon).log() # size (m, padded_window_size // 2 + 1)
  270. power_spectrum[:, 0] = signal_log_energy
  271. power_spectrum = _subtract_column_mean(power_spectrum, subtract_mean)
  272. return power_spectrum
  273. def inverse_mel_scale_scalar(mel_freq: float) -> float:
  274. return 700.0 * (math.exp(mel_freq / 1127.0) - 1.0)
  275. def inverse_mel_scale(mel_freq: Tensor) -> Tensor:
  276. return 700.0 * ((mel_freq / 1127.0).exp() - 1.0)
  277. def mel_scale_scalar(freq: float) -> float:
  278. return 1127.0 * math.log(1.0 + freq / 700.0)
  279. def mel_scale(freq: Tensor) -> Tensor:
  280. return 1127.0 * (1.0 + freq / 700.0).log()
  281. def vtln_warp_freq(
  282. vtln_low_cutoff: float,
  283. vtln_high_cutoff: float,
  284. low_freq: float,
  285. high_freq: float,
  286. vtln_warp_factor: float,
  287. freq: Tensor,
  288. ) -> Tensor:
  289. r"""This computes a VTLN warping function that is not the same as HTK's one,
  290. but has similar inputs (this function has the advantage of never producing
  291. empty bins).
  292. This function computes a warp function F(freq), defined between low_freq
  293. and high_freq inclusive, with the following properties:
  294. F(low_freq) == low_freq
  295. F(high_freq) == high_freq
  296. The function is continuous and piecewise linear with two inflection
  297. points.
  298. The lower inflection point (measured in terms of the unwarped
  299. frequency) is at frequency l, determined as described below.
  300. The higher inflection point is at a frequency h, determined as
  301. described below.
  302. If l <= f <= h, then F(f) = f/vtln_warp_factor.
  303. If the higher inflection point (measured in terms of the unwarped
  304. frequency) is at h, then max(h, F(h)) == vtln_high_cutoff.
  305. Since (by the last point) F(h) == h/vtln_warp_factor, then
  306. max(h, h/vtln_warp_factor) == vtln_high_cutoff, so
  307. h = vtln_high_cutoff / max(1, 1/vtln_warp_factor).
  308. = vtln_high_cutoff * min(1, vtln_warp_factor).
  309. If the lower inflection point (measured in terms of the unwarped
  310. frequency) is at l, then min(l, F(l)) == vtln_low_cutoff
  311. This implies that l = vtln_low_cutoff / min(1, 1/vtln_warp_factor)
  312. = vtln_low_cutoff * max(1, vtln_warp_factor)
  313. Args:
  314. vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
  315. vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
  316. low_freq (float): Lower frequency cutoffs in mel computation
  317. high_freq (float): Upper frequency cutoffs in mel computation
  318. vtln_warp_factor (float): Vtln warp factor
  319. freq (Tensor): given frequency in Hz
  320. Returns:
  321. Tensor: Freq after vtln warp
  322. """
  323. assert vtln_low_cutoff > low_freq, "be sure to set the vtln_low option higher than low_freq"
  324. assert vtln_high_cutoff < high_freq, "be sure to set the vtln_high option lower than high_freq [or negative]"
  325. l = vtln_low_cutoff * max(1.0, vtln_warp_factor)
  326. h = vtln_high_cutoff * min(1.0, vtln_warp_factor)
  327. scale = 1.0 / vtln_warp_factor
  328. Fl = scale * l # F(l)
  329. Fh = scale * h # F(h)
  330. assert l > low_freq and h < high_freq
  331. # slope of left part of the 3-piece linear function
  332. scale_left = (Fl - low_freq) / (l - low_freq)
  333. # [slope of center part is just "scale"]
  334. # slope of right part of the 3-piece linear function
  335. scale_right = (high_freq - Fh) / (high_freq - h)
  336. res = torch.empty_like(freq)
  337. outside_low_high_freq = torch.lt(freq, low_freq) | torch.gt(freq, high_freq) # freq < low_freq || freq > high_freq
  338. before_l = torch.lt(freq, l) # freq < l
  339. before_h = torch.lt(freq, h) # freq < h
  340. after_h = torch.ge(freq, h) # freq >= h
  341. # order of operations matter here (since there is overlapping frequency regions)
  342. res[after_h] = high_freq + scale_right * (freq[after_h] - high_freq)
  343. res[before_h] = scale * freq[before_h]
  344. res[before_l] = low_freq + scale_left * (freq[before_l] - low_freq)
  345. res[outside_low_high_freq] = freq[outside_low_high_freq]
  346. return res
  347. def vtln_warp_mel_freq(
  348. vtln_low_cutoff: float,
  349. vtln_high_cutoff: float,
  350. low_freq,
  351. high_freq: float,
  352. vtln_warp_factor: float,
  353. mel_freq: Tensor,
  354. ) -> Tensor:
  355. r"""
  356. Args:
  357. vtln_low_cutoff (float): Lower frequency cutoffs for VTLN
  358. vtln_high_cutoff (float): Upper frequency cutoffs for VTLN
  359. low_freq (float): Lower frequency cutoffs in mel computation
  360. high_freq (float): Upper frequency cutoffs in mel computation
  361. vtln_warp_factor (float): Vtln warp factor
  362. mel_freq (Tensor): Given frequency in Mel
  363. Returns:
  364. Tensor: ``mel_freq`` after vtln warp
  365. """
  366. return mel_scale(
  367. vtln_warp_freq(
  368. vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq, vtln_warp_factor, inverse_mel_scale(mel_freq)
  369. )
  370. )
  371. def get_mel_banks(
  372. num_bins: int,
  373. window_length_padded: int,
  374. sample_freq: float,
  375. low_freq: float,
  376. high_freq: float,
  377. vtln_low: float,
  378. vtln_high: float,
  379. vtln_warp_factor: float,
  380. ) -> Tuple[Tensor, Tensor]:
  381. """
  382. Returns:
  383. (Tensor, Tensor): The tuple consists of ``bins`` (which is
  384. melbank of size (``num_bins``, ``num_fft_bins``)) and ``center_freqs`` (which is
  385. center frequencies of bins of size (``num_bins``)).
  386. """
  387. assert num_bins > 3, "Must have at least 3 mel bins"
  388. assert window_length_padded % 2 == 0
  389. num_fft_bins = window_length_padded / 2
  390. nyquist = 0.5 * sample_freq
  391. if high_freq <= 0.0:
  392. high_freq += nyquist
  393. assert (
  394. (0.0 <= low_freq < nyquist) and (0.0 < high_freq <= nyquist) and (low_freq < high_freq)
  395. ), "Bad values in options: low-freq {} and high-freq {} vs. nyquist {}".format(low_freq, high_freq, nyquist)
  396. # fft-bin width [think of it as Nyquist-freq / half-window-length]
  397. fft_bin_width = sample_freq / window_length_padded
  398. mel_low_freq = mel_scale_scalar(low_freq)
  399. mel_high_freq = mel_scale_scalar(high_freq)
  400. # divide by num_bins+1 in next line because of end-effects where the bins
  401. # spread out to the sides.
  402. mel_freq_delta = (mel_high_freq - mel_low_freq) / (num_bins + 1)
  403. if vtln_high < 0.0:
  404. vtln_high += nyquist
  405. assert vtln_warp_factor == 1.0 or (
  406. (low_freq < vtln_low < high_freq) and (0.0 < vtln_high < high_freq) and (vtln_low < vtln_high)
  407. ), "Bad values in options: vtln-low {} and vtln-high {}, versus " "low-freq {} and high-freq {}".format(
  408. vtln_low, vtln_high, low_freq, high_freq
  409. )
  410. bin = torch.arange(num_bins).unsqueeze(1)
  411. left_mel = mel_low_freq + bin * mel_freq_delta # size(num_bins, 1)
  412. center_mel = mel_low_freq + (bin + 1.0) * mel_freq_delta # size(num_bins, 1)
  413. right_mel = mel_low_freq + (bin + 2.0) * mel_freq_delta # size(num_bins, 1)
  414. if vtln_warp_factor != 1.0:
  415. left_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, left_mel)
  416. center_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, center_mel)
  417. right_mel = vtln_warp_mel_freq(vtln_low, vtln_high, low_freq, high_freq, vtln_warp_factor, right_mel)
  418. center_freqs = inverse_mel_scale(center_mel) # size (num_bins)
  419. # size(1, num_fft_bins)
  420. mel = mel_scale(fft_bin_width * torch.arange(num_fft_bins)).unsqueeze(0)
  421. # size (num_bins, num_fft_bins)
  422. up_slope = (mel - left_mel) / (center_mel - left_mel)
  423. down_slope = (right_mel - mel) / (right_mel - center_mel)
  424. if vtln_warp_factor == 1.0:
  425. # left_mel < center_mel < right_mel so we can min the two slopes and clamp negative values
  426. bins = torch.max(torch.zeros(1), torch.min(up_slope, down_slope))
  427. else:
  428. # warping can move the order of left_mel, center_mel, right_mel anywhere
  429. bins = torch.zeros_like(up_slope)
  430. up_idx = torch.gt(mel, left_mel) & torch.le(mel, center_mel) # left_mel < mel <= center_mel
  431. down_idx = torch.gt(mel, center_mel) & torch.lt(mel, right_mel) # center_mel < mel < right_mel
  432. bins[up_idx] = up_slope[up_idx]
  433. bins[down_idx] = down_slope[down_idx]
  434. return bins, center_freqs
  435. def fbank(
  436. waveform: Tensor,
  437. blackman_coeff: float = 0.42,
  438. channel: int = -1,
  439. dither: float = 0.0,
  440. energy_floor: float = 1.0,
  441. frame_length: float = 25.0,
  442. frame_shift: float = 10.0,
  443. high_freq: float = 0.0,
  444. htk_compat: bool = False,
  445. low_freq: float = 20.0,
  446. min_duration: float = 0.0,
  447. num_mel_bins: int = 23,
  448. preemphasis_coefficient: float = 0.97,
  449. raw_energy: bool = True,
  450. remove_dc_offset: bool = True,
  451. round_to_power_of_two: bool = True,
  452. sample_frequency: float = 16000.0,
  453. snip_edges: bool = True,
  454. subtract_mean: bool = False,
  455. use_energy: bool = False,
  456. use_log_fbank: bool = True,
  457. use_power: bool = True,
  458. vtln_high: float = -500.0,
  459. vtln_low: float = 100.0,
  460. vtln_warp: float = 1.0,
  461. window_type: str = POVEY,
  462. ) -> Tensor:
  463. r"""Create a fbank from a raw audio signal. This matches the input/output of Kaldi's
  464. compute-fbank-feats.
  465. Args:
  466. waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
  467. blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
  468. channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
  469. dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
  470. the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
  471. energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
  472. this floor is applied to the zeroth component, representing the total signal energy. The floor on the
  473. individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
  474. frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
  475. frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
  476. high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
  477. (Default: ``0.0``)
  478. htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible features
  479. (need to change other parameters). (Default: ``False``)
  480. low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
  481. min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
  482. num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
  483. preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
  484. raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
  485. remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
  486. round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
  487. to FFT. (Default: ``True``)
  488. sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
  489. specified there) (Default: ``16000.0``)
  490. snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
  491. in the file, and the number of frames depends on the frame_length. If False, the number of frames
  492. depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
  493. subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
  494. it this way. (Default: ``False``)
  495. use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
  496. use_log_fbank (bool, optional):If true, produce log-filterbank, else produce linear. (Default: ``True``)
  497. use_power (bool, optional): If true, use power, else use magnitude. (Default: ``True``)
  498. vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
  499. negative, offset from high-mel-freq (Default: ``-500.0``)
  500. vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
  501. vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
  502. window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
  503. (Default: ``'povey'``)
  504. Returns:
  505. Tensor: A fbank identical to what Kaldi would output. The shape is (m, ``num_mel_bins + use_energy``)
  506. where m is calculated in _get_strided
  507. """
  508. device, dtype = waveform.device, waveform.dtype
  509. waveform, window_shift, window_size, padded_window_size = _get_waveform_and_window_properties(
  510. waveform, channel, sample_frequency, frame_shift, frame_length, round_to_power_of_two, preemphasis_coefficient
  511. )
  512. if len(waveform) < min_duration * sample_frequency:
  513. # signal is too short
  514. return torch.empty(0, device=device, dtype=dtype)
  515. # strided_input, size (m, padded_window_size) and signal_log_energy, size (m)
  516. strided_input, signal_log_energy = _get_window(
  517. waveform,
  518. padded_window_size,
  519. window_size,
  520. window_shift,
  521. window_type,
  522. blackman_coeff,
  523. snip_edges,
  524. raw_energy,
  525. energy_floor,
  526. dither,
  527. remove_dc_offset,
  528. preemphasis_coefficient,
  529. )
  530. # size (m, padded_window_size // 2 + 1)
  531. spectrum = torch.fft.rfft(strided_input).abs()
  532. if use_power:
  533. spectrum = spectrum.pow(2.0)
  534. # size (num_mel_bins, padded_window_size // 2)
  535. mel_energies, _ = get_mel_banks(
  536. num_mel_bins, padded_window_size, sample_frequency, low_freq, high_freq, vtln_low, vtln_high, vtln_warp
  537. )
  538. mel_energies = mel_energies.to(device=device, dtype=dtype)
  539. # pad right column with zeros and add dimension, size (num_mel_bins, padded_window_size // 2 + 1)
  540. mel_energies = torch.nn.functional.pad(mel_energies, (0, 1), mode="constant", value=0)
  541. # sum with mel fiterbanks over the power spectrum, size (m, num_mel_bins)
  542. mel_energies = torch.mm(spectrum, mel_energies.T)
  543. if use_log_fbank:
  544. # avoid log of zero (which should be prevented anyway by dithering)
  545. mel_energies = torch.max(mel_energies, _get_epsilon(device, dtype)).log()
  546. # if use_energy then add it as the last column for htk_compat == true else first column
  547. if use_energy:
  548. signal_log_energy = signal_log_energy.unsqueeze(1) # size (m, 1)
  549. # returns size (m, num_mel_bins + 1)
  550. if htk_compat:
  551. mel_energies = torch.cat((mel_energies, signal_log_energy), dim=1)
  552. else:
  553. mel_energies = torch.cat((signal_log_energy, mel_energies), dim=1)
  554. mel_energies = _subtract_column_mean(mel_energies, subtract_mean)
  555. return mel_energies
  556. def _get_dct_matrix(num_ceps: int, num_mel_bins: int) -> Tensor:
  557. # returns a dct matrix of size (num_mel_bins, num_ceps)
  558. # size (num_mel_bins, num_mel_bins)
  559. dct_matrix = torchaudio.functional.create_dct(num_mel_bins, num_mel_bins, "ortho")
  560. # kaldi expects the first cepstral to be weighted sum of factor sqrt(1/num_mel_bins)
  561. # this would be the first column in the dct_matrix for torchaudio as it expects a
  562. # right multiply (which would be the first column of the kaldi's dct_matrix as kaldi
  563. # expects a left multiply e.g. dct_matrix * vector).
  564. dct_matrix[:, 0] = math.sqrt(1 / float(num_mel_bins))
  565. dct_matrix = dct_matrix[:, :num_ceps]
  566. return dct_matrix
  567. def _get_lifter_coeffs(num_ceps: int, cepstral_lifter: float) -> Tensor:
  568. # returns size (num_ceps)
  569. # Compute liftering coefficients (scaling on cepstral coeffs)
  570. # coeffs are numbered slightly differently from HTK: the zeroth index is C0, which is not affected.
  571. i = torch.arange(num_ceps)
  572. return 1.0 + 0.5 * cepstral_lifter * torch.sin(math.pi * i / cepstral_lifter)
  573. def mfcc(
  574. waveform: Tensor,
  575. blackman_coeff: float = 0.42,
  576. cepstral_lifter: float = 22.0,
  577. channel: int = -1,
  578. dither: float = 0.0,
  579. energy_floor: float = 1.0,
  580. frame_length: float = 25.0,
  581. frame_shift: float = 10.0,
  582. high_freq: float = 0.0,
  583. htk_compat: bool = False,
  584. low_freq: float = 20.0,
  585. num_ceps: int = 13,
  586. min_duration: float = 0.0,
  587. num_mel_bins: int = 23,
  588. preemphasis_coefficient: float = 0.97,
  589. raw_energy: bool = True,
  590. remove_dc_offset: bool = True,
  591. round_to_power_of_two: bool = True,
  592. sample_frequency: float = 16000.0,
  593. snip_edges: bool = True,
  594. subtract_mean: bool = False,
  595. use_energy: bool = False,
  596. vtln_high: float = -500.0,
  597. vtln_low: float = 100.0,
  598. vtln_warp: float = 1.0,
  599. window_type: str = POVEY,
  600. ) -> Tensor:
  601. r"""Create a mfcc from a raw audio signal. This matches the input/output of Kaldi's
  602. compute-mfcc-feats.
  603. Args:
  604. waveform (Tensor): Tensor of audio of size (c, n) where c is in the range [0,2)
  605. blackman_coeff (float, optional): Constant coefficient for generalized Blackman window. (Default: ``0.42``)
  606. cepstral_lifter (float, optional): Constant that controls scaling of MFCCs (Default: ``22.0``)
  607. channel (int, optional): Channel to extract (-1 -> expect mono, 0 -> left, 1 -> right) (Default: ``-1``)
  608. dither (float, optional): Dithering constant (0.0 means no dither). If you turn this off, you should set
  609. the energy_floor option, e.g. to 1.0 or 0.1 (Default: ``0.0``)
  610. energy_floor (float, optional): Floor on energy (absolute, not relative) in Spectrogram computation. Caution:
  611. this floor is applied to the zeroth component, representing the total signal energy. The floor on the
  612. individual spectrogram elements is fixed at std::numeric_limits<float>::epsilon(). (Default: ``1.0``)
  613. frame_length (float, optional): Frame length in milliseconds (Default: ``25.0``)
  614. frame_shift (float, optional): Frame shift in milliseconds (Default: ``10.0``)
  615. high_freq (float, optional): High cutoff frequency for mel bins (if <= 0, offset from Nyquist)
  616. (Default: ``0.0``)
  617. htk_compat (bool, optional): If true, put energy last. Warning: not sufficient to get HTK compatible
  618. features (need to change other parameters). (Default: ``False``)
  619. low_freq (float, optional): Low cutoff frequency for mel bins (Default: ``20.0``)
  620. num_ceps (int, optional): Number of cepstra in MFCC computation (including C0) (Default: ``13``)
  621. min_duration (float, optional): Minimum duration of segments to process (in seconds). (Default: ``0.0``)
  622. num_mel_bins (int, optional): Number of triangular mel-frequency bins (Default: ``23``)
  623. preemphasis_coefficient (float, optional): Coefficient for use in signal preemphasis (Default: ``0.97``)
  624. raw_energy (bool, optional): If True, compute energy before preemphasis and windowing (Default: ``True``)
  625. remove_dc_offset (bool, optional): Subtract mean from waveform on each frame (Default: ``True``)
  626. round_to_power_of_two (bool, optional): If True, round window size to power of two by zero-padding input
  627. to FFT. (Default: ``True``)
  628. sample_frequency (float, optional): Waveform data sample frequency (must match the waveform file, if
  629. specified there) (Default: ``16000.0``)
  630. snip_edges (bool, optional): If True, end effects will be handled by outputting only frames that completely fit
  631. in the file, and the number of frames depends on the frame_length. If False, the number of frames
  632. depends only on the frame_shift, and we reflect the data at the ends. (Default: ``True``)
  633. subtract_mean (bool, optional): Subtract mean of each feature file [CMS]; not recommended to do
  634. it this way. (Default: ``False``)
  635. use_energy (bool, optional): Add an extra dimension with energy to the FBANK output. (Default: ``False``)
  636. vtln_high (float, optional): High inflection point in piecewise linear VTLN warping function (if
  637. negative, offset from high-mel-freq (Default: ``-500.0``)
  638. vtln_low (float, optional): Low inflection point in piecewise linear VTLN warping function (Default: ``100.0``)
  639. vtln_warp (float, optional): Vtln warp factor (only applicable if vtln_map not specified) (Default: ``1.0``)
  640. window_type (str, optional): Type of window ('hamming'|'hanning'|'povey'|'rectangular'|'blackman')
  641. (Default: ``"povey"``)
  642. Returns:
  643. Tensor: A mfcc identical to what Kaldi would output. The shape is (m, ``num_ceps``)
  644. where m is calculated in _get_strided
  645. """
  646. assert num_ceps <= num_mel_bins, "num_ceps cannot be larger than num_mel_bins: %d vs %d" % (num_ceps, num_mel_bins)
  647. device, dtype = waveform.device, waveform.dtype
  648. # The mel_energies should not be squared (use_power=True), not have mean subtracted
  649. # (subtract_mean=False), and use log (use_log_fbank=True).
  650. # size (m, num_mel_bins + use_energy)
  651. feature = fbank(
  652. waveform=waveform,
  653. blackman_coeff=blackman_coeff,
  654. channel=channel,
  655. dither=dither,
  656. energy_floor=energy_floor,
  657. frame_length=frame_length,
  658. frame_shift=frame_shift,
  659. high_freq=high_freq,
  660. htk_compat=htk_compat,
  661. low_freq=low_freq,
  662. min_duration=min_duration,
  663. num_mel_bins=num_mel_bins,
  664. preemphasis_coefficient=preemphasis_coefficient,
  665. raw_energy=raw_energy,
  666. remove_dc_offset=remove_dc_offset,
  667. round_to_power_of_two=round_to_power_of_two,
  668. sample_frequency=sample_frequency,
  669. snip_edges=snip_edges,
  670. subtract_mean=False,
  671. use_energy=use_energy,
  672. use_log_fbank=True,
  673. use_power=True,
  674. vtln_high=vtln_high,
  675. vtln_low=vtln_low,
  676. vtln_warp=vtln_warp,
  677. window_type=window_type,
  678. )
  679. if use_energy:
  680. # size (m)
  681. signal_log_energy = feature[:, num_mel_bins if htk_compat else 0]
  682. # offset is 0 if htk_compat==True else 1
  683. mel_offset = int(not htk_compat)
  684. feature = feature[:, mel_offset : (num_mel_bins + mel_offset)]
  685. # size (num_mel_bins, num_ceps)
  686. dct_matrix = _get_dct_matrix(num_ceps, num_mel_bins).to(dtype=dtype, device=device)
  687. # size (m, num_ceps)
  688. feature = feature.matmul(dct_matrix)
  689. if cepstral_lifter != 0.0:
  690. # size (1, num_ceps)
  691. lifter_coeffs = _get_lifter_coeffs(num_ceps, cepstral_lifter).unsqueeze(0)
  692. feature *= lifter_coeffs.to(device=device, dtype=dtype)
  693. # if use_energy then replace the last column for htk_compat == true else first column
  694. if use_energy:
  695. feature[:, 0] = signal_log_energy
  696. if htk_compat:
  697. energy = feature[:, 0].unsqueeze(1) # size (m, 1)
  698. feature = feature[:, 1:] # size (m, num_ceps - 1)
  699. if not use_energy:
  700. # scale on C0 (actually removing a scale we previously added that's
  701. # part of one common definition of the cosine transform.)
  702. energy *= math.sqrt(2)
  703. feature = torch.cat((feature, energy), dim=1)
  704. feature = _subtract_column_mean(feature, subtract_mean)
  705. return feature