From f868cc4f70aa220b54fba3f12bcf2e10760faf48 Mon Sep 17 00:00:00 2001 From: Mark Qvist Date: Sun, 8 Nov 2026 13:50:44 +0100 Subject: [PATCH] Sync upstream --- LXST/Call.py | 55 - LXST/Codecs/Codec.py | 6 + LXST/Codecs/Codec2.py | 6 +- LXST/Codecs/Opus.py | 19 +- LXST/Codecs/Raw.py | 6 +- LXST/Codecs/__init__.py | 2 + LXST/Codecs/libs/pydub/LICENSE | 20 + LXST/Codecs/libs/pydub/__init__.py | 21 + LXST/Codecs/libs/pydub/audio_segment.py | 21 + LXST/Codecs/libs/pydub/effects.py | 21 + LXST/Codecs/libs/pydub/exceptions.py | 21 + LXST/Codecs/libs/pydub/generators.py | 21 + LXST/Codecs/libs/pydub/logging_utils.py | 21 + LXST/Codecs/libs/pydub/playback.py | 21 + LXST/Codecs/libs/pydub/pyaudioop.py | 21 + LXST/Codecs/libs/pydub/scipy_effects.py | 21 + LXST/Codecs/libs/pydub/silence.py | 21 + LXST/Codecs/libs/pydub/utils.py | 21 + LXST/Codecs/libs/pyogg/LICENSE | 213 +++ LXST/Common.py | 2 + LXST/Filters.c | 6 +- LXST/Filters.h | 2 + LXST/Filters.py | 1292 ++++++++++++++++- LXST/Generators.py | 2 + LXST/Mixer.py | 25 +- LXST/Network.py | 15 +- LXST/Pipeline.py | 33 +- LXST/Platforms/android/soundcard.py | 167 ++- LXST/Platforms/linux/soundcard.py | 5 +- LXST/Platforms/windows.c | 1 - LXST/Primitives/Players.py | 49 +- LXST/Primitives/Recorders.py | 2 + LXST/Primitives/Telephony.py | 218 ++- LXST/Primitives/__init__.py | 2 + .../hardware/display_i2c_lcd1602.py | 2 + LXST/Primitives/hardware/keypad_gpio_4x4.py | 2 + LXST/Primitives/hardware/keypad_gpio_5x5.py | 131 -- LXST/Sinks.py | 32 +- LXST/Sources.py | 88 +- LXST/Utilities/rnphone.py | 2 + LXST/__init__.py | 2 + LXST/_version.py | 2 +- Makefile | 19 +- README.md | 62 +- examples/fileplayer.py | 1 + setup.py | 15 +- 46 files changed, 2404 insertions(+), 333 deletions(-) delete mode 100644 LXST/Call.py create mode 100644 LXST/Codecs/libs/pydub/LICENSE create mode 100644 LXST/Codecs/libs/pyogg/LICENSE delete mode 100644 LXST/Platforms/windows.c delete mode 100644 LXST/Primitives/hardware/keypad_gpio_5x5.py diff --git a/LXST/Call.py b/LXST/Call.py deleted file mode 100644 index c67b237..0000000 --- a/LXST/Call.py +++ /dev/null @@ -1,55 +0,0 @@ -import RNS -from .Pipeline import Pipeline -from .Codecs import * -from .Sources import * -from .Sinks import * -from . import APP_NAME - -class CallEndpoint(): - def __init__(self, identity): - self.identity = identity - self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "call", "endpoint") - self.destination.set_link_established_callback(self._incoming_call) - self.active_call = None - self.auto_answer = True - self.receive_pipeline = None - self.transmit_pipeline = None - self._incoming_call_callback = None - - def announce(self): - if self.destination: - self.destination.announce() - - @property - def incoming_call_callback(self): - return self._incoming_call_callback - - @incoming_call_callback.setter - def incoming_call_callback(self, callback): - if callable(callback): - self._incoming_call_callback = callback - else: - raise TypeError(f"Invalid callback for {self}: Not callable") - - def _incoming_call(self, link): - RNS.log(f"Incoming call on {self}", RNS.LOG_DEBUG) - if callable(self._incoming_call_callback): - self._incoming_call_callback(link) - - def answer(self, call_link): - RNS.log(f"Answering call on {call_link}", RNS.LOG_DEBUG) - self.active_call = call_link - - self.receive_pipeline = Pipeline(source=PacketSource(self), - codec=Opus(), - sink=LineSink()) - - self.transmit_pipeline = Pipeline(source=LineSource(target_frame_ms=target_frame_ms), - codec=Opus(), - sink=PacketSink(self)) - - def terminate(self): - self.receive_pipeline.stop() - self.transmit_pipeline.stop() - if self.active_call: - self.active_call.teardown() \ No newline at end of file diff --git a/LXST/Codecs/Codec.py b/LXST/Codecs/Codec.py index 911d7f5..4b74d5f 100644 --- a/LXST/Codecs/Codec.py +++ b/LXST/Codecs/Codec.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import numpy as np from .libs.pydub import AudioSegment @@ -11,6 +13,8 @@ class Codec(): source = None sink = None + def __str__(self): return f"" + class CodecError(Exception): pass @@ -24,6 +28,8 @@ class Null(Codec): def decode(self, frame): return frame + def __str__(self): return f"" + def resample_bytes(sample_bytes, bitdepth, channels, input_rate, output_rate, normalize=False): sample_width = bitdepth//8 audio = AudioSegment( diff --git a/LXST/Codecs/Codec2.py b/LXST/Codecs/Codec2.py index ab37ebe..c4619d0 100644 --- a/LXST/Codecs/Codec2.py +++ b/LXST/Codecs/Codec2.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import time import math import struct @@ -118,4 +120,6 @@ class Codec2(Codec): frame_samples = np.zeros((len(decoded_samples), 1), dtype="float32") frame_samples[:, 0] = decoded_samples - return frame_samples \ No newline at end of file + return frame_samples + + def __str__(self): return f"" \ No newline at end of file diff --git a/LXST/Codecs/Opus.py b/LXST/Codecs/Opus.py index 96a85ea..733cd84 100644 --- a/LXST/Codecs/Opus.py +++ b/LXST/Codecs/Opus.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import io import RNS import time @@ -22,6 +24,19 @@ class Opus(Codec): PROFILE_AUDIO_HIGH = 0x07 PROFILE_AUDIO_MAX = 0x08 + @staticmethod + def profile_name(profile): + if profile == Opus.PROFILE_VOICE_LOW: return "Voice, Low" + elif profile == Opus.PROFILE_VOICE_MEDIUM: return "Voice, Medium" + elif profile == Opus.PROFILE_VOICE_HIGH: return "Voice, High" + elif profile == Opus.PROFILE_VOICE_MAX: return "Voice, Max" + elif profile == Opus.PROFILE_AUDIO_MIN: return "Audio, Min" + elif profile == Opus.PROFILE_AUDIO_LOW: return "Audio, Low" + elif profile == Opus.PROFILE_AUDIO_MEDIUM: return "Audio, Medium" + elif profile == Opus.PROFILE_AUDIO_HIGH: return "Audio, High" + elif profile == Opus.PROFILE_AUDIO_MAX: return "Audio, Max" + else: return "Default" + def __init__(self, profile=PROFILE_VOICE_LOW): self.frame_quanta_ms = self.FRAME_QUANTA_MS self.frame_max_ms = self.FRAME_MAX_MS @@ -164,4 +179,6 @@ class Opus(Codec): decoded_samples = np.frombuffer(decoded_frame_bytes, dtype="int16")/self.TYPE_MAP_FACTOR frame_samples = decoded_samples.reshape(len(decoded_samples)//self.channels, self.channels) - return frame_samples \ No newline at end of file + return frame_samples + + def __str__(self): return f"" \ No newline at end of file diff --git a/LXST/Codecs/Raw.py b/LXST/Codecs/Raw.py index 70652d8..878cf33 100644 --- a/LXST/Codecs/Raw.py +++ b/LXST/Codecs/Raw.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import RNS import numpy as np from .Codec import Codec @@ -55,4 +57,6 @@ class Raw(Codec): frame_samples = frame_samples.reshape(len(frame_samples)//frame_channels, frame_channels) if not self.channels: self.channels = frame_channels - return frame_samples \ No newline at end of file + return frame_samples + + def __str__(self): return f"" \ No newline at end of file diff --git a/LXST/Codecs/__init__.py b/LXST/Codecs/__init__.py index b081b02..c794aa4 100644 --- a/LXST/Codecs/__init__.py +++ b/LXST/Codecs/__init__.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + from .Codec import CodecError as CodecError from .Codec import Codec as Codec from .Codec import Null as Null diff --git a/LXST/Codecs/libs/pydub/LICENSE b/LXST/Codecs/libs/pydub/LICENSE new file mode 100644 index 0000000..0cb49b7 --- /dev/null +++ b/LXST/Codecs/libs/pydub/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 James Robert, http://jiaaro.com + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/LXST/Codecs/libs/pydub/__init__.py b/LXST/Codecs/libs/pydub/__init__.py index 65e30b4..ab49a62 100644 --- a/LXST/Codecs/libs/pydub/__init__.py +++ b/LXST/Codecs/libs/pydub/__init__.py @@ -1 +1,22 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + from .audio_segment import AudioSegment \ No newline at end of file diff --git a/LXST/Codecs/libs/pydub/audio_segment.py b/LXST/Codecs/libs/pydub/audio_segment.py index 14ea46e..4991c51 100644 --- a/LXST/Codecs/libs/pydub/audio_segment.py +++ b/LXST/Codecs/libs/pydub/audio_segment.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + from __future__ import division import array diff --git a/LXST/Codecs/libs/pydub/effects.py b/LXST/Codecs/libs/pydub/effects.py index 0210521..aa84cf2 100644 --- a/LXST/Codecs/libs/pydub/effects.py +++ b/LXST/Codecs/libs/pydub/effects.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + import sys import math import array diff --git a/LXST/Codecs/libs/pydub/exceptions.py b/LXST/Codecs/libs/pydub/exceptions.py index 79d0743..e1c11cc 100644 --- a/LXST/Codecs/libs/pydub/exceptions.py +++ b/LXST/Codecs/libs/pydub/exceptions.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + class PydubException(Exception): """ Base class for any Pydub exception diff --git a/LXST/Codecs/libs/pydub/generators.py b/LXST/Codecs/libs/pydub/generators.py index b04cb4c..0808e1e 100644 --- a/LXST/Codecs/libs/pydub/generators.py +++ b/LXST/Codecs/libs/pydub/generators.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ Each generator will return float samples from -1.0 to 1.0, which can be converted to actual audio with 8, 16, 24, or 32 bit depth using the diff --git a/LXST/Codecs/libs/pydub/logging_utils.py b/LXST/Codecs/libs/pydub/logging_utils.py index a312bd2..e1fd8e3 100644 --- a/LXST/Codecs/libs/pydub/logging_utils.py +++ b/LXST/Codecs/libs/pydub/logging_utils.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ """ diff --git a/LXST/Codecs/libs/pydub/playback.py b/LXST/Codecs/libs/pydub/playback.py index 72ce4a5..c483e50 100644 --- a/LXST/Codecs/libs/pydub/playback.py +++ b/LXST/Codecs/libs/pydub/playback.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ Support for playing AudioSegments. Pyaudio will be used if it's installed, otherwise will fallback to ffplay. Pyaudio is a *much* nicer solution, but diff --git a/LXST/Codecs/libs/pydub/pyaudioop.py b/LXST/Codecs/libs/pydub/pyaudioop.py index c636a4a..dfd00d8 100644 --- a/LXST/Codecs/libs/pydub/pyaudioop.py +++ b/LXST/Codecs/libs/pydub/pyaudioop.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + try: from __builtin__ import max as builtin_max from __builtin__ import min as builtin_min diff --git a/LXST/Codecs/libs/pydub/scipy_effects.py b/LXST/Codecs/libs/pydub/scipy_effects.py index abab2b4..79b3a88 100644 --- a/LXST/Codecs/libs/pydub/scipy_effects.py +++ b/LXST/Codecs/libs/pydub/scipy_effects.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ This module provides scipy versions of high_pass_filter, and low_pass_filter as well as an additional band_pass_filter. diff --git a/LXST/Codecs/libs/pydub/silence.py b/LXST/Codecs/libs/pydub/silence.py index 0ad1499..ba08692 100644 --- a/LXST/Codecs/libs/pydub/silence.py +++ b/LXST/Codecs/libs/pydub/silence.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + """ Various functions for finding/manipulating silence in AudioSegments """ diff --git a/LXST/Codecs/libs/pydub/utils.py b/LXST/Codecs/libs/pydub/utils.py index bf69f66..62fa931 100644 --- a/LXST/Codecs/libs/pydub/utils.py +++ b/LXST/Codecs/libs/pydub/utils.py @@ -1,3 +1,24 @@ +# Copyright (c) 2011 James Robert, http://jiaaro.com +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + from __future__ import division import json diff --git a/LXST/Codecs/libs/pyogg/LICENSE b/LXST/Codecs/libs/pyogg/LICENSE new file mode 100644 index 0000000..9701f94 --- /dev/null +++ b/LXST/Codecs/libs/pyogg/LICENSE @@ -0,0 +1,213 @@ +The following License terms are included in the scripts of the +respective packages, so you will have to include them manually +if you're distributing compiled sources: + +================================================== +Ogg License +================================================== +Copyright (c) 2002, Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================== +Opus License +================================================== +Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Internet Society, IETF or IETF Trust, nor the +names of specific contributors, may be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ + +================================================== +Opusfile License +================================================== +Copyright (c) 1994-2013 Xiph.Org Foundation and contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================== +Opusenc License +================================================== +Copyright (c) 1994-2013 Xiph.Org Foundation and contributors +Copyright (c) 2017 Jean-Marc Valin + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================== +Vorbis License +================================================== +Copyright (c) 2002-2015 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================== +Flac License +================================================== +Copyright (C) 2000-2009 Josh Coalson +Copyright (C) 2011-2016 Xiph.Org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/LXST/Common.py b/LXST/Common.py index 6ba1e9c..74e2c02 100644 --- a/LXST/Common.py +++ b/LXST/Common.py @@ -1,2 +1,4 @@ +# Copyright 2024-2026, Mark Qvist + def nop(): pass \ No newline at end of file diff --git a/LXST/Filters.c b/LXST/Filters.c index 607a8e0..f61ac1d 100644 --- a/LXST/Filters.c +++ b/LXST/Filters.c @@ -1,3 +1,5 @@ +// Copyright 2024-2026, Mark Qvist + #include void highpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states, float* last_inputs) { @@ -62,8 +64,8 @@ void agc_process(float* input, float* output, int samples, int channels, float t float peak = 0.0f; for (int i = 0; i < samples; i++) { int idx = i * channels + ch; float abs_val = fabsf(output[idx]); if (abs_val > peak) { peak = abs_val; } } - + if (peak > peak_limit) { float scale = peak_limit / peak; for (int i = 0; i < samples; i++) { int idx = i * channels + ch; output[idx] *= scale; } } } -} \ No newline at end of file +} diff --git a/LXST/Filters.h b/LXST/Filters.h index cefeb6c..aa58664 100644 --- a/LXST/Filters.h +++ b/LXST/Filters.h @@ -1,3 +1,5 @@ +// Copyright 2024-2026, Mark Qvist + void highpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states, float* last_inputs); void lowpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states); void agc_process(float* input, float* output, int samples, int channels, float target_linear, float max_gain_linear, float trigger_level, float attack_coeff, float release_coeff, float hold_samples, float* current_gain_lin, int* hold_counter, int block_target); \ No newline at end of file diff --git a/LXST/Filters.py b/LXST/Filters.py index c08ec95..3fc3263 100644 --- a/LXST/Filters.py +++ b/LXST/Filters.py @@ -1,5 +1,9 @@ +# Copyright 2024-2026, Mark Qvist + from importlib.util import find_spec +from collections import deque import numpy as np +import threading import time import RNS import os @@ -98,8 +102,6 @@ class HighPass(Filter): for i in range(1, samples): output[i] = self._alpha * (output[i-1] + input_diff[i]) - - output = self._alpha * (output + input_diff) self._filter_states = output[-1].copy() self._last_inputs = frame_2d[-1].copy() @@ -184,6 +186,7 @@ class AGC(Filter): self.hold_time = hold_time self.target_linear = 10 ** (target_level / 10) self.max_gain_linear = 10 ** (max_gain / 10) + self.paused = False self._samplerate = None self._channels = None self._current_gain_lin = 1.0 @@ -196,6 +199,7 @@ class AGC(Filter): def handle_frame(self, frame, samplerate): # TODO: Remove debug # st = time.time() + if self.paused: return frame if len(frame) == 0: return frame if len(frame.shape) == 1: frame_2d = frame.reshape(-1, 1) else: frame_2d = frame @@ -279,4 +283,1286 @@ class AGC(Filter): else: self._attack_coeff = 0.1 self._release_coeff = 0.01 - self._hold_samples = 1000 \ No newline at end of file + self._hold_samples = 1000 + +class EchoSuppressor(Filter): + DEFAULT_MAX_DELAY_MS = 550 + DEFAULT_TRACK_WINDOW_MS = 150 + DEFAULT_CORRELATION_FRAME_MS = 120 + DEFAULT_CORRELATION_THRESHOLD = 0.070 + DEFAULT_RMS_THRESHOLD = 0.002 + DEFAULT_EMA_ALPHA = 0.2 + DEFAULT_PREEMPH_ALPHA = 0.95 + DEFAULT_ACC_FORGET = 0.92 + + DEFAULT_COUPLING_WINDOW_S = 5.0 + DEFAULT_COUPLING_PERCENTILE = 15 + DEFAULT_COUPLING_THRESHOLD_DB = -30.0 + DEFAULT_GATE_RATIO_DB = -3.0 + DEFAULT_CORR_THRESHOLD = 0.13 + DEFAULT_DTD_ENERGY_DB = 3.0 + DEFAULT_HANGOVER_MS = 150 + DEFAULT_ATTACK_MS = 5 + DEFAULT_RELEASE_MS = 80 + DEFAULT_REF_RMS_THRESHOLD = 0.0001 + REQUIRED_COUPLING_HISTORY = 4 + DEFAULT_ESTIMATE_EVERY_N = 2 + + DEFAULT_CNG_ENABLED = True + DEFAULT_CNG_GAIN = 0.0015 + DEFAULT_CNG_COLOR = 0.98 + DEFAULT_CNG_BLOCK_SIZE = 16384 + + LOG_INTERVAL_LOCKED = 0.25 + LOG_INTERVAL_SEARCH = 0.5 + LOG_INTERVAL_GATE = 0.25 + + def __init__(self, max_delay_ms=DEFAULT_MAX_DELAY_MS, track_window_ms=DEFAULT_TRACK_WINDOW_MS, + correlation_frame_ms=DEFAULT_CORRELATION_FRAME_MS, correlation_threshold=DEFAULT_CORRELATION_THRESHOLD, + rms_threshold=DEFAULT_RMS_THRESHOLD, ema_alpha=DEFAULT_EMA_ALPHA, preemph_alpha=DEFAULT_PREEMPH_ALPHA, + acc_forget=DEFAULT_ACC_FORGET, coupling_window_s=DEFAULT_COUPLING_WINDOW_S, + coupling_percentile=DEFAULT_COUPLING_PERCENTILE, coupling_threshold_db=DEFAULT_COUPLING_THRESHOLD_DB, + gate_ratio_db=DEFAULT_GATE_RATIO_DB, corr_threshold=DEFAULT_CORR_THRESHOLD, dtd_energy_db=DEFAULT_DTD_ENERGY_DB, + hangover_ms=DEFAULT_HANGOVER_MS, attack_ms=DEFAULT_ATTACK_MS, release_ms=DEFAULT_RELEASE_MS, + ref_rms_threshold=DEFAULT_REF_RMS_THRESHOLD, estimate_every_n=DEFAULT_ESTIMATE_EVERY_N, + cng_enabled=DEFAULT_CNG_ENABLED, cng_gain=DEFAULT_CNG_GAIN, cng_color=DEFAULT_CNG_COLOR): + + super().__init__() + + self.max_delay_ms = max_delay_ms + self.track_window_ms = track_window_ms + self.correlation_frame_ms = correlation_frame_ms + self.correlation_threshold = correlation_threshold + self.rms_threshold = rms_threshold + self.ema_alpha = ema_alpha + self.preemph_alpha = preemph_alpha + self.acc_forget = acc_forget + self.estimate_every_n = estimate_every_n + self.debug_metrics = False + + self.cng_enabled = cng_enabled + self.cng_gain = cng_gain + self.cng_color = min(max(float(cng_color), 0.0), 0.999) + + self.coupling_window_s = coupling_window_s + self.coupling_percentile = coupling_percentile + self.coupling_threshold_db = coupling_threshold_db + self.gate_ratio_db = gate_ratio_db + self.corr_threshold = corr_threshold + self.dtd_energy_db = dtd_energy_db + self.hangover_ms = hangover_ms + self.attack_ms = attack_ms + self.release_ms = release_ms + self.ref_rms_threshold = ref_rms_threshold + self._last_echo_correlation = 0 + self._near_end_active_hold = 0 + self.echo_correlation_window = 1.0 + self.ser_db = 0 + + self._lock = threading.Lock() + self._samplerate = None + + # 48 kHz buffers (gating path) + self._buffer_size = None + self._ref_buffer = None + self._ref_write_pos = 0 + self._ref_valid = 0 + self._max_delay_samples = None + self._track_window_samples = None + self._correlation_samples = None + + # Downsampling + # self._decim_factor = 3 + # self._decim_taps = self._design_decimator_taps(num_taps=12, cutoff_hz=7500, samplerate=48000) + self._decim_factor = 6 + self._decim_taps = self._design_decimator_taps(num_taps=12, cutoff_hz=3700, samplerate=48000) + self._decim_state_ref = np.zeros(len(self._decim_taps) - 1, dtype=np.float32) + self._decim_total_ref = 0 + self._decim_state_mic = np.zeros(len(self._decim_taps) - 1, dtype=np.float32) + self._decim_total_mic = 0 + + # Comfort noise generator + self._cng_buffer = np.array([], dtype=np.float32) + self._cng_buffer_pos = 0 + self._cng_state = 0.0 + self._cng_block_size = self.DEFAULT_CNG_BLOCK_SIZE + + # 16 kHz buffers (delay-estimation path) + self._samplerate_ds = None + self._buffer_size_ds = None + self._ref_buffer_ds = None + self._ref_write_pos_ds = 0 + self._ref_valid_ds = 0 + self._max_delay_samples_ds = None + self._track_window_samples_ds = None + self._correlation_samples_ds = None + + # Pre-emphasis states + self._ref_preemph_state = np.float32(0.0) + self._mic_preemph_state = np.float32(0.0) + self._ref_preemph_state_ds = np.float32(0.0) + self._mic_preemph_state_ds = np.float32(0.0) + + # Mic history (48 kHz unused, kept for API compat; 16 kHz active) + self._mic_hist = None + self._mic_hist_write = 0 + self._mic_hist_valid = 0 + + self._mic_hist_ds = None + self._mic_hist_write_ds = 0 + self._mic_hist_valid_ds = 0 + + self._corr_acc = None + self._corr_acc_ds = None + + self._delay_samples = None + self._delay_ms = None + self._delay_confidence = 0.0 + + self._last_log_time = 0 + self._last_gate_log_time = 0 + self._frame_count = 0 + + self._coupling_history = deque(maxlen=10) + self._coupling = 1e-3 + self._coupling_db = -30.0 + self._disabled_by_coupling = False + self._current_gain = 1.0 + self._hangover_samples = 0 + self._last_gate_open = True + self._ser_db_threshold = 11.0 + self._ser_hysterisis = 2 + self._ser_threshold_count = 0 + + # Helpers + @staticmethod + def _to_mono(frame): + if frame.ndim == 1: return frame.astype(np.float32, copy=False) + elif frame.ndim == 2: + if frame.shape[1] == 1: return frame[:, 0].astype(np.float32, copy=False) + mono = frame[:, 0].copy() + mono += frame[:, 1] + mono *= 0.5 + if mono.dtype != np.float32: return mono.astype(np.float32) + else: return mono + else: return frame.astype(np.float32, copy=False).ravel() + + # @staticmethod + # def _to_mono(frame): + # if frame.ndim == 1: return frame.astype(np.float32, copy=False) + # elif frame.ndim == 2: + # if frame.shape[1] == 1: return frame[:, 0].astype(np.float32, copy=False) + # return frame.mean(axis=1).astype(np.float32) + # else: return frame.astype(np.float32, copy=False).ravel() + + @staticmethod + def _design_decimator_taps(num_taps=12, cutoff_hz=7500, samplerate=48000): + n = np.arange(num_taps, dtype=np.float64) + fc = cutoff_hz / samplerate + m = n - (num_taps - 1) / 2.0 + h = 2.0 * fc * np.sinc(2.0 * fc * m) + w = 0.54 - 0.46 * np.cos(2.0 * np.pi * n / (num_taps - 1)) + h = h * w + h = h / np.sum(h) + return h.astype(np.float32) + + def _decimate(self, x, state_attr, total_attr): + x = np.asarray(x, dtype=np.float32) + if len(x) == 0: + return np.array([], dtype=np.float32) + L = len(self._decim_taps) + state = getattr(self, state_attr) + total = getattr(self, total_attr) + buf = np.concatenate((state, x)) + y = np.convolve(buf, self._decim_taps, mode='valid') + m = (-total) % self._decim_factor + out = y[m::self._decim_factor] + setattr(self, total_attr, total + len(x)) + setattr(self, state_attr, buf[-(L - 1):].copy()) + return out + + def _preemph(self, x, state): + if len(x) == 0: return x, state + y = np.empty_like(x) + a = np.float32(self.preemph_alpha) + y[0] = x[0] - a * state + y[1:] = x[1:] - a * x[:-1] + return y, x[-1] + + def _generate_cng_block(self, n): + white = np.random.normal(0, 1, n).astype(np.float32) + out = np.empty(n, dtype=np.float32) + s = self._cng_state + a = self.cng_color + # Normalise so output RMS ≈ cng_gain regardless of alpha + scale = self.cng_gain * np.sqrt(max(0.0, 1.0 - a * a)) + for i in range(n): + s = a * s + white[i] + out[i] = s * scale + self._cng_state = s + return out + + def _get_cng(self, n): + if self._cng_buffer_pos + n > len(self._cng_buffer): + self._cng_buffer = self._generate_cng_block(self._cng_block_size) + self._cng_buffer_pos = 0 + result = self._cng_buffer[self._cng_buffer_pos:self._cng_buffer_pos + n] + self._cng_buffer_pos += n + return result + + # Buffer management + def _ensure_buffer(self, samplerate): + if self._samplerate != samplerate or self._ref_buffer is None: + self._samplerate = samplerate + self._max_delay_samples = int(self.max_delay_ms / 1000.0 * samplerate) + self._track_window_samples = int(self.track_window_ms / 1000.0 * samplerate) + self._correlation_samples = int(self.correlation_frame_ms / 1000.0 * samplerate) + + self._buffer_size = self._max_delay_samples + 16384 + self._ref_buffer = np.zeros(self._buffer_size, dtype=np.float32) + self._ref_write_pos = 0 + self._ref_valid = 0 + + self._corr_acc = np.zeros(self._max_delay_samples + 1, dtype=np.float64) + self._mic_hist = np.zeros(self._correlation_samples, dtype=np.float32) + self._mic_hist_write = 0 + self._mic_hist_valid = 0 + + # 16 kHz path + self._samplerate_ds = int(samplerate / self._decim_factor) + self._max_delay_samples_ds = int(self.max_delay_ms / 1000.0 * self._samplerate_ds) + self._track_window_samples_ds = int(self.track_window_ms / 1000.0 * self._samplerate_ds) + self._correlation_samples_ds = int(self.correlation_frame_ms / 1000.0 * self._samplerate_ds) + + self._buffer_size_ds = self._max_delay_samples_ds + 4096 + self._ref_buffer_ds = np.zeros(self._buffer_size_ds, dtype=np.float32) + self._ref_write_pos_ds = 0 + self._ref_valid_ds = 0 + + self._corr_acc_ds = np.zeros(self._max_delay_samples_ds + 1, dtype=np.float64) + self._mic_hist_ds = np.zeros(self._correlation_samples_ds, dtype=np.float32) + self._mic_hist_write_ds = 0 + self._mic_hist_valid_ds = 0 + + # Reset decimator states + self._decim_state_ref = np.zeros(len(self._decim_taps) - 1, dtype=np.float32) + self._decim_total_ref = 0 + self._decim_state_mic = np.zeros(len(self._decim_taps) - 1, dtype=np.float32) + self._decim_total_mic = 0 + self._ref_preemph_state_ds = np.float32(0.0) + self._mic_preemph_state_ds = np.float32(0.0) + + self._coupling_history.clear() + self._coupling = 1e-3 + self._coupling_db = -30.0 + self._disabled_by_coupling = False + self._current_gain = 1.0 + self._hangover_samples = 0 + self._last_gate_open = True + + RNS.log(f"EchoSuppressor initialised: max_delay={self.max_delay_ms}ms, " + f"corr_window={self.correlation_frame_ms}ms, threshold={self.correlation_threshold}, " + f"coupling_th={self.coupling_threshold_db}dB, gate_ratio={self.gate_ratio_db}dB, " + f"DTD={self.dtd_energy_db}dB, hangover={self.hangover_ms}ms, " + f"attack={self.attack_ms}ms, release={self.release_ms}ms, " + f"est_rate=1/{self.estimate_every_n}, ds={self._samplerate_ds}Hz, @ {samplerate}Hz", + RNS.LOG_DEBUG) + + def _append_reference(self, mono): + N = len(mono) + if N > self._buffer_size: + mono = mono[-self._buffer_size:] + N = self._buffer_size + end = self._ref_write_pos + N + + if end <= self._buffer_size: self._ref_buffer[self._ref_write_pos:end] = mono + else: + part1 = self._buffer_size - self._ref_write_pos + self._ref_buffer[self._ref_write_pos:] = mono[:part1] + self._ref_buffer[:end - self._buffer_size] = mono[part1:] + + self._ref_write_pos = end % self._buffer_size + self._ref_valid = min(self._ref_valid + N, self._buffer_size) + + def _append_reference_ds(self, mono): + N = len(mono) + if N > self._buffer_size_ds: + mono = mono[-self._buffer_size_ds:] + N = self._buffer_size_ds + end = self._ref_write_pos_ds + N + + if end <= self._buffer_size_ds: self._ref_buffer_ds[self._ref_write_pos_ds:end] = mono + else: + part1 = self._buffer_size_ds - self._ref_write_pos_ds + self._ref_buffer_ds[self._ref_write_pos_ds:] = mono[:part1] + self._ref_buffer_ds[:end - self._buffer_size_ds] = mono[part1:] + + self._ref_write_pos_ds = end % self._buffer_size_ds + self._ref_valid_ds = min(self._ref_valid_ds + N, self._buffer_size_ds) + + def _append_mic_history(self, mono): + N = len(mono) + if N >= self._correlation_samples: + self._mic_hist[:] = mono[-self._correlation_samples:] + self._mic_hist_write = 0 + self._mic_hist_valid = self._correlation_samples + return + + end = self._mic_hist_write + N + if end <= self._correlation_samples: self._mic_hist[self._mic_hist_write:end] = mono + else: + part1 = self._correlation_samples - self._mic_hist_write + self._mic_hist[self._mic_hist_write:] = mono[:part1] + self._mic_hist[:end - self._correlation_samples] = mono[part1:] + + self._mic_hist_write = end % self._correlation_samples + self._mic_hist_valid = min(self._mic_hist_valid + N, self._correlation_samples) + + def _append_mic_history_ds(self, mono): + N = len(mono) + if N >= self._correlation_samples_ds: + self._mic_hist_ds[:] = mono[-self._correlation_samples_ds:] + self._mic_hist_write_ds = 0 + self._mic_hist_valid_ds = self._correlation_samples_ds + return + + end = self._mic_hist_write_ds + N + if end <= self._correlation_samples_ds: self._mic_hist_ds[self._mic_hist_write_ds:end] = mono + else: + part1 = self._correlation_samples_ds - self._mic_hist_write_ds + self._mic_hist_ds[self._mic_hist_write_ds:] = mono[:part1] + self._mic_hist_ds[:end - self._correlation_samples_ds] = mono[part1:] + + self._mic_hist_write_ds = end % self._correlation_samples_ds + self._mic_hist_valid_ds = min(self._mic_hist_valid_ds + N, self._correlation_samples_ds) + + def _get_reference_window(self, length): + length = min(length, self._ref_valid) + if length <= 0: return np.array([], dtype=np.float32) + start = (self._ref_write_pos - length) % self._buffer_size + end = self._ref_write_pos + if start < end: return self._ref_buffer[start:end].copy() + else: return np.concatenate( (self._ref_buffer[start:].copy(), self._ref_buffer[:end].copy()) ) + + def _get_reference_window_ds(self, length): + length = min(length, self._ref_valid_ds) + if length <= 0: return np.array([], dtype=np.float32) + start = (self._ref_write_pos_ds - length) % self._buffer_size_ds + end = self._ref_write_pos_ds + if start < end: return self._ref_buffer_ds[start:end].copy() + else: return np.concatenate( (self._ref_buffer_ds[start:].copy(), self._ref_buffer_ds[:end].copy()) ) + + def _get_delayed_reference(self, delay_samples, length): + if delay_samples + length > self._ref_valid: return None + start = (self._ref_write_pos - delay_samples - length) % self._buffer_size + end = (self._ref_write_pos - delay_samples) % self._buffer_size + if start < end: return self._ref_buffer[start:end] + else: return np.concatenate( (self._ref_buffer[start:], self._ref_buffer[:end]) ) + + def _get_mic_history(self): + length = min(self._mic_hist_valid, self._correlation_samples) + if length <= 0: return np.array([], dtype=np.float32) + start = (self._mic_hist_write - length) % self._correlation_samples + end = self._mic_hist_write + if start < end: return self._mic_hist[start:end].copy() + else: return np.concatenate( (self._mic_hist[start:].copy(), self._mic_hist[:end].copy()) ) + + def _get_mic_history_ds(self): + length = min(self._mic_hist_valid_ds, self._correlation_samples_ds) + if length <= 0: return np.array([], dtype=np.float32) + start = (self._mic_hist_write_ds - length) % self._correlation_samples_ds + end = self._mic_hist_write_ds + if start < end: return self._mic_hist_ds[start:end].copy() + else: return np.concatenate( (self._mic_hist_ds[start:].copy(), self._mic_hist_ds[:end].copy()) ) + + # Coupling estimation + def _update_coupling(self, mic_energy, ref_energy, corr): + mic_energy_threshold = 6e-7 + ref_energy_threshold = 6e-7 + in_bootstrap = len(self._coupling_history) < self.REQUIRED_COUPLING_HISTORY + + if (ref_energy > ref_energy_threshold and corr > self.corr_threshold and mic_energy > mic_energy_threshold): + ratio = mic_energy / ref_energy + self._coupling_history.append(ratio) + + if len(self._coupling_history) >= self.REQUIRED_COUPLING_HISTORY: + self._coupling = np.percentile(np.array(self._coupling_history, dtype=np.float64), self.coupling_percentile) + self._coupling_db = 10.0 * np.log10(self._coupling + 1e-12) + + if self._coupling_db < self.coupling_threshold_db: self._disabled_by_coupling = True + elif self._coupling_db > self.coupling_threshold_db + 1.5: self._disabled_by_coupling = False + + # Public interface + def handle_reference(self, frame, samplerate): + # st = time.time() + mono = self._to_mono(frame) + # RNS.log(f"Ref mono (dtype={frame.dtype}, ndim={frame.ndim}, frame.shape[1]={frame.shape[1]}) conversion in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_DEBUG) + + # 16 kHz path: downsample raw, then pre-emphasise + mono_ds = self._decimate(mono, '_decim_state_ref', '_decim_total_ref') + if len(mono_ds) > 0: + mono_ds, self._ref_preemph_state_ds = self._preemph(mono_ds, self._ref_preemph_state_ds) + + # 48 kHz path: pre-emphasise + mono, self._ref_preemph_state = self._preemph(mono, self._ref_preemph_state) + + with self._lock: + self._ensure_buffer(samplerate) + self._append_reference(mono) + if len(mono_ds) > 0: + self._append_reference_ds(mono_ds) + + def handle_frame(self, frame, samplerate): + st = time.time() + + original_shape = frame.shape + mono_raw = self._to_mono(frame) + N = len(mono_raw) + if N == 0: return frame + + # mic_rms = np.sqrt(np.mean(mono_raw ** 2)) # TODO: Remove and clean + # if mic_rms < self.rms_threshold: return frame + + # RNS.log(f"Mono conversion (dtype={frame.dtype}, ndim={frame.ndim}, frame.shape[1]={frame.shape[1]}) in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_DEBUG) + # dst = time.time() + + # Downsample for delay estimation + mono_ds = self._decimate(mono_raw, '_decim_state_mic', '_decim_total_mic') + # RNS.log(f"Decimation in {RNS.prettyshorttime(time.time()-dst)}", RNS.LOG_DEBUG) + # pest = time.time() + + # Pre-emphasis + mono_pre, self._mic_preemph_state = self._preemph(mono_raw, self._mic_preemph_state) + if len(mono_ds) > 0: mono_pre_ds, self._mic_preemph_state_ds = self._preemph(mono_ds, self._mic_preemph_state_ds) + else: mono_pre_ds = mono_ds + + # RNS.log(f"Pre-emphasis in {RNS.prettyshorttime(time.time()-pest)}", RNS.LOG_DEBUG) + + # 1. Delay estimation + self._frame_count += 1 + ref_delayed = None + + if self._ref_valid < N + 100: return frame + if self._samplerate != samplerate: + RNS.log(f"EchoSuppressor samplerate mismatch (ref={self._samplerate}, mic={samplerate}), skipping", RNS.LOG_WARNING) + return frame + + if not (self._frame_count % self.estimate_every_n) == 0: + with self._lock: + if len(mono_pre_ds) > 0: + self._append_mic_history_ds(mono_pre_ds) + if self._mic_hist_valid_ds < self._correlation_samples_ds // 2: return frame + + else: + # pst = time.time() + + with self._lock: + if len(mono_pre_ds) > 0: + self._append_mic_history_ds(mono_pre_ds) + if self._mic_hist_valid_ds < self._correlation_samples_ds // 2: return frame + mic_window = self._get_mic_history_ds() + search_length = min(self._ref_valid_ds, self._max_delay_samples_ds + len(mic_window)) + if search_length <= len(mic_window): return frame + ref_window = self._get_reference_window_ds(search_length) + + # RNS.log(f"Prep in {RNS.prettyshorttime(time.time()-pst)}", RNS.LOG_DEBUG) + # fst = time.time() + + # FFT-based cross-correlation at 16 kHz + M = len(ref_window) + Nc = len(mic_window) + fft_size = 1 << (M + Nc - 1).bit_length() + C = np.fft.irfft( np.fft.rfft(ref_window, n=fft_size) * + np.conj(np.fft.rfft(mic_window, n=fft_size)), + n=fft_size ) + c = C[:M - Nc + 1] + + # RNS.log(f"{fft_size} FFT ops in {RNS.prettyshorttime(time.time()-fst)}", RNS.LOG_DEBUG) + # nst = time.time() + + mic_norm = np.linalg.norm(mic_window) + if mic_norm == 0: return frame + + ref_cumsum = np.empty(len(ref_window) + 1, dtype=np.float64) + ref_cumsum[0] = 0.0 + np.multiply(ref_window, ref_window, out=ref_cumsum[1:]) + np.cumsum(ref_cumsum[1:], out=ref_cumsum[1:]) + window_norms = np.sqrt(ref_cumsum[Nc:] - ref_cumsum[:-Nc]) + + with np.errstate(divide='ignore', invalid='ignore'): corr = c / (mic_norm * window_norms) + corr[window_norms == 0] = 0 + abs_corr = np.abs(corr) + + # RNS.log(f"Correlation in {RNS.prettyshorttime(time.time()-nst)}", RNS.LOG_DEBUG) + # ast = time.time() + + # Accumulate + self._corr_acc_ds *= self.acc_forget + self._corr_acc_ds[:len(abs_corr)] += abs_corr[::-1] + acc_norm = self._corr_acc_ds * (1.0 - self.acc_forget) + + abs_mean = float(np.mean(abs_corr)) + abs_std = float(np.std(abs_corr)) + + # RNS.log(f"Accumulation in {RNS.prettyshorttime(time.time()-ast)}", RNS.LOG_DEBUG) + # pst = time.time() + + # Search for peak + if self._delay_samples is not None: + # _delay_samples is stored in 48 kHz units; convert to 16 kHz for search window + d_est_ds = int(round(self._delay_samples / self._decim_factor)) + d_min = max(0, d_est_ds - self._track_window_samples_ds) + d_max = min(len(acc_norm) - 1, d_est_ds + self._track_window_samples_ds) + track_acc = acc_norm[d_min:d_max + 1] + best_local_idx = np.argmax(track_acc) + best_delay_ds = d_min + best_local_idx + best_val = float(track_acc[best_local_idx]) + if best_val < self.correlation_threshold: + best_delay_ds = int(np.argmax(acc_norm)) + best_val = float(acc_norm[best_delay_ds]) + else: + best_delay_ds = int(np.argmax(acc_norm)) + best_val = float(acc_norm[best_delay_ds]) + + prominence = (best_val - abs_mean) / (abs_std + 1e-12) + raw_delay_ms = best_delay_ds / self._samplerate_ds * 1000.0 + + # RNS.log(f"Peak search in {RNS.prettyshorttime(time.time()-pst)}", RNS.LOG_DEBUG) + # rst = time.time() + + if best_val >= self.correlation_threshold: + if self._delay_samples is None: + self._delay_samples = float(best_delay_ds * self._decim_factor) + self._delay_ms = raw_delay_ms + self._delay_confidence = best_val + else: + self._delay_samples = (self.ema_alpha * best_delay_ds * self._decim_factor + + (1.0 - self.ema_alpha) * self._delay_samples) + self._delay_ms = self._delay_samples / self._samplerate * 1000.0 + self._delay_confidence = (self.ema_alpha * best_val + + (1.0 - self.ema_alpha) * self._delay_confidence) + + # RNS.log(f"Result calc in {RNS.prettyshorttime(time.time()-rst)}", RNS.LOG_DEBUG) + + # Fetch delayed reference aligned with current mic frame (48 kHz) + if self._delay_samples is not None: + int_delay = int(round(self._delay_samples)) + ref_delayed = self._get_delayed_reference(int_delay, N) + + # RNS.log(f"Total delay estimation in {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_DEBUG) # TODO: Remove + + # 2. Echo detection and gating + if ref_delayed is None or len(ref_delayed) != N: return frame + + # Energy on pre-emphasised signals + mic_energy = np.mean(mono_pre ** 2) + ref_energy = np.mean(ref_delayed ** 2) + + # Normalised correlation + mic_norm = np.linalg.norm(mono_pre) + ref_norm = np.linalg.norm(ref_delayed) + if mic_norm > 1e-12 and ref_norm > 1e-12: corr = abs(np.dot(mono_pre, ref_delayed) / (mic_norm * ref_norm)) + else: corr = 0.0 + + # Predicted echo energy from current coupling estimate + now = time.time() + predicted_echo_energy = self._coupling * ref_energy + + if corr > self.corr_threshold: self._last_echo_correlation = time.time() + echo_correlated = now < self._last_echo_correlation + self.echo_correlation_window + + if mic_energy > 2e-6: + try: self.ser_db = 10.0 * np.log10(mic_energy/predicted_echo_energy + 1e-12) + except Exception as e: RNS.log(f"Numerical error in energy calculation: {e}", RNS.LOG_DEBUG) + + # Near-end energy estimate (residual after predicted echo) + near_energy = max(0.0, mic_energy - predicted_echo_energy) + + # Determine near-end activity + near_end_active = False + in_bootstrap = len(self._coupling_history) < self.REQUIRED_COUPLING_HISTORY + if self._near_end_active_hold > now: near_end_active = True + elif in_bootstrap: near_end_active = near_energy > 2e-6 and corr < self.corr_threshold + else: + if now > self._last_echo_correlation + self.echo_correlation_window: near_end_active = True + if self.ser_db > self._ser_db_threshold: + self._ser_threshold_count += 1 + if self._ser_threshold_count >= self._ser_hysterisis: + near_end_active = True + self._near_end_active_hold = now+0.75 + else: self._ser_threshold_count = 0 + + # Update coupling estimate + if time.time() < self._last_echo_correlation + self.echo_correlation_window: self._update_coupling(mic_energy, ref_energy, corr) + if self._disabled_by_coupling: return frame + if len(self._coupling_history) < self.REQUIRED_COUPLING_HISTORY: return frame + + # RNS.log(f"nA: {near_end_active}, coupling_db: {self._coupling_db}, eE: {predicted_echo_energy*1e7}, nE: {near_energy*1e7}") + + should_gate = echo_correlated and not near_end_active + + # Gain smoothing + frame_duration_ms = N / samplerate * 1000.0 + attack_coeff = 1.0 - np.exp(-frame_duration_ms / self.attack_ms) + release_coeff = 1.0 - np.exp(-frame_duration_ms / self.release_ms) + + if near_end_active: + target_gain = 1.0 + self._hangover_samples = 0 + elif should_gate: + target_gain = 0.0 + self._hangover_samples = int(self.hangover_ms / 1000.0 * samplerate) + elif self._hangover_samples > 0: + target_gain = 0.0 + self._hangover_samples -= N + else: + target_gain = 1.0 + + coeff = attack_coeff if target_gain < self._current_gain else release_coeff + self._current_gain += (target_gain - self._current_gain) * coeff + + if self._current_gain < 1e-6: self._current_gain = 0.0 + elif self._current_gain > 1.0: self._current_gain = 1.0 + + if len(original_shape) == 1: output = mono_raw * self._current_gain + else: output = frame * self._current_gain + + # Comfort noise injection when gated + if self.cng_enabled and self._current_gain < 0.05: + cng = self._get_cng(output.shape[0]) + if len(original_shape) == 1: + output = output + cng + else: + output = output + cng[:, np.newaxis] + output = np.clip(output, -1.0, 1.0) + + if self.debug_metrics: RNS.log(f"GT: {self._current_gain < 0.5}, nA: {near_end_active}, EC: {echo_correlated}, SER: {round(self.ser_db,2)} dB, coupling: {round(self._coupling_db,2)} dB, finish {RNS.prettyshorttime(time.time()-st)}", RNS.LOG_DEBUG) + + return output + + @property + def delay_ms(self): return self._delay_ms + + @property + def delay_samples(self): return self._delay_samples + + @property + def confidence(self): return self._delay_confidence + + @property + def coupling_db(self): return self._coupling_db + + @property + def gain(self): return self._current_gain + +# class EchoCanceller(Filter): +# # Delay estimator defaults +# DEFAULT_MAX_DELAY_MS = 1000 +# DEFAULT_TRACK_WINDOW_MS = 150 +# DEFAULT_CORRELATION_FRAME_MS = 120 +# DEFAULT_CORRELATION_THRESHOLD = 0.070 +# DEFAULT_RMS_THRESHOLD = 0.002 +# DEFAULT_EMA_ALPHA = 0.2 +# DEFAULT_PREEMPH_ALPHA = 0.95 +# DEFAULT_ACC_FORGET = 0.92 + +# # NLMS defaults +# DEFAULT_FILTER_TAPS = 4096 +# DEFAULT_NLMS_MU = 0.8 +# DEFAULT_NLMS_EPS = 1e-12 +# DEFAULT_LEAKAGE = 0.9999 + +# # Double-talk detection defaults +# DEFAULT_DTD_THRESHOLD = 5.0 # hard freeze threshold, linear (~9.5 dB) +# DEFAULT_DTD_HANGOVER_MS = 300 # keep frozen for N ms after trigger +# DEFAULT_SOFT_DTD_THRESHOLD = 2.5 # soft freeze threshold, linear (~3.5 dB) +# DEFAULT_SOFT_DTD_MU_SCALE = 0.3 # mu multiplier when in soft freeze + +# # Post-filter defaults +# DEFAULT_PF_ENABLE = True +# DEFAULT_PF_FFT_SIZE = 256 +# DEFAULT_PF_HOP_SIZE = 128 +# DEFAULT_PF_ALPHA = 12.0 # over-subtraction factor (1.0 = Wiener) +# DEFAULT_PF_BETA = 0.0001 # spectral floor +# DEFAULT_PF_SMOOTH = 0.5 # power smoothing coeff +# DEFAULT_PF_ALPHA_SOFT = 0.8 # reduced aggression in soft freeze +# DEFAULT_PF_ALPHA_HARD = 0.5 # minimal aggression in hard freeze + +# # Logging +# LOG_INTERVAL_LOCKED = 0.25 +# LOG_INTERVAL_SEARCH = 0.5 +# PF_LOG_INTERVAL = 0.2 # post-filter debug output interval + +# def __init__(self, max_delay_ms=DEFAULT_MAX_DELAY_MS, track_window_ms=DEFAULT_TRACK_WINDOW_MS, +# correlation_frame_ms=DEFAULT_CORRELATION_FRAME_MS, correlation_threshold=DEFAULT_CORRELATION_THRESHOLD, +# rms_threshold=DEFAULT_RMS_THRESHOLD, ema_alpha=DEFAULT_EMA_ALPHA, preemph_alpha=DEFAULT_PREEMPH_ALPHA, +# acc_forget=DEFAULT_ACC_FORGET, filter_taps=DEFAULT_FILTER_TAPS, nlms_mu=DEFAULT_NLMS_MU, nlms_eps=DEFAULT_NLMS_EPS, +# leakage=DEFAULT_LEAKAGE, dtd_threshold=DEFAULT_DTD_THRESHOLD, dtd_hangover_ms=DEFAULT_DTD_HANGOVER_MS, +# soft_dtd_threshold=DEFAULT_SOFT_DTD_THRESHOLD, soft_dtd_mu_scale=DEFAULT_SOFT_DTD_MU_SCALE, +# pf_enable=DEFAULT_PF_ENABLE, pf_fft_size=DEFAULT_PF_FFT_SIZE, pf_hop_size=DEFAULT_PF_HOP_SIZE, +# pf_alpha=DEFAULT_PF_ALPHA, pf_beta=DEFAULT_PF_BETA, pf_smooth=DEFAULT_PF_SMOOTH, +# pf_alpha_soft=DEFAULT_PF_ALPHA_SOFT, pf_alpha_hard=DEFAULT_PF_ALPHA_HARD): + +# super().__init__() + +# # Delay estimator parameters +# self.max_delay_ms = max_delay_ms +# self.track_window_ms = track_window_ms +# self.correlation_frame_ms = correlation_frame_ms +# self.correlation_threshold = correlation_threshold +# self.rms_threshold = rms_threshold +# self.ema_alpha = ema_alpha +# self.preemph_alpha = preemph_alpha +# self.acc_forget = acc_forget + +# # NLMS parameters +# self.filter_taps = filter_taps +# self.nlms_mu = nlms_mu +# self.nlms_eps = nlms_eps +# self.leakage = leakage +# self.dtd_threshold = dtd_threshold +# self.dtd_hangover_ms = dtd_hangover_ms +# self.soft_dtd_threshold = soft_dtd_threshold +# self.soft_dtd_mu_scale = soft_dtd_mu_scale + +# # Post-filter parameters +# self.pf_enable = pf_enable +# self.pf_fft_size = pf_fft_size +# self.pf_hop_size = pf_hop_size +# self.pf_alpha = pf_alpha +# self.pf_beta = pf_beta +# self.pf_smooth = pf_smooth +# self.pf_alpha_soft = pf_alpha_soft +# self.pf_alpha_hard = pf_alpha_hard + +# # Threading / state +# self._lock = threading.Lock() +# self._samplerate = None + +# # Reference ring buffer (pre-emphasised) +# self._buffer_size = None +# self._ref_buffer = None +# self._ref_write_pos = 0 +# self._ref_valid = 0 +# self._max_delay_samples = None +# self._track_window_samples = None +# self._correlation_samples = None + +# # Pre-emphasis / de-emphasis states +# self._ref_preemph_state = np.float32(0.0) +# self._mic_preemph_state = np.float32(0.0) +# self._deemph_state = np.float32(0.0) + +# # Mic history for delay estimation +# self._mic_hist = None +# self._mic_hist_write = 0 +# self._mic_hist_valid = 0 + +# # Delay accumulator +# self._corr_acc = None + +# # NLMS coefficients +# self._w = None + +# # Delay estimate +# self._delay_samples = None +# self._delay_ms = None +# self._delay_confidence = 0.0 + +# # Logging / counters +# self._last_log_time = 0 +# self._frame_count = 0 + +# # Double-talk state +# self._dtd_hangover_counter = 0 +# self._dtd_was_frozen = False + +# # Post-filter state +# self._pf_inbuf = None +# self._pf_ecbuf = None +# self._pf_outbuf = None +# self._pf_synbuf = None +# self._pf_window = None +# self._pf_echo_power = None +# self._pf_res_power = None + +# # Post-filter debug accumulator +# self._pf_last_debug_time = 0 +# self._pf_debug_frames = 0 +# self._pf_debug_acc = None + +# # Helpers +# @staticmethod +# def _to_mono(frame): +# if frame.ndim == 1: return frame.astype(np.float32, copy=False) +# elif frame.ndim == 2: +# if frame.shape[1] == 1: return frame[:, 0].astype(np.float32, copy=False) +# return frame.mean(axis=1).astype(np.float32) +# else: return frame.astype(np.float32, copy=False).ravel() + +# def _preemph(self, x, state): +# # First-order pre-emphasis filter +# y = np.empty_like(x) +# a = np.float32(self.preemph_alpha) +# y[0] = x[0] - a * state +# y[1:] = x[1:] - a * x[:-1] +# return y, x[-1] + +# def _deemph(self, x, state): +# # Inverse of pre-emphasis +# y = np.empty_like(x) +# a = np.float32(self.preemph_alpha) +# y[0] = x[0] + a * state +# for i in range(1, len(x)): +# y[i] = x[i] + a * y[i - 1] +# return y, y[-1] + +# def _ensure_buffer(self, samplerate): +# if self._samplerate != samplerate or self._ref_buffer is None: +# self._samplerate = samplerate +# self._max_delay_samples = int(self.max_delay_ms / 1000.0 * samplerate) +# self._track_window_samples = int(self.track_window_ms / 1000.0 * samplerate) +# self._correlation_samples = int(self.correlation_frame_ms / 1000.0 * samplerate) + +# # Reference buffer: max delay + margin +# self._buffer_size = self._max_delay_samples + 16384 +# self._ref_buffer = np.zeros(self._buffer_size, dtype=np.float32) +# self._ref_write_pos = 0 +# self._ref_valid = 0 + +# self._corr_acc = np.zeros(self._max_delay_samples + 1, dtype=np.float64) +# self._mic_hist = np.zeros(self._correlation_samples, dtype=np.float32) +# self._mic_hist_write = 0 +# self._mic_hist_valid = 0 + +# self._w = np.zeros(self.filter_taps, dtype=np.float32) + +# # Post-filter state +# if self.pf_enable: +# self._pf_inbuf = [] +# self._pf_ecbuf = [] +# self._pf_outbuf = [] +# self._pf_synbuf = np.zeros(self.pf_fft_size, dtype=np.float32) +# self._pf_window = np.sqrt(np.hanning(self.pf_fft_size)).astype(np.float32) +# half_bins = self.pf_fft_size // 2 + 1 +# self._pf_echo_power = np.zeros(half_bins, dtype=np.float64) +# self._pf_res_power = np.zeros(half_bins, dtype=np.float64) + +# # Debug accumulator +# self._pf_last_debug_time = 0 +# self._pf_debug_frames = 0 +# self._pf_debug_acc = { 'nlms_pre': 0.0, 'nlms_out': 0.0, 'total_out': 0.0, +# 'gain_mean': 0.0, 'gain_min': 0.0, 'floor_pct': 0.0, +# 'ratio_mean_db': 0.0, 'ratio_max_db': 0.0, +# 'power_echo_db': 0.0, 'power_res_db': 0.0 } + +# pf_info = f", post-filter={self.pf_fft_size}/{self.pf_hop_size}" if self.pf_enable else ", post-filter=off" +# RNS.log(f"EchoCanceller initialised: max_delay={self.max_delay_ms}ms, " +# f"corr_window={self.correlation_frame_ms}ms, taps={self.filter_taps}, " +# f"mu={self.nlms_mu}, threshold={self.correlation_threshold}, " +# f"DTD_hard={self.dtd_threshold}dB({20*np.log10(self.dtd_threshold):.1f}), " +# f"DTD_soft={self.soft_dtd_threshold}dB({20*np.log10(self.soft_dtd_threshold):.1f}), " +# f"hangover={self.dtd_hangover_ms}ms{pf_info}, @ {samplerate}Hz", +# RNS.LOG_DEBUG) + +# def _append_reference(self, mono): +# N = len(mono) +# if N > self._buffer_size: +# mono = mono[-self._buffer_size:] +# N = self._buffer_size +# end = self._ref_write_pos + N + +# if end <= self._buffer_size: self._ref_buffer[self._ref_write_pos:end] = mono +# else: +# part1 = self._buffer_size - self._ref_write_pos +# self._ref_buffer[self._ref_write_pos:] = mono[:part1] +# self._ref_buffer[:end - self._buffer_size] = mono[part1:] + +# self._ref_write_pos = end % self._buffer_size +# self._ref_valid = min(self._ref_valid + N, self._buffer_size) + +# def _append_mic_history(self, mono): +# N = len(mono) +# if N >= self._correlation_samples: +# self._mic_hist[:] = mono[-self._correlation_samples:] +# self._mic_hist_write = 0 +# self._mic_hist_valid = self._correlation_samples +# return + +# end = self._mic_hist_write + N +# if end <= self._correlation_samples: self._mic_hist[self._mic_hist_write:end] = mono +# else: +# part1 = self._correlation_samples - self._mic_hist_write +# self._mic_hist[self._mic_hist_write:] = mono[:part1] +# self._mic_hist[:end - self._correlation_samples] = mono[part1:] + +# self._mic_hist_write = end % self._correlation_samples +# self._mic_hist_valid = min(self._mic_hist_valid + N, self._correlation_samples) + +# def _get_reference_window(self, length): +# length = min(length, self._ref_valid) +# if length <= 0: return np.array([], dtype=np.float32) +# start = (self._ref_write_pos - length) % self._buffer_size +# end = self._ref_write_pos +# if start < end: return self._ref_buffer[start:end].copy() +# else: return np.concatenate( (self._ref_buffer[start:].copy(), self._ref_buffer[:end].copy()) ) + +# def _get_mic_history(self): +# length = min(self._mic_hist_valid, self._correlation_samples) +# if length <= 0: return np.array([], dtype=np.float32) +# start = (self._mic_hist_write - length) % self._correlation_samples +# end = self._mic_hist_write +# if start < end: return self._mic_hist[start:end].copy() +# else: return np.concatenate( (self._mic_hist[start:].copy(), self._mic_hist[:end].copy()) ) + +# # Post-filter +# def _pf_process(self, residual, echo_estimate, alpha): +# # STFT overlap-add power-subtraction post-filter +# # +# # Operates in the time domain after de-emphasis so that +# # suppression is not undone by the de-emphasis IIR. +# # +# # Uses the gain rule:: +# # +# # G = max( 1 - alpha * P_echo / P_res , beta ) +# # +# # where *P_res* is the smoothed power of the residual and +# # *P_echo* the smoothed power of the echo estimate. Returns +# # the filtered time-domain signal and a dict of diagnostic stats. + +# N = len(residual) +# self._pf_inbuf.extend(residual) +# self._pf_ecbuf.extend(echo_estimate) + +# fft_size = self.pf_fft_size +# hop = self.pf_hop_size +# window = self._pf_window +# synbuf = self._pf_synbuf +# outbuf = self._pf_outbuf + +# block_stats = [] + +# while len(self._pf_inbuf) >= fft_size: +# x = np.array(self._pf_inbuf[:fft_size], dtype=np.float32) * window +# e = np.array(self._pf_ecbuf[:fft_size], dtype=np.float32) * window + +# X = np.fft.rfft(x) +# E = np.fft.rfft(e) + +# absX2 = np.abs(X) ** 2 +# absE2 = np.abs(E) ** 2 + +# self._pf_res_power = self.pf_smooth * self._pf_res_power + (1.0 - self.pf_smooth) * absX2 +# self._pf_echo_power = self.pf_smooth * self._pf_echo_power + (1.0 - self.pf_smooth) * absE2 + +# # Classic power-subtraction ratio +# with np.errstate(divide='ignore', invalid='ignore'): +# ratio = self._pf_echo_power / (self._pf_res_power + 1e-12) +# ratio = np.clip(ratio, 0.0, 1e6) + +# gain = 1.0 - alpha * ratio +# np.clip(gain, self.pf_beta, 1.0, out=gain) + +# # Collect stats for this block +# valid_bins = len(gain) +# floor_count = int(np.sum(gain <= self.pf_beta + 1e-9)) +# block_stats.append( {'gain_mean': float(np.mean(gain)), +# 'gain_min': float(np.min(gain)), +# 'floor_pct': 100.0 * floor_count / valid_bins, +# 'ratio_mean_db': float(10.0 * np.log10(np.mean(ratio) + 1e-12)), +# 'ratio_max_db': float(10.0 * np.log10(np.max(ratio) + 1e-12)), +# 'power_echo_db': float(10.0 * np.log10(np.mean(self._pf_echo_power) + 1e-12)), +# 'power_res_db': float(10.0 * np.log10(np.mean(self._pf_res_power) + 1e-12))} ) + +# Y = X * gain +# y = np.fft.irfft(Y, n=fft_size) * window + +# synbuf += y +# outbuf.extend(synbuf[:hop].tolist()) +# synbuf[:-hop] = synbuf[hop:] +# synbuf[-hop:] = 0.0 + +# del self._pf_inbuf[:hop] +# del self._pf_ecbuf[:hop] + +# if len(outbuf) >= N: +# result = np.array(outbuf[:N], dtype=np.float32) +# del outbuf[:N] +# return result, block_stats + +# else: +# available = len(outbuf) +# result = np.empty(N, dtype=np.float32) +# if available > 0: +# result[:available] = np.array(outbuf[:available], dtype=np.float32) +# del outbuf[:available] +# result[available:] = residual[available:] +# return result, block_stats + +# def _pf_flush_debug(self, now, force=False): +# if self._pf_debug_frames == 0: return +# if not force and now - self._pf_last_debug_time < self.PF_LOG_INTERVAL: return + +# n = self._pf_debug_frames +# acc = self._pf_debug_acc +# RNS.log(f"EchoCanceller PF: " +# f"nlms_pre={acc['nlms_pre']/n:.1f}dB " +# f"nlms_out={acc['nlms_out']/n:.1f}dB " +# f"total_out={acc['total_out']/n:.1f}dB " +# f"gain_mean={acc['gain_mean']/n:.3f} " +# f"gain_min={acc['gain_min']/n:.3f} " +# f"floor_pct={acc['floor_pct']/n:.1f}% " +# f"ratio_mean={acc['ratio_mean_db']/n:.1f}dB " +# f"ratio_max={acc['ratio_max_db']/n:.1f}dB " +# f"Pecho={acc['power_echo_db']/n:.1f}dB " +# f"Pres={acc['power_res_db']/n:.1f}dB " +# f"frames={n}", +# RNS.LOG_DEBUG) + +# self._pf_last_debug_time = now +# self._pf_debug_frames = 0 +# for k in acc: acc[k] = 0.0 + +# # Public interface +# def handle_reference(self, frame, samplerate): +# mono = self._to_mono(frame) +# mono, self._ref_preemph_state = self._preemph(mono, self._ref_preemph_state) +# with self._lock: +# self._ensure_buffer(samplerate) +# self._append_reference(mono) + +# def handle_frame(self, frame, samplerate): +# original_shape = frame.shape +# mono = self._to_mono(frame) +# N = len(mono) +# if N == 0: return frame + +# mic_rms = np.sqrt(np.mean(mono ** 2)) +# if mic_rms < self.rms_threshold: return frame + +# # Pre-emphasise mic for both delay estimation and NLMS +# mono_pre, self._mic_preemph_state = self._preemph(mono, self._mic_preemph_state) + +# # 1. Delay estimation +# seg = None +# with self._lock: +# if self._ref_valid < N + 100: return frame +# if self._samplerate != samplerate: +# RNS.log(f"EchoCanceller samplerate mismatch (ref={self._samplerate}, mic={samplerate}), skipping", RNS.LOG_WARNING) +# return frame + +# # Accumulate history +# self._append_mic_history(mono_pre) +# if self._mic_hist_valid < self._correlation_samples // 2: return frame + +# mic_window = self._get_mic_history() +# search_length = min(self._ref_valid, self._max_delay_samples + len(mic_window)) +# if search_length <= len(mic_window): return frame +# ref_window = self._get_reference_window(search_length) + +# # FFT-based cross-correlation +# M = len(ref_window) +# Nc = len(mic_window) +# fft_size = 1 << (M + Nc - 1).bit_length() +# C = np.fft.irfft( np.fft.rfft(ref_window, n=fft_size) * +# np.conj(np.fft.rfft(mic_window, n=fft_size)), +# n=fft_size ) +# c = C[:M - Nc + 1] + +# mic_norm = np.linalg.norm(mic_window) +# if mic_norm == 0: return frame + +# ref_sq = ref_window ** 2 +# ref_cumsum = np.concatenate(([0.0], np.cumsum(ref_sq, dtype=np.float64))) +# window_norms = np.sqrt(ref_cumsum[Nc:] - ref_cumsum[:-Nc]) + +# with np.errstate(divide='ignore', invalid='ignore'): corr = c / (mic_norm * window_norms) +# corr[window_norms == 0] = 0 +# abs_corr = np.abs(corr) + +# # Accumulate +# self._corr_acc *= self.acc_forget +# self._corr_acc[:len(abs_corr)] += abs_corr[::-1] +# acc_norm = self._corr_acc * (1.0 - self.acc_forget) + +# # Statistics for logging +# abs_mean = float(np.mean(abs_corr)) +# abs_std = float(np.std(abs_corr)) + +# # Search for peak +# if self._delay_samples is not None: +# d_est = int(round(self._delay_samples)) +# d_min = max(0, d_est - self._track_window_samples) +# d_max = min(len(acc_norm) - 1, d_est + self._track_window_samples) +# track_acc = acc_norm[d_min:d_max + 1] +# best_local_idx = np.argmax(track_acc) +# best_delay = d_min + best_local_idx +# best_val = float(track_acc[best_local_idx]) +# if best_val < self.correlation_threshold: +# best_delay = int(np.argmax(acc_norm)) +# best_val = float(acc_norm[best_delay]) +# else: +# best_delay = int(np.argmax(acc_norm)) +# best_val = float(acc_norm[best_delay]) + +# prominence = (best_val - abs_mean) / (abs_std + 1e-12) +# raw_delay_ms = best_delay / self._samplerate * 1000.0 +# self._frame_count += 1 +# now = time.time() + +# if best_val >= self.correlation_threshold: +# if self._delay_samples is None: +# self._delay_samples = float(best_delay) +# self._delay_ms = raw_delay_ms +# self._delay_confidence = best_val +# else: +# self._delay_samples = ( self.ema_alpha * best_delay + (1.0 - self.ema_alpha) * self._delay_samples ) +# self._delay_ms = self._delay_samples / self._samplerate * 1000.0 +# self._delay_confidence = ( self.ema_alpha * best_val + (1.0 - self.ema_alpha) * self._delay_confidence ) + +# # if (now - self._last_log_time > self.LOG_INTERVAL_LOCKED or abs(raw_delay_ms - self._delay_ms) > 5): +# # RNS.log(f"EchoCanceller delay estimate: {self._delay_ms:.1f} ms " +# # f"(confidence={self._delay_confidence:.3f}, " +# # f"raw={raw_delay_ms:.1f} ms, val={best_val:.4f}, " +# # f"prom={prominence:.1f})", +# # RNS.LOG_DEBUG) +# # self._last_log_time = now +# # else: +# # if (self._delay_samples is None and (self._frame_count % 3 == 0 or now - self._last_log_time > self.LOG_INTERVAL_SEARCH)): +# # RNS.log(f"EchoCanceller searching: max={best_val:.4f}, " +# # f"mean={abs_mean:.4f}, std={abs_std:.4f}, " +# # f"prom={prominence:.1f}, peak_delay={raw_delay_ms:.1f}ms, " +# # f"hist_valid={self._mic_hist_valid}", +# # RNS.LOG_DEBUG) +# # self._last_log_time = now + +# # Prepare aligned reference segment for NLMS +# if self._delay_samples is not None: +# int_delay = int(round(self._delay_samples)) +# needed = int_delay + N + self.filter_taps - 1 +# if self._ref_valid >= needed: +# rw = self._get_reference_window(needed) +# seg = rw[:N + self.filter_taps - 1] + +# # 2. NLMS adaptive filter +# if seg is None or len(seg) < N + self.filter_taps - 1: return frame + +# L = self.filter_taps +# w = self._w +# mu = self.nlms_mu +# eps = self.nlms_eps +# leakage = self.leakage + +# clean_pre = np.empty(N, dtype=np.float32) +# echo_pre = np.empty(N, dtype=np.float32) + +# # Frame-level double-talk detection +# ref_aligned = seg[L - 1:L - 1 + N] +# ref_peak = np.max(np.abs(ref_aligned)) +# mic_peak = np.max(np.abs(mono_pre)) +# ratio = mic_peak / (ref_peak + 1e-12) + +# hard_freeze = ratio > self.dtd_threshold + +# if hard_freeze: +# self._dtd_hangover_counter = int(self.dtd_hangover_ms / 1000.0 * self._samplerate) +# freeze = True +# elif self._dtd_hangover_counter > 0: +# freeze = True +# self._dtd_hangover_counter -= N +# else: +# freeze = False + +# soft_freeze = (not freeze) and (ratio > self.soft_dtd_threshold) +# effective_mu = mu * self.soft_dtd_mu_scale if soft_freeze else mu + +# if freeze: pf_alpha = self.pf_alpha_hard +# elif soft_freeze: pf_alpha = self.pf_alpha_soft +# else: pf_alpha = self.pf_alpha + +# if freeze != self._dtd_was_frozen: +# state = "frozen" if freeze else "active" +# RNS.log(f"EchoCanceller DTD {state} (ratio={ratio:.2f}, ref_peak={ref_peak:.4f}, mic_peak={mic_peak:.4f})", RNS.LOG_DEBUG) +# self._dtd_was_frozen = freeze + +# for i in range(N): +# x = seg[i:i + L][::-1] +# y_hat = np.dot(w, x) +# e = mono_pre[i] - y_hat +# clean_pre[i] = e +# echo_pre[i] = y_hat + +# if not freeze: +# pw = np.dot(x, x) +# w *= leakage +# w += effective_mu * e * x / (pw + eps) + +# # 3. De-emphasis +# clean_raw_nlms, self._deemph_state = self._deemph(clean_pre, self._deemph_state) + +# if self.pf_enable and self._pf_window is not None: +# echo_time = mono - clean_raw_nlms +# filtered_raw, block_stats = self._pf_process(clean_raw_nlms, echo_time, pf_alpha) +# else: +# filtered_raw = clean_raw_nlms +# block_stats = [] + +# # 4. Frame-level ERLE and spectral diagnostics +# power_mic = np.mean(mono ** 2) +# power_nlms = np.mean(clean_raw_nlms ** 2) +# power_pf = np.mean(filtered_raw ** 2) +# power_mic_pre = np.mean(mono_pre ** 2) +# power_nlms_pre = np.mean(clean_pre ** 2) + +# if power_nlms_pre > 1e-18: erle_nlms_pre = 10.0 * np.log10(power_mic_pre / power_nlms_pre) +# else: erle_nlms_pre = 99.0 + +# if power_nlms > 1e-18: erle_nlms_out = 10.0 * np.log10(power_mic / power_nlms) +# else: erle_nlms_out = 99.0 + +# if power_pf > 1e-18: erle_total_out = 10.0 * np.log10(power_mic / power_pf) +# else: erle_total_out = 99.0 + +# if block_stats: +# avg = { 'gain_mean': sum(s['gain_mean'] for s in block_stats) / len(block_stats), +# 'gain_min': sum(s['gain_min'] for s in block_stats) / len(block_stats), +# 'floor_pct': sum(s['floor_pct'] for s in block_stats) / len(block_stats), +# 'ratio_mean_db': sum(s['ratio_mean_db'] for s in block_stats) / len(block_stats), +# 'ratio_max_db': sum(s['ratio_max_db'] for s in block_stats) / len(block_stats), +# 'power_echo_db': sum(s['power_echo_db'] for s in block_stats) / len(block_stats), +# 'power_res_db': sum(s['power_res_db'] for s in block_stats) / len(block_stats) } +# else: +# avg = { 'gain_mean': 1.0, 'gain_min': 1.0, 'floor_pct': 0.0, 'ratio_mean_db': -99.0, +# 'ratio_max_db': -99.0, 'power_echo_db': -99.0, 'power_res_db': -99.0 } + +# acc = self._pf_debug_acc +# acc['nlms_pre'] += erle_nlms_pre +# acc['nlms_out'] += erle_nlms_out +# acc['total_out'] += erle_total_out +# acc['gain_mean'] += avg['gain_mean'] +# acc['gain_min'] += avg['gain_min'] +# acc['floor_pct'] += avg['floor_pct'] +# acc['ratio_mean_db'] += avg['ratio_mean_db'] +# acc['ratio_max_db'] += avg['ratio_max_db'] +# acc['power_echo_db'] += avg['power_echo_db'] +# acc['power_res_db'] += avg['power_res_db'] +# self._pf_debug_frames += 1 + +# now = time.time() +# self._pf_flush_debug(now) + +# # Compute echo estimate and subtract from original channels +# echo_mono = mono - filtered_raw +# if len(original_shape) == 1: output = filtered_raw +# else: output = frame - echo_mono[:, np.newaxis] + +# return output + +# @property +# def delay_ms(self): return self._delay_ms + +# @property +# def delay_samples(self): return self._delay_samples + +# @property +# def confidence(self): return self._delay_confidence diff --git a/LXST/Generators.py b/LXST/Generators.py index fa37bc1..77586c8 100644 --- a/LXST/Generators.py +++ b/LXST/Generators.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import os import RNS import math diff --git a/LXST/Mixer.py b/LXST/Mixer.py index 2a4cda5..3326cb3 100644 --- a/LXST/Mixer.py +++ b/LXST/Mixer.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import RNS import LXST import time @@ -17,6 +19,7 @@ class Mixer(LocalSource, LocalSink): def __init__(self, target_frame_ms=40, samplerate=None, codec=None, sink=None, gain=0.0): self.incoming_frames = {} + self.reference_outs = [] self.target_frame_ms = target_frame_ms self.frame_time = self.target_frame_ms/1000 self.should_run = False @@ -99,6 +102,7 @@ class Mixer(LocalSource, LocalSink): else: return 10**(self.gain/10) def _mixer_job(self): + if self.mixer_lock.locked(): return with self.mixer_lock: while self.should_run: if self.sink and self.sink.can_receive(): @@ -117,13 +121,22 @@ class Mixer(LocalSource, LocalSink): if mixed_frame.max() >= 1.0 or mixed_frame.min() <= -1.0: RNS.log(f"Signal clipped on {self}", RNS.LOG_WARNING) - if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self) - else: self.sink.handle_frame(mixed_frame, self) - else: - time.sleep(self.frame_time*0.1) + try: + if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self) + else: self.sink.handle_frame(mixed_frame, self) + + except Exception as e: RNS.log(f"Error while mixing frame on {self}: {e}", RNS.LOG_ERROR) - else: - time.sleep(self.frame_time*0.1) + try: + for ref in self.reference_outs: ref.handle_reference(mixed_frame, self.samplerate) + + except Exception as e: RNS.log(f"Error while handling reference output on {self}: {e}", RNS.LOG_ERROR) + + else: time.sleep(self.frame_time*0.1) + + else: time.sleep(self.frame_time*0.1) + + RNS.log(f"{self} stopped", RNS.LOG_DEBUG) @property def codec(self): diff --git a/LXST/Network.py b/LXST/Network.py index a266c07..7f21838 100644 --- a/LXST/Network.py +++ b/LXST/Network.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import RNS import time import threading @@ -23,7 +25,8 @@ class SignallingReceiver(): if self.proxy: self.proxy.signalling_received(signals, source) def signal(self, signal, destination, immediate=True): - signalling_data = {FIELD_SIGNALLING:[signal]} + if type(signal) != list: signalling_data = {FIELD_SIGNALLING: [signal]} + else: signalling_data = {FIELD_SIGNALLING: signal} if immediate: signalling_packet = RNS.Packet(destination, mp.packb(signalling_data), create_receipt=False) @@ -52,11 +55,12 @@ class Packetizer(RemoteSink): self.should_run = False self.source = None self.transmit_failure = False + self.squelched = False self.__failure_calback = failure_callback def handle_frame(self, frame, source=None): - if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE: - return + if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE: return + if self.squelched: return # TODO: Add inband signalling scheduler frame = codec_header_byte(type(self.source.codec))+frame @@ -92,8 +96,9 @@ class Packetizer(RemoteSink): RNS.log(f"{self} starting", RNS.LOG_DEBUG) self.should_run = True - def stop(self): - self.should_run = False + def stop(self): self.should_run = False + def squelch(self): self.squelched = True + def unsquelch(self): self.squelched = False class LinkSource(RemoteSource, SignallingReceiver): def __init__(self, link, signalling_receiver, sink=None): diff --git a/LXST/Pipeline.py b/LXST/Pipeline.py index 6fd377b..02681a1 100644 --- a/LXST/Pipeline.py +++ b/LXST/Pipeline.py @@ -1,3 +1,7 @@ +# Copyright 2024-2026, Mark Qvist + +import threading + from .Sources import * from .Sinks import * from .Codecs import * @@ -8,6 +12,8 @@ class PipelineError(Exception): pass class Pipeline(): + release_lock = threading.Lock() + def __init__(self, source, codec, sink, processor = None): if not issubclass(type(source), Source): raise PipelineError("Audio pipeline initialised with invalid source") if not issubclass(type(sink), Sink) : raise PipelineError("Audio pipeline initialised with invalid sink") @@ -20,15 +26,22 @@ class Pipeline(): if isinstance(sink, Loopback): sink.samplerate = source.samplerate if isinstance(source, Loopback): source._sink = sink + if isinstance(source, Mixer): source._sink = sink if isinstance(sink, Packetizer): sink.source = source if isinstance(sink, OpusFileSink): sink.source = source + def release(self): + if self.release_lock.locked(): return + with self.release_lock: + if not hasattr(self, "released") or not self.released: + self.released = True + self.source = None + self._codec = None + @property def codec(self): - if self.source: - return self.source.codec - else: - return None + if self.source: return self.source.codec + else: return None @codec.setter def codec(self, codec): @@ -40,19 +53,15 @@ class Pipeline(): @property def sink(self): - if self.source: - return self.source.sink - else: - return None + if self.source: return self.source.sink + else: return None @property def running(self): return self.source.should_run def start(self): - if not self.running: - self.source.start() + if not self.running: self.source.start() def stop(self): - if self.running: - self.source.stop() \ No newline at end of file + if self.running: self.source.stop() \ No newline at end of file diff --git a/LXST/Platforms/android/soundcard.py b/LXST/Platforms/android/soundcard.py index b7e22c9..e269c67 100644 --- a/LXST/Platforms/android/soundcard.py +++ b/LXST/Platforms/android/soundcard.py @@ -1,32 +1,4 @@ -# Reticulum License -# -# Copyright (c) 2025 Mark Qvist -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# - The Software shall not be used in any kind of system which includes amongst -# its functions the ability to purposefully do harm to human beings. -# -# - The Software shall not be used, directly or indirectly, in the creation of -# an artificial intelligence, machine learning or language model training -# dataset, including but not limited to any use that contributes to the -# training or development of such a model or algorithm. -# -# - The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. +# Copyright 2024-2026, Mark Qvist import atexit import collections.abc @@ -448,6 +420,7 @@ class _Stream: self.AudioManager = activity.getSystemService(autoclass("android.media.AudioManager")) self.AudioTrack = autoclass("android.media.AudioTrack") + self.AudioRecord = autoclass("android.media.AudioRecord") self.AudioFormat = autoclass("android.media.AudioFormat") self.AudioDeviceInfo = autoclass("android.media.AudioDeviceInfo") @@ -586,8 +559,8 @@ class _Stream: else: raise ValueError(f"Unsupported channel count {channels} on Android audio backend") - self.min_buffer_playback = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_out, self.audio_encoding); - self.min_buffer_recording = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding); + self.min_buffer_playback = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_out, self.audio_encoding) + self.min_buffer_recording = self.AudioRecord.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding) self.bytes_per_sample = (self.bit_depth//8)*self.channels self._samplerate = int(self.AudioManager.getProperty(self.AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)) @@ -678,7 +651,9 @@ class _Player(_Stream): aa_builder.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN) self.performance_mode = AudioTrack.PERFORMANCE_MODE_NONE - aa_builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_NONE) + if _audio.android_api_version >= 29: + aa_builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_NONE) + self.audio_attributes = aa_builder.build() af_builder = AudioFormatBuilder() @@ -728,6 +703,11 @@ class _Player(_Stream): while data.nbytes > 0: samples_bytes = data.ravel().tobytes() written_bytes = self.audio_track.write(samples_bytes, 0, len(samples_bytes), self._write_mode) + + if written_bytes < 0: + RNS.log(f"{self} frame write error: {written_bytes}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None + return + written_samples = written_bytes//self.bytes_per_sample if self._low_latency_activated: @@ -743,6 +723,9 @@ class _Player(_Stream): written_samples = remaining_frame_samples # TODO: Remove debug # RNS.log(f"Buffer overrun. Target buffer samples {self._target_buffer_samples}. Needed to write {remaining_frame_samples} samples / {len(samples_bytes)} bytes. Discarding {written_samples} input samples.") + else: time.sleep(0.001) # Yield thread, buffer full inside overrun lock window + + if written_bytes == 0 and not self._low_latency_activated: time.sleep(0.001) # Yield thread, buffer full data = data[written_samples:] @@ -759,40 +742,108 @@ class _Player(_Stream): # RNS.log(f"{delta} underruns on {self}") class _Recorder(_Stream): + READ_MODE_FAST = "fast" + READ_MODE_LEGACY = "legacy" + READ_MODE_FAUX = "faux" + READ_MODE = READ_MODE_FAST + DBG_READ_PACING = 0.0 + def __init__(self, *args, **kwargs): super(_Recorder, self).__init__(*args, **kwargs) - self.AudioRecord = autoclass("android.media.AudioRecord") - self._pending_chunk = numpy.zeros((0, ), dtype='float32') + self._pending_chunk = numpy.zeros((0, ), dtype='float32') + self._helper_service = None + self._helper_ok = False def _connect_stream(self): try: AudioSource = autoclass("android.media.MediaRecorder$AudioSource") + self.min_buffer_recording = self.AudioRecord.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding) - self.audio_record = self.AudioRecord(AudioSource.VOICE_COMMUNICATION, self._samplerate, self.audio_format_in, self.audio_encoding, self.min_buffer_recording) + buffer_target_ms = 200 + buffer_target_samples = int((self._samplerate/1000)*buffer_target_ms) + buffer_target_bytes = buffer_target_samples*self.bytes_per_sample + # RNS.log(f"hz={self._samplerate}, Bps={self.bytes_per_sample}, bd={self.bit_depth}, ch={self.channels}, mbr={self.min_buffer_recording}") + # RNS.log(f"ms={buffer_target_ms}, smpls={buffer_target_samples}, bytes={buffer_target_bytes}") + if buffer_target_bytes < self.min_buffer_recording: buffer_target_bytes = self.min_buffer_recording + self.audio_record = self.AudioRecord(AudioSource.VOICE_COMMUNICATION, self._samplerate, self.audio_format_in, self.audio_encoding, buffer_target_bytes) self.audio_record.startRecording() + if _Recorder.READ_MODE == _Recorder.READ_MODE_FAST: self.__check_read_helper() except Exception as e: RNS.log(f"Error while connecting input audio stream via JNI: {e}", RNS.LOG_ERROR) RNS.trace_exception(e) - def _record_chunk(self): + def __check_read_helper(self): try: - audio_data = bytearray(self.min_buffer_recording) - bytes_read = self.audio_record.read(audio_data, 0, self.min_buffer_recording, self.audio_record.READ_NON_BLOCKING) - if bytes_read == 0: time.sleep(0.005) + service = autoclass("org.kivy.android.PythonService").mService + if service == None: raise AttributeError("No PythonService instance available") + probe = service.audioRecordRead(self.audio_record, 0, self.audio_record.READ_NON_BLOCKING) + if probe == None: raise AttributeError("audioRecordRead returned None for probe") + if len(probe) != 0: raise ValueError("audioRecordRead probe returned unexpected data") + self._helper_service = service + self._helper_ok = True + RNS.log(f"{self} using audio read helper", RNS.LOG_DEBUG) + return - if bytes_read == self.audio_record.ERROR_INVALID_OPERATION: RNS.log(f"Invalid operation error from JNI on {self}", RNS.LOG_ERROR) - elif bytes_read == self.audio_record.ERROR_BAD_VALUE: RNS.log(f"Bad value error from JNI on {self}", RNS.LOG_ERROR) + except Exception as e: RNS.log(f"{self} audio read helper not available, using legacy read path: {e}", RNS.LOG_DEBUG) + + self._helper_service = None + self._helper_ok = False + + def _read_fast(self, read_bytes, read_mode): + result = self._helper_service.audioRecordRead(self.audio_record, int(read_bytes), int(read_mode)) + + if result == None: + bytes_read = -1 + RNS.log(f"{self} audio read error in helper", RNS.LOG_ERROR) + return None + + bytes_read = len(result) + + if bytes_read == 0: return numpy.zeros((0, ), dtype="float32") + else: + recorded_samples = numpy.frombuffer(result.tostring(), dtype="int16")/self.TYPE_MAP_FACTOR + return recorded_samples.astype("float32") + + def _read_legacy(self, read_bytes, read_mode): + audio_data = bytearray(int(read_bytes)) + bytes_read = self.audio_record.read(audio_data, 0, read_bytes, read_mode) + + if bytes_read == self.audio_record.ERROR_INVALID_OPERATION: RNS.log(f"Invalid operation error from JNI on {self}", RNS.LOG_ERROR) + elif bytes_read == self.audio_record.ERROR_BAD_VALUE: RNS.log(f"Bad value error from JNI on {self}", RNS.LOG_ERROR) + elif bytes_read < 0: RNS.log(f"Audio read error ({bytes_read}) on {self}", RNS.LOG_ERROR) + elif bytes_read == 0: return numpy.zeros((0, ), dtype="float32") + else: + recorded_samples = numpy.frombuffer(audio_data[:bytes_read], dtype="int16")/self.TYPE_MAP_FACTOR + return recorded_samples.astype("float32") + + # Debug-only faux-read shim + def _read_faux(self, read_bytes, read_mode): + bytes_read = int(read_bytes) + audio_data = bytes(bytes_read) + time.sleep(bytes_read/self.bytes_per_sample/self._samplerate) + return numpy.zeros((bytes_read//2, ), dtype="float32") + + def _record_chunk(self, read_bytes=None): + try: + if read_bytes: + read_mode = self.audio_record.READ_BLOCKING else: - recorded_samples = numpy.frombuffer(audio_data[:bytes_read], dtype="int16")/self.TYPE_MAP_FACTOR - return recorded_samples.astype("float32") + read_bytes = self.min_buffer_recording + read_mode = self.audio_record.READ_NON_BLOCKING + + if _Recorder.READ_MODE == _Recorder.READ_MODE_FAUX: chunk = self._read_faux(read_bytes, read_mode) + elif _Recorder.READ_MODE == _Recorder.READ_MODE_FAST and self._helper_ok: chunk = self._read_fast(read_bytes, read_mode) + else: chunk = self._read_legacy(read_bytes, read_mode) + + if _Recorder.DBG_READ_PACING > 0 and _Recorder.READ_MODE != _Recorder.READ_MODE_FAUX: time.sleep(_Recorder.DBG_READ_PACING) + + return chunk except Exception as e: RNS.log(f"Error while reading audio chunk: {e}", RNS.LOG_ERROR) - RNS.trace_exception(e) return None - def record(self, numframes=None): if numframes is None: return numpy.reshape(numpy.concatenate([self.flush().ravel(), self._record_chunk()]), [-1, self.channels]) else: @@ -803,10 +854,30 @@ class _Recorder(_Stream): return numpy.reshape(keep, [-1, self.channels]) else: + timeout = time.time()+(numframes/self._samplerate)*8 while captured_frames < numframes: - chunk = self._record_chunk() - captured_data.append(chunk) - captured_frames += len(chunk)/self.channels + if time.time() > timeout: + RNS.log(f"{self} capture timed out at {captured_frames} out of {numframes} frames, emitting silence", RNS.LOG_WARNING) + self._pending_chunk = numpy.zeros((0, ), dtype="float32") + return numpy.zeros((int(numframes), self.channels), dtype="float32") + + try: + m_frames = numframes - captured_frames + m_bytes = m_frames * self.bytes_per_sample + # RNS.log(f"RECORD {m_bytes} bytes ({m_frames} samples) (min {self.min_buffer_recording})") # TODO: Remove + chunk = self._record_chunk(read_bytes=m_bytes) + captured_data.append(chunk) + captured_frames += len(chunk)/self.channels + if captured_frames < numframes: + wait_factor=0.65 + m_frames = numframes - captured_frames + st = (m_frames / self._samplerate) * wait_factor + # RNS.log(f"Missing {m_frames}/{numframes} samples, sleeping for {RNS.prettyshorttime(st)}") # TODO: Remove + time.sleep(st) + + except Exception as e: + RNS.log(f"Could not acquire audio frame: {e}", RNS.LOG_WARNING) + return None to_split = int(len(chunk) - (captured_frames - numframes) * self.channels) captured_data[-1], self._pending_chunk = numpy.split(captured_data[-1], [to_split]) diff --git a/LXST/Platforms/linux/soundcard.py b/LXST/Platforms/linux/soundcard.py index d628e69..666436d 100644 --- a/LXST/Platforms/linux/soundcard.py +++ b/LXST/Platforms/linux/soundcard.py @@ -147,7 +147,8 @@ class _PulseAudio: import sys prog_name = sys.argv[0] if prog_name == "-c": - return sys.argv[1][:30] + "..." + if len(sys.argv) > 1: return sys.argv[1][:30] + "..." + else: return f"lxst_application_{os.getpid()}" if prog_name == "-m": prog_name = sys.argv[1] # Usually even with -m, sys.argv[0] will already be a path, @@ -230,7 +231,7 @@ class _PulseAudio: info.append(info_dict) self._pa_context_get_source_info_by_name(self.context, id.encode(), callback, _ffi.NULL) - return info[0] + return info[0] if len(info) else None @property def sink_list(self): diff --git a/LXST/Platforms/windows.c b/LXST/Platforms/windows.c deleted file mode 100644 index 7efb938..0000000 --- a/LXST/Platforms/windows.c +++ /dev/null @@ -1 +0,0 @@ -void PyInit_filterlib(void) { } \ No newline at end of file diff --git a/LXST/Primitives/Players.py b/LXST/Primitives/Players.py index 381b7da..18f55f3 100644 --- a/LXST/Primitives/Players.py +++ b/LXST/Primitives/Players.py @@ -1,18 +1,23 @@ +# Copyright 2024-2026, Mark Qvist + import LXST import time import threading import os +import gc from LXST.Sinks import LineSink from LXST.Sources import OpusFileSource class FilePlayer(): - def __init__(self, path=None, device=None, loop=False): + def __init__(self, path=None, device=None, loop=False, gain=0.0, release_on_finish=False): self._file_path = path self._playback_device = None self.__finished_callback = None + self.__release_on_finish = release_on_finish self.__loop = loop self.__source = None + self.__gain = gain self.__sink = LineSink(self._playback_device) self.__raw = LXST.Codecs.Raw() self.__loopback = LXST.Sources.Loopback() @@ -20,14 +25,32 @@ class FilePlayer(): self.__input_pipeline = None if path: self.set_source(self._file_path) + @property + def gain(self): return self.__gain + + @gain.setter + def gain(self, db): + try: db = float(db) + except: raise TypeError("Invalid gain type, must be decibel as a floating point number") + self.__gain = db + if self.__source: self.__source.gain = self.__gain + @property def running(self): if not self.__source: return False - else: return self.__source.should_run + else: return self.__source.should_run or len(self.__sink.frame_deque) @property def playing(self): return self.running + @property + def release_on_finish(self): return self.__release_on_finish + + @release_on_finish.setter + def release_on_finish(self, value): + if type(value) != bool: raise TypeError("Provided value is not bool") + else: self.__release_on_finish = value + @property def finished_callback(self): return self.__finished_callback @@ -38,17 +61,18 @@ class FilePlayer(): else: self.__finished_callback = callback def __callback_job(self): - if self.__finished_callback: + if self.__finished_callback or self.__release_on_finish: time.sleep(0.2) while self.running: time.sleep(0.1) - self.__finished_callback(self) + if self.__finished_callback: self.__finished_callback(self) + if self.__release_on_finish: self.release() def set_source(self, path=None): if not path: return else: if not os.path.isfile(path): raise OSError(f"File not found: {path}") else: - self.__source = OpusFileSource(path, loop=self.__loop) + self.__source = OpusFileSource(path, loop=self.__loop, gain=self.gain) self.__input_pipeline = LXST.Pipeline(source=self.__source, codec=self.__raw, sink=self.__loopback) def loop(self, loop=True): @@ -60,7 +84,7 @@ class FilePlayer(): if not self.running and self.__source: self.__input_pipeline.start() self.__output_pipeline.start() - if self.__finished_callback: + if self.__finished_callback or self.__release_on_finish: threading.Thread(target=self.__callback_job, daemon=True).start() def stop(self): @@ -68,4 +92,15 @@ class FilePlayer(): self.__input_pipeline.stop() self.__output_pipeline.stop() - def play(self): self.start() \ No newline at end of file + def play(self): self.start() + + def release(self): + self.stop() + self.__source.release() + self.__input_pipeline.release() + self.__output_pipeline.release() + self.__input_pipeline = None + self.__output_pipeline = None + self.__sink = None + self.__source = None + self.__loopback = None \ No newline at end of file diff --git a/LXST/Primitives/Recorders.py b/LXST/Primitives/Recorders.py index b4c8d20..d52fb7c 100644 --- a/LXST/Primitives/Recorders.py +++ b/LXST/Primitives/Recorders.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import RNS import LXST import time diff --git a/LXST/Primitives/Telephony.py b/LXST/Primitives/Telephony.py index 0bf762f..996d84b 100644 --- a/LXST/Primitives/Telephony.py +++ b/LXST/Primitives/Telephony.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import os import RNS import LXST @@ -11,23 +13,43 @@ from LXST.Sinks import LineSink from LXST.Sources import LineSource, OpusFileSource from LXST.Generators import ToneSource from LXST.Network import SignallingReceiver, Packetizer, LinkSource -from LXST.Filters import BandPass, AGC +from LXST.Filters import BandPass, AGC, EchoSuppressor PRIMITIVE_NAME = "telephony" class Profiles(): - BANDWIDTH_ULTRA_LOW = 0x10 - BANDWIDTH_VERY_LOW = 0x20 + BANDWIDTH_ULTRA_LOW = 0x10 + BANDWIDTH_VERY_LOW = 0x20 BANDWIDTH_LOW = 0x30 QUALITY_MEDIUM = 0x40 QUALITY_HIGH = 0x50 QUALITY_MAX = 0x60 LATENCY_ULTRA_LOW = 0x70 LATENCY_LOW = 0x80 - DEFAULT_PROFILE = QUALITY_MEDIUM + MODE_FULL_DUPLEX = 0x01 + MODE_HALF_DUPLEX = 0x02 + DEFAULT_MODE = MODE_FULL_DUPLEX + + @staticmethod + def available_modes(): + return [Profiles.MODE_FULL_DUPLEX, + Profiles.MODE_HALF_DUPLEX] + + @staticmethod + def mode_name(profile): + if profile == Profiles.MODE_FULL_DUPLEX: return "Full Duplex" + elif profile == Profiles.MODE_HALF_DUPLEX: return "Half Duplex" + else: return "Default" + + @staticmethod + def mode_abbrevation(profile): + if profile == Profiles.MODE_FULL_DUPLEX: return "FDX" + elif profile == Profiles.MODE_HALF_DUPLEX: return "HDX" + else: return "DFLT" + @staticmethod def available_profiles(): return [Profiles.BANDWIDTH_ULTRA_LOW, @@ -92,6 +114,18 @@ class Profiles(): elif profile == Profiles.LATENCY_ULTRA_LOW: return 10 else: return 60 + @staticmethod + def get_buffer_frames(profile): + if profile == Profiles.BANDWIDTH_ULTRA_LOW: return 2 + elif profile == Profiles.BANDWIDTH_VERY_LOW: return 2 + elif profile == Profiles.BANDWIDTH_LOW: return 2 + elif profile == Profiles.QUALITY_MEDIUM: return 5 + elif profile == Profiles.QUALITY_HIGH: return 5 + elif profile == Profiles.QUALITY_MAX: return 5 + elif profile == Profiles.LATENCY_LOW: return 3 + elif profile == Profiles.LATENCY_ULTRA_LOW: return 2 + else: return 5 + @staticmethod def next_profile(profile): profile_list = Profiles.available_profiles() @@ -107,6 +141,7 @@ class Signalling(): STATUS_RINGING = 0x04 STATUS_CONNECTING = 0x05 STATUS_ESTABLISHED = 0x06 + PREFERRED_MODE = 0xF0 PREFERRED_PROFILE = 0xFF AUTO_STATUS_CODES = [STATUS_CALLING, STATUS_AVAILABLE, STATUS_RINGING, STATUS_CONNECTING, STATUS_ESTABLISHED] @@ -137,6 +172,7 @@ class Telephone(SignallingReceiver): def __init__(self, identity, ring_time=RING_TIME, wait_time=WAIT_TIME, auto_answer=None, allowed=ALLOW_ALL, receive_gain=0.0, transmit_gain=0.0): super().__init__() + RNS.Reticulum.get_instance().wants_destination_type(f"{APP_NAME}.{PRIMITIVE_NAME}") self.identity = identity self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, PRIMITIVE_NAME) self.destination.set_proof_strategy(RNS.Destination.PROVE_NONE) @@ -155,6 +191,8 @@ class Telephone(SignallingReceiver): self.receive_gain = receive_gain self.transmit_gain = transmit_gain self.use_agc = True + self.use_bandpass = True + self.use_echo_cancellation = True self.active_call = None self.call_status = Signalling.STATUS_AVAILABLE self._external_busy = False @@ -164,6 +202,7 @@ class Telephone(SignallingReceiver): self.__busy_callback = None self.__rejected_callback = None self.target_frame_time_ms = None + self.target_buffer_frames = None self.audio_output = None self.audio_input = None self.dial_tone = None @@ -178,11 +217,13 @@ class Telephone(SignallingReceiver): self.transmit_pipeline = None self.__receive_muted = False self.__transmit_muted = False + self.__loudspeaker_on = False self.ringer_lock = threading.Lock() self.ringer_output = None self.ringer_pipeline = None self.ringtone_path = None self.speaker_device = None + self.loudspeaker_device = None self.microphone_device = None self.ringer_device = None self.low_latency_output = False @@ -241,6 +282,10 @@ class Telephone(SignallingReceiver): self.speaker_device = device RNS.log(f"{self} speaker device set to {device}", RNS.LOG_DEBUG) + def set_loudspeaker(self, device): + self.loudspeaker_device = device + RNS.log(f"{self} loudspeaker device set to {device}", RNS.LOG_DEBUG) + def set_microphone(self, device): self.microphone_device = device RNS.log(f"{self} microphone device set to {device}", RNS.LOG_DEBUG) @@ -265,6 +310,22 @@ class Telephone(SignallingReceiver): if disable == True: self.use_agc = False else: self.use_agc = True + def enable_bandpass(self, enable=True): + if enable == True: self.use_bandpass = True + else: self.use_bandpass = False + + def disable_bandpass(self, disable=True): + if disable == True: self.use_bandpass = False + else: self.use_bandpass = True + + def enable_echo_cancellation(self, enable=True): + if enable == True: self.use_echo_cancellation = True + else: self.use_echo_cancellation = False + + def disable_echo_cancellation(self, disable=True): + if disable == True: self.use_echo_cancellation = False + else: self.use_echo_cancellation = True + def set_low_latency_output(self, enabled): if enabled: self.low_latency_output = True @@ -321,7 +382,9 @@ class Telephone(SignallingReceiver): link.ring_timeout = False link.answered = False link.is_terminating = False + link.established_at = None link.profile = None + link.call_mode = None with self.call_handler_lock: if self.active_call or self.busy: RNS.log(f"Incoming call, but line is already active, signalling busy", RNS.LOG_DEBUG) @@ -360,8 +423,7 @@ class Telephone(SignallingReceiver): self.answer(identity) threading.Thread(target=cb, daemon=True).start() - else: - self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time) + else: self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time) def __link_closed(self, link): if link == self.active_call: @@ -383,6 +445,13 @@ class Telephone(SignallingReceiver): if not hasattr(self.active_call, "profile"): return None else: return self.active_call.profile + @property + def active_mode(self): + if not self.active_call: return None + else: + if not hasattr(self.active_call, "call_mode"): return None + else: return self.active_call.call_mode + @property def receive_muted(self): if not self.active_call: return False @@ -397,9 +466,16 @@ class Telephone(SignallingReceiver): if not self.transmit_mixer: return False else: return self.transmit_mixer.muted - def signal(self, signal, link): - if signal in Signalling.AUTO_STATUS_CODES: self.call_status = signal - super().signal(signal, link) + @property + def loudspeaker_on(self): + return self.__loudspeaker_on + + def signal(self, signals, link): + if type(signals) != list: signals = [signals] + for signal in signals: + if signal in Signalling.AUTO_STATUS_CODES: self.call_status = signal + + super().signal(signals, link) def answer(self, identity): with self.call_handler_lock: @@ -415,6 +491,7 @@ class Telephone(SignallingReceiver): else: RNS.log(f"Answering call from {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) self.active_call.answered = True + self.active_call.established_at = time.time() self.__open_pipelines(identity) self.__start_pipelines() RNS.log(f"Call setup complete for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) @@ -443,6 +520,7 @@ class Telephone(SignallingReceiver): self.call_status = Signalling.STATUS_AVAILABLE self.__receive_muted = False self.__transmit_muted = False + self.__loudspeaker_on = False if remote_identity: RNS.log(f"Call with {RNS.prettyhexrep(remote_identity.hash)} terminated", RNS.LOG_DEBUG) else: RNS.log(f"Outgoing call could not be connected, link establishment failed", RNS.LOG_DEBUG) @@ -471,6 +549,38 @@ class Telephone(SignallingReceiver): self.__transmit_muted = not unmute if self.transmit_mixer: self.transmit_mixer.unmute(unmute) + def enable_loudspeaker(self, enable=True): + was_on = self.__loudspeaker_on + self.__loudspeaker_on = enable + if was_on != self.__loudspeaker_on: self.__update_audio_output() + + def disable_loudspeaker(self, disable=True): + was_on = self.__loudspeaker_on + self.__loudspeaker_on = not disable + if was_on != self.__loudspeaker_on: self.__update_audio_output() + + def pause_agc(self, pause=True): + if self.active_call and hasattr(self.active_call, "filter_agc"): + if pause: self.active_call.filter_agc.paused = True + else: self.active_call.filter_agc.paused = False + + def resume_agc(self, resume=True): + if self.active_call and hasattr(self.active_call, "filter_agc"): + if resume: self.active_call.filter_agc.paused = False + else: self.active_call.filter_agc.paused = True + + def squelch_transmit(self, squelch=True): + self.pause_agc(squelch) + if self.active_call and hasattr(self.active_call, "packetizer"): + if squelch: self.active_call.packetizer.squelch() + else: self.active_call.packetizer.unsquelch() + + def unsquelch_transmit(self, unsquelch=True): + self.resume_agc(unsquelch) + if self.active_call and hasattr(self.active_call, "packetizer"): + if unsquelch: self.active_call.packetizer.unsquelch() + else: self.active_call.packetizer.squelch() + def set_receive_gain(self, gain=0.0): self.receive_gain = float(gain) if self.receive_mixer: self.receive_mixer.set_gain(self.receive_gain) @@ -479,6 +589,31 @@ class Telephone(SignallingReceiver): self.transmit_gain = float(gain) if self.transmit_mixer: self.transmit_mixer.set_gain(self.transmit_gain) + def disable_remote_mode_follow(self): + if not self.active_call: return False + else: + self.active_call.mode_switch_disabled = True + return True + + def switch_mode(self, mode=None, from_signalling=False): + if self.active_call: + if from_signalling and hasattr(self.active_call, "mode_switch_disabled"): return + if self.active_call.call_mode == mode: return + elif not mode in Profiles.available_modes(): return + else: + if self.call_status == Signalling.STATUS_ESTABLISHED: + self.active_call.call_mode = mode + if not from_signalling: self.signal(Signalling.PREFERRED_MODE+self.active_call.call_mode, self.active_call) + self.__select_call_mode(mode) + + def __select_call_mode(self, mode=None): + if mode == None: mode = Profiles.DEFAULT_MODE + self.active_call.call_mode = mode + if hasattr(self.active_call, "packetizer"): + if self.active_call.call_mode == Profiles.MODE_HALF_DUPLEX: self.active_call.packetizer.squelch() + elif self.active_call.call_mode == Profiles.MODE_FULL_DUPLEX: self.active_call.packetizer.unsquelch() + RNS.log(f"Selected call mode 0x{RNS.hexrep(mode, delimit=False)}", RNS.LOG_DEBUG) + def switch_profile(self, profile=None, from_signalling=False): if self.active_call: if self.active_call.profile == profile: return @@ -487,14 +622,18 @@ class Telephone(SignallingReceiver): self.active_call.profile = profile self.transmit_codec = Profiles.get_codec(self.active_call.profile) self.target_frame_time_ms = Profiles.get_frame_time(self.active_call.profile) + self.target_buffer_frames = Profiles.get_buffer_frames(self.active_call.profile) if not from_signalling: self.signal(Signalling.PREFERRED_PROFILE+self.active_call.profile, self.active_call) self.__reconfigure_transmit_pipeline() + self.receive_mixer.set_source_max_frames(self.active_call.audio_source, self.target_buffer_frames) + self.__update_output_buffer_targets() def __select_call_profile(self, profile=None): if profile == None: profile = Profiles.DEFAULT_PROFILE self.active_call.profile = profile self.__select_call_codecs(self.active_call.profile) self.__select_call_frame_time(self.active_call.profile) + self.__select_call_buffer_frames(self.active_call.profile) RNS.log(f"Selected call profile 0x{RNS.hexrep(profile, delimit=False)}", RNS.LOG_DEBUG) def __select_call_codecs(self, profile=None): @@ -504,6 +643,9 @@ class Telephone(SignallingReceiver): def __select_call_frame_time(self, profile=None): self.target_frame_time_ms = Profiles.get_frame_time(profile) + def __select_call_buffer_frames(self, profile=None): + self.target_buffer_frames = Profiles.get_buffer_frames(self.active_call.profile) + def __reset_dialling_pipelines(self): with self.pipeline_lock: if self.audio_output: self.audio_output.stop() @@ -516,12 +658,37 @@ class Telephone(SignallingReceiver): self.receive_mixer = None self.__prepare_dialling_pipelines() + def __update_output_buffer_targets(self): + if self.audio_output and self.target_buffer_frames: + if self.audio_output.buffer_max_height != self.target_buffer_frames: + self.audio_output.buffer_max_height = self.target_buffer_frames+1 + RNS.log(f"Updated {self.audio_output} buffer size to {self.audio_output.buffer_max_height} frames", RNS.LOG_DEBUG) + if self.audio_output.autostart_min != self.target_buffer_frames: + self.audio_output.autostart_min = max(1, self.target_buffer_frames-2) + RNS.log(f"Updated {self.audio_output} buffer trigger height to {self.audio_output.autostart_min} frames", RNS.LOG_DEBUG) + self.audio_output.streaming = True + self.audio_output.wait_for_frames() + def __prepare_dialling_pipelines(self): self.__select_call_profile(self.active_call.profile) - if self.audio_output == None: self.audio_output = LineSink(preferred_device=self.speaker_device) + self.__select_call_mode(self.active_call.call_mode) + if self.audio_output == None: self.audio_output = LineSink(preferred_device=self.speaker_device) if not self.__loudspeaker_on else LineSink(preferred_device=self.loudspeaker_device) if self.receive_mixer == None: self.receive_mixer = Mixer(target_frame_ms=self.target_frame_time_ms, gain=self.receive_gain) if self.dial_tone == None: self.dial_tone = ToneSource(frequency=self.dial_tone_frequency, gain=0.0, ease_time_ms=self.dial_tone_ease_ms, target_frame_ms=self.target_frame_time_ms, codec=Null(), sink=self.receive_mixer) if self.receive_pipeline == None: self.receive_pipeline = Pipeline(source=self.receive_mixer, codec=Null(), sink=self.audio_output) + self.__update_output_buffer_targets() + + def __update_audio_output(self): + if self.active_call and self.audio_output and self.receive_pipeline and self.receive_mixer: + with self.pipeline_lock: + previous_output = self.audio_output + previous_pipeline = self.receive_pipeline + self.audio_output = LineSink(preferred_device=self.speaker_device) if not self.__loudspeaker_on else LineSink(preferred_device=self.loudspeaker_device) + self.receive_pipeline = Pipeline(source=self.receive_mixer, codec=Null(), sink=self.audio_output) + self.receive_pipeline.start() + previous_pipeline.stop() + previous_output.stop() + self.receive_mixer.start() def __activate_ring_tone(self): if self.ringtone_path != None and os.path.isfile(self.ringtone_path): @@ -532,6 +699,7 @@ class Telephone(SignallingReceiver): def job(): with self.ringer_lock: + time.sleep(0.5) while self.active_call and self.active_call.is_incoming and self.call_status == Signalling.STATUS_RINGING: if not self.ringer_pipeline.running: self.ringer_pipeline.start() time.sleep(0.1) @@ -605,11 +773,20 @@ class Telephone(SignallingReceiver): RNS.log(f"Opening audio pipelines for call with {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) if self.active_call.is_incoming: self.signal(Signalling.STATUS_CONNECTING, self.active_call) - if self.use_agc: self.active_call.filters = [BandPass(250, 8500), AGC(target_level=-15.0)] - else: self.active_call.filters = [BandPass(250, 8500)] + filter_chain = [] + if self.use_bandpass: filter_chain.append(BandPass(250, 8500)) + if self.use_agc: self.active_call.filter_agc = AGC(target_level=-15.0) + if self.use_agc: filter_chain.append(self.active_call.filter_agc) + if self.use_echo_cancellation: + self.active_call.echo_suppressor = EchoSuppressor() + self.receive_mixer.reference_outs = [self.active_call.echo_suppressor] + filter_chain.append(self.active_call.echo_suppressor) + + self.active_call.filters = filter_chain self.__prepare_dialling_pipelines() self.active_call.packetizer = Packetizer(self.active_call, failure_callback=self.__packetizer_failure) + if self.active_call.call_mode == Profiles.MODE_HALF_DUPLEX: self.active_call.packetizer.squelch() self.transmit_mixer = Mixer(target_frame_ms=self.target_frame_time_ms, gain=self.transmit_gain) @@ -619,7 +796,7 @@ class Telephone(SignallingReceiver): self.transmit_pipeline = Pipeline(source=self.transmit_mixer, codec=self.transmit_codec, sink=self.active_call.packetizer) self.active_call.audio_source = LinkSource(link=self.active_call, signalling_receiver=self, sink=self.receive_mixer) - self.receive_mixer.set_source_max_frames(self.active_call.audio_source, 2) + self.receive_mixer.set_source_max_frames(self.active_call.audio_source, self.target_buffer_frames) self.signal(Signalling.STATUS_ESTABLISHED, self.active_call) @@ -645,7 +822,7 @@ class Telephone(SignallingReceiver): if self.transmit_pipeline: self.transmit_pipeline.stop() RNS.log(f"Audio pipelines stopped", RNS.LOG_DEBUG) - def call(self, identity, profile=None): + def call(self, identity, profile=None, mode=None): with self.call_handler_lock: if not self.active_call: self.call_status = Signalling.STATUS_CALLING @@ -668,7 +845,9 @@ class Telephone(SignallingReceiver): self.active_call.is_outgoing = True self.active_call.is_terminating = False self.active_call.ring_timeout = False + self.active_call.established_at = None self.active_call.profile = profile + self.active_call.call_mode = mode self.__timeout_outgoing_call_at(self.active_call, outgoing_call_timeout) self.__timeout_outgoing_establishment_at(self.active_call, outgoing_establishment_timeout) @@ -684,8 +863,7 @@ class Telephone(SignallingReceiver): for signal in signals: if source != self.active_call: RNS.log("Received signalling on non-active call, ignoring", RNS.LOG_DEBUG) else: - if self.active_call.is_incoming and not self.active_call.answered and signal < Signalling.PREFERRED_PROFILE: - return + if self.active_call.is_incoming and not self.active_call.answered and signal < Signalling.PREFERRED_MODE: return elif signal == Signalling.STATUS_BUSY: RNS.log("Remote is busy, terminating", RNS.LOG_DEBUG) self.active_call.is_terminating = True @@ -705,7 +883,8 @@ class Telephone(SignallingReceiver): RNS.log("Identification accepted, remote is now ringing", RNS.LOG_DEBUG) self.call_status = signal self.__prepare_dialling_pipelines() - self.signal(Signalling.PREFERRED_PROFILE+self.active_call.profile, self.active_call) + self.signal([Signalling.PREFERRED_PROFILE+self.active_call.profile, + Signalling.PREFERRED_MODE+self.active_call.call_mode], self.active_call) if self.active_call and self.active_call.is_outgoing: self.__activate_dial_tone() elif signal == Signalling.STATUS_CONNECTING: RNS.log("Call answered, remote is performing call setup, opening audio pipelines", RNS.LOG_DEBUG) @@ -721,12 +900,17 @@ class Telephone(SignallingReceiver): self.__disable_dial_tone() RNS.log(f"Call setup complete for {RNS.prettyhexrep(self.active_call.get_remote_identity().hash)}", RNS.LOG_DEBUG) self.call_status = signal + self.active_call.established_at = time.time() if callable(self.__established_callback): self.__established_callback(self.active_call.get_remote_identity()) if self.low_latency_output: self.audio_output.enable_low_latency() elif signal >= Signalling.PREFERRED_PROFILE: profile = signal - Signalling.PREFERRED_PROFILE if self.active_call and self.call_status == Signalling.STATUS_ESTABLISHED: self.switch_profile(profile, from_signalling=True) else: self.__select_call_profile(profile) + elif signal >= Signalling.PREFERRED_MODE: + mode = signal - Signalling.PREFERRED_MODE + if self.active_call and self.call_status == Signalling.STATUS_ESTABLISHED: self.switch_mode(mode, from_signalling=True) + else: self.__select_call_mode(mode) def __str__(self): return f"" \ No newline at end of file diff --git a/LXST/Primitives/__init__.py b/LXST/Primitives/__init__.py index e285a45..17ccdf4 100644 --- a/LXST/Primitives/__init__.py +++ b/LXST/Primitives/__init__.py @@ -1 +1,3 @@ +# Copyright 2024-2026, Mark Qvist + from .Telephony import Telephone \ No newline at end of file diff --git a/LXST/Primitives/hardware/display_i2c_lcd1602.py b/LXST/Primitives/hardware/display_i2c_lcd1602.py index c609cf9..02424e9 100644 --- a/LXST/Primitives/hardware/display_i2c_lcd1602.py +++ b/LXST/Primitives/hardware/display_i2c_lcd1602.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import os import time import threading diff --git a/LXST/Primitives/hardware/keypad_gpio_4x4.py b/LXST/Primitives/hardware/keypad_gpio_4x4.py index dd977fe..6704af0 100644 --- a/LXST/Primitives/hardware/keypad_gpio_4x4.py +++ b/LXST/Primitives/hardware/keypad_gpio_4x4.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import os import time import threading diff --git a/LXST/Primitives/hardware/keypad_gpio_5x5.py b/LXST/Primitives/hardware/keypad_gpio_5x5.py deleted file mode 100644 index 5840d25..0000000 --- a/LXST/Primitives/hardware/keypad_gpio_5x5.py +++ /dev/null @@ -1,131 +0,0 @@ -import os -import time -import threading -from importlib.util import find_spec -if find_spec("RPi"): import RPi.GPIO as GPIO -else: raise OSError(f"No GPIO module available, cannot use {os.path.basename(__file__)} driver") - -class Event: - UP = 0x00 - DOWN = 0x01 - -class Keypad(): - ROWS = 5 - COLS = 5 - SCAN_INTERVAL_MS = 20 - - LOW = 0x00 - HIGH = 0x01 - - DEFAULT_MAP = [["P", "R", "M", "-", "+"], - ["1", "2", "3", "A", "B"], - ["4", "5", "6", "C", "D"], - ["7", "8", "9", "E", "F"], - ["*", "0", "#", "N", "K"]] - - DEFAULT_ROWPINS = [21, 20, 16, 12, 7] - DEFAULT_COLPINS = [26, 19, 13, 6, 5] - DEFAULT_HOOKPIN = 11 - HOOK_DEBOUNCE_MS = 150 - - def __init__(self, row_pins=None, col_pins=None, key_map=None, callback=None): - if not row_pins == None and (not type(row_pins) == list or len(row_pins) != 5): - raise ValueError("Invalid row pins specification") - if not col_pins == None and (not type(col_pins) == list or len(col_pins) != 5): - raise ValueError("Invalid row pins specification") - - self.row_pins = row_pins or self.DEFAULT_ROWPINS - self.col_pins = col_pins or self.DEFAULT_COLPINS - self.scan_lock = threading.Lock() - self.callback = callback - self.hook_time = 0 - self.hook_pin = None - self.on_hook = True - self.check_hook = False - self.should_run = False - self.ec = Event - self.set_key_map(key_map) - - def enable_hook(self, pin=None): - if pin == None: pin = self.DEFAULT_HOOKPIN - self.hook_pin = pin - GPIO.setup(self.hook_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) - self.key_states["hook"] = False - self.check_hook = True - - def set_key_map(self, key_map): - self.key_map = key_map or self.DEFAULT_MAP - self.key_states = {} - for row in self.key_map: - for key in row: self.key_states[key] = False - - def is_down(self, key): - if not key in self.key_states: return False - else: - return self.key_states[key] - - def is_up(self, key): - if not key in self.key_states: return False - else: - return not self.key_states[key] - - def __job(self): - while self.should_run: - self.__scan() - time.sleep(self.SCAN_INTERVAL_MS/1000) - - def __handle(self, active_keys): - events = [] - for key in self.key_states: - if self.key_states[key] == False: - if key in active_keys: - self.key_states[key] = True - events.append((key, Event.DOWN)) - - elif self.key_states[key] == True: - if not key in active_keys: - self.key_states[key] = False - events.append((key, Event.UP)) - - if callable(self.callback): - for event in events: - self.callback(self, event) - - def __scan(self): - active_keys = [] - for row in range(0, self.ROWS): - GPIO.setup(self.row_pins[row], GPIO.OUT) - GPIO.output(self.row_pins[row], GPIO.HIGH) - for col in range(0, self.COLS): - if GPIO.input(self.col_pins[col]): - active_keys.append(self.key_map[row][col]) - - GPIO.output(self.row_pins[row], GPIO.LOW) - GPIO.setup(self.row_pins[row], GPIO.IN, pull_up_down=GPIO.PUD_OFF) - - if self.check_hook: - on_hook = GPIO.input(self.hook_pin) == GPIO.LOW - - if on_hook: - active_keys.append("hook") - self.hook_time = time.time() - - if self.key_states["hook"] == True and not on_hook: - if time.time()-self.hook_time < self.HOOK_DEBOUNCE_MS/1000: - active_keys.append("hook") - else: - self.hook_time = time.time() - - if len(active_keys) >= 0 and len(active_keys) <= 4: self.__handle(active_keys) - - def start(self): - GPIO.setwarnings(False) - GPIO.setmode(GPIO.BCM) - for row_pin in self.row_pins: GPIO.setup(row_pin, GPIO.OUT) - for col_pin in self.col_pins: GPIO.setup(col_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) - - self.should_run = True - threading.Thread(target=self.__job, daemon=True).start() - - def stop(self): - self.should_run = False diff --git a/LXST/Sinks.py b/LXST/Sinks.py index 06bd364..586ee85 100644 --- a/LXST/Sinks.py +++ b/LXST/Sinks.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import RNS import math import time @@ -109,6 +111,16 @@ def get_backend(): Backend = get_backend() class Sink(): + release_lock = threading.Lock() + def release(self): + if self.release_lock.locked(): return + with self.release_lock: + if not hasattr(self, "released") or not self.released: + self.released = True + self.should_run = False + self.frame_deque = None + self.backend = None + def handle_frame(self, frame, source): pass def can_receive(self, from_source=None): return True @@ -133,6 +145,7 @@ class LineSink(LocalSink): self.autostart_min = self.AUTOSTART_MIN self.buffer_max_height = self.MAX_FRAMES-3 self.low_latency = low_latency + self.streaming = False self.preferred_samplerate = Backend.SAMPLERATE self.backend = Backend(preferred_device=self.preferred_device, samplerate=self.preferred_samplerate) @@ -161,7 +174,9 @@ class LineSink(LocalSink): RNS.log(f"{self} starting at {self.samples_per_frame} samples per frame, {self.channels} channels", RNS.LOG_DEBUG) if self.autodigest and not self.should_run: - if len(self.frame_deque) >= self.autostart_min: self.start() + if len(self.frame_deque) >= self.autostart_min: + RNS.log(f"Auto-digest buffer height of {self.autostart_min} reached on {self}, starting", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None + self.start() def start(self): if not self.should_run: @@ -172,6 +187,12 @@ class LineSink(LocalSink): def stop(self): self.should_run = False + def wait_for_frames(self): + if len(self.frame_deque) < self.autostart_min: + self.stop() + self.autodigest = True + RNS.log(f"{self} waiting for frames before re-engaging output", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None + def enable_low_latency(self): self.__wants_low_latency = True @@ -189,11 +210,15 @@ class LineSink(LocalSink): self.underrun_at = None with self.insert_lock: frame = self.frame_deque.popleft() + if self.channels != self.backend.device.channels: + RNS.log(f"Underlying device for {self} re-configured channel map mid-stream (from {self.channels} to {self.backend.device.channels})", RNS.LOG_WARNING) + self.channels = self.backend.device.channels + if frame.shape[1] > self.channels: frame = frame[:, 0:self.channels] player.play(frame) if len(self.frame_deque) > self.buffer_max_height: - RNS.log(f"Buffer lag on {self} (height {len(self.frame_deque)}), dropping one frame", RNS.LOG_DEBUG) + RNS.log(f"Buffer lag on {self} (height {len(self.frame_deque)}), dropping one frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None self.frame_deque.popleft() else: @@ -201,6 +226,7 @@ class LineSink(LocalSink): # TODO: Remove debug # RNS.log(f"Buffer underrun on {self}", RNS.LOG_DEBUG) self.underrun_at = time.time() + if self.streaming: time.sleep((self.frame_time*self.buffer_max_height)/3.0) else: if time.time() > self.underrun_at+(self.frame_time*self.frame_timeout): RNS.log(f"No frames available on {self}, stopping playback", RNS.LOG_DEBUG) @@ -325,7 +351,7 @@ class OpusFileSink(LocalSink): frame = np.hstack([frame, frame[:, -1:]]) if frame.shape[0] < self.samples_per_frame: - RNS.log("Insufficient frame data, padding with silence", RNS.LOG_DEBUG) + RNS.log("Insufficient frame data, padding with silence", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None silence_frame = np.zeros((self.samples_per_frame-frame.shape[0], frame.shape[1]), dtype=frame.dtype) frame = np.vstack([frame, silence_frame]) diff --git a/LXST/Sources.py b/LXST/Sources.py index 7e894f2..9929e21 100644 --- a/LXST/Sources.py +++ b/LXST/Sources.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + import os import RNS import math @@ -118,7 +120,21 @@ def get_backend(): Backend = get_backend() -class Source(): pass +class Source(): + release_lock = threading.Lock() + def release(self): + if self.release_lock.locked(): return + with self.release_lock: + if not hasattr(self, "released") or not self.released: + self.released = True + self.should_run = False + self.frame_deque = None + self.codec = None + self._sink = None + self._source = None + self._filters = None + self.backend = None + class LocalSource(Source): pass class RemoteSource(Source): pass @@ -159,6 +175,7 @@ class Loopback(LocalSource, LocalSink): class LineSource(LocalSource): MAX_FRAMES = 128 DEFAULT_FRAME_MS = 80 + SIGNAL_FAIL_REINIT_THRESHOLD = 1.5 @staticmethod def linear_gain(gain_db): return 10**(gain_db/10) @@ -183,6 +200,11 @@ class LineSource(LocalSource): self.__gain = self.linear_gain(self.gain) self.__target_gain = self.__gain + self.__check_signal = RNS.vendor.platformutils.is_android() + self.__signal_failed = None + self.__signal_ok = False + self.__must_reinit = False + if filters != None: if type(filters) == list: self.filters = filters else: self.filters = [filters] @@ -243,19 +265,46 @@ class LineSource(LocalSource): ease_in_completed = True if self.ease_in <= 0.0 else False skip_completed = True if self.__skip <= 0.0 else False while self.should_run: + # st = time.perf_counter() # TODO: Remove debug frame_samples = recorder.record(numframes=self.samples_per_frame) + # rt = time.perf_counter()-st # TODO: Remove debug + + if self.__check_signal and not self.__signal_ok: + if np.all(frame_samples == 0): + if not self.__signal_failed: self.__signal_failed = time.time() + else: + self.__signal_ok = True + RNS.log(f"Input signal detected on {self}", RNS.LOG_DEBUG) + + if not self.__signal_ok and self.__signal_failed: + fail_duration = time.time()-self.__signal_failed + RNS.log(f"No signal for {RNS.prettyshorttime(fail_duration)} on {self}", RNS.LOG_DEBUG) + if fail_duration > self.SIGNAL_FAIL_REINIT_THRESHOLD: + RNS.log(f"Scheduling re-init on {self}", RNS.LOG_DEBUG) + self.__must_reinit = True + self.stop() + if not skip_completed: if time.time()-started > self.__skip: skip_completed = True started = time.time() else: + # ft = 0 # TODO: Remove debug if self.filters != None: + # st = time.perf_counter() # TODO: Remove debug for f in self.filters: frame_samples = f.handle_frame(frame_samples, self.samplerate) + # ft = time.perf_counter()-st # TODO: Remove debug if self.__gain != 1.0: frame_samples *= self.__gain if self.codec: - frame = self.codec.encode(frame_samples) if self.sink and self.sink.can_receive(from_source=self): - self.sink.handle_frame(frame, self) + try: + # st = time.perf_counter() # TODO: Remove debug + frame = self.codec.encode(frame_samples) + self.sink.handle_frame(frame, self) + # et = time.perf_counter()-st # TODO: Remove debug + except Exception as e: RNS.log(f"Encode error on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None + # RNS.log(f"REC/FLT/SNK: {RNS.prettyshorttime(rt)} / {RNS.prettyshorttime(ft)}, / {RNS.prettyshorttime(et)}", RNS.LOG_DEBUG) # TODO: Remove debug + if not ease_in_completed: d = time.time()-started self.__gain = (d/self.ease_in)*self.__target_gain @@ -263,13 +312,22 @@ class LineSource(LocalSource): self.__gain = self.__target_gain ease_in_completed = True + if self.__must_reinit: + self.__must_reinit = False + self.__signal_ok = False + self.__signal_failed = None + self.start() + class OpusFileSource(LocalSource): MAX_FRAMES = 128 DEFAULT_FRAME_MS = 100 TYPE_MAP_FACTOR = np.iinfo("int16").max - def __init__(self, file_path, target_frame_ms=DEFAULT_FRAME_MS, loop=False, codec=None, sink=None, timed=False): + @staticmethod + def linear_gain(gain_db): return 10**(gain_db/10) + + def __init__(self, file_path, target_frame_ms=DEFAULT_FRAME_MS, loop=False, codec=None, sink=None, timed=False, gain=0.0): self.target_frame_ms = target_frame_ms self.loop = loop self.timed = timed @@ -278,6 +336,8 @@ class OpusFileSource(LocalSource): self.ingest_thread = None self.next_frame = None self._codec = None + self._gain_db = gain + self.__gain = self.linear_gain(self._gain_db) if file_path == None: raise TypeError(f"{self} initialised with invalid file path: {file_path}") elif os.path.isfile(file_path): @@ -296,6 +356,19 @@ class OpusFileSource(LocalSource): self.codec = codec self.sink = sink + @property + def running(self): return self.should_run + + @property + def gain(self): return self._gain_db + + @gain.setter + def gain(self, db): + try: db = float(db) + except: raise TypeError("Invalid gain type, must be decibel as a floating point number") + self._gain_db = db + self.__gain = self.linear_gain(self._gain_db) + @property def codec(self): return self._codec @@ -344,6 +417,7 @@ class OpusFileSource(LocalSource): fi += 1 fs = (fi-1)*spf; fe = min(fi*spf, sc) frame_samples = self.samples[fs:fe, :] + if self.__gain != 1.0: frame_samples *= self.__gain if len(frame_samples) < 1: if self.loop: RNS.log(f"{self} exhausted file samples, looping...", RNS.LOG_DEBUG) @@ -353,8 +427,10 @@ class OpusFileSource(LocalSource): self.should_run = False else: if self.codec: - frame = self.codec.encode(frame_samples) if self.sink and self.sink.can_receive(from_source=self): - self.sink.handle_frame(frame, self) + try: + frame = self.codec.encode(frame_samples) + self.sink.handle_frame(frame, self) + except Exception as e: RNS.log(f"Encode error on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None else: time.sleep(self.frame_time*0.1) diff --git a/LXST/Utilities/rnphone.py b/LXST/Utilities/rnphone.py index 3abd043..bb2fb39 100644 --- a/LXST/Utilities/rnphone.py +++ b/LXST/Utilities/rnphone.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 +# Copyright 2024-2026, Mark Qvist + import RNS import os import sys diff --git a/LXST/__init__.py b/LXST/__init__.py index 97a0d90..77a4695 100644 --- a/LXST/__init__.py +++ b/LXST/__init__.py @@ -1,3 +1,5 @@ +# Copyright 2024-2026, Mark Qvist + APP_NAME = "lxst" from .Pipeline import Pipeline diff --git a/LXST/_version.py b/LXST/_version.py index 98a433b..906d362 100644 --- a/LXST/_version.py +++ b/LXST/_version.py @@ -1 +1 @@ -__version__ = "0.4.5" +__version__ = "0.6.0" diff --git a/Makefile b/Makefile index 7eeb1c7..5494255 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,15 @@ create_symlinks: build_wheel: cp ./lib/static/* ./LXST/ touch ./skip_extensions - python3 setup.py sdist bdist_wheel + python3 setup.py bdist_wheel + rm ./skip_extensions + -@(rm ./LXST/*.so) + -@(rm ./LXST/*.dll) + +build_sdist: + cp ./lib/static/* ./LXST/ + touch ./skip_extensions + python3 setup.py sdist rm ./skip_extensions -@(rm ./LXST/*.so) -@(rm ./LXST/*.dll) @@ -40,11 +48,18 @@ persist_libs: -cp ./lib/dev/*.so ./lib/static/ -cp ./lib/dev/*.dll ./lib/static/ +build_spkg: remove_symlinks build_sdist create_symlinks + release: remove_symlinks build_wheel create_symlinks upload: + @echo Ready to publish release over Reticulum + @read VOID + rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/lxst create $$(python setup.py --getversion):dist --name lxst + +upload-pip: @echo Ready to publish release, hit enter to continue @read VOID @echo Uploading to PyPi... - twine upload dist/* + twine upload dist/lxst-*.whl @echo Release published diff --git a/README.md b/README.md index cca1321..7b90ca1 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,21 @@ # Lightweight Extensible Signal Transport -*This repository is [a public mirror](./MIRROR.md). All development is happening elsewhere.* +> [!WARNING] +> Several hastily launched, incorrect, and in most cases entirely LLM-generated fakes of LXST and associated tools and applications are currently being circulated and marketed. Most of these "projects" violate the license that LXST was published under, but claim independent ownership and license grants. Such claims or grants are **not** legally valid, and **not** recognized by the LXST author and copyright holder. +> +> Any claimed assertion of copyright or grant of license that such projects are making are [void grants](https://reticulum.network/manual/brandolinis.html#void-grants-legal-foundations-of-machine-generated-code). +> +> Both the violators themselves, and **all** downstream projects using the infringing derivatives, are **directly** and **personally** liable for the legal consequences. +> +> For more detailed information, see the relevant sections of the [Brandolini's Reference](https://reticulum.network/manual/brandolinis.html) chapter of the Reticulum Manual. For software and projects recognized by the Reticulum community, see the [Programs Using Reticulum](https://reticulum.network/manual/software.html) chapter. +> +> Do **not** use these "projects", they are a hazard to the entire ecosystem we have been carefully building over the last ten years. -LXST is a simple and flexible real-time streaming format and delivery protocol that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://reticulum.network) and offers zero-conf stream routing, end-to-end encryption and Forward Secrecy, and can be transported over any kind of medium that Reticulum supports. For a user-facing client using LXST for real-time voice communication, see [Sideband](https://github.com/markqvist/Sideband). +*Due to the blatant copyright infringement and LLM-laundering, the source code in this repository is no longer updated. All development is happening over Reticulum, where the latest source is available. Packages and updates continue to ship on PyPI and over `rngit`.* + +--- + +LXST is a simple and flexible real-time streaming format and delivery protocol that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://reticulum.network) and offers zero-conf stream routing, end-to-end encryption and Forward Secrecy, and can be transported over any kind of medium that Reticulum supports. - Cross-platform, works on Linux, Android, Windows and Mac - Provides a variety of ready-to-use primitives, for easily creating applications such as: @@ -33,15 +46,36 @@ LXST is a simple and flexible real-time streaming format and delivery protocol t - Uses a fully staged signal pipelining, allowing arbitrary stream routing - Provides built-in signal mixing support for any number of channels +User-facing clients built on LXST include: + +- [Sideband](https://unsigned.io/sideband) +- [MeshChatX](https://meshchatx.com/) +- [Partyline](https://github.com/RFnexus/partyline) +- [Columba](https://github.com/torlando-tech/columba) +- [rnphone](https://reticulum.network/manual/software.html#reticulum-network-telephone) +- [LXST Phone](https://github.com/kc1awv/lxst_phone) + ## Transport Encryption LXST uses encryption provided by [Reticulum](https://reticulum.network), and thus provides end-to-end encryption, guaranteed data integrity and authenticity, as well as forward secrecy by default. ## Project Status & License -This software is in a very early alpha state, and will change rapidly with ongoing development. Consider no APIs stable. Consider everything explosive. Not all features are implemented. Nothing is documented. For a fully functional LXST program, take a look at [Sideband](https://github.com/markqvist/Sideband) or the included `rnphone` program, which provides telephony service over Reticulum. Everything else will currently be a voyage of your own making. +This software and its interfaces will change rapidly with ongoing development. Consider no APIs stable. Consider everything explosive. Not all features are implemented. Nothing is documented. For a fully functional LXST program, take a look at [Sideband](https://github.com/markqvist/Sideband) or the included `rnphone` program, which provides telephony service over Reticulum. Everything else will currently be a voyage of your own making. -While under early development, and unless otherwise noted, the project is kept under a `CC BY-NC-ND 4.0` license. +The LXST project is available under a `CC BY-NC-ND 4.0` license. You can deploy LXST freely for non-commercial, personal and humanitarian purposes. For commercial (including institutionalised educational) licensing, contact me. + +LXST uses third-party codecs, and where included in source and binary distributions, these are distributed under their respective licenses: + +- Parts of `pydub`, under the [MIT License](./LXST/Codecs/libs/pydub/LICENSE), Copyright (c) 2011 James Robert. +- The [Ogg License](./LXST/Codecs/libs/pyogg/LICENSE) +- The [Opus License](./LXST/Codecs/libs/pyogg/LICENSE) +- The [Opusenc License](./LXST/Codecs/libs/pyogg/LICENSE) +- The [Opusfile License](./LXST/Codecs/libs/pyogg/LICENSE) +- The [Vorbis License](./LXST/Codecs/libs/pyogg/LICENSE) +- The [Flac License](./LXST/Codecs/libs/pyogg/LICENSE) + +Additionally, some parts of the platform abstraction code is released under the BSD 3-Clause license. See the relevant license headers for details. ## Installation @@ -62,23 +96,3 @@ pip install smbus2 --break-system-packages # Install smbus module if not already sudo raspi-config # Enable the I2C bus under "Interface Options" sudo apt install python3-rpi.gpio # Install gpio module system-wide ``` - -## Support LXST Development -You can help support the continued development of open, free and private communications systems by donating via one of the following channels: - -- Monero: - ``` - 84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w - ``` -- Bitcoin - ``` - bc1pgqgu8h8xvj4jtafslq396v7ju7hkgymyrzyqft4llfslz5vp99psqfk3a6 - ``` -- Ethereum - ``` - 0x91C421DdfB8a30a49A71d63447ddb54cEBe3465E - ``` -- Liberapay: https://liberapay.com/Reticulum/ - -- Ko-Fi: https://ko-fi.com/markqvist - diff --git a/examples/fileplayer.py b/examples/fileplayer.py index c0724f9..be493f3 100644 --- a/examples/fileplayer.py +++ b/examples/fileplayer.py @@ -15,6 +15,7 @@ if loop: else: player = FilePlayer("./docs/speech_stereo.opus") + player.release_on_finish = True player.start() while player.running: time.sleep(0.1) diff --git a/setup.py b/setup.py index 9151057..012fc5c 100644 --- a/setup.py +++ b/setup.py @@ -2,18 +2,23 @@ import setuptools from setuptools import setup, Extension from setuptools.command.build_ext import build_ext import os +import sys import platform if os.path.isfile("./skip_extensions"): BUILD_EXTENSIONS = False else: BUILD_EXTENSIONS = True if os.name == "nt": BUILD_EXTENSIONS = False -if BUILD_EXTENSIONS: print(f"Building LXST with native extensions...") -else: print(f"Building LXST without native extensions...") - with open("README.md", "r") as fh: long_description = fh.read() exec(open("LXST/_version.py", "r").read()) +if "--getversion" in sys.argv: + print(__version__, end="") + exit(0) + +if BUILD_EXTENSIONS: print(f"Building LXST with native extensions...") +else: print(f"Building LXST without native extensions...") + c_sources = ["LXST/Filters.c"] if BUILD_EXTENSIONS: extensions = [ Extension("LXST.filterlib", sources=c_sources, include_dirs=["LXST"], language="c"), ] @@ -65,8 +70,8 @@ setuptools.setup( 'rnphone=LXST.Utilities.rnphone:main', ] }, - install_requires=["rns>=1.0.4", - "lxmf>=0.9.3", + install_requires=["rns>=1.6.0", + "lxmf>=1.3.0", "numpy>=2.3.4", "pycodec2>=4.1.0", "audioop-lts>=0.2.1;python_version>='3.13'",