functional.py 41.9 KB
Newer Older
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
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math
from typing import List, Optional, Tuple, Union

import paddle
from paddle import Tensor

from .core import *
from .utils import ParameterError

EPS = 1e-10

__all_ = [
    'dft_matrix',
    'idft_matrix',
    'stft',
    'istft',
    'spectrogram',
    'melspectrogram',
    'complex_norm',
    'magphase',
    'mel_to_hz',
    'hz_to_mel',
    'mel_frequencies',
    'fft_frequencies',
    'compute_fbank_matrix',
    'get_window',
    'power_to_db',
    'enframe',
    'deframe',
    'mu_law_encode',
    'mu_law_decode',
    'random_masking',
    'random_cropping',
    'center_padding',
]


def _randint(n):
    """The helper function for computing randint.
    """
    return int(paddle.randint(n))


def complex_norm(x: Tensor) -> Tensor:
    """Compute compext norm of a given tensor.
    Typically, the input tensor is the result of a complex Fourier transform.
    Parameters:
62
        x(Tensor): The input tensor of shape (..., 2)
63 64 65

    Returns:
        The element-wised l2-norm of input complex tensor.
66 67 68 69 70 71 72 73 74 75
     Examples:

        .. code-block:: python

        x = paddle.rand((32, 16000))
        y = F.stft(x, n_fft=512)
        z = F.complex_norm(y)
        print(z.shape)
        >> [32, 257, 126]

76 77 78
    """
    if x.shape[-1] != 2:
        raise ParameterError(
79
            f'complex tensor must be of shape (..., 2), but received {x.shape} instead'
80 81 82 83 84 85 86 87
        )
    return paddle.sqrt(paddle.square(x).sum(axis=-1))


def magphase(x: Tensor) -> Tuple[Tensor, Tensor]:
    """Compute compext norm of a given tensor.
    Typically,the input tensor is the result of a complex Fourier transform.
    Parameters:
88
        x(Tensor): The input tensor of shape (..., 2).
89 90
    Returns:
        The tuple of magnitude and phase.
91 92 93 94 95 96 97 98 99 100 101 102 103 104

    Shape:
        x: the shape of x is arbitrary, with the shape of last axis being 2
        outputs: the shapes of magnitude and phase are both input.shape[:-1]

     Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = paddle.randn((10, 10, 2))
        angle, phase = F.magphase(x)

105 106 107
    """
    if x.shape[-1] != 2:
        raise ParameterError(
108
            f'complex tensor must be of shape (..., 2), but received {x.shape} instead'
109 110 111 112 113 114 115 116 117
        )
    mag = paddle.sqrt(paddle.square(x).sum(axis=-1))
    x0 = x.reshape((-1, 2))
    phase = paddle.atan2(x0[:, 0], x0[:, 1])
    phase = phase.reshape(x.shape[:-1])

    return mag, phase


118 119
def hz_to_mel(freq: Union[Tensor, float],
              htk: bool = False) -> Union[Tensor, float]:
120 121 122 123 124 125 126 127 128 129
    """Convert Hz to Mels.

    Parameters:
        freq: the input tensor of arbitrary shape, or a single floating point number.
        htk: use HTK formula to do the conversion.
            The default value is False.
    Returns:
        The frequencies represented in Mel-scale.
    Notes:
        This function is consistent with librosa.hz_to_mel().
130 131 132 133 134 135 136 137 138 139 140 141 142

     Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        print(F.hz_to_mel(10))
        >> 10
        print(F.hz_to_mel(paddle.to_tensor([0, 100, 1600])))
        >> Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [0., 1.50000000, 21.83624077])

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
    """

    if htk:
        if isinstance(freq, Tensor):
            return 2595.0 * paddle.log10(1.0 + freq / 700.0)
        else:
            return 2595.0 * math.log10(1.0 + freq / 700.0)

    # Fill in the linear part
    f_min = 0.0
    f_sp = 200.0 / 3

    mels = (freq - f_min) / f_sp

    # Fill in the log-scale part

    min_log_hz = 1000.0  # beginning of log region (Hz)
    min_log_mel = (min_log_hz - f_min) / f_sp  # same (Mels)
    logstep = math.log(6.4) / 27.0  # step size for log region

    if isinstance(freq, Tensor):
        target = min_log_mel + paddle.log(
            freq / min_log_hz + 1e-10) / logstep  # prevent nan with 1e-10
        mask = (freq > min_log_hz).astype('float32')
        mels = target * mask + mels * (
            1 - mask)  # will replace by masked_fill OP in future
    else:
        if freq >= min_log_hz:
            mels = min_log_mel + math.log(freq / min_log_hz + 1e-10) / logstep

    return mels


176 177
def mel_to_hz(mel: Union[float, Tensor],
              htk: bool = False) -> Union[float, Tensor]:
