File size: 3,005 Bytes
c413e6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MP3 encode via PyAV/libmp3lame. ffmpeg CLI is not installed on this cluster;
PyAV 18 bundles libmp3lame, so this is the only available CBR MP3 path.
160 kbps CBR, mono, 48 kHz."""
import io, numpy as np
try:
    import av
    _HAVE_AV = True
except ImportError:            # env_asr (NeMo) has no PyAV; libsndfile 1.2 reads mp3 fine
    _HAVE_AV = False

def encode_mp3(wav, sr=48000, bitrate=160000):
    """wav: float32 mono numpy in [-1,1] -> bytes of a 160 kbps CBR mono mp3."""
    if not _HAVE_AV:
        raise RuntimeError("MP3 encoding needs PyAV (libmp3lame); this env has none")
    buf = io.BytesIO()
    c = av.open(buf, "w", format="mp3")
    st = c.add_stream("libmp3lame", rate=sr)
    st.bit_rate = bitrate
    st.bit_rate_tolerance = 0          # CBR, not ABR/VBR
    st.codec_context.layout = "mono"
    x = np.clip(np.asarray(wav, dtype=np.float32), -1.0, 1.0)
    x = (x * 32767.0).astype(np.int16).reshape(1, -1)
    fr = av.AudioFrame.from_ndarray(x, format="s16", layout="mono")
    fr.sample_rate = sr; fr.pts = 0
    for p in st.encode(fr): c.mux(p)
    for p in st.encode(None): c.mux(p)
    c.close()
    return buf.getvalue()

def decode_mp3(b):
    if not _HAVE_AV:
        import soundfile as sf
        x, sr = sf.read(io.BytesIO(b), dtype="float32")
        if x.ndim > 1: x = x.mean(1)
        return x.astype(np.float32), sr
    c = av.open(io.BytesIO(b))
    st = c.streams.audio[0]
    nch = st.channels or 1
    # STEREO BUG (fixed 2026-08-21). The old body was
    #     fr = [f.to_ndarray().reshape(-1) for f in c.decode(audio=0)]
    # which is only correct for MONO. PyAV hands back either (channels, nb_samples) for planar
    # formats or (1, nb_samples*channels) for packed ones; a blind reshape(-1) turns BOTH into a
    # signal of length nb_samples*channels instead of nb_samples. The voice-profile audio is
    # duplicated mono written as 2-channel mp3, so every sample appeared twice and the decoded
    # signal was exactly 2x too long -- i.e. HALF SPEED. dur_s and moss_frames came out 2x on
    # every vprof_* row, and because BOTH were doubled the internal consistency check
    # `moss_frames == floor(dur_s * 12.5)` still passed, which is why this hid for so long.
    # The MOSS codes for those rows encode half-speed audio and are unusable; they must be
    # re-encoded. The soundfile fallback above was always correct (it does `x.mean(1)`).
    fr = []
    for f in c.decode(audio=0):
        a = f.to_ndarray()
        if nch > 1:
            if a.ndim == 2 and a.shape[0] == nch:      # planar: (channels, nb_samples)
                a = a.mean(0)
            else:                                       # packed: (1, nb_samples*channels)
                a = a.reshape(-1, nch).mean(1)
        else:
            a = a.reshape(-1)
        fr.append(a)
    sr = st.rate; c.close()
    x = np.concatenate(fr) if fr else np.zeros(0, np.float32)
    if x.dtype == np.int16: x = x.astype(np.float32)/32768.0
    return x.astype(np.float32), sr