Ejemplo n.º 1
0
def encode(encoder_state: ctypes.Structure, pcm_data: bytes, frame_size: int,
           max_data_bytes: int) -> typing.Union[bytes, typing.Any]:
    """
    Encodes an Opus Frame.

    Returns string output payload.

    Parameters:
    [in]	st	OpusEncoder*: Encoder state
    [in]	pcm	opus_int16*: Input signal (interleaved if 2 channels). length
        is frame_size*channels*sizeof(opus_int16)
    [in]	frame_size	int: Number of samples per channel in the input signal.
        This must be an Opus frame size for the encoder's sampling rate. For
            example, at 48 kHz the permitted values are 120, 240, 480, 960,
            1920, and 2880. Passing in a duration of less than 10 ms
            (480 samples at 48 kHz) will prevent the encoder from using the
            LPC or hybrid modes.
    [out]	data	unsigned char*: Output payload. This must contain storage
        for at least max_data_bytes.
    [in]	max_data_bytes	opus_int32: Size of the allocated memory for the
        output payload. This may be used to impose an upper limit on the
        instant bitrate, but should not be used as the only bitrate control.
        Use OPUS_SET_BITRATE to control the bitrate.
    """
    pcm_pointer = ctypes.cast(pcm_data, opuslib.api.c_int16_pointer)
    opus_data = (ctypes.c_char * max_data_bytes)()

    result = libopus_encode(encoder_state, pcm_pointer, frame_size, opus_data,
                            max_data_bytes)

    if result < 0:
        raise opuslib.OpusError(
            'Opus Encoder returned result="{}"'.format(result))

    return array.array('b', opus_data[:result]).tobytes()
Ejemplo n.º 2
0
def create_state(fs: int, channels: int, application: int) -> ctypes.Structure:
    """Allocates and initializes an encoder state."""
    result_code = ctypes.c_int()

    result = libopus_create(fs, channels, application,
                            ctypes.byref(result_code))

    if result_code.value is not opuslib.OK:
        raise opuslib.OpusError(result_code.value)

    return result
Ejemplo n.º 3
0
def encode_float(encoder_state: ctypes.Structure, pcm_data: bytes,
                 frame_size: int,
                 max_data_bytes: int) -> typing.Union[bytes, typing.Any]:
    """Encodes an Opus frame from floating point input"""
    pcm_pointer = ctypes.cast(pcm_data, opuslib.api.c_float_pointer)
    opus_data = (ctypes.c_char * max_data_bytes)()

    result = libopus_encode_float(encoder_state, pcm_pointer, frame_size,
                                  opus_data, max_data_bytes)

    if result < 0:
        raise opuslib.OpusError('Encoder returned result="{}"'.format(result))

    return array.array('b', opus_data[:result]).tobytes()