178 179 180 181 182 183 184 185 186
    """Convert mel bin numbers to frequencies.

    Parameters:
        mel: the mel frequency represented as a tensor of arbitrary shape, or a floating point number.
        htk: use HTK formula to do the conversion.
    Returns:
        The frequencies represented in hz.
    Notes:
        This function is consistent with librosa.mel_to_hz().
187 188 189 190 191 192 193 194 195 196 197 198 199

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        print(F.mel_to_hz(10))
        >> 666.6666666666667
        print(F.mel_to_hz(paddle.to_tensor([0, 1.0, 10.0])))
        >> Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [0., 66.66666412, 666.66662598])

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
    """
    if htk:
        return 700.0 * (10.0**(mel / 2595.0) - 1.0)

    f_min = 0.0
    f_sp = 200.0 / 3
    freqs = f_min + f_sp * mel
    # And now the nonlinear scale
    min_log_hz = 1000.0  # beginning of log region (Hz)
    min_log_mel = (min_log_hz - f_min) / f_sp  # same (Mels)
    logstep = math.log(6.4) / 27.0  # step size for log region
    if isinstance(mel, Tensor):
        target = min_log_hz * paddle.exp(logstep * (mel - min_log_mel))
        mask = (mel > min_log_mel).astype('float32')
        freqs = target * mask + freqs * (
            1 - mask)  # will replace by masked_fill OP in future
    else:
        if mel >= min_log_mel:
            freqs = min_log_hz * math.exp(logstep * (mel - min_log_mel))

    return freqs


def mel_frequencies(n_mels: int = 128,
                    f_min: float = 0.0,
                    f_max: float = 11025.0,
226
                    htk: bool = False) -> Tensor:
227 228 229 230 231 232 233 234 235
    """Compute mel frequencies.

    Parameters:
        n_mels(int): number of Mel bins.
        f_min(float): the lower cut-off frequency, below which the filter response is zero.
        f_max(float): the upper cut-off frequency, above which the filter response is zero.
        htk: whether to use htk formula.
    Returns:
        The frequencies represented in Mel-scale
236

237 238
    Notes:
        This function is consistent with librosa.mel_frequencies().
239 240 241 242 243 244 245 246 247 248 249 250

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        print(F.mel_frequencies(8))
        >> Tensor(shape=[8], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [0., 475.33898926, 950.67797852, 1551.68481445, 2533.36230469,
                4136.09960938, 6752.81396484, 11024.99902344])

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    """
    # 'Center freqs' of mel bands - uniformly spaced between limits
    min_mel = hz_to_mel(f_min, htk=htk)
    max_mel = hz_to_mel(f_max, htk=htk)
    mels = paddle.linspace(min_mel, max_mel, n_mels)
    freqs = mel_to_hz(mels, htk=htk)
    return freqs


