You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 lines
5.8 KiB

  1. """
  2. BSD 3-Clause License
  3. Copyright (c) 2017, Prem Seetharaman
  4. All rights reserved.
  5. * Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. * Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright notice, this
  10. list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. * Neither the name of the copyright holder nor the names of its
  13. contributors may be used to endorse or promote products derived from this
  14. software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  19. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  22. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. """
  26. import torch
  27. import numpy as np
  28. import torch.nn.functional as F
  29. from torch.autograd import Variable
  30. from scipy.signal import get_window
  31. from librosa.util import pad_center, tiny
  32. from audio_processing import window_sumsquare
  33. class STFT(torch.nn.Module):
  34. """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft"""
  35. def __init__(self, filter_length=800, hop_length=200, win_length=800,
  36. window='hann'):
  37. super(STFT, self).__init__()
  38. self.filter_length = filter_length
  39. self.hop_length = hop_length
  40. self.win_length = win_length
  41. self.window = window
  42. self.forward_transform = None
  43. scale = self.filter_length / self.hop_length
  44. fourier_basis = np.fft.fft(np.eye(self.filter_length))
  45. cutoff = int((self.filter_length / 2 + 1))
  46. fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
  47. np.imag(fourier_basis[:cutoff, :])])
  48. forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
  49. inverse_basis = torch.FloatTensor(
  50. np.linalg.pinv(scale * fourier_basis).T[:, None, :])
  51. if window is not None:
  52. assert(filter_length >= win_length)
  53. # get window and zero center pad it to filter_length
  54. fft_window = get_window(window, win_length, fftbins=True)
  55. fft_window = pad_center(fft_window, filter_length)
  56. fft_window = torch.from_numpy(fft_window).float()
  57. # window the bases
  58. forward_basis *= fft_window
  59. inverse_basis *= fft_window
  60. self.register_buffer('forward_basis', forward_basis.float())
  61. self.register_buffer('inverse_basis', inverse_basis.float())
  62. def transform(self, input_data):
  63. num_batches = input_data.size(0)
  64. num_samples = input_data.size(1)
  65. self.num_samples = num_samples
  66. # similar to librosa, reflect-pad the input
  67. input_data = input_data.view(num_batches, 1, num_samples)
  68. input_data = F.pad(
  69. input_data.unsqueeze(1),
  70. (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0),
  71. mode='reflect')
  72. input_data = input_data.squeeze(1)
  73. forward_transform = F.conv1d(
  74. input_data,
  75. Variable(self.forward_basis, requires_grad=False),
  76. stride=self.hop_length,
  77. padding=0)
  78. cutoff = int((self.filter_length / 2) + 1)
  79. real_part = forward_transform[:, :cutoff, :]
  80. imag_part = forward_transform[:, cutoff:, :]
  81. magnitude = torch.sqrt(real_part**2 + imag_part**2)
  82. phase = torch.autograd.Variable(
  83. torch.atan2(imag_part.data, real_part.data))
  84. return magnitude, phase
  85. def inverse(self, magnitude, phase):
  86. recombine_magnitude_phase = torch.cat(
  87. [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1)
  88. inverse_transform = F.conv_transpose1d(
  89. recombine_magnitude_phase,
  90. Variable(self.inverse_basis, requires_grad=False),
  91. stride=self.hop_length,
  92. padding=0)
  93. if self.window is not None:
  94. window_sum = window_sumsquare(
  95. self.window, magnitude.size(-1), hop_length=self.hop_length,
  96. win_length=self.win_length, n_fft=self.filter_length,
  97. dtype=np.float32)
  98. # remove modulation effects
  99. approx_nonzero_indices = torch.from_numpy(
  100. np.where(window_sum > tiny(window_sum))[0])
  101. window_sum = torch.autograd.Variable(
  102. torch.from_numpy(window_sum), requires_grad=False)
  103. window_sum = window_sum.cuda() if magnitude.is_cuda else window_sum
  104. inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices]
  105. # scale by hop ratio
  106. inverse_transform *= float(self.filter_length) / self.hop_length
  107. inverse_transform = inverse_transform[:, :, int(self.filter_length/2):]
  108. inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):]
  109. return inverse_transform
  110. def forward(self, input_data):
  111. self.magnitude, self.phase = self.transform(input_data)
  112. reconstruction = self.inverse(self.magnitude, self.phase)
  113. return reconstruction