File size: 5,293 Bytes
21f5301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Makes clean recitation sound like it does in real reels and videos.

The app captures the phone's playback audio digitally (no microphone), so
what differs from the clean training recordings is the recording itself:
mosque echo, a crowd, hiss and hum, social-app compression, loud or quiet
uploads. Each effect is switched on at random, so pieces get different mixes.

Works on a batch, on the CPU (train.py runs it in the data-loading workers;
on the GPU, FFTs of many lengths broke cuFFT), with a torch.Generator so a
seed gives the same result every time:

    audio = reel_like(audio, samples, generator)   # (B, S) floats in [-1, 1]

Used by train.py (on the fly, 80% of pieces) and make_reel_set.py (the
reel-like test set, which adds real AAC compression on top).
"""

from __future__ import annotations

import math

import torch

RATE = 16000


def _uniform(g: torch.Generator, low: float, high: float) -> float:
    return low + (high - low) * torch.rand((), generator=g).item()


def _chance(g: torch.Generator, p: float) -> bool:
    return torch.rand((), generator=g).item() < p


def _power(x: torch.Tensor) -> torch.Tensor:
    return x.pow(2).mean().clamp_min(1e-10)


def room_response(g: torch.Generator, device) -> torch.Tensor:
    """A simulated room: the direct sound, then echoes decaying by 60 dB over
    rt60 seconds (0.3 s for a small room up to 2 s for a big mosque)."""
    rt60 = _uniform(g, 0.3, 2.0)
    length = int(min(rt60, 1.2) * RATE)
    t = torch.arange(length, device=device) / RATE
    tail = torch.randn(length, generator=g).to(device) * torch.exp(-6.9 * t / rt60)
    gap = int(_uniform(g, 0.005, 0.03) * RATE)  # first reflection after the direct sound
    tail[:gap] = 0
    response = tail * _uniform(g, 0.3, 1.0) / tail.norm().clamp_min(1e-6)
    response[0] = 1.0
    return response


def _convolve(x: torch.Tensor, response: torch.Tensor) -> torch.Tensor:
    n = x.shape[-1] + response.shape[-1] - 1
    size = 1 << (n - 1).bit_length()
    y = torch.fft.irfft(torch.fft.rfft(x, size) * torch.fft.rfft(response, size), size)
    return y[..., : x.shape[-1]]


def _coloured_noise(g: torch.Generator, n: int, device) -> torch.Tensor:
    """White, pink or brown noise."""
    white = torch.randn(n, generator=g).to(device)
    slope = [0.0, 0.5, 1.0][int(torch.randint(3, (), generator=g))]
    if slope == 0:
        return white
    spectrum = torch.fft.rfft(white)
    f = torch.arange(spectrum.shape[0], device=device).clamp_min(1)
    return torch.fft.irfft(spectrum / f.pow(slope), n)


def _hum(g: torch.Generator, n: int, device) -> torch.Tensor:
    base = 50.0 if _chance(g, 0.5) else 60.0
    t = torch.arange(n, device=device) / RATE
    return sum(torch.sin(2 * math.pi * base * k * t) / k for k in (1, 2, 3))


def _low_pass(x: torch.Tensor, cutoff: float) -> torch.Tensor:
    """What low-bitrate compression does most audibly: drops the highs."""
    spectrum = torch.fft.rfft(x)
    freqs = torch.fft.rfftfreq(x.shape[-1], 1 / RATE).to(x.device)
    roll = torch.clamp((freqs - cutoff) / 400, 0, 1)  # a 400 Hz slope, not a brick wall
    return torch.fft.irfft(spectrum * (1 - roll), x.shape[-1])


def degrade(
    x: torch.Tensor,
    g: torch.Generator,
    crowd: torch.Tensor | None = None,
) -> torch.Tensor:
    """One clip (S,) in [-1, 1] -> the same clip, made reel-like.
    crowd: other recitation to murmur underneath (same length), or None."""
    n = x.shape[-1]
    if n == 0:
        return x
    level = _power(x)
    y = x
    if _chance(g, 0.6):
        wet = _convolve(y, room_response(g, x.device))
        y = wet * torch.sqrt(level / _power(wet))
    if crowd is not None and _chance(g, 0.35):
        snr = _uniform(g, 10, 25)
        y = y + crowd * torch.sqrt(level / _power(crowd) / 10 ** (snr / 10))
    if _chance(g, 0.5):
        snr = _uniform(g, 15, 40)
        noise = _coloured_noise(g, n, x.device)
        y = y + noise * torch.sqrt(level / _power(noise) / 10 ** (snr / 10))
    if _chance(g, 0.15):
        snr = _uniform(g, 25, 40)
        hum = _hum(g, n, x.device)
        y = y + hum * torch.sqrt(level / _power(hum) / 10 ** (snr / 10))
    if _chance(g, 0.5):
        y = _low_pass(y, _uniform(g, 3500, 7500))
    # Loud or quiet uploads; loud ones sometimes clip.
    peak = y.abs().max().clamp_min(1e-6)
    target = _uniform(g, 0.05, 1.0) if not _chance(g, 0.1) else _uniform(g, 1.0, 2.5)
    return (y * target / peak).clamp(-1, 1)


def reel_like(
    audio: torch.Tensor,
    samples: torch.Tensor,
    g: torch.Generator,
    share: float = 0.8,
) -> torch.Tensor:
    """A padded batch (B, S) with true lengths `samples`: about `share` of the
    clips degraded, the rest left clean. The crowd for a clip is the next clip
    in the batch, so no extra audio is needed."""
    out = audio.clone()
    count = audio.shape[0]
    for i in range(count):
        if not _chance(g, share):
            continue
        n = int(samples[i])
        crowd = None
        if count > 1:
            j = (i + 1 + int(torch.randint(count - 1, (), generator=g))) % count
            other = audio[j, : int(samples[j])]
            if other.numel() > 0:
                crowd = other.repeat(n // other.numel() + 1)[:n]
        out[i, :n] = degrade(audio[i, :n], g, crowd)
    return out