├── .gitignore ├── requirements.txt ├── newdevice.png ├── test ├── respeaker.wav ├── REAME.md ├── kws.py ├── player.py ├── rms.py └── echo.py ├── 1_channel_firmware.bin ├── 6_channels_firmware.bin ├── .gitmodules ├── MicArrayV3_firmware ├── 1_channel_dfu_4.0.0_firmware.bin └── 6_channels_dfu_4.0.0_firmware.bin ├── README.md ├── odas.cfg ├── dfu.py ├── dfu_windows.py ├── tuning.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .python-version -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyusb==1.0.2 2 | click==7.0 3 | -------------------------------------------------------------------------------- /newdevice.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/newdevice.png -------------------------------------------------------------------------------- /test/respeaker.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/test/respeaker.wav -------------------------------------------------------------------------------- /1_channel_firmware.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/1_channel_firmware.bin -------------------------------------------------------------------------------- /6_channels_firmware.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/6_channels_firmware.bin -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "test/pocketsphinx-data"] 2 | path = test/pocketsphinx-data 3 | url = https://github.com/respeaker/pocketsphinx-data.git 4 | -------------------------------------------------------------------------------- /MicArrayV3_firmware/1_channel_dfu_4.0.0_firmware.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/MicArrayV3_firmware/1_channel_dfu_4.0.0_firmware.bin -------------------------------------------------------------------------------- /MicArrayV3_firmware/6_channels_dfu_4.0.0_firmware.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/respeaker/usb_4_mic_array/HEAD/MicArrayV3_firmware/6_channels_dfu_4.0.0_firmware.bin -------------------------------------------------------------------------------- /test/REAME.md: -------------------------------------------------------------------------------- 1 | 2 | ### requirements 3 | ``` 4 | pip install https://github.com/voice-engine/voice-engine/archive/master.zip 5 | pip install numpy 6 | git submodule init && git submodule update 7 | ``` 8 | 9 | + windows 10 | 11 | pip install 12 | pip install https://github.com/respeaker/respeaker_python_library/releases/download/v0.4.1/pocketsphinx-0.0.9-cp27-cp27m-win32.whl 13 | 14 | + linux / macos 15 | 16 | pip install pocketsphinx 17 | 18 | ### Get RMS 19 | 20 | ``` 21 | python rms.py 22 | ``` 23 | 24 | ### Compare recording audio and playing audio 25 | 26 | ``` 27 | python echo.py 28 | ``` -------------------------------------------------------------------------------- /test/kws.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Keyword spotting using pocketsphinx 5 | """ 6 | 7 | import os 8 | import threading 9 | 10 | try: 11 | import Queue as queue 12 | except ImportError: 13 | import queue 14 | 15 | from voice_engine.element import Element 16 | from pocketsphinx.pocketsphinx import Decoder 17 | 18 | class KWS(Element): 19 | def __init__(self): 20 | super(KWS, self).__init__() 21 | 22 | self.queue = queue.Queue() 23 | self.on_detected = None 24 | self.done = False 25 | 26 | def put(self, data): 27 | self.queue.put(data) 28 | 29 | def start(self): 30 | self.done = False 31 | thread = threading.Thread(target=self.run) 32 | thread.daemon = True 33 | thread.start() 34 | 35 | def stop(self): 36 | self.done = True 37 | 38 | def set_callback(self, callback): 39 | self.on_detected = callback 40 | 41 | def run(self): 42 | pocketsphinx_data = os.path.join(os.path.dirname(__file__), 'pocketsphinx-data') 43 | hmm = os.path.join(pocketsphinx_data, 'hmm') 44 | dic = os.path.join(pocketsphinx_data, 'dictionary.txt') 45 | kws_list = os.path.join(pocketsphinx_data, 'keywords.txt') 46 | 47 | config = Decoder.default_config() 48 | config.set_string('-hmm', hmm) 49 | config.set_string('-dict', dic) 50 | config.set_string('-kws', kws_list) 51 | # config.set_int('-samprate', SAMPLE_RATE) # uncomment if rate is not 16000. use config.set_float() on ubuntu 52 | config.set_int('-nfft', 512) 53 | config.set_float('-vad_threshold', 2.7) 54 | config.set_string('-logfn', os.devnull) 55 | 56 | decoder = Decoder(config) 57 | 58 | decoder.start_utt() 59 | 60 | while not self.done: 61 | data = self.queue.get() 62 | decoder.process_raw(data, False, False) 63 | hypothesis = decoder.hyp() 64 | if hypothesis: 65 | keyword = hypothesis.hypstr 66 | if callable(self.on_detected): 67 | self.on_detected(keyword) 68 | 69 | decoder.end_utt() 70 | decoder.start_utt() 71 | 72 | super(KWS, self).put(data) 73 | 74 | 75 | def main(): 76 | import time 77 | from .source import Source 78 | 79 | src = Source() 80 | kws = KWS() 81 | 82 | src.link(kws) 83 | 84 | def on_detected(keyword): 85 | print('found {}'.format(keyword)) 86 | 87 | kws.set_callback(on_detected) 88 | 89 | kws.start() 90 | src.start() 91 | 92 | while True: 93 | try: 94 | time.sleep(1) 95 | except KeyboardInterrupt: 96 | break 97 | 98 | kws.stop() 99 | src.stop() 100 | 101 | 102 | if __name__ == '__main__': 103 | main() 104 | -------------------------------------------------------------------------------- /test/player.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | """ 4 | 5 | import threading 6 | import types 7 | import wave 8 | import pyaudio 9 | 10 | 11 | CHUNK_SIZE = 1024 12 | 13 | 14 | class Player: 15 | def __init__(self, pyaudio_instance=None): 16 | self.pyaudio_instance = pyaudio_instance if pyaudio_instance else pyaudio.PyAudio() 17 | self.stop_event = threading.Event() 18 | 19 | self.device_index = None 20 | for i in range(self.pyaudio_instance.get_device_count()): 21 | dev = self.pyaudio_instance.get_device_info_by_index(i) 22 | name = dev['name'].encode('utf-8') 23 | print('{}:{} with {} input channels'.format(i, name, dev['maxOutputChannels'])) 24 | if name.find('ReSpeaker 4 Mic Array') >= 0 and dev['maxOutputChannels'] >= 1: 25 | self.device_index = i 26 | break 27 | 28 | if self.device_index is None: 29 | raise ValueError('Can not find {}'.format('ReSpeaker 4 Mic Array')) 30 | 31 | def _play(self, data, rate=16000, channels=1, width=2): 32 | stream = self.pyaudio_instance.open( 33 | format=self.pyaudio_instance.get_format_from_width(width), 34 | channels=channels, 35 | rate=rate, 36 | output=True, 37 | output_device_index=self.device_index, 38 | frames_per_buffer=CHUNK_SIZE, 39 | ) 40 | 41 | if isinstance(data, types.GeneratorType): 42 | for d in data: 43 | if self.stop_event.is_set(): 44 | break 45 | 46 | stream.write(d) 47 | else: 48 | stream.write(data) 49 | 50 | stream.close() 51 | 52 | def play(self, wav=None, data=None, rate=16000, channels=1, width=2, block=True): 53 | """ 54 | play wav file or raw audio (string or generator) 55 | Args: 56 | wav: wav file path 57 | data: raw audio data, str or iterator 58 | rate: sample rate, only for raw audio 59 | channels: channel number, only for raw data 60 | width: raw audio data width, 16 bit is 2, only for raw data 61 | block: if true, block until audio is played. 62 | spectrum: if true, use a spectrum analyzer thread to analyze data 63 | """ 64 | if wav: 65 | f = wave.open(wav, 'rb') 66 | rate = f.getframerate() 67 | channels = f.getnchannels() 68 | width = f.getsampwidth() 69 | 70 | def gen(w): 71 | d = w.readframes(CHUNK_SIZE) 72 | while d: 73 | yield d 74 | d = w.readframes(CHUNK_SIZE) 75 | w.close() 76 | 77 | data = gen(f) 78 | 79 | self.stop_event.clear() 80 | if block: 81 | self._play(data, rate, channels, width) 82 | else: 83 | thread = threading.Thread(target=self._play, args=(data, rate, channels, width)) 84 | thread.start() 85 | 86 | def stop(self): 87 | self.stop_event.set() 88 | 89 | def close(self): 90 | pass 91 | 92 | 93 | def main(): 94 | import sys 95 | 96 | if len(sys.argv) < 2: 97 | print('Usage: python {} music.wav'.format(sys.argv[0])) 98 | sys.exit(1) 99 | 100 | player = Player() 101 | player.play(sys.argv[1]) 102 | 103 | 104 | if __name__ == '__main__': 105 | main() 106 | -------------------------------------------------------------------------------- /test/rms.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import threading 4 | import sys 5 | if sys.version_info[0] < 3: 6 | import Queue as queue 7 | else: 8 | import queue 9 | 10 | import numpy as np 11 | import audioop 12 | import pyaudio 13 | 14 | from voice_engine.element import Element 15 | from voice_engine.file_sink import FileSink 16 | 17 | 18 | class Source(Element): 19 | def __init__(self, rate=16000, frames_size=None): 20 | 21 | super(Source, self).__init__() 22 | 23 | self.rate = rate 24 | self.frames_size = frames_size if frames_size else rate / 100 25 | self.channels = 6 26 | 27 | self.pyaudio_instance = pyaudio.PyAudio() 28 | 29 | device_index = None 30 | for i in range(self.pyaudio_instance.get_device_count()): 31 | dev = self.pyaudio_instance.get_device_info_by_index(i) 32 | name = dev['name'].encode('utf-8') 33 | print('{}:{} with {} input channels'.format(i, name, dev['maxInputChannels'])) 34 | if name.find('ReSpeaker 4 Mic Array') >= 0 and dev['maxInputChannels'] == self.channels: 35 | device_index = i 36 | break 37 | 38 | if device_index is None: 39 | raise ValueError('Can not find an input device with {} channel(s)'.format(self.channels)) 40 | 41 | self.stream = self.pyaudio_instance.open( 42 | start=False, 43 | format=pyaudio.paInt16, 44 | input_device_index=device_index, 45 | channels=self.channels, 46 | rate=int(self.rate), 47 | frames_per_buffer=int(self.frames_size), 48 | stream_callback=self._callback, 49 | input=True 50 | ) 51 | 52 | def _callback(self, in_data, frame_count, time_info, status): 53 | super(Source, self).put(in_data) 54 | 55 | return None, pyaudio.paContinue 56 | 57 | def start(self): 58 | self.stream.start_stream() 59 | 60 | def stop(self): 61 | self.stream.stop_stream() 62 | 63 | 64 | class RMS(Element): 65 | def __init__(self): 66 | super(RMS, self).__init__() 67 | 68 | self.channels = 6 69 | self.channels_mask = [1, 2, 3, 4] 70 | 71 | self.queue = queue.Queue() 72 | self.done = True 73 | 74 | def put(self, data): 75 | self.queue.put(data) 76 | 77 | def start(self): 78 | self.done = False 79 | thread = threading.Thread(target=self.run) 80 | thread.daemon = True 81 | thread.start() 82 | 83 | def stop(self): 84 | self.done = True 85 | 86 | def on_data(self, data): 87 | pass 88 | 89 | def run(self): 90 | while not self.done: 91 | data = self.queue.get() 92 | data = np.fromstring(data, dtype='int16') 93 | 94 | rms_data = [] 95 | rms_data_db = [] 96 | for ch in self.channels_mask: 97 | mono = data[ch::self.channels] 98 | rms = np.sqrt(np.mean(np.square(mono.astype('int32')))) 99 | rms_data.append(rms) 100 | # rms = 20 * np.log10(rms) 101 | # rms_data_db.append(rms) 102 | 103 | print(rms_data) 104 | 105 | # x = np.fromstring(data, dtype='int16') 106 | 107 | super(RMS, self).put(data) 108 | 109 | 110 | def main(): 111 | import time 112 | import datetime 113 | 114 | src = Source(frames_size=1600) 115 | rms = RMS() 116 | 117 | # filename = '1.quiet.' + datetime.datetime.now().strftime("%Y%m%d.%H:%M:%S") + '.wav' 118 | # sink = FileSink(filename, channels=src.channels, rate=src.rate) 119 | 120 | src.pipeline(rms) 121 | 122 | # src.link(sink) 123 | 124 | src.pipeline_start() 125 | 126 | while True: 127 | try: 128 | time.sleep(1) 129 | except KeyboardInterrupt: 130 | break 131 | 132 | src.pipeline_stop() 133 | 134 | 135 | if __name__ == '__main__': 136 | main() 137 | -------------------------------------------------------------------------------- /test/echo.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import threading 4 | import sys 5 | if sys.version_info[0] < 3: 6 | import Queue as queue 7 | else: 8 | import queue 9 | 10 | import numpy as np 11 | import audioop 12 | import pyaudio 13 | 14 | from voice_engine.element import Element 15 | from voice_engine.file_sink import FileSink 16 | from kws import KWS 17 | from player import Player 18 | 19 | 20 | class Source(Element): 21 | def __init__(self, rate=16000, frames_size=None): 22 | 23 | super(Source, self).__init__() 24 | 25 | self.rate = rate 26 | self.frames_size = frames_size if frames_size else rate / 100 27 | self.channels = 6 28 | 29 | self.pyaudio_instance = pyaudio.PyAudio() 30 | 31 | device_index = None 32 | for i in range(self.pyaudio_instance.get_device_count()): 33 | dev = self.pyaudio_instance.get_device_info_by_index(i) 34 | name = dev['name'].encode('utf-8') 35 | print('{}:{} with {} input channels'.format(i, name, dev['maxInputChannels'])) 36 | if name.find('ReSpeaker 4 Mic Array') >= 0 and dev['maxInputChannels'] == self.channels: 37 | device_index = i 38 | break 39 | 40 | if device_index is None: 41 | raise ValueError('Can not find an input device with {} channel(s)'.format(self.channels)) 42 | 43 | self.stream = self.pyaudio_instance.open( 44 | start=False, 45 | format=pyaudio.paInt16, 46 | input_device_index=device_index, 47 | channels=self.channels, 48 | rate=int(self.rate), 49 | frames_per_buffer=int(self.frames_size), 50 | stream_callback=self._callback, 51 | input=True 52 | ) 53 | 54 | def _callback(self, in_data, frame_count, time_info, status): 55 | super(Source, self).put(in_data) 56 | 57 | return None, pyaudio.paContinue 58 | 59 | def start(self): 60 | self.stream.start_stream() 61 | 62 | def stop(self): 63 | self.stream.stop_stream() 64 | 65 | 66 | class Route(Element): 67 | def __init__(self): 68 | super(Route, self).__init__() 69 | 70 | self.channels = 6 71 | self.detect_mask = 0 72 | 73 | self.kws_list = [] 74 | for ch in range(self.channels): 75 | def callback_gen(channel): 76 | def on_detected(keyword): 77 | self.detect_mask |= 1 << channel 78 | print('channel {} detected'.format(channel)) 79 | 80 | return on_detected 81 | 82 | kws = KWS() 83 | self.kws_list.append(kws) 84 | kws.on_detected = callback_gen(ch) 85 | kws.start() 86 | 87 | self.queue = queue.Queue() 88 | self.done = True 89 | 90 | def put(self, data): 91 | self.queue.put(data) 92 | 93 | def start(self): 94 | self.done = False 95 | thread = threading.Thread(target=self.run) 96 | thread.daemon = True 97 | thread.start() 98 | 99 | def stop(self): 100 | self.done = True 101 | 102 | for ch in range(self.channels): 103 | self.kws_list[ch].stop() 104 | 105 | def on_data(self, data): 106 | pass 107 | 108 | def run(self): 109 | while not self.done: 110 | data = self.queue.get() 111 | data = np.fromstring(data, dtype='int16') 112 | 113 | rms_data = [] 114 | rms_data_db = [] 115 | for ch in range(self.channels): 116 | mono = data[ch::self.channels] 117 | self.kws_list[ch].put(mono.tostring()) 118 | 119 | 120 | def main(): 121 | import time 122 | import datetime 123 | 124 | src = Source(frames_size=1600) 125 | route = Route() 126 | 127 | player = Player(pyaudio_instance=src.pyaudio_instance) 128 | 129 | # filename = '1.quiet.' + datetime.datetime.now().strftime("%Y%m%d.%H:%M:%S") + '.wav' 130 | # sink = FileSink(filename, channels=src.channels, rate=src.rate) 131 | 132 | src.pipeline(route) 133 | 134 | # src.link(sink) 135 | 136 | src.pipeline_start() 137 | 138 | time.sleep(1) 139 | player.play('respeaker.wav') 140 | time.sleep(1) 141 | player.play('respeaker.wav') 142 | 143 | for _ in range(10): 144 | time.sleep(1) 145 | if route.detect_mask == 0b111111: 146 | print('all channels detected') 147 | break 148 | 149 | src.pipeline_stop() 150 | 151 | if route.detect_mask != 0b111111: 152 | print('Not all channels detected') 153 | 154 | 155 | if __name__ == '__main__': 156 | main() 157 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ReSpeaker USB 4 Mic Array 2 | 3 | >Available at [Seeed](https://www.seeedstudio.com/ReSpeaker-Mic-Array-v2.0-p-3053.html) 4 | 5 | ![](http://respeaker.io/assets/images/usb_4_mic_array.png) 6 | 7 | The ReSpeaker USB 4 Mic Array is the successor of the ReSpeaker USB 6+1 Mic Array. It has better built-in audio processing algorithms than the 6+1 Mic Array, so it has better audio recording quality, although it only has 4 microphones. 8 | 9 | ## Features 10 | + 4 microphones 11 | + 12 RGB LEDs 12 | + USB 13 | + built-in AEC, VAD, DOA, Beamforming and NS 14 | + 16000 sample rate 15 | 16 | ## Usage 17 | [Audacity](https://www.audacityteam.org/) is recommended to test audio recording. 18 | 19 | ## Install DFU and LED control driver for Windows 20 | On Linux and macOS, the USB 4 Mic Array will just work. On Windows, audio recording and playback will also work without installing a driver. But in order to upgrade the device's firmware or to control LEDs an DSP parameters on Windows, the libusb-win32 driver is required. We use [a handy tool - Zadig](https://zadig.akeo.ie/) to install the libusb-win32 driver for both `SEEED DFU` and `SEEED Control` (the USB 4 Mic Array has 4 devices on Windows Device Manager). 21 | 22 | ![](http://respeaker.io/assets/images/usb_4mic_array_driver.png) 23 | 24 | >Make sure that libusb-win32 is selected, not WinUSB or libusbK 25 | 26 | ## Device Firmware Update 27 | The Microphone Array supports USB DFU. We have [a python script - dfu.py](https://github.com/respeaker/mic_array_dfu/blob/master/dfu.py) to do that. 28 | 29 | ``` 30 | pip install pyusb 31 | python dfu.py --download new_firmware.bin # with sudo if usb permission error 32 | ``` 33 | 34 | | firmware | channels | note | 35 | |---------------------------------|----------|-----------------------------------------------------------------------------------------------| 36 | | 1_channel_firmware.bin | 1 | processed audio for ASR | 37 | | 6_channels_firmware.bin | 6 | channel 0: processed audio for ASR, channel 1-4: 4 microphones' raw data, channel 5: playback | 38 | 39 | 40 | >**Note: The flash memory of XVF3000 has updated from 90nm to 65nm, the Jedec ID between the 90nm and 65nm flash memories has a 1-bit different. This will cause the new device not upgradable after you download old firmware(v2.0.0 or below) to an new device. The new firmware(v3.0.0 or above) is already compatible with old device and new device, so we advise customers to use the new firmware when DFU. The new 65nm flash memory device will use new part numbers with a suffix 'A' as the following picture:** 41 | 42 | ![](./newdevice.png) 43 | 44 | ### Summary of programming and dfu scenarios: 45 | 46 | | | hardware | factory programmed | DFU firmware | outcome | 47 | | :-----| :-----| :-----| :-----| :-----| 48 | | 1 | old device | any | any | DFU succeed, device operates correctly and upgradeable | 49 | | 2 | new device (XVF3000 with a suffix 'A') | 3.0.0 | 3.0.0 or above | DFU succeed, device operates correctly and upgradeable | 50 | | 3 | new device (XVF3000 with a suffix 'A') | 3.0.0 | 2.0.0 or below | DFU succeed, device operates correctly, but **not upgradeable** | 51 | 52 | ## How to control the RGB LED ring 53 | The USB 4 Mic Array has on-board 12 RGB LEDs and has a variety of light effects. Go to the [respeaker/pixel_ring](https://github.com/respeaker/pixel_ring) to learn how to use it. The LED control protocol is at [respeaker/pixel_ring wiki](https://github.com/respeaker/pixel_ring/wiki/ReSpeaker-USB-4-Mic-Array-LED-Control-Protocol). 54 | 55 | 56 | ## Tuning 57 | There are some parameters of built-in algorithms to configure. For example, we can turn off Automatic Gain Control (AGC): 58 | 59 | ``` 60 | python tuning.py AGCONOFF 0i6_firmware.bin 61 | ``` 62 | 63 | To get the full list parameters, run: 64 | 65 | ``` 66 | python tuning.py -p 67 | ``` 68 | 69 | ## Realtime sound source localization and tracking 70 | [ODAS](https://github.com/introlab/odas) is a very cool project to perform sound source localization, tracking, separation and post-filtering. Let's have a try! 71 | 72 | 1. get ODAS and build it 73 | 74 | ``` 75 | sudo apt-get install libfftw3-dev libconfig-dev libasound2-dev 76 | git clone https://github.com/introlab/odas.git --branch=dev 77 | mkdir odas/build 78 | cd odas/build 79 | cmake .. 80 | make 81 | ``` 82 | 83 | 2. get ODAS Studio from https://github.com/introlab/odas_web/releases and open it. 84 | 85 | The `odascore` will be at `odas/bin/odascore`, the config file is at [odas.cfg](odas.cfg). Change `odas.cfg` based on your sound card number. 86 | 87 | 88 | ``` 89 | interface: { 90 | type = "soundcard"; 91 | card = 1; 92 | device = 0; 93 | } 94 | ``` 95 | 96 | 3. upgrade your usb 4 mic array with [6_channels_firmware_6.02dB.bin](6_channels_firmware_6.02dB.bin) (or 6_channels_firmware.bin, 6_channels_firmware_12.04dB.bin) which includes 4 channels raw audio data. 97 | 98 | ![](https://github.com/introlab/odas_web/raw/master/screenshots/live_data.png) 99 | -------------------------------------------------------------------------------- /odas.cfg: -------------------------------------------------------------------------------- 1 | # Configuration file for XMOS circular sound card 2 | 3 | version = "2.1"; 4 | 5 | # Raw 6 | 7 | raw: 8 | { 9 | 10 | fS = 16000; 11 | hopSize = 128; 12 | nBits = 16; 13 | nChannels = 6; 14 | 15 | # Input with raw signal from microphones 16 | interface: { 17 | type = "soundcard"; 18 | card = 1; 19 | device = 0; 20 | } 21 | 22 | } 23 | 24 | # Mapping 25 | 26 | mapping: 27 | { 28 | 29 | map: (2, 3, 4, 5); 30 | 31 | } 32 | 33 | # General 34 | 35 | general: 36 | { 37 | 38 | epsilon = 1E-20; 39 | 40 | size: 41 | { 42 | hopSize = 128; 43 | frameSize = 256; 44 | }; 45 | 46 | samplerate: 47 | { 48 | mu = 16000; 49 | sigma2 = 0.01; 50 | }; 51 | 52 | speedofsound: 53 | { 54 | mu = 343.0; 55 | sigma2 = 25.0; 56 | }; 57 | 58 | mics = ( 59 | 60 | # Microphone 2 61 | { 62 | mu = ( -0.032, +0.000, +0.000 ); 63 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 64 | direction = ( +0.000, +0.000, +1.000 ); 65 | angle = ( 80.0, 100.0 ); 66 | }, 67 | 68 | # Microphone 3 69 | { 70 | mu = ( +0.000, -0.032, +0.000 ); 71 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 72 | direction = ( +0.000, +0.000, +1.000 ); 73 | angle = ( 80.0, 100.0 ); 74 | }, 75 | 76 | # Microphone 4 77 | { 78 | mu = ( +0.032, +0.000, +0.000 ); 79 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 80 | direction = ( +0.000, +0.000, +1.000 ); 81 | angle = ( 80.0, 100.0 ); 82 | }, 83 | 84 | # Microphone 5 85 | { 86 | mu = ( +0.000, +0.032, +0.000 ); 87 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 88 | direction = ( +0.000, +0.000, +1.000 ); 89 | angle = ( 80.0, 100.0 ); 90 | } 91 | 92 | ); 93 | 94 | # Spatial filter to include only a range of direction if required 95 | # (may be useful to remove false detections from the floor) 96 | spatialfilters = ( 97 | 98 | { 99 | direction = ( +0.000, +0.000, +1.000 ); 100 | angle = (80.0, 100.0); 101 | 102 | } 103 | 104 | ); 105 | 106 | nThetas = 181; 107 | gainMin = 0.25; 108 | 109 | }; 110 | 111 | # Stationnary noise estimation 112 | 113 | sne: 114 | { 115 | 116 | b = 3; 117 | alphaS = 0.1; 118 | L = 150; 119 | delta = 3.0; 120 | alphaD = 0.1; 121 | 122 | } 123 | 124 | # Sound Source Localization 125 | 126 | ssl: 127 | { 128 | 129 | nPots = 4; 130 | nMatches = 10; 131 | probMin = 0.5; 132 | nRefinedLevels = 1; 133 | interpRate = 4; 134 | 135 | # Number of scans: level is the resolution of the sphere 136 | # and delta is the size of the maximum sliding window 137 | # (delta = -1 means the size is automatically computed) 138 | scans = ( 139 | { level = 2; delta = -1; }, 140 | { level = 4; delta = -1; } 141 | ); 142 | 143 | # Output to export potential sources 144 | potential: { 145 | 146 | # format = "undefined"; 147 | format = "json"; 148 | 149 | interface: { 150 | # type = "blackhole"; 151 | type = "socket"; ip = "127.0.0.1"; port = 9001; 152 | }; 153 | 154 | }; 155 | 156 | }; 157 | 158 | # Sound Source Tracking 159 | 160 | sst: 161 | { 162 | 163 | # Mode is either "kalman" or "particle" 164 | 165 | mode = "kalman"; 166 | 167 | # Add is either "static" or "dynamic" 168 | 169 | add = "dynamic"; 170 | 171 | # Parameters used by both the Kalman and particle filter 172 | 173 | active = ( 174 | { weight = 1.0; mu = 0.4; sigma2 = 0.0025 } 175 | ); 176 | 177 | inactive = ( 178 | { weight = 1.0; mu = 0.25; sigma2 = 0.0025 } 179 | ); 180 | 181 | sigmaR2_prob = 0.0025; 182 | sigmaR2_active = 0.0225; 183 | sigmaR2_target = 0.0025; 184 | Pfalse = 0.1; 185 | Pnew = 0.1; 186 | Ptrack = 0.8; 187 | 188 | theta_new = 0.9; 189 | N_prob = 5; 190 | theta_prob = 0.8; 191 | N_inactive = ( 250, 250, 250, 250 ); 192 | theta_inactive = 0.9; 193 | 194 | # Parameters used by the Kalman filter only 195 | 196 | kalman: { 197 | 198 | sigmaQ = 0.001; 199 | 200 | }; 201 | 202 | # Parameters used by the particle filter only 203 | 204 | particle: { 205 | 206 | nParticles = 1000; 207 | st_alpha = 2.0; 208 | st_beta = 0.04; 209 | st_ratio = 0.5; 210 | ve_alpha = 0.05; 211 | ve_beta = 0.2; 212 | ve_ratio = 0.3; 213 | ac_alpha = 0.5; 214 | ac_beta = 0.2; 215 | ac_ratio = 0.2; 216 | Nmin = 0.7; 217 | 218 | }; 219 | 220 | target: (); 221 | 222 | # Output to export tracked sources 223 | tracked: { 224 | 225 | format = "json"; 226 | 227 | interface: { 228 | # type = "file"; 229 | # path = "tracks.txt"; 230 | type = "socket"; ip = "127.0.0.1"; port = 9000; 231 | }; 232 | 233 | }; 234 | 235 | } 236 | 237 | sss: 238 | { 239 | 240 | # Mode is either "dds", "dgss" or "dmvdr" 241 | 242 | mode_sep = "dgss"; 243 | mode_pf = "ms"; 244 | 245 | gain_sep = 1.0; 246 | gain_pf = 10.0; 247 | 248 | dds: { 249 | 250 | }; 251 | 252 | dgss: { 253 | 254 | mu = 0.01; 255 | lambda = 0.5; 256 | 257 | }; 258 | 259 | dmvdr: { 260 | 261 | }; 262 | 263 | ms: { 264 | 265 | alphaPmin = 0.07; 266 | eta = 0.5; 267 | alphaZ = 0.8; 268 | thetaWin = 0.3; 269 | alphaWin = 0.3; 270 | maxAbsenceProb = 0.9; 271 | Gmin = 0.01; 272 | winSizeLocal = 3; 273 | winSizeGlobal = 23; 274 | winSizeFrame = 256; 275 | 276 | }; 277 | 278 | ss: { 279 | 280 | Gmin = 0.01; 281 | Gmid = 0.9; 282 | Gslope = 10.0; 283 | 284 | }; 285 | 286 | separated: { 287 | 288 | fS = 16000; 289 | hopSize = 128; 290 | nBits = 16; 291 | 292 | interface: { 293 | type = "file"; 294 | path = "separated.raw"; 295 | }; 296 | 297 | }; 298 | 299 | postfiltered: { 300 | 301 | fS = 16000; 302 | hopSize = 128; 303 | nBits = 16; 304 | gain = 10.0; 305 | 306 | interface: { 307 | type = "file"; 308 | path = "postfiltered.raw"; 309 | }; 310 | 311 | }; 312 | 313 | }; 314 | 315 | classify: 316 | { 317 | 318 | frameSize = 4096; 319 | winSize = 3; 320 | tauMin = 88; 321 | tauMax = 551; 322 | deltaTauMax = 20; 323 | alpha = 0.3; 324 | gamma = 0.05; 325 | phiMin = 0.5; 326 | r0 = 0.2; 327 | 328 | category: { 329 | 330 | format = "undefined"; 331 | 332 | interface: { 333 | type = "blackhole"; 334 | } 335 | 336 | } 337 | 338 | } 339 | -------------------------------------------------------------------------------- /dfu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | DFU tool for ReSpeaker USB Mic Array 4 | 5 | Requirements: 6 | pip install pyusb click 7 | 8 | Usage: 9 | python dfu.py --download new_firmware.bin 10 | python dfu.py --revertfactory 11 | """ 12 | 13 | import sys 14 | import time 15 | import usb.core 16 | import usb.util 17 | import click 18 | 19 | 20 | class DFU(object): 21 | TIMEOUT = 120000 22 | 23 | DFU_DETACH = 0 24 | DFU_DNLOAD = 1 25 | DFU_UPLOAD = 2 26 | DFU_GETSTATUS = 3 27 | DFU_CLRSTATUS = 4 28 | DFU_GETSTATE = 5 29 | DFU_ABORT = 6 30 | 31 | DFU_STATUS_DICT = { 32 | 0x00: 'No error condition is present.', 33 | 0x01: 'File is not targeted for use by this device.', 34 | 0x02: 'File is for this device but fails some vendor-specific ' 35 | 'verification test.', 36 | 0x03: 'Device is unable to write memory.', 37 | 0x04: 'Memory erase function failed.', 38 | 0x05: 'Memory erase check failed.', 39 | 0x06: 'Program memory function failed.', 40 | 0x07: 'Programmed memory failed verification.', 41 | 0x08: 'Cannot program memory due to received address that is our of ' 42 | 'range.', 43 | 0x09: 'Received DFU_DNLOAD with wLength = 0, but device does not think it' 44 | 'has all of the data yet.', 45 | 0x0a: "Device's firmware is corrupt. It cannot return to run-time " 46 | "(non-DFU) operations.", 47 | 0x0b: 'iString indicates a vendor-specific error.', 48 | 0x0c: 'Device detected unexpected USB reset signaling.', 49 | 0x0d: 'Device detected unexpected power on reset.', 50 | 0x0e: 'Something went wrong, but the device does not know what is was.', 51 | 0x0f: 'Device stalled a unexpected request.', 52 | } 53 | 54 | @staticmethod 55 | def find(): 56 | """ 57 | find all USB devices with a DFU interface 58 | """ 59 | devices = [] 60 | for device in usb.core.find(find_all=True, idVendor=0x2886, idProduct=0x0018): 61 | configuration = device.get_active_configuration() 62 | 63 | for interface in configuration: 64 | if interface.bInterfaceClass == 0xFE and interface.bInterfaceSubClass == 0x01: 65 | devices.append((device, interface.bInterfaceNumber, configuration.bNumInterfaces)) 66 | break 67 | 68 | return devices 69 | 70 | def __init__(self): 71 | devices = self.find() 72 | if not devices: 73 | raise ValueError('No DFU device found') 74 | 75 | # TODO: support multiple devices 76 | if len(devices) > 1: 77 | raise ValueError('Multiple DFU devices found') 78 | 79 | self.device, self.interface, self.num_interfaces = devices[0] 80 | 81 | # if self.device.is_kernel_driver_active(self.interface): 82 | # self.device.detach_kernel_driver(self.interface) 83 | 84 | usb.util.claim_interface(self.device, self.interface) 85 | 86 | def __enter__(self): 87 | # TODO: suppose the device has more than 1 interface at Run-Time 88 | if self.num_interfaces > 1: 89 | print('entering dfu mode') 90 | self._detach() 91 | self.close() 92 | 93 | # wait for re-enumerating device 94 | timeout = 20 95 | while timeout: 96 | timeout -= 1 97 | time.sleep(1) 98 | devices = self.find() 99 | 100 | if len(devices) and devices[0][2] == 1: 101 | print('found dfu device') 102 | break 103 | else: 104 | raise ValueError('No re-enumerated DFU device found') 105 | 106 | self.device, self.interface, _ = devices[0] 107 | 108 | # # Windows doesn't implement this 109 | # if self.device.is_kernel_driver_active(self.interface): 110 | # self.device.detach_kernel_driver(self.interface) 111 | 112 | usb.util.claim_interface(self.device, self.interface) 113 | 114 | return self 115 | 116 | def __exit__(self, exc_type, exc_value, traceback): 117 | pass 118 | 119 | def download(self, firmware): 120 | """ 121 | Args: 122 | firmware (file object): the file to download. 123 | """ 124 | block_size = 64 125 | block_number = 0 126 | print('downloading') 127 | while True: 128 | data = firmware.read(block_size) 129 | self._download(block_number, data) 130 | status = self._get_status()[0] 131 | if status: 132 | raise IOError(self.DFU_STATUS_DICT[status]) 133 | 134 | block_number += 1 135 | sys.stdout.write('{} bytes\r'.format(block_number * block_size)) 136 | sys.stdout.flush() 137 | 138 | if not data: 139 | break 140 | 141 | print('\ndone') 142 | 143 | def upload(self, firmware): 144 | pass 145 | 146 | def _detach(self): 147 | return self._out_request(self.DFU_DETACH) 148 | 149 | def _download(self, block_number, data): 150 | return self._out_request(self.DFU_DNLOAD, value=block_number, data=data) 151 | 152 | 153 | def _get_status(self): 154 | data = self._in_request(self.DFU_GETSTATUS, 6) 155 | 156 | status = data[0] 157 | timeout = data[1] + data[2] << 8 + data[3] << 16 158 | state = data[4] 159 | status_description = data[5] # index of status description in string table 160 | 161 | return status, timeout, state, status_description 162 | 163 | def _clear_status(self): 164 | return self._out_request(self.DFU_CLRSTATUS) 165 | 166 | def _get_state(self): 167 | return self._in_request(self.DFU_GETSTATE, 1)[0] 168 | 169 | def _abort(self): 170 | return self._out_request(self.DFU_ABORT) 171 | 172 | def _out_request(self, request, value=0, data=None): 173 | return self.device.ctrl_transfer( 174 | usb.util.CTRL_OUT | usb.util.CTRL_TYPE_CLASS | usb.util.CTRL_RECIPIENT_INTERFACE, 175 | request, value, self.interface, data, self.TIMEOUT) 176 | 177 | def _in_request(self, request, length): 178 | return self.device.ctrl_transfer( 179 | usb.util.CTRL_IN | usb.util.CTRL_TYPE_CLASS | usb.util.CTRL_RECIPIENT_INTERFACE, 180 | request, 0x0, self.interface, length, self.TIMEOUT) 181 | 182 | def close(self): 183 | """ 184 | close the interface 185 | """ 186 | usb.util.dispose_resources(self.device) 187 | 188 | 189 | class XMOS_DFU(DFU): 190 | XMOS_DFU_RESETDEVICE = 0xf0 191 | XMOS_DFU_REVERTFACTORY = 0xf1 192 | XMOS_DFU_RESETINTODFU = 0xf2 193 | XMOS_DFU_RESETFROMDFU = 0xf3 194 | XMOS_DFU_SAVESTATE = 0xf5 195 | XMOS_DFU_RESTORESTATE = 0xf6 196 | 197 | def __init__(self): 198 | super(XMOS_DFU, self).__init__() 199 | 200 | def _detach(self): 201 | return self._out_request(self.XMOS_DFU_RESETINTODFU) 202 | 203 | def leave(self): 204 | return self._out_request(self.XMOS_DFU_RESETFROMDFU) 205 | 206 | def revertfactory(self): 207 | return self._out_request(self.XMOS_DFU_REVERTFACTORY) 208 | 209 | def __exit__(self, exc_type, exc_value, traceback): 210 | self.leave() 211 | 212 | 213 | 214 | @click.command() 215 | @click.option('--download', '-d', nargs=1, type=click.File('rb'), help='the firmware to download') 216 | @click.option('--revertfactory', is_flag=True, help="factory reset") 217 | def main(download, revertfactory): 218 | dev = XMOS_DFU() 219 | 220 | with dev: 221 | if download: 222 | dev.download(download) 223 | elif revertfactory: 224 | dev.revertfactory() 225 | 226 | dev.close() 227 | 228 | if __name__ == '__main__': 229 | main() 230 | 231 | 232 | -------------------------------------------------------------------------------- /dfu_windows.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | DFU tool for ReSpeaker USB Mic Array 4 | 5 | Requirements: 6 | pip install pyusb click 7 | 8 | Usage: 9 | python dfu.py --download new_firmware.bin 10 | python dfu.py --revertfactory 11 | """ 12 | 13 | import sys 14 | import time 15 | import usb.core 16 | import usb.util 17 | import click 18 | 19 | 20 | class DFU(object): 21 | TIMEOUT = 120000 22 | 23 | DFU_DETACH = 0 24 | DFU_DNLOAD = 1 25 | DFU_UPLOAD = 2 26 | DFU_GETSTATUS = 3 27 | DFU_CLRSTATUS = 4 28 | DFU_GETSTATE = 5 29 | DFU_ABORT = 6 30 | 31 | DFU_STATUS_DICT = { 32 | 0x00: 'No error condition is present.', 33 | 0x01: 'File is not targeted for use by this device.', 34 | 0x02: 'File is for this device but fails some vendor-specific ' 35 | 'verification test.', 36 | 0x03: 'Device is unable to write memory.', 37 | 0x04: 'Memory erase function failed.', 38 | 0x05: 'Memory erase check failed.', 39 | 0x06: 'Program memory function failed.', 40 | 0x07: 'Programmed memory failed verification.', 41 | 0x08: 'Cannot program memory due to received address that is our of ' 42 | 'range.', 43 | 0x09: 'Received DFU_DNLOAD with wLength = 0, but device does not think it' 44 | 'has all of the data yet.', 45 | 0x0a: "Device's firmware is corrupt. It cannot return to run-time " 46 | "(non-DFU) operations.", 47 | 0x0b: 'iString indicates a vendor-specific error.', 48 | 0x0c: 'Device detected unexpected USB reset signaling.', 49 | 0x0d: 'Device detected unexpected power on reset.', 50 | 0x0e: 'Something went wrong, but the device does not know what is was.', 51 | 0x0f: 'Device stalled a unexpected request.', 52 | } 53 | 54 | @staticmethod 55 | def find(): 56 | """ 57 | find all USB devices with a DFU interface 58 | """ 59 | devices = [] 60 | for device in usb.core.find(find_all=True): 61 | configuration = device.get_active_configuration() 62 | 63 | for interface in configuration: 64 | if interface.bInterfaceClass == 0xFE and interface.bInterfaceSubClass == 0x01: 65 | devices.append((device, interface.bInterfaceNumber, configuration.bNumInterfaces)) 66 | break 67 | 68 | return devices 69 | 70 | def __init__(self): 71 | devices = self.find() 72 | if not devices: 73 | raise ValueError('No DFU device found') 74 | 75 | # TODO: support multiple devices 76 | if len(devices) > 1: 77 | raise ValueError('Multiple DFU devices found') 78 | 79 | self.device, self.interface, self.num_interfaces = devices[0] 80 | 81 | # if self.device.is_kernel_driver_active(self.interface): 82 | # self.device.detach_kernel_driver(self.interface) 83 | 84 | usb.util.claim_interface(self.device, self.interface) 85 | 86 | def __enter__(self): 87 | # TODO: suppose the device has more than 1 interface at Run-Time 88 | # on windows, self.num_interfaces can be 1 even if not in dfu mode -_-! 89 | if True: # self.num_interfaces > 1: 90 | print('entering dfu mode') 91 | self._detach() 92 | self.close() 93 | 94 | # wait 6 seconds 95 | time.sleep(6) 96 | 97 | # wait for re-enumerating device 98 | timeout = 12 99 | while timeout: 100 | timeout -= 1 101 | devices = self.find() 102 | 103 | if len(devices) and devices[0][2] == 1: 104 | print('found dfu device') 105 | break 106 | time.sleep(1) 107 | else: 108 | raise ValueError('No re-enumerated DFU device found') 109 | 110 | self.device, self.interface, _ = devices[0] 111 | 112 | # # Windows doesn't implement this 113 | # if self.device.is_kernel_driver_active(self.interface): 114 | # self.device.detach_kernel_driver(self.interface) 115 | 116 | usb.util.claim_interface(self.device, self.interface) 117 | 118 | return self 119 | 120 | def __exit__(self, exc_type, exc_value, traceback): 121 | pass 122 | 123 | def download(self, firmware): 124 | """ 125 | Args: 126 | firmware (file object): the file to download. 127 | """ 128 | block_size = 64 129 | block_number = 0 130 | print('downloading') 131 | while True: 132 | data = firmware.read(block_size) 133 | self._download(block_number, data) 134 | status = self._get_status()[0] 135 | if status: 136 | raise IOError(self.DFU_STATUS_DICT[status]) 137 | 138 | block_number += 1 139 | 140 | # on windows, sys.stdout.write() or print() may got IOError -_-! 141 | # sys.stdout.write('{} bytes\r'.format(block_number * block_size)) 142 | # sys.stdout.flush() 143 | 144 | if not data: 145 | break 146 | 147 | print('\ndone') 148 | 149 | def upload(self, firmware): 150 | pass 151 | 152 | def _detach(self): 153 | return self._out_request(self.DFU_DETACH) 154 | 155 | def _download(self, block_number, data): 156 | return self._out_request(self.DFU_DNLOAD, value=block_number, data=data) 157 | 158 | 159 | def _get_status(self): 160 | data = self._in_request(self.DFU_GETSTATUS, 6) 161 | 162 | status = data[0] 163 | timeout = data[1] + data[2] << 8 + data[3] << 16 164 | state = data[4] 165 | status_description = data[5] # index of status description in string table 166 | 167 | return status, timeout, state, status_description 168 | 169 | def _clear_status(self): 170 | return self._out_request(self.DFU_CLRSTATUS) 171 | 172 | def _get_state(self): 173 | return self._in_request(self.DFU_GETSTATE, 1)[0] 174 | 175 | def _abort(self): 176 | return self._out_request(self.DFU_ABORT) 177 | 178 | def _out_request(self, request, value=0, data=None): 179 | return self.device.ctrl_transfer( 180 | usb.util.CTRL_OUT | usb.util.CTRL_TYPE_CLASS | usb.util.CTRL_RECIPIENT_INTERFACE, 181 | request, value, self.interface, data, self.TIMEOUT) 182 | 183 | def _in_request(self, request, length): 184 | return self.device.ctrl_transfer( 185 | usb.util.CTRL_IN | usb.util.CTRL_TYPE_CLASS | usb.util.CTRL_RECIPIENT_INTERFACE, 186 | request, 0x0, self.interface, length, self.TIMEOUT) 187 | 188 | def close(self): 189 | """ 190 | close the interface 191 | """ 192 | usb.util.dispose_resources(self.device) 193 | 194 | 195 | class XMOS_DFU(DFU): 196 | XMOS_DFU_RESETDEVICE = 0xf0 197 | XMOS_DFU_REVERTFACTORY = 0xf1 198 | XMOS_DFU_RESETINTODFU = 0xf2 199 | XMOS_DFU_RESETFROMDFU = 0xf3 200 | XMOS_DFU_SAVESTATE = 0xf5 201 | XMOS_DFU_RESTORESTATE = 0xf6 202 | 203 | def __init__(self): 204 | super(XMOS_DFU, self).__init__() 205 | 206 | def _detach(self): 207 | return self._out_request(self.XMOS_DFU_RESETINTODFU) 208 | 209 | def leave(self): 210 | return self._out_request(self.XMOS_DFU_RESETFROMDFU) 211 | 212 | def revertfactory(self): 213 | return self._out_request(self.XMOS_DFU_REVERTFACTORY) 214 | 215 | def __exit__(self, exc_type, exc_value, traceback): 216 | self.leave() 217 | 218 | 219 | 220 | @click.command() 221 | @click.option('--download', '-d', nargs=1, type=click.File('rb'), help='the firmware to download') 222 | @click.option('--revertfactory', is_flag=True, help="factory reset") 223 | def main(download, revertfactory): 224 | dev = XMOS_DFU() 225 | 226 | with dev: 227 | if download: 228 | dev.download(download) 229 | elif revertfactory: 230 | dev.revertfactory() 231 | 232 | dev.close() 233 | 234 | if __name__ == '__main__': 235 | main() 236 | 237 | 238 | -------------------------------------------------------------------------------- /tuning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | import struct 5 | import usb.core 6 | import usb.util 7 | 8 | USAGE = """Usage: python {} -h 9 | -p show all parameters 10 | -r read all parameters 11 | NAME get the parameter with the NAME 12 | NAME VALUE set the parameter with the NAME and the VALUE 13 | """ 14 | 15 | 16 | 17 | # parameter list 18 | # name: (id, offset, type, max, min , r/w, info) 19 | PARAMETERS = { 20 | 'AECFREEZEONOFF': (18, 7, 'int', 1, 0, 'rw', 'Adaptive Echo Canceler updates inhibit.', '0 = Adaptation enabled', '1 = Freeze adaptation, filter only'), 21 | 'AECNORM': (18, 19, 'float', 16, 0.25, 'rw', 'Limit on norm of AEC filter coefficients'), 22 | 'AECPATHCHANGE': (18, 25, 'int', 1, 0, 'ro', 'AEC Path Change Detection.', '0 = false (no path change detected)', '1 = true (path change detected)'), 23 | 'RT60': (18, 26, 'float', 0.9, 0.25, 'ro', 'Current RT60 estimate in seconds'), 24 | 'HPFONOFF': (18, 27, 'int', 3, 0, 'rw', 'High-pass Filter on microphone signals.', '0 = OFF', '1 = ON - 70 Hz cut-off', '2 = ON - 125 Hz cut-off', '3 = ON - 180 Hz cut-off'), 25 | 'RT60ONOFF': (18, 28, 'int', 1, 0, 'rw', 'RT60 Estimation for AES. 0 = OFF 1 = ON'), 26 | 'AECSILENCELEVEL': (18, 30, 'float', 1, 1e-09, 'rw', 'Threshold for signal detection in AEC [-inf .. 0] dBov (Default: -80dBov = 10log10(1x10-8))'), 27 | 'AECSILENCEMODE': (18, 31, 'int', 1, 0, 'ro', 'AEC far-end silence detection status. ', '0 = false (signal detected) ', '1 = true (silence detected)'), 28 | 'AGCONOFF': (19, 0, 'int', 1, 0, 'rw', 'Automatic Gain Control. ', '0 = OFF ', '1 = ON'), 29 | 'AGCMAXGAIN': (19, 1, 'float', 1000, 1, 'rw', 'Maximum AGC gain factor. ', '[0 .. 60] dB (default 30dB = 20log10(31.6))'), 30 | 'AGCDESIREDLEVEL': (19, 2, 'float', 0.99, 1e-08, 'rw', 'Target power level of the output signal. ', '[-inf .. 0] dBov (default: -23dBov = 10log10(0.005))'), 31 | 'AGCGAIN': (19, 3, 'float', 1000, 1, 'rw', 'Current AGC gain factor. ', '[0 .. 60] dB (default: 0.0dB = 20log10(1.0))'), 32 | 'AGCTIME': (19, 4, 'float', 1, 0.1, 'rw', 'Ramps-up / down time-constant in seconds.'), 33 | 'CNIONOFF': (19, 5, 'int', 1, 0, 'rw', 'Comfort Noise Insertion.', '0 = OFF', '1 = ON'), 34 | 'FREEZEONOFF': (19, 6, 'int', 1, 0, 'rw', 'Adaptive beamformer updates.', '0 = Adaptation enabled', '1 = Freeze adaptation, filter only'), 35 | 'STATNOISEONOFF': (19, 8, 'int', 1, 0, 'rw', 'Stationary noise suppression.', '0 = OFF', '1 = ON'), 36 | 'GAMMA_NS': (19, 9, 'float', 3, 0, 'rw', 'Over-subtraction factor of stationary noise. min .. max attenuation'), 37 | 'MIN_NS': (19, 10, 'float', 1, 0, 'rw', 'Gain-floor for stationary noise suppression.', '[-inf .. 0] dB (default: -16dB = 20log10(0.15))'), 38 | 'NONSTATNOISEONOFF': (19, 11, 'int', 1, 0, 'rw', 'Non-stationary noise suppression.', '0 = OFF', '1 = ON'), 39 | 'GAMMA_NN': (19, 12, 'float', 3, 0, 'rw', 'Over-subtraction factor of non- stationary noise. min .. max attenuation'), 40 | 'MIN_NN': (19, 13, 'float', 1, 0, 'rw', 'Gain-floor for non-stationary noise suppression.', '[-inf .. 0] dB (default: -10dB = 20log10(0.3))'), 41 | 'ECHOONOFF': (19, 14, 'int', 1, 0, 'rw', 'Echo suppression.', '0 = OFF', '1 = ON'), 42 | 'GAMMA_E': (19, 15, 'float', 3, 0, 'rw', 'Over-subtraction factor of echo (direct and early components). min .. max attenuation'), 43 | 'GAMMA_ETAIL': (19, 16, 'float', 3, 0, 'rw', 'Over-subtraction factor of echo (tail components). min .. max attenuation'), 44 | 'GAMMA_ENL': (19, 17, 'float', 5, 0, 'rw', 'Over-subtraction factor of non-linear echo. min .. max attenuation'), 45 | 'NLATTENONOFF': (19, 18, 'int', 1, 0, 'rw', 'Non-Linear echo attenuation.', '0 = OFF', '1 = ON'), 46 | 'NLAEC_MODE': (19, 20, 'int', 2, 0, 'rw', 'Non-Linear AEC training mode.', '0 = OFF', '1 = ON - phase 1', '2 = ON - phase 2'), 47 | 'SPEECHDETECTED': (19, 22, 'int', 1, 0, 'ro', 'Speech detection status.', '0 = false (no speech detected)', '1 = true (speech detected)'), 48 | 'FSBUPDATED': (19, 23, 'int', 1, 0, 'ro', 'FSB Update Decision.', '0 = false (FSB was not updated)', '1 = true (FSB was updated)'), 49 | 'FSBPATHCHANGE': (19, 24, 'int', 1, 0, 'ro', 'FSB Path Change Detection.', '0 = false (no path change detected)', '1 = true (path change detected)'), 50 | 'TRANSIENTONOFF': (19, 29, 'int', 1, 0, 'rw', 'Transient echo suppression.', '0 = OFF', '1 = ON'), 51 | 'VOICEACTIVITY': (19, 32, 'int', 1, 0, 'ro', 'VAD voice activity status.', '0 = false (no voice activity)', '1 = true (voice activity)'), 52 | 'STATNOISEONOFF_SR': (19, 33, 'int', 1, 0, 'rw', 'Stationary noise suppression for ASR.', '0 = OFF', '1 = ON'), 53 | 'NONSTATNOISEONOFF_SR': (19, 34, 'int', 1, 0, 'rw', 'Non-stationary noise suppression for ASR.', '0 = OFF', '1 = ON'), 54 | 'GAMMA_NS_SR': (19, 35, 'float', 3, 0, 'rw', 'Over-subtraction factor of stationary noise for ASR. ', '[0.0 .. 3.0] (default: 1.0)'), 55 | 'GAMMA_NN_SR': (19, 36, 'float', 3, 0, 'rw', 'Over-subtraction factor of non-stationary noise for ASR. ', '[0.0 .. 3.0] (default: 1.1)'), 56 | 'MIN_NS_SR': (19, 37, 'float', 1, 0, 'rw', 'Gain-floor for stationary noise suppression for ASR.', '[-inf .. 0] dB (default: -16dB = 20log10(0.15))'), 57 | 'MIN_NN_SR': (19, 38, 'float', 1, 0, 'rw', 'Gain-floor for non-stationary noise suppression for ASR.', '[-inf .. 0] dB (default: -10dB = 20log10(0.3))'), 58 | 'GAMMAVAD_SR': (19, 39, 'float', 1000, 0, 'rw', 'Set the threshold for voice activity detection.', '[-inf .. 60] dB (default: 3.5dB 20log10(1.5))'), 59 | # 'KEYWORDDETECT': (20, 0, 'int', 1, 0, 'ro', 'Keyword detected. Current value so needs polling.'), 60 | 'DOAANGLE': (21, 0, 'int', 359, 0, 'ro', 'DOA angle. Current value. Orientation depends on build configuration.') 61 | } 62 | 63 | 64 | class Tuning: 65 | TIMEOUT = 100000 66 | 67 | def __init__(self, dev): 68 | self.dev = dev 69 | 70 | def write(self, name, value): 71 | try: 72 | data = PARAMETERS[name] 73 | except KeyError: 74 | return 75 | 76 | if data[5] == 'ro': 77 | raise ValueError('{} is read-only'.format(name)) 78 | 79 | id = data[0] 80 | 81 | # 4 bytes offset, 4 bytes value, 4 bytes type 82 | if data[2] == 'int': 83 | payload = struct.pack(b'iii', data[1], int(value), 1) 84 | else: 85 | payload = struct.pack(b'ifi', data[1], float(value), 0) 86 | 87 | self.dev.ctrl_transfer( 88 | usb.util.CTRL_OUT | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE, 89 | 0, 0, id, payload, self.TIMEOUT) 90 | 91 | def read(self, name): 92 | try: 93 | data = PARAMETERS[name] 94 | except KeyError: 95 | return 96 | 97 | id = data[0] 98 | 99 | cmd = 0x80 | data[1] 100 | if data[2] == 'int': 101 | cmd |= 0x40 102 | 103 | length = 8 104 | 105 | response = self.dev.ctrl_transfer( 106 | usb.util.CTRL_IN | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE, 107 | 0, cmd, id, length, self.TIMEOUT) 108 | 109 | response = struct.unpack(b'ii', response.tostring()) 110 | 111 | if data[2] == 'int': 112 | result = response[0] 113 | else: 114 | result = response[0] * (2.**response[1]) 115 | 116 | return result 117 | 118 | def set_vad_threshold(self, db): 119 | self.write('GAMMAVAD_SR', db) 120 | 121 | def is_voice(self): 122 | return self.read('VOICEACTIVITY') 123 | 124 | @property 125 | def direction(self): 126 | return self.read('DOAANGLE') 127 | 128 | @property 129 | def version(self): 130 | return self.dev.ctrl_transfer( 131 | usb.util.CTRL_IN | usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE, 132 | 0, 0x80, 0, 1, self.TIMEOUT)[0] 133 | 134 | def close(self): 135 | """ 136 | close the interface 137 | """ 138 | usb.util.dispose_resources(self.dev) 139 | 140 | 141 | def find(vid=0x2886, pid=0x0018): 142 | dev = usb.core.find(idVendor=vid, idProduct=pid) 143 | if not dev: 144 | return 145 | 146 | # configuration = dev.get_active_configuration() 147 | 148 | # interface_number = None 149 | # for interface in configuration: 150 | # interface_number = interface.bInterfaceNumber 151 | 152 | # if dev.is_kernel_driver_active(interface_number): 153 | # dev.detach_kernel_driver(interface_number) 154 | 155 | return Tuning(dev) 156 | 157 | 158 | 159 | def main(): 160 | if len(sys.argv) > 1: 161 | if sys.argv[1] == '-p': 162 | print('name\t\t\ttype\tmax\tmin\tr/w\tinfo') 163 | print('-------------------------------') 164 | for name in sorted(PARAMETERS.keys()): 165 | data = PARAMETERS[name] 166 | print('{:16}\t{}'.format(name, '\t'.join([str(i) for i in data[2:7]]))) 167 | for extra in data[7:]: 168 | print('{}{}'.format(' '*60, extra)) 169 | else: 170 | dev = find() 171 | if not dev: 172 | print('No device found') 173 | sys.exit(1) 174 | 175 | # print('version: {}'.format(dev.version)) 176 | 177 | if sys.argv[1] == '-r': 178 | print('{:24} {}'.format('name', 'value')) 179 | print('-------------------------------') 180 | for name in sorted(PARAMETERS.keys()): 181 | print('{:24} {}'.format(name, dev.read(name))) 182 | else: 183 | name = sys.argv[1].upper() 184 | if name in PARAMETERS: 185 | if len(sys.argv) > 2: 186 | dev.write(name, sys.argv[2]) 187 | 188 | print('{}: {}'.format(name, dev.read(name))) 189 | else: 190 | print('{} is not a valid name'.format(name)) 191 | 192 | dev.close() 193 | else: 194 | print(USAGE.format(sys.argv[0])) 195 | 196 | if __name__ == '__main__': 197 | main() 198 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------