def fft_frequencies(sr: int, n_fft: int) -> Tensor:
    """Compute fourier frequencies.

    Parameters:
        sr(int): the audio sample rate.
        n_fft(float): he number of fft bins.
    Returns:
        The frequencies represented in hz.
268 269 270 271 272 273 274 275 276 277 278
    Notes:
        This function is consistent with librosa.fft_frequencies().

    Examples:
        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        print(F.fft_frequencies(16000, 512))
        >> Tensor(shape=[257], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [0., 31.25000000, 62.50000000, ...]
279 280 281 282 283 284 285 286 287 288

    """
    return paddle.linspace(0, float(sr) / 2, int(1 + n_fft // 2))


def compute_fbank_matrix(sr: int,
                         n_fft: int,
                         n_mels: int = 128,
                         f_min: float = 0.0,
                         f_max: Optional[float] = None,
289
                         htk: bool = False) -> Tensor:
290 291 292 293 294 295 296 297 298 299 300 301 302
    """Compute fbank matrix.

    Parameters:
        sr(int): the audio sample rate.
        n_fft(int): the number of fft bins.
        n_mels(int): the number of Mel bins.
        f_min(float): the lower cut-off frequency, below which the filter response is zero.
        f_max(float): the upper cut-off frequency, above which the filter response is zero.
        htk: whether to use htk formula.
        return_complex(bool): whether to return complex matrix. If True, the matrix will
        be complex type. Otherwise, the real and image part will be stored in the last
        axis of returned tensor.
    Returns:
303 304 305
        The fbank matrix of shape (n_mels, int(1+n_fft//2)).
    Shape:
        output: (n_mels, int(1+n_fft//2))
306 307
    Notes:
        This function is consistent with librosa.filters.mel().
308 309 310 311 312 313 314 315 316 317 318

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        m = F.compute_fbank_matrix(16000, 512)
        print(m.shape)
        >>[128, 257]

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
    """

    if f_max is None:
        f_max = float(sr) / 2

    # Initialize the weights
    weights = paddle.zeros((n_mels, int(1 + n_fft // 2)), dtype='float32')

    # Center freqs of each FFT bin
    fftfreqs = fft_frequencies(sr=sr, n_fft=n_fft)

    # 'Center freqs' of mel bands - uniformly spaced between limits
    mel_f = mel_frequencies(n_mels + 2, f_min=f_min, f_max=f_max, htk=htk)

    fdiff = mel_f[1:] - mel_f[:-1]  #np.diff(mel_f)
    ramps = mel_f.unsqueeze(1) - fftfreqs.unsqueeze(0)
    #ramps = np.subtract.outer(mel_f, fftfreqs)

    for i in range(n_mels):
        # lower and upper slopes for all bins
        lower = -ramps[i] / fdiff[i]
        upper = ramps[i + 2] / fdiff[i + 1]

        # .. then intersect them with each other and zero
        weights[i] = paddle.maximum(paddle.zeros_like(lower),
                                    paddle.minimum(lower, upper))

    # Slaney-style mel is scaled to be approx constant energy per channel
    enorm = 2.0 / (mel_f[2:n_mels + 2] - mel_f[:n_mels])
    weights *= enorm.unsqueeze(1)

    return weights


def dft_matrix(n: int, return_complex: bool = False) -> Tensor:
    """Compute discrete Fourier transform matrix.

    Parameters:
        n(int): the size of dft matrix.
        return_complex(bool): whether to return complex matrix. If True, the matrix will
            be complex type. Otherwise, the real and image part will be stored in the last
            axis of returned tensor.
361 362 363
    Shape:
        output: [n, n] or [n,n,2]

364
    Returns:
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        Complex tensor of shape (n,n) if return_complex=True, and of shape (n,n,2) otherwise.

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        m = F.dft_matrix(512)
        print(m.shape)
        >> [512, 512, 2]
        m = F.dft_matrix(512, return_complex=True)
        print(m.shape)
        >> [512, 512]

380 381 382
    """
    x, y = paddle.meshgrid(paddle.arange(0, n), paddle.arange(0, n))
    z = x * y * (-2 * math.pi / n)
383 384
    cos = paddle.cos(z)
    sin = paddle.sin(z)
385 386
    if return_complex:
        return cos + paddle.to_tensor([1j]) * sin
387 388
    cos = cos.unsqueeze(-1)
    sin = sin.unsqueeze(-1)
389 390 391 392 393 394 395 396 397 398 399 400
    return paddle.concat([cos, sin], -1)


def idft_matrix(n: int, return_complex: bool = False) -> Tensor:
    """Compute inverse discrete Fourier transform matrix

    Parameters:
        n(int): the size of idft matrix.
        return_complex(bool): whether to return complex matrix. If True, the matrix will
            be complex type. Otherwise, the real and image part will be stored in the last
            axis of returned tensor.
    Returns:
401 402 403 404 405 406 407 408 409 410 411 412 413 414
        Complex tensor of shape (n,n) if return_complex=True, and of shape (n,n,2) otherwise.
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        m = F.dft_matrix(512)
        print(m.shape)
        >> [512, 512, 2]
        m = F.dft_matrix(512, return_complex=True)
        print(m.shape)
        >> [512, 512]

415 416 417 418
    """

    x, y = paddle.meshgrid(paddle.arange(0, n), paddle.arange(0, n))
    z = x * y * (2 * math.pi / n)
419 420
    cos = paddle.cos(z)
    sin = paddle.sin(z)
421 422
    if return_complex:
        return cos + paddle.to_tensor([1j]) * sin
423 424
    cos = cos.unsqueeze(-1)
    sin = sin.unsqueeze(-1)
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    return paddle.concat([cos, sin], -1)


def get_window(window: Union[str, Tuple[str, float]],
               win_length: int,
               fftbins: bool = True) -> Tensor:
    """Return a window of a given length and type.
    Parameters:
        window(str|(str,float)): the type of window to create.
        win_length(int): the number of samples in the window.
        fftbins(bool): If True, create a "periodic" window. Otherwise,
            create a "symmetric" window, for use in filter design.
    Returns:
       The window represented as a tensor.
    Notes:
        This functional is consistent with scipy.signal.get_window()
441 442 443 444 445 446 447 448 449 450
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        w = F.get_window('hann', win_length=128)
        print(w.shape)
        >> [128]

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
    """
    sym = not fftbins

    args = ()
    if isinstance(window, tuple):
        winstr = window[0]
        if len(window) > 1:
            args = window[1:]
    elif isinstance(window, str):
        if window in ['gaussian', 'exponential']:
            raise ValueError("The '" + window + "' window needs one or "
                             "more parameters -- pass a tuple.")
        else:
            winstr = window
    else:
        raise ValueError("%s as window type is not supported." %
                         str(type(window)))

    try:
        winfunc = eval(winstr + '_window')
    except KeyError as e:
        raise ValueError("Unknown window type.") from e

    params = (win_length, ) + args
    kwargs = {'sym': sym}
    return winfunc(*params, **kwargs)


def power_to_db(magnitude: Tensor,
                ref_value: float = 1.0,
                amin: float = 1e-10,
                top_db: Optional[float] = 80.0) -> Tensor:
    """Convert a power spectrogram (amplitude squared) to decibel (dB) units.
    The function computes the scaling ``10 * log10(x / ref)`` in a numerically
    stable way.

    Parameters:
        magnitude(Tensor): the input magnitude tensor of any shape.
        ref_value(float): the reference value. If smaller than 1.0, the db level
            of the signal will be pulled up accordingly. Otherwise, the db level
            is pushed down.
        amin(float): the minimum value of input magnitude, below which the input
            magnitude is clipped(to amin).
        top_db(float): the maximum db value of resulting spectrum, above which the
495
            spectrum is clipped(to top_db).
496 497
    Returns:
        The spectrogram in log-scale.
498 499 500
    shape:
        input: any shape
        output: same as input
501 502
    Notes:
        This function is consistent with librosa.power_to_db().
503 504 505 506 507 508 509 510 511 512 513
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        F.power_to_db(paddle.rand((10, 10)))
        >> Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [[-6.22858429, -3.51512218],
                [-0.38168561, -1.44466150]])

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    """
    if amin <= 0:
        raise ParameterError("amin must be strictly positive")

    if ref_value <= 0:
        raise ParameterError("ref_value must be strictly positive")

    ones = paddle.ones_like(magnitude)
    log_spec = 10.0 * paddle.log10(paddle.maximum(ones * amin, magnitude))
    log_spec -= 10.0 * math.log10(max(ref_value, amin))

    if top_db is not None:
        if top_db < 0:
            raise ParameterError("top_db must be non-negative")
        log_spec = paddle.maximum(log_spec, ones * (log_spec.max() - top_db))

    return log_spec


def mu_law_encode(x: Tensor, mu: int = 256, quantized: bool = True) -> Tensor:
    """Mu-law encoding.
    Compute the mu-law decoding given an input code.
    When quantized is True, the result will be converted to
    integer in range [0,mu-1]. Otherwise, the resulting signal
    is in range [-1,1]

    Parameters:
        x(Tensor): the input tensor of arbitrary shape to be encoded.
        mu(int): the maximum value (depth) of encoded signal. The signal will be
        clip to be in range [0,mu-1].
        quantized(bool): indicate whether the signal will quantized to integers.

546 547 548 549 550 551 552 553 554 555
    Examples:
        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        F.mu_law_encode(paddle.randn((2, 8)))
        >> Tensor(shape=[2, 8], dtype=int32, place=CUDAPlace(0), stop_gradient=True,
                [[0, 5, 30, 255, 255, 255, 12, 13],
                [0, 241, 8, 243, 7, 35, 84, 228]])

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    Reference:
        https://en.wikipedia.org/wiki/%CE%9C-law_algorithm
    """
    mu = mu - 1
    y = paddle.sign(x) * paddle.log1p(mu * paddle.abs(x)) / math.log1p(mu)
    if quantized:
        y = (y + 1) / 2 * mu + 0.5  # convert to [0 , mu-1]
        y = paddle.clip(y, min=0, max=mu).astype('int32')
    return y


def mu_law_decode(x: Tensor, mu: int = 256, quantized: bool = True) -> Tensor:
    """Mu-law decoding.
    Compute the mu-law decoding given an input code.

    Parameters:
        x(Tensor): the input tensor of arbitrary shape to be decoded.
        mu(int): the maximum value of encoded signal, which should be the
        same as that in mu_law_encode().

        quantized(bool): whether the signal has been quantized to integers.
        The value should be the same as that used in mu_law_encode()
578 579 580
    shape:
        input: any shape
        output: same as input
581 582 583

    Notes:
        This function assumes that the input x is in the
584 585 586 587 588 589 590 591 592 593 594 595 596 597
        range [0,mu-1] when quantize is True and [-1,1] otherwise.



    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        F.mu_law_decode(paddle.randint(0, 255, shape=(2, 8)))
        >> Tensor(shape=[2, 8], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [[0.00796641, -0.28048742, -0.13789690,  0.67482352, -0.05550348, -0.00377374,  0.64593655,  0.03134083],
                [0.45497340, -0.29312974,  0.29312995, -0.70499402,  0.51892924, -0.15078513,  0.07322186,  0.70499456]])
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624

    Reference:
        https://en.wikipedia.org/wiki/%CE%9C-law_algorithm
    """
    if mu < 1:
        raise ParameterError('mu is typically set as 2**k-1, k=1, 2, 3,...')

    mu = mu - 1
    if quantized:  # undo the quantization
        x = x * 2 / mu - 1
    x = paddle.sign(x) / mu * ((1 + mu)**paddle.abs(x) - 1)
    return x


def enframe(signal: Tensor, hop_length: int, win_length: int) -> Tensor:
    raise NotImplementedError()


def deframe(frames: Tensor,
            n_fft: int,
            hop_length: int,
            win_length: int,
            signal_length: Optional[int] = None):
    """Unpack audio frames into audio singal.
    The frames are typically the output of inverse STFT that needs to be converted back to audio signals.

    Parameters:
625
        frames(Tensor): the input audio frames of shape (N,n_fft,frame_number) or (n_fft,frame_number)
626 627 628 629 630 631 632 633 634 635 636 637 638
        The frames are typically obtained from the output of inverse STFT.
        n_fft(int): the number of fft bins, see paddleaudio.functional.stft()
        hop_length(int): the hop length, see paddleaudio.functional.stft()
        win_length(int): the window length, see paddleaudio.functional.stft()
        signal_length(int): the original signal length. If None, the resulting
        signal length is determined by hop_length*win_length. Otherwised, the signal is
        centrally cropped to signal_length.
    Returns:
        Tensor: the unpacked signal.
    Notes:
        This function is implemented by transposing and reshaping.

     Shape:
639 640 641 642 643 644 645 646 647 648 649 650 651 652
        - input:  (N,n_fft,frame_number] or (n_fft,frame_number)
        - output: ( N, signal_length)

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = paddle.rand((128, 200))
        x = F.deframe(x, n_fft=128, hop_length=64, win_length=200)
        print(x.shape)
        >> [128, 200]

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    """
    assert frames.ndim == 2 or frames.ndim == 3, (
        f'The input frame must be a 2-d or 3-d tensor, ' +
        f'but received ndim={frames.ndim} instead')
    if frames.ndim == 2:
        frames = frames.unsqueeze(0)
    assert n_fft == frames.shape[1], (
        f'n_fft must be the same as the frequency dimension of frames, ' +
        f'but received {n_fft}!={frames.shape[1]}')

    frame_num = frames.shape[-1]
    overlap = (win_length - hop_length) // 2
    signal = paddle.zeros((
        frames.shape[0],
        hop_length * frame_num,
    ))
    start = n_fft // 2 - win_length // 2
    signal = frames[:, start + overlap:start + win_length - overlap, :]
    signal = signal.transpose((0, 2, 1))
    signal = signal.reshape((frames.shape[0], -1))
    if signal_length is None or signal_length == signal.shape[-1]:
        return signal
    else:
        assert signal_length < signal.shape[-1], (
            'signal_length must be smaller than hop_length*win_length, ' +
            f'but received signal_length={signal_length}, ' +
            f'hop_length*win_length={hop_length*win_length}')
        diff = signal.shape[-1] - signal_length
        return signal[:, diff // 2:-diff // 2]


def random_masking(x: Tensor,
                   max_mask_count: int,
                   max_mask_width: int,
                   axis: int = -1) -> Tensor:
    """Apply random masking to a given input tensor x along axis.
    The function randomly mask input x with zeros along axis. The maximum number of masking regions
    is defined by max_mask_count, each of which has maximum zero-out width defined by max_mask_width.

    Parameters:
        x(Tensor): The maximum number of masking regions.
        max_mask_count(int): the maximum number of masking regions.
        max_mask_width(int):the maximum zero-out width of each region.
        axis(int): the axis along which to apply masking.
            The default value is -1.
    Returns:
        Tensor: the tensor after masking.
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    Examples:

        .. code-block:: python

        x = paddle.rand((64, 100))
        x = F.random_masking(x, max_mask_count=10, max_mask_width=2, axis=0)
        print((x[:, 0] == 0).astype('int32').sum())
        >> Tensor(shape=[1], dtype=int32, place=CUDAPlace(0), stop_gradient=True,
                [5])

        x = paddle.rand((64, 100))
        x = F.random_masking(x, max_mask_count=10, max_mask_width=2, axis=1)
        print((x[0, :] == 0).astype('int32').sum())
        >> Tensor(shape=[1], dtype=int32, place=CUDAPlace(0), stop_gradient=True,
                [8])

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    """

    assert x.ndim == 2 or x.ndim, (f'only supports 2d or 3d tensor, ' +
                                   f'but received ndim={x.ndim}')

    if x.ndim == 2:
        x = x.unsqueeze(0)  #extend for batching
        squeeze = True
        if axis != -1:
            assert axis in [
                0, 1, -1
            ], (f'mask axis must be in [0,1,-1] for 2d tensor input, ' +
                f'but received {axis}')
            axis += 1
    else:
        squeeze = False
        assert axis in [1, 2, -1,
                        -2], ('mask axis must be in [1,2,-1,-2] ' +
                              f'for 3d tensor input,but received {axis}')

    zero_tensor = paddle.to_tensor(0.0, dtype=x.dtype)

    n = x.shape[axis]
    num_masks = _randint(max_mask_count + 1)
    mask_width = _randint(max_mask_width) + 1

    if axis == 1:
        for _ in range(num_masks):
            start = _randint(n - mask_width)
            x[:, start:start + mask_width, :] = zero_tensor
    else:
        for _ in range(num_masks):
            start = _randint(n - mask_width)
            x[:, :, start:start + mask_width] = zero_tensor
    if squeeze:
        x = x.squeeze()
    return x


def random_cropping(x: Tensor, target_size: int, axis=-1) -> Tensor:
    """Randomly crops input tensor x along given axis.
    The function randomly crops input x to target_size along axis, such that output.shape[axis] == target_size

    Parameters:
        x(Tensor): the input tensor to apply random cropping.
        target_size(int): the target length after cropping.
        axis(int):the axis along which to apply cropping.
    Returns:
        Tensor: the cropped tensor. If target_size >= x.shape[axis], the original input tensor is returned
        without cropping.
766 767 768 769 770 771 772 773 774 775 776 777 778 779
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = paddle.randn((2, 8))
        y = F.random_cropping(x, target_size=6)
        print(y.shape)
        >> [2, 6]
        y = F.random_cropping(x, target_size=10)
        print(y.shape)
        >> [2, 8]  # same as x

780
    """
781

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    assert axis < x.ndim, ('axis must be smaller than x.ndim, ' +
                           f'but received aixs={axis},x.ndim={x.ndim}')

    assert x.ndim in [1, 2, 3], ('only accept 1d/2d/3d tensor, ' +
                                 f'but received x.ndim={x.ndim}')

    shape = x.shape
    if target_size >= shape[axis]:
        return x  # nothing to do

    start = _randint(shape[axis] - target_size)
    axes = [i for i in range(x.ndim)]
    starts = [0 for i in range(x.ndim)]
    ends = [shape[i] for i in range(x.ndim)]
    starts[axis] = start
    ends[axis] = start + target_size
    return paddle.slice(x, axes, starts, ends)


def center_padding(x: Tensor,
                   target_size: int,
                   axis: int = -1,
                   pad_value: float = 0.0) -> Tensor:
    """Centrally pad input tensor x along given axis.
    The function pads input x with pad_value to target_size along axis, such that output.shape[axis] == target_size

    Parameters:
809 810
        x(Tensor): the input tensor to apply padding in a central way.
        target_size(int): the target length after padding.
811 812 813 814 815 816 817
        axis(int):the axis along which to apply padding.
            The default value is -1.
        pad_value(int):the padding value.
            The default value is 0.0.
    Returns:
        Tensor: the padded tensor. If target_size <= x.shape[axis], the original input tensor is returned
        without padding.
818 819 820 821 822 823 824 825 826 827
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = F.center_padding(paddle.randn(([8, 10])), target_size=12, axis=1)
        print(x.shape)
        >> [8, 12]

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
    """
    assert axis < x.ndim, ('axis must be smaller than x.ndim, ' +
                           f'but received aixs={axis},x.ndim={x.ndim}')
    assert x.ndim in [1, 2, 3], (f'only accept 1d/2d/3d tensor, ' +
                                 f'but recieved x.ndim={x.ndim}')

    shape = x.shape
    if target_size <= shape[axis]:
        return x  # nothing to do

    size_diff_hf = (target_size - shape[axis]) // 2
    pad_shape = shape[:]
    pad_shape[axis] = size_diff_hf
    pad_tensor = paddle.ones(pad_shape, x.dtype) * pad_value
    size_diff_hf2 = target_size - shape[axis] - size_diff_hf
    if size_diff_hf2 != size_diff_hf:
        pad_shape = shape[:]
        pad_shape[axis] = size_diff_hf2
        pad_tensor2 = paddle.ones(pad_shape, x.dtype) * pad_value
    else:
        pad_tensor2 = pad_tensor

    return paddle.concat([pad_tensor, x, pad_tensor2], axis=axis)


def stft(x: Tensor,
         n_fft: int = 2048,
         hop_length: Optional[int] = None,
         win_length: Optional[int] = None,
         window: str = 'hann',
         center: bool = True,
         pad_mode: str = 'reflect',
         one_sided: bool = True):
    """Compute short-time Fourier transformation(STFT) of a given signal,
    typically an audio waveform.
    The STFT is implemented with strided 1d convolution. The convluational weights are
    not learnable by default. To enable learning, set stop_gradient=False before training.

    Parameters:
        n_fft(int): the number of frequency components of the discrete Fourier transform.
            The default value is 2048.
        hop_length(int|None): the hop length of the short time FFT. If None, it is set to win_length//4.
            The default value is None.
        win_length: the window length of the short time FFt. If None, it is set to same as n_fft.
            The default value is None.
        window(str): the name of the window function applied to the single before the Fourier transform.
            The folllowing window names are supported: 'hamming','hann','kaiser','gaussian',
            'exponential','triang','bohman','blackman','cosine','tukey','taylor'.
            The default value is 'hann'
        center(bool): if True, the signal is padded so that frame t is centered at x[t * hop_length].
            If False, frame t begins at x[t * hop_length]
            The default value is True
        pad_mode(str): the mode to pad the signal if necessary. The supported modes are 'reflect' and 'constant'.
            The default value is 'reflect'.
        one_sided(bool): If True, the output spectrum will have n_fft//2+1 frequency components.
            Otherwise, it will return the full spectrum that have n_fft+1 frequency values.
            The default value is True.
    Shape:
886 887
        - x: 1-D tensor with shape: (signal_length,) or 2-D tensor with shape (N, signal_length).
        - output: 2-D tensor with shape (N, freq_dim, frame_number,2),
888
        where freq_dim = n_fft+1 if one_sided is False and n_fft//2+1 if True.
889
        The batch size N is set to 1 if input singal x is 1D tensor.
890 891
    Notes:
        This result of stft function is consistent with librosa.stft() for the default value setting.
892 893 894 895 896 897 898 899 900 901
    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = F.istft(paddle.randn(([8, 1025, 32, 2])), signal_length=16000)
        print(x.shape)
        >> [8, 16000]

902 903 904 905 906
    """
    assert x.ndim in [
        1, 2
    ], (f'The input signal x must be a 1-d tensor for ' +
        'non-batched signal or 2-d tensor for batched signal, ' +
907
        f'but received ndim={x.ndim} instead')
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

    if x.ndim == 1:
        x = x.unsqueeze((0, 1))
    elif x.ndim == 2:
        x = x.unsqueeze(1)

    # By default, use the entire frame.
    if win_length is None:
        win_length = n_fft
    # Set the default hop, if it's not already specified.
    if hop_length is None:
        hop_length = int(win_length // 4)
    fft_window = get_window(window, win_length, fftbins=True)
    fft_window = center_padding(fft_window, n_fft)
    dft_mat = dft_matrix(n_fft)
    if one_sided:
        out_channels = n_fft // 2 + 1
    else:
        out_channels = n_fft
    weight = fft_window.unsqueeze([1, 2]) * dft_mat[:, 0:out_channels, :]
    weight = weight.transpose([1, 2, 0])
    weight = weight.reshape([-1, weight.shape[-1]]).unsqueeze(1)

    if center:
        x = paddle.nn.functional.pad(x,
                                     pad=[n_fft // 2, n_fft // 2],
                                     mode=pad_mode,
                                     data_format="NCL")
    signal = paddle.nn.functional.conv1d(x, weight, stride=hop_length)

    signal = signal.transpose([0, 2, 1])
    signal = signal.reshape(
        [signal.shape[0], signal.shape[1], signal.shape[2] // 2, 2])
    signal = signal.transpose((0, 2, 1, 3))
    return signal


def istft(x: Tensor,
          n_fft: int = 2048,
          hop_length: Optional[int] = None,
          win_length: Optional[int] = None,
          window: str = 'hann',
          center: bool = True,
          pad_mode: str = 'reflect',
952
          signal_length: Optional[int] = None) -> Tensor:
953 954 955 956 957 958 959 960 961 962 963
    """Compute inverse short-time Fourier transform(ISTFT) of a given spectrum signal x.
    To accurately recover the input signal, the exact value of parameters should match
    those used in stft.

    Parameters:
        n_fft, hop_length, win_length, window, center, pad_mode: please refer to stft()
        signal_length(int): the origin signal length for exactly aligning recovered signal
            with original signal. If set to None, the length is solely determined by hop_length
            and win_length.
            The default value is None.
    Shape:
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
        - x: 1-D tensor with shape: (signal_length,) or 2-D tensor with shape (N, signal_length).
        - output: the signal represented as a 2-D tensor with shape (N, single_length)
            The batch size N is set to 1 if input singal x is 1D tensor.

    Examples:
        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = paddle.rand((32, 16000))
        y = F.stft(x, n_fft=512)
        print(x.shape)
        >> [32, 16000]
        z = F.istft(y, n_fft=512, signal_length=16000)
        print(z.shape)
        >> [32, 16000]
        print((z-x).abs().mean())
        >> Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
                [0.00000707])

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    """
    assert pad_mode in [
        'constant', 'reflect'
    ], (f'only support "constant" or ' +
        f'"reflect" for pad_mode, but received pad_mode={pad_mode}')

    assert x.ndim in [
        3, 4
    ], (f'The input spectrum x must be a 3-d or 4-d tensor, ' +
        f'but received ndim={x.ndim} instead')

    if x.ndim == 3:
        x = x.unsqueeze(0)

    bs, freq_dim, frame_num, complex_dim = x.shape
    assert freq_dim == n_fft or freq_dim == n_fft // 2 + 1, (
        f'The input spectrum x should have {n_fft} or {n_fft//2+1} frequency ' +
        f'components, but received {freq_dim} instead')

    assert complex_dim == 2, (
        f'The last dimension of input spectrum should be 2 for storing ' +
        f'real and imaginary part of spectrum, but received {complex_dim} instead'
    )

    # By default, use the entire frame.
    if win_length is None:
        win_length = n_fft
    # Set the default hop, if it's not already specified.
    if hop_length is None:
        hop_length = int(win_length // 4)

    assert hop_length < win_length, (
        f'hop_length must be smaller than win_length, ' +
        f'but {hop_length}>={win_length}')

    fft_window = get_window(window, win_length)
    fft_window = 1.0 / fft_window
    fft_window = center_padding(fft_window, n_fft)
    fft_window = fft_window.unsqueeze((1, 2))
    idft_mat = fft_window * idft_matrix(n_fft) / n_fft
    idft_mat = idft_mat.unsqueeze((0, 1))

    #let's do the inverse transformation
    real = x[:, :, :, 0]
    imag = x[:, :, :, 1]
    if real.shape[1] == n_fft:
        real_full = real
        imag_full = imag
    else:
        real_full = paddle.concat([real, real[:, -2:0:-1]], 1)
        imag_full = paddle.concat([imag, -imag[:, -2:0:-1]], 1)
    part1 = paddle.matmul(idft_mat[:, :, :, :, 0], real_full)
    part2 = paddle.matmul(idft_mat[:, :, :, :, 1], imag_full)
    frames = part1[0] - part2[0]
    signal = deframe(frames, n_fft, hop_length, win_length, signal_length)
    return signal


def spectrogram(x,
                n_fft: int = 2048,
                hop_length: Optional[int] = None,
                win_length: Optional[int] = None,
                window: str = 'hann',
                center: bool = True,
                pad_mode: str = 'reflect',
1049
                power: float = 2.0) -> Tensor:
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    """Compute spectrogram of a given signal, typically an audio waveform.
        The spectorgram is defined as the complex norm of the short-time
        Fourier transformation.

        Parameters:
            n_fft(int): the number of frequency components of the discrete Fourier transform.
                The default value is 2048,
            hop_length(int|None): the hop length of the short time FFT. If None, it is set to win_length//4.
                The default value is None.
            win_length: the window length of the short time FFt. If None, it is set to same as n_fft.
                The default value is None.
            window(str): the name of the window function applied to the single before the Fourier transform.
                The folllowing window names are supported: 'hamming','hann','kaiser','gaussian',
                'exponential','triang','bohman','blackman','cosine','tukey','taylor'.
                The default value is 'hann'
            center(bool): if True, the signal is padded so that frame t is centered at x[t * hop_length].
                If False, frame t begins at x[t * hop_length]
                The default value is True
            pad_mode(str): the mode to pad the signal if necessary. The supported modes are 'reflect'
                and 'constant'.
                The default value is 'reflect'.
            power(float): The power of the complex norm.
                The default value is 2.0
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
        Shape:
            - x: 1-D tensor with shape: (signal_length,) or 2-D tensor with shape (N, signal_length).
            - output: 2-D tensor with shape (N, n_fft//2+1, frame_number),
            The batch size N is set to 1 if input singal x is 1D tensor.

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = F.spectrogram(paddle.randn((8, 16000,)))
        print(x.shape)
        >> [8, 1025, 32]
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

      """
    fft_signal = stft(x,
                      n_fft=n_fft,
                      hop_length=hop_length,
                      win_length=win_length,
                      window=window,
                      center=center,
                      pad_mode=pad_mode,
                      one_sided=True)
    spectrogram = paddle.square(fft_signal).sum(-1)
    if power == 2.0:
        pass
    else:
        spectrogram = spectrogram**(power / 2.0)
    return spectrogram


def melspectrogram(x: Tensor,
                   sr: int = 22050,
                   n_fft: int = 2048,
                   hop_length: Optional[int] = None,
                   win_length: Optional[int] = None,
                   window: str = 'hann',
                   center: bool = True,
                   pad_mode: str = 'reflect',
                   power: float = 2.0,
                   n_mels: int = 128,
                   f_min: float = 0.0,
                   f_max: Optional[float] = None,
                   to_db: bool = False,
1118
                   **kwargs) -> Tensor:
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    """Compute the melspectrogram of a given signal, typically an audio waveform.
        The melspectrogram is also known as filterbank or fbank feature in audio community.
        It is computed by multiplying spectrogram with Mel filter bank matrix.

        Parameters:
            sr(int): the audio sample rate.
                The default value is 22050.
            n_fft(int): the number of frequency components of the discrete Fourier transform.
                The default value is 2048,
            hop_length(int|None): the hop length of the short time FFT. If None, it is set to win_length//4.
                The default value is None.
            win_length: the window length of the short time FFt. If None, it is set to same as n_fft.
                The default value is None.
            window(str): the name of the window function applied to the single before the Fourier transform.
                The folllowing window names are supported: 'hamming','hann','kaiser','gaussian',
                'exponential','triang','bohman','blackman','cosine','tukey','taylor'.
                The default value is 'hann'
            center(bool): if True, the signal is padded so that frame t is centered at x[t * hop_length].
                If False, frame t begins at x[t * hop_length]
                The default value is True
            pad_mode(str): the mode to pad the signal if necessary. The supported modes are 'reflect'
                and 'constant'.
                The default value is 'reflect'.
            power(float): The power of the complex norm.
                The default value is 2.0
            n_mels(int): the mel bins, comman choices are 32, 40, 64, 80, 128.
            f_min(float): the lower cut-off frequency, below which the filter response is zero. Tips:
                set f_min to slightly higher than 0.
                The default value is 0.

            f_max(float): the upper cut-off frequency, above which the filter response is zero.
                If None, it is set to half of the sample rate, i.e., sr//2. Tips: set it a slightly
                smaller than half of sample rate.
                The default value is None.

1154
            to_db(bool): whether to convert the magnitude to db scale.
1155 1156 1157
                The default value is False.
            kwargs: the key-word arguments that are passed to F.power_to_db if to_db is True

1158 1159 1160 1161 1162
        Shape:
            - x: 1-D tensor with shape: (signal_length,) or 2-D tensor with shape (N, signal_length).
            - output: 2-D tensor with shape (N, n_mels, frame_number),
            The batch size N is set to 1 if input singal x is 1D tensor.

1163 1164
        Notes:
            1. The melspectrogram function relies on F.spectrogram and F.compute_fbank_matrix.
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
            2. The melspectrogram function does not convert magnitude to db by default.

    Examples:

        .. code-block:: python

        import paddle
        import paddleaudio.functional as F
        x = F.melspectrogram(paddle.randn((8, 16000,)))
        print(x.shape)
        >> [8, 128, 32]

    """
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

    x = spectrogram(x, n_fft, hop_length, win_length, window, center, pad_mode,
                    power)
    if f_max is None:
        f_max = sr // 2
    fbank_matrix = compute_fbank_matrix(sr=sr,
                                        n_fft=n_fft,
                                        n_mels=n_mels,
                                        f_min=f_min,
                                        f_max=f_max)
    fbank_matrix = fbank_matrix.unsqueeze(0)
    mel_feature = paddle.matmul(fbank_matrix, x)
    if to_db:
        mel_feature = power_to_db(mel_feature, **kwargs)

    return mel_feature