We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Cannot connect to voice channels
Running `await voice_channel.connect()` raises
`AttributeError: 'LP_EncoderStruct' object has no attribute 'value'`

Relevant portions of the traceback ([and the line itself](https://github.com/Rapptz/discord.py/blob/rewrite/discord/opus.py#L52)):
```
  File ".../lib/python3.6/site-packages/discord/abc.py", line 985, in connect
    voice = VoiceClient(state=state, timeout=timeout, channel=self)
  File ".../lib/python3.6/site-packages/discord/voice_client.py", line 109, in __init__
    self.encoder = opus.Encoder()
  File ".../lib/python3.6/site-packages/discord/opus.py", line 225, in __init__
    self._state = self._create_state()
  File ".../lib/python3.6/site-packages/discord/opus.py", line 239, in _create_state
    return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret))
  File ".../lib/python3.6/site-packages/discord/opus.py", line 52, in _err_ne
    if result.value != 0:
AttributeError: 'LP_EncoderStruct' object has no attribute 'value'
```
I have opus 1.2.1 installed on 64-bit Linux, and it is loaded according to `discord.opus.is_loaded()`.

Any clue as to what might be the issue?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `discord/opus.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 """
4 The MIT License (MIT)
5 
6 Copyright (c) 2015-2017 Rapptz
7 
8 Permission is hereby granted, free of charge, to any person obtaining a
9 copy of this software and associated documentation files (the "Software"),
10 to deal in the Software without restriction, including without limitation
11 the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 and/or sell copies of the Software, and to permit persons to whom the
13 Software is furnished to do so, subject to the following conditions:
14 
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17 
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE.
25 """
26 
27 import ctypes
28 import ctypes.util
29 import array
30 from .errors import DiscordException
31 import logging
32 import sys
33 import os.path
34 
35 log = logging.getLogger(__name__)
36 c_int_ptr = ctypes.POINTER(ctypes.c_int)
37 c_int16_ptr = ctypes.POINTER(ctypes.c_int16)
38 c_float_ptr = ctypes.POINTER(ctypes.c_float)
39 
40 class EncoderStruct(ctypes.Structure):
41     pass
42 
43 EncoderStructPtr = ctypes.POINTER(EncoderStruct)
44 
45 def _err_lt(result, func, args):
46     if result < 0:
47         log.info('error has happened in {0.__name__}'.format(func))
48         raise OpusError(result)
49     return result
50 
51 def _err_ne(result, func, args):
52     if result.value != 0:
53         log.info('error has happened in {0.__name__}'.format(func))
54         raise OpusError(result.value)
55     return result
56 
57 # A list of exported functions.
58 # The first argument is obviously the name.
59 # The second one are the types of arguments it takes.
60 # The third is the result type.
61 # The fourth is the error handler.
62 exported_functions = [
63     ('opus_strerror',
64         [ctypes.c_int], ctypes.c_char_p, None),
65     ('opus_encoder_get_size',
66         [ctypes.c_int], ctypes.c_int, None),
67     ('opus_encoder_create',
68         [ctypes.c_int, ctypes.c_int, ctypes.c_int, c_int_ptr], EncoderStructPtr, _err_ne),
69     ('opus_encode',
70         [EncoderStructPtr, c_int16_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt),
71     ('opus_encoder_ctl',
72         None, ctypes.c_int32, _err_lt),
73     ('opus_encoder_destroy',
74         [EncoderStructPtr], None, None),
75 ]
76 
77 def libopus_loader(name):
78     # create the library...
79     lib = ctypes.cdll.LoadLibrary(name)
80 
81     # register the functions...
82     for item in exported_functions:
83         try:
84             func = getattr(lib, item[0])
85         except Exception as e:
86             raise e
87 
88         try:
89             if item[1]:
90                 func.argtypes = item[1]
91 
92             func.restype = item[2]
93         except KeyError:
94             pass
95 
96         try:
97             if item[3]:
98                 func.errcheck = item[3]
99         except KeyError:
100             log.exception("Error assigning check function to %s", func)
101 
102     return lib
103 
104 try:
105     if sys.platform == 'win32':
106         _basedir = os.path.dirname(os.path.abspath(__file__))
107         _bitness = 'x64' if sys.maxsize > 2**32 else 'x86'
108         _filename = os.path.join(_basedir, 'bin', 'libopus-0.{}.dll'.format(_bitness))
109         _lib = libopus_loader(_filename)
110     else:
111         _lib = libopus_loader(ctypes.util.find_library('opus'))
112 except Exception as e:
113     _lib = None
114 
115 def load_opus(name):
116     """Loads the libopus shared library for use with voice.
117 
118     If this function is not called then the library uses the function
119     `ctypes.util.find_library`__ and then loads that one
120     if available.
121 
122     .. _find library: https://docs.python.org/3.5/library/ctypes.html#finding-shared-libraries
123     __ `find library`_
124 
125     Not loading a library leads to voice not working.
126 
127     This function propagates the exceptions thrown.
128 
129     Warning
130     --------
131     The bitness of the library must match the bitness of your python
132     interpreter. If the library is 64-bit then your python interpreter
133     must be 64-bit as well. Usually if there's a mismatch in bitness then
134     the load will throw an exception.
135 
136     Note
137     ----
138     On Windows, the .dll extension is not necessary. However, on Linux
139     the full extension is required to load the library, e.g. ``libopus.so.1``.
140     On Linux however, `find library`_ will usually find the library automatically
141     without you having to call this.
142 
143     Parameters
144     ----------
145     name: str
146         The filename of the shared library.
147     """
148     global _lib
149     _lib = libopus_loader(name)
150 
151 def is_loaded():
152     """Function to check if opus lib is successfully loaded either
153     via the ``ctypes.util.find_library`` call of :func:`load_opus`.
154 
155     This must return ``True`` for voice to work.
156 
157     Returns
158     -------
159     bool
160         Indicates if the opus library has been loaded.
161     """
162     global _lib
163     return _lib is not None
164 
165 class OpusError(DiscordException):
166     """An exception that is thrown for libopus related errors.
167 
168     Attributes
169     ----------
170     code : :class:`int`
171         The error code returned.
172     """
173 
174     def __init__(self, code):
175         self.code = code
176         msg = _lib.opus_strerror(self.code).decode('utf-8')
177         log.info('"%s" has happened', msg)
178         super().__init__(msg)
179 
180 class OpusNotLoaded(DiscordException):
181     """An exception that is thrown for when libopus is not loaded."""
182     pass
183 
184 
185 # Some constants...
186 OK = 0
187 APPLICATION_AUDIO    = 2049
188 APPLICATION_VOIP     = 2048
189 APPLICATION_LOWDELAY = 2051
190 CTL_SET_BITRATE      = 4002
191 CTL_SET_BANDWIDTH    = 4008
192 CTL_SET_FEC          = 4012
193 CTL_SET_PLP          = 4014
194 CTL_SET_SIGNAL       = 4024
195 
196 band_ctl = {
197     'narrow': 1101,
198     'medium': 1102,
199     'wide': 1103,
200     'superwide': 1104,
201     'full': 1105,
202 }
203 
204 signal_ctl = {
205     'auto': -1000,
206     'voice': 3001,
207     'music': 3002,
208 }
209 
210 class Encoder:
211     SAMPLING_RATE = 48000
212     CHANNELS = 2
213     FRAME_LENGTH = 20
214     SAMPLE_SIZE = 4 # (bit_rate / 8) * CHANNELS (bit_rate == 16)
215     SAMPLES_PER_FRAME = int(SAMPLING_RATE / 1000 * FRAME_LENGTH)
216 
217     FRAME_SIZE = SAMPLES_PER_FRAME * SAMPLE_SIZE
218 
219     def __init__(self, application=APPLICATION_AUDIO):
220         self.application = application
221 
222         if not is_loaded():
223             raise OpusNotLoaded()
224 
225         self._state = self._create_state()
226         self.set_bitrate(128)
227         self.set_fec(True)
228         self.set_expected_packet_loss_percent(0.15)
229         self.set_bandwidth('full')
230         self.set_signal_type('auto')
231 
232     def __del__(self):
233         if hasattr(self, '_state'):
234             _lib.opus_encoder_destroy(self._state)
235             self._state = None
236 
237     def _create_state(self):
238         ret = ctypes.c_int()
239         return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret))
240 
241     def set_bitrate(self, kbps):
242         kbps = min(128, max(16, int(kbps)))
243 
244         _lib.opus_encoder_ctl(self._state, CTL_SET_BITRATE, kbps * 1024)
245         return kbps
246 
247     def set_bandwidth(self, req):
248         if req not in band_ctl:
249             raise KeyError('%r is not a valid bandwidth setting. Try one of: %s' % (req, ','.join(band_ctl)))
250 
251         k = band_ctl[req]
252         _lib.opus_encoder_ctl(self._state, CTL_SET_BANDWIDTH, k)
253 
254     def set_signal_type(self, req):
255         if req not in signal_ctl:
256             raise KeyError('%r is not a valid signal setting. Try one of: %s' % (req, ','.join(signal_ctl)))
257 
258         k = signal_ctl[req]
259         _lib.opus_encoder_ctl(self._state, CTL_SET_SIGNAL, k)
260 
261     def set_fec(self, enabled=True):
262         _lib.opus_encoder_ctl(self._state, CTL_SET_FEC, 1 if enabled else 0)
263 
264     def set_expected_packet_loss_percent(self, percentage):
265         _lib.opus_encoder_ctl(self._state, CTL_SET_PLP, min(100, max(0, int(percentage * 100))))
266 
267     def encode(self, pcm, frame_size):
268         max_data_bytes = len(pcm)
269         pcm = ctypes.cast(pcm, c_int16_ptr)
270         data = (ctypes.c_char * max_data_bytes)()
271 
272         ret = _lib.opus_encode(self._state, pcm, frame_size, data, max_data_bytes)
273 
274         return array.array('b', data[:ret]).tobytes()
275
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/discord/opus.py b/discord/opus.py
--- a/discord/opus.py
+++ b/discord/opus.py
@@ -49,9 +49,10 @@
     return result
 
 def _err_ne(result, func, args):
-    if result.value != 0:
+    ret = args[-1]._obj
+    if ret.value != 0:
         log.info('error has happened in {0.__name__}'.format(func))
-        raise OpusError(result.value)
+        raise OpusError(ret.value)
     return result
 
 # A list of exported functions.

{"golden_diff": "diff --git a/discord/opus.py b/discord/opus.py\n--- a/discord/opus.py\n+++ b/discord/opus.py\n@@ -49,9 +49,10 @@\n     return result\n \n def _err_ne(result, func, args):\n-    if result.value != 0:\n+    ret = args[-1]._obj\n+    if ret.value != 0:\n         log.info('error has happened in {0.__name__}'.format(func))\n-        raise OpusError(result.value)\n+        raise OpusError(ret.value)\n     return result\n \n # A list of exported functions.\n", "issue": "Cannot connect to voice channels\nRunning `await voice_channel.connect()` raises\r\n`AttributeError: 'LP_EncoderStruct' object has no attribute 'value'`\r\n\r\nRelevant portions of the traceback ([and the line itself](https://github.com/Rapptz/discord.py/blob/rewrite/discord/opus.py#L52)):\r\n```\r\n  File \".../lib/python3.6/site-packages/discord/abc.py\", line 985, in connect\r\n    voice = VoiceClient(state=state, timeout=timeout, channel=self)\r\n  File \".../lib/python3.6/site-packages/discord/voice_client.py\", line 109, in __init__\r\n    self.encoder = opus.Encoder()\r\n  File \".../lib/python3.6/site-packages/discord/opus.py\", line 225, in __init__\r\n    self._state = self._create_state()\r\n  File \".../lib/python3.6/site-packages/discord/opus.py\", line 239, in _create_state\r\n    return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret))\r\n  File \".../lib/python3.6/site-packages/discord/opus.py\", line 52, in _err_ne\r\n    if result.value != 0:\r\nAttributeError: 'LP_EncoderStruct' object has no attribute 'value'\r\n```\r\nI have opus 1.2.1 installed on 64-bit Linux, and it is loaded according to `discord.opus.is_loaded()`.\r\n\r\nAny clue as to what might be the issue?\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-2017 Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport ctypes\nimport ctypes.util\nimport array\nfrom .errors import DiscordException\nimport logging\nimport sys\nimport os.path\n\nlog = logging.getLogger(__name__)\nc_int_ptr = ctypes.POINTER(ctypes.c_int)\nc_int16_ptr = ctypes.POINTER(ctypes.c_int16)\nc_float_ptr = ctypes.POINTER(ctypes.c_float)\n\nclass EncoderStruct(ctypes.Structure):\n    pass\n\nEncoderStructPtr = ctypes.POINTER(EncoderStruct)\n\ndef _err_lt(result, func, args):\n    if result < 0:\n        log.info('error has happened in {0.__name__}'.format(func))\n        raise OpusError(result)\n    return result\n\ndef _err_ne(result, func, args):\n    if result.value != 0:\n        log.info('error has happened in {0.__name__}'.format(func))\n        raise OpusError(result.value)\n    return result\n\n# A list of exported functions.\n# The first argument is obviously the name.\n# The second one are the types of arguments it takes.\n# The third is the result type.\n# The fourth is the error handler.\nexported_functions = [\n    ('opus_strerror',\n        [ctypes.c_int], ctypes.c_char_p, None),\n    ('opus_encoder_get_size',\n        [ctypes.c_int], ctypes.c_int, None),\n    ('opus_encoder_create',\n        [ctypes.c_int, ctypes.c_int, ctypes.c_int, c_int_ptr], EncoderStructPtr, _err_ne),\n    ('opus_encode',\n        [EncoderStructPtr, c_int16_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt),\n    ('opus_encoder_ctl',\n        None, ctypes.c_int32, _err_lt),\n    ('opus_encoder_destroy',\n        [EncoderStructPtr], None, None),\n]\n\ndef libopus_loader(name):\n    # create the library...\n    lib = ctypes.cdll.LoadLibrary(name)\n\n    # register the functions...\n    for item in exported_functions:\n        try:\n            func = getattr(lib, item[0])\n        except Exception as e:\n            raise e\n\n        try:\n            if item[1]:\n                func.argtypes = item[1]\n\n            func.restype = item[2]\n        except KeyError:\n            pass\n\n        try:\n            if item[3]:\n                func.errcheck = item[3]\n        except KeyError:\n            log.exception(\"Error assigning check function to %s\", func)\n\n    return lib\n\ntry:\n    if sys.platform == 'win32':\n        _basedir = os.path.dirname(os.path.abspath(__file__))\n        _bitness = 'x64' if sys.maxsize > 2**32 else 'x86'\n        _filename = os.path.join(_basedir, 'bin', 'libopus-0.{}.dll'.format(_bitness))\n        _lib = libopus_loader(_filename)\n    else:\n        _lib = libopus_loader(ctypes.util.find_library('opus'))\nexcept Exception as e:\n    _lib = None\n\ndef load_opus(name):\n    \"\"\"Loads the libopus shared library for use with voice.\n\n    If this function is not called then the library uses the function\n    `ctypes.util.find_library`__ and then loads that one\n    if available.\n\n    .. _find library: https://docs.python.org/3.5/library/ctypes.html#finding-shared-libraries\n    __ `find library`_\n\n    Not loading a library leads to voice not working.\n\n    This function propagates the exceptions thrown.\n\n    Warning\n    --------\n    The bitness of the library must match the bitness of your python\n    interpreter. If the library is 64-bit then your python interpreter\n    must be 64-bit as well. Usually if there's a mismatch in bitness then\n    the load will throw an exception.\n\n    Note\n    ----\n    On Windows, the .dll extension is not necessary. However, on Linux\n    the full extension is required to load the library, e.g. ``libopus.so.1``.\n    On Linux however, `find library`_ will usually find the library automatically\n    without you having to call this.\n\n    Parameters\n    ----------\n    name: str\n        The filename of the shared library.\n    \"\"\"\n    global _lib\n    _lib = libopus_loader(name)\n\ndef is_loaded():\n    \"\"\"Function to check if opus lib is successfully loaded either\n    via the ``ctypes.util.find_library`` call of :func:`load_opus`.\n\n    This must return ``True`` for voice to work.\n\n    Returns\n    -------\n    bool\n        Indicates if the opus library has been loaded.\n    \"\"\"\n    global _lib\n    return _lib is not None\n\nclass OpusError(DiscordException):\n    \"\"\"An exception that is thrown for libopus related errors.\n\n    Attributes\n    ----------\n    code : :class:`int`\n        The error code returned.\n    \"\"\"\n\n    def __init__(self, code):\n        self.code = code\n        msg = _lib.opus_strerror(self.code).decode('utf-8')\n        log.info('\"%s\" has happened', msg)\n        super().__init__(msg)\n\nclass OpusNotLoaded(DiscordException):\n    \"\"\"An exception that is thrown for when libopus is not loaded.\"\"\"\n    pass\n\n\n# Some constants...\nOK = 0\nAPPLICATION_AUDIO    = 2049\nAPPLICATION_VOIP     = 2048\nAPPLICATION_LOWDELAY = 2051\nCTL_SET_BITRATE      = 4002\nCTL_SET_BANDWIDTH    = 4008\nCTL_SET_FEC          = 4012\nCTL_SET_PLP          = 4014\nCTL_SET_SIGNAL       = 4024\n\nband_ctl = {\n    'narrow': 1101,\n    'medium': 1102,\n    'wide': 1103,\n    'superwide': 1104,\n    'full': 1105,\n}\n\nsignal_ctl = {\n    'auto': -1000,\n    'voice': 3001,\n    'music': 3002,\n}\n\nclass Encoder:\n    SAMPLING_RATE = 48000\n    CHANNELS = 2\n    FRAME_LENGTH = 20\n    SAMPLE_SIZE = 4 # (bit_rate / 8) * CHANNELS (bit_rate == 16)\n    SAMPLES_PER_FRAME = int(SAMPLING_RATE / 1000 * FRAME_LENGTH)\n\n    FRAME_SIZE = SAMPLES_PER_FRAME * SAMPLE_SIZE\n\n    def __init__(self, application=APPLICATION_AUDIO):\n        self.application = application\n\n        if not is_loaded():\n            raise OpusNotLoaded()\n\n        self._state = self._create_state()\n        self.set_bitrate(128)\n        self.set_fec(True)\n        self.set_expected_packet_loss_percent(0.15)\n        self.set_bandwidth('full')\n        self.set_signal_type('auto')\n\n    def __del__(self):\n        if hasattr(self, '_state'):\n            _lib.opus_encoder_destroy(self._state)\n            self._state = None\n\n    def _create_state(self):\n        ret = ctypes.c_int()\n        return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret))\n\n    def set_bitrate(self, kbps):\n        kbps = min(128, max(16, int(kbps)))\n\n        _lib.opus_encoder_ctl(self._state, CTL_SET_BITRATE, kbps * 1024)\n        return kbps\n\n    def set_bandwidth(self, req):\n        if req not in band_ctl:\n            raise KeyError('%r is not a valid bandwidth setting. Try one of: %s' % (req, ','.join(band_ctl)))\n\n        k = band_ctl[req]\n        _lib.opus_encoder_ctl(self._state, CTL_SET_BANDWIDTH, k)\n\n    def set_signal_type(self, req):\n        if req not in signal_ctl:\n            raise KeyError('%r is not a valid signal setting. Try one of: %s' % (req, ','.join(signal_ctl)))\n\n        k = signal_ctl[req]\n        _lib.opus_encoder_ctl(self._state, CTL_SET_SIGNAL, k)\n\n    def set_fec(self, enabled=True):\n        _lib.opus_encoder_ctl(self._state, CTL_SET_FEC, 1 if enabled else 0)\n\n    def set_expected_packet_loss_percent(self, percentage):\n        _lib.opus_encoder_ctl(self._state, CTL_SET_PLP, min(100, max(0, int(percentage * 100))))\n\n    def encode(self, pcm, frame_size):\n        max_data_bytes = len(pcm)\n        pcm = ctypes.cast(pcm, c_int16_ptr)\n        data = (ctypes.c_char * max_data_bytes)()\n\n        ret = _lib.opus_encode(self._state, pcm, frame_size, data, max_data_bytes)\n\n        return array.array('b', data[:ret]).tobytes()\n", "path": "discord/opus.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2015-2017 Rapptz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport ctypes\nimport ctypes.util\nimport array\nfrom .errors import DiscordException\nimport logging\nimport sys\nimport os.path\n\nlog = logging.getLogger(__name__)\nc_int_ptr = ctypes.POINTER(ctypes.c_int)\nc_int16_ptr = ctypes.POINTER(ctypes.c_int16)\nc_float_ptr = ctypes.POINTER(ctypes.c_float)\n\nclass EncoderStruct(ctypes.Structure):\n    pass\n\nEncoderStructPtr = ctypes.POINTER(EncoderStruct)\n\ndef _err_lt(result, func, args):\n    if result < 0:\n        log.info('error has happened in {0.__name__}'.format(func))\n        raise OpusError(result)\n    return result\n\ndef _err_ne(result, func, args):\n    ret = args[-1]._obj\n    if ret.value != 0:\n        log.info('error has happened in {0.__name__}'.format(func))\n        raise OpusError(ret.value)\n    return result\n\n# A list of exported functions.\n# The first argument is obviously the name.\n# The second one are the types of arguments it takes.\n# The third is the result type.\n# The fourth is the error handler.\nexported_functions = [\n    ('opus_strerror',\n        [ctypes.c_int], ctypes.c_char_p, None),\n    ('opus_encoder_get_size',\n        [ctypes.c_int], ctypes.c_int, None),\n    ('opus_encoder_create',\n        [ctypes.c_int, ctypes.c_int, ctypes.c_int, c_int_ptr], EncoderStructPtr, _err_ne),\n    ('opus_encode',\n        [EncoderStructPtr, c_int16_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt),\n    ('opus_encoder_ctl',\n        None, ctypes.c_int32, _err_lt),\n    ('opus_encoder_destroy',\n        [EncoderStructPtr], None, None),\n]\n\ndef libopus_loader(name):\n    # create the library...\n    lib = ctypes.cdll.LoadLibrary(name)\n\n    # register the functions...\n    for item in exported_functions:\n        try:\n            func = getattr(lib, item[0])\n        except Exception as e:\n            raise e\n\n        try:\n            if item[1]:\n                func.argtypes = item[1]\n\n            func.restype = item[2]\n        except KeyError:\n            pass\n\n        try:\n            if item[3]:\n                func.errcheck = item[3]\n        except KeyError:\n            log.exception(\"Error assigning check function to %s\", func)\n\n    return lib\n\ntry:\n    if sys.platform == 'win32':\n        _basedir = os.path.dirname(os.path.abspath(__file__))\n        _bitness = 'x64' if sys.maxsize > 2**32 else 'x86'\n        _filename = os.path.join(_basedir, 'bin', 'libopus-0.{}.dll'.format(_bitness))\n        _lib = libopus_loader(_filename)\n    else:\n        _lib = libopus_loader(ctypes.util.find_library('opus'))\nexcept Exception as e:\n    _lib = None\n\ndef load_opus(name):\n    \"\"\"Loads the libopus shared library for use with voice.\n\n    If this function is not called then the library uses the function\n    `ctypes.util.find_library`__ and then loads that one\n    if available.\n\n    .. _find library: https://docs.python.org/3.5/library/ctypes.html#finding-shared-libraries\n    __ `find library`_\n\n    Not loading a library leads to voice not working.\n\n    This function propagates the exceptions thrown.\n\n    Warning\n    --------\n    The bitness of the library must match the bitness of your python\n    interpreter. If the library is 64-bit then your python interpreter\n    must be 64-bit as well. Usually if there's a mismatch in bitness then\n    the load will throw an exception.\n\n    Note\n    ----\n    On Windows, the .dll extension is not necessary. However, on Linux\n    the full extension is required to load the library, e.g. ``libopus.so.1``.\n    On Linux however, `find library`_ will usually find the library automatically\n    without you having to call this.\n\n    Parameters\n    ----------\n    name: str\n        The filename of the shared library.\n    \"\"\"\n    global _lib\n    _lib = libopus_loader(name)\n\ndef is_loaded():\n    \"\"\"Function to check if opus lib is successfully loaded either\n    via the ``ctypes.util.find_library`` call of :func:`load_opus`.\n\n    This must return ``True`` for voice to work.\n\n    Returns\n    -------\n    bool\n        Indicates if the opus library has been loaded.\n    \"\"\"\n    global _lib\n    return _lib is not None\n\nclass OpusError(DiscordException):\n    \"\"\"An exception that is thrown for libopus related errors.\n\n    Attributes\n    ----------\n    code : :class:`int`\n        The error code returned.\n    \"\"\"\n\n    def __init__(self, code):\n        self.code = code\n        msg = _lib.opus_strerror(self.code).decode('utf-8')\n        log.info('\"%s\" has happened', msg)\n        super().__init__(msg)\n\nclass OpusNotLoaded(DiscordException):\n    \"\"\"An exception that is thrown for when libopus is not loaded.\"\"\"\n    pass\n\n\n# Some constants...\nOK = 0\nAPPLICATION_AUDIO    = 2049\nAPPLICATION_VOIP     = 2048\nAPPLICATION_LOWDELAY = 2051\nCTL_SET_BITRATE      = 4002\nCTL_SET_BANDWIDTH    = 4008\nCTL_SET_FEC          = 4012\nCTL_SET_PLP          = 4014\nCTL_SET_SIGNAL       = 4024\n\nband_ctl = {\n    'narrow': 1101,\n    'medium': 1102,\n    'wide': 1103,\n    'superwide': 1104,\n    'full': 1105,\n}\n\nsignal_ctl = {\n    'auto': -1000,\n    'voice': 3001,\n    'music': 3002,\n}\n\nclass Encoder:\n    SAMPLING_RATE = 48000\n    CHANNELS = 2\n    FRAME_LENGTH = 20\n    SAMPLE_SIZE = 4 # (bit_rate / 8) * CHANNELS (bit_rate == 16)\n    SAMPLES_PER_FRAME = int(SAMPLING_RATE / 1000 * FRAME_LENGTH)\n\n    FRAME_SIZE = SAMPLES_PER_FRAME * SAMPLE_SIZE\n\n    def __init__(self, application=APPLICATION_AUDIO):\n        self.application = application\n\n        if not is_loaded():\n            raise OpusNotLoaded()\n\n        self._state = self._create_state()\n        self.set_bitrate(128)\n        self.set_fec(True)\n        self.set_expected_packet_loss_percent(0.15)\n        self.set_bandwidth('full')\n        self.set_signal_type('auto')\n\n    def __del__(self):\n        if hasattr(self, '_state'):\n            _lib.opus_encoder_destroy(self._state)\n            self._state = None\n\n    def _create_state(self):\n        ret = ctypes.c_int()\n        return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret))\n\n    def set_bitrate(self, kbps):\n        kbps = min(128, max(16, int(kbps)))\n\n        _lib.opus_encoder_ctl(self._state, CTL_SET_BITRATE, kbps * 1024)\n        return kbps\n\n    def set_bandwidth(self, req):\n        if req not in band_ctl:\n            raise KeyError('%r is not a valid bandwidth setting. Try one of: %s' % (req, ','.join(band_ctl)))\n\n        k = band_ctl[req]\n        _lib.opus_encoder_ctl(self._state, CTL_SET_BANDWIDTH, k)\n\n    def set_signal_type(self, req):\n        if req not in signal_ctl:\n            raise KeyError('%r is not a valid signal setting. Try one of: %s' % (req, ','.join(signal_ctl)))\n\n        k = signal_ctl[req]\n        _lib.opus_encoder_ctl(self._state, CTL_SET_SIGNAL, k)\n\n    def set_fec(self, enabled=True):\n        _lib.opus_encoder_ctl(self._state, CTL_SET_FEC, 1 if enabled else 0)\n\n    def set_expected_packet_loss_percent(self, percentage):\n        _lib.opus_encoder_ctl(self._state, CTL_SET_PLP, min(100, max(0, int(percentage * 100))))\n\n    def encode(self, pcm, frame_size):\n        max_data_bytes = len(pcm)\n        pcm = ctypes.cast(pcm, c_int16_ptr)\n        data = (ctypes.c_char * max_data_bytes)()\n\n        ret = _lib.opus_encode(self._state, pcm, frame_size, data, max_data_bytes)\n\n        return array.array('b', data[:ret]).tobytes()\n", "path": "discord/opus.py"}]}