opus

nim-opus is a high-level wrapper for the opus audio decoder. It uses nim features to achieve a concise, flexible interface and memory safety.

If the low-level api is required to be accessed, opus/wrapper can be imported directly into a project.

Types

SampleRate = enum
  sr8k = 8000, sr12k = 12000, sr16k = 16000, sr24k = 24000, sr48k = 48000
The possible sample rates for Opus encoding
Channels = enum
  chMono = 1, chStereo = 2
The possible channel setups for Opus encoding This is the number of channels that the Opus encoder will use to optimize compression- more channels than this can be encoded seperately and then used together
DecoderObj = object
  raw*: ptr cDecoder
  sampleRate*: SampleRate
  channels*: Channels
An object to refer to the low-level decoder and some select metadata
Decoder = ref DecoderObj
The high-level object to refer to the decoder. This object is memory safe, as all low-level memory allocations are freed when it goes out of scope
SamplesObj = object
  len*: int
  data*: ptr UncheckedArray[int16]
An object to hold an array of samples
Samples = ref SamplesObj
A simple container for an array full of samples. Sample values can be read or edited directly like this:

get

if mySampleObject.len >= 40:
echo $mySampleObject.data[40]

set

if mySampleObject.len >= 40:
mySampleObject.data[40] = -1

This is unsafe, please do manual bounds checks

This object should be converted to a data view when they become available

InitError = object of Exception
  
An error that occurs during decoder initialization
DecodeError = object of ValueError
  
An error that occurrs during the decoding process

Procs

proc newDecoder(sampleRate: SampleRate = sr48k; channels: Channels = chStereo): Decoder {...}{.
    raises: [InitError], tags: [].}
Initialize a new decoder for a given sample rate and channel setup. A decoder allocated this way will be memory safe.
proc decode(decoder: Decoder; encoded: openArray[byte];
            errorCorrection: bool = false): Samples {...}{.raises: [DecodeError],
    tags: [].}
Use a decoder to get samples from a packet of compressed data. The samples are PCM and can be played back using any audio interface, or converted to a different format.

Templates

template bytes(samples: Samples): int
template decode(decoder: Decoder; encoded: ptr UncheckedArray[byte]; len: int;
                errorCorrection: bool = false): Samples
Decode from data in an unchecked array with a length