Files
lintunes/lintunes/mumble/opus.py
T

106 lines
3.4 KiB
Python

"""libopus's encoder through ctypes — the system library Mumble itself and
Qt's ffmpeg already need, so no pip dependency (opuslib is unmaintained)."""
import ctypes
import ctypes.util
SAMPLE_RATE = 48000
APPLICATION_AUDIO = 2049
SET_BITRATE = 4002
SET_VBR = 4006
SET_COMPLEXITY = 4010
SET_VBR_CONSTRAINT = 4020
SET_SIGNAL = 4024
SIGNAL_MUSIC = 3002
MAX_PACKET = 4000
_lib = None
def _library():
global _lib
if _lib is None:
name = ctypes.util.find_library("opus")
candidates = [name] if name else []
candidates += ["libopus.so.0", "libopus.0.dylib", "libopus.dylib"]
for candidate in candidates:
try:
lib = ctypes.CDLL(candidate)
break
except OSError:
continue
else:
raise OSError("libopus isn't installed")
lib.opus_encoder_create.restype = ctypes.c_void_p
lib.opus_encoder_create.argtypes = [
ctypes.c_int32, ctypes.c_int, ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
lib.opus_encode.restype = ctypes.c_int32
lib.opus_encode.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int,
ctypes.c_char_p, ctypes.c_int32]
lib.opus_encoder_destroy.argtypes = [ctypes.c_void_p]
lib.opus_encoder_ctl.restype = ctypes.c_int
lib.opus_strerror.restype = ctypes.c_char_p
lib.opus_strerror.argtypes = [ctypes.c_int]
_lib = lib
return _lib
def available() -> bool:
try:
_library()
return True
except OSError:
return False
class OpusError(RuntimeError):
pass
class Encoder:
"""48 kHz music encoder; int16 interleaved PCM in, one Opus packet out."""
def __init__(self, channels: int, bitrate: int):
lib = _library()
error = ctypes.c_int(0)
self.channels = channels
self._state = lib.opus_encoder_create(
SAMPLE_RATE, channels, APPLICATION_AUDIO, ctypes.byref(error))
if error.value != 0 or not self._state:
raise OpusError(lib.opus_strerror(error.value).decode())
self._out = ctypes.create_string_buffer(MAX_PACKET)
# Constrained VBR: the server's bandwidth check is over each second,
# and unconstrained VBR can swing past it on a loud passage.
self._ctl(SET_VBR, 1)
self._ctl(SET_VBR_CONSTRAINT, 1)
self._ctl(SET_COMPLEXITY, 10)
self._ctl(SET_SIGNAL, SIGNAL_MUSIC)
self.set_bitrate(bitrate)
def _ctl(self, request: int, value: int):
if self._state:
_library().opus_encoder_ctl(ctypes.c_void_p(self._state),
ctypes.c_int(request),
ctypes.c_int32(int(value)))
def set_bitrate(self, bitrate: int):
self.bitrate = int(bitrate)
self._ctl(SET_BITRATE, self.bitrate)
def encode(self, pcm: bytes, samples_per_channel: int) -> bytes:
count = _library().opus_encode(self._state, pcm, samples_per_channel,
self._out, MAX_PACKET)
if count < 0:
raise OpusError(_library().opus_strerror(count).decode())
return self._out.raw[:count]
def close(self):
state, self._state = self._state, None
if state:
_library().opus_encoder_destroy(state)
def __del__(self):
self.close()