Sync upstream

This commit is contained in:
Mark Qvist committed 2026-11-08 13:50:44 +01:00
1 parent 1194c9011f
commit f868cc4f70
46 files changed
+2404 -333

No files matched your search

-55
View File
@@ -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()
+6
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import numpy as np import numpy as np
from .libs.pydub import AudioSegment from .libs.pydub import AudioSegment
@@ -11,6 +13,8 @@ class Codec():
source = None source = None
sink = None sink = None
def __str__(self): return f"<LXST/Codec>"
class CodecError(Exception): class CodecError(Exception):
pass pass
@@ -24,6 +28,8 @@ class Null(Codec):
def decode(self, frame): def decode(self, frame):
return frame return frame
def __str__(self): return f"<LXST/NullCodec>"
def resample_bytes(sample_bytes, bitdepth, channels, input_rate, output_rate, normalize=False): def resample_bytes(sample_bytes, bitdepth, channels, input_rate, output_rate, normalize=False):
sample_width = bitdepth//8 sample_width = bitdepth//8
audio = AudioSegment( audio = AudioSegment(
+5 -1
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import time import time
import math import math
import struct import struct
@@ -118,4 +120,6 @@ class Codec2(Codec):
frame_samples = np.zeros((len(decoded_samples), 1), dtype="float32") frame_samples = np.zeros((len(decoded_samples), 1), dtype="float32")
frame_samples[:, 0] = decoded_samples frame_samples[:, 0] = decoded_samples
return frame_samples return frame_samples
def __str__(self): return f"<LXST/Codec2 @ {RNS.prettyspeed(self.mode)}>"
+18 -1
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import io import io
import RNS import RNS
import time import time
@@ -22,6 +24,19 @@ class Opus(Codec):
PROFILE_AUDIO_HIGH = 0x07 PROFILE_AUDIO_HIGH = 0x07
PROFILE_AUDIO_MAX = 0x08 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): def __init__(self, profile=PROFILE_VOICE_LOW):
self.frame_quanta_ms = self.FRAME_QUANTA_MS self.frame_quanta_ms = self.FRAME_QUANTA_MS
self.frame_max_ms = self.FRAME_MAX_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 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) frame_samples = decoded_samples.reshape(len(decoded_samples)//self.channels, self.channels)
return frame_samples return frame_samples
def __str__(self): return f"<LXST/Opus @ {self.profile_name(self.profile)}>"
+5 -1
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import numpy as np import numpy as np
from .Codec import Codec from .Codec import Codec
@@ -55,4 +57,6 @@ class Raw(Codec):
frame_samples = frame_samples.reshape(len(frame_samples)//frame_channels, frame_channels) frame_samples = frame_samples.reshape(len(frame_samples)//frame_channels, frame_channels)
if not self.channels: self.channels = frame_channels if not self.channels: self.channels = frame_channels
return frame_samples return frame_samples
def __str__(self): return f"<LXST/Raw @ {RNS.prettyspeed(self.channels*self.bitdepth*48000)}>"
+2
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
from .Codec import CodecError as CodecError from .Codec import CodecError as CodecError
from .Codec import Codec as Codec from .Codec import Codec as Codec
from .Codec import Null as Null from .Codec import Null as Null
+20
View File
@@ -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.
+21
View File
@@ -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 from .audio_segment import AudioSegment
+21
View File
@@ -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 from __future__ import division
import array import array
+21
View File
@@ -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 sys
import math import math
import array import array
+21
View File
@@ -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): class PydubException(Exception):
""" """
Base class for any Pydub exception Base class for any Pydub exception
+21
View File
@@ -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 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 converted to actual audio with 8, 16, 24, or 32 bit depth using the
+21
View File
@@ -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.
""" """
""" """
+21
View File
@@ -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, Support for playing AudioSegments. Pyaudio will be used if it's installed,
otherwise will fallback to ffplay. Pyaudio is a *much* nicer solution, but otherwise will fallback to ffplay. Pyaudio is a *much* nicer solution, but
+21
View File
@@ -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: try:
from __builtin__ import max as builtin_max from __builtin__ import max as builtin_max
from __builtin__ import min as builtin_min from __builtin__ import min as builtin_min
+21
View File
@@ -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 This module provides scipy versions of high_pass_filter, and low_pass_filter
as well as an additional band_pass_filter. as well as an additional band_pass_filter.
+21
View File
@@ -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 Various functions for finding/manipulating silence in AudioSegments
""" """
+21
View File
@@ -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 from __future__ import division
import json import json
+213
View File
@@ -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.
+2
View File
@@ -1,2 +1,4 @@
# Copyright 2024-2026, Mark Qvist
def nop(): def nop():
pass pass
+4 -2
View File
@@ -1,3 +1,5 @@
// Copyright 2024-2026, Mark Qvist
#include <math.h> #include <math.h>
void highpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states, float* last_inputs) { 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; float peak = 0.0f;
for (int i = 0; i < samples; i++) { int idx = i * channels + ch; float abs_val = fabsf(output[idx]); 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 (abs_val > peak) { peak = abs_val; } }
if (peak > peak_limit) { float scale = peak_limit / peak; if (peak > peak_limit) { float scale = peak_limit / peak;
for (int i = 0; i < samples; i++) { int idx = i * channels + ch; output[idx] *= scale; } } for (int i = 0; i < samples; i++) { int idx = i * channels + ch; output[idx] *= scale; } }
} }
} }
+2
View File
@@ -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 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 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); 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);
+1289 -3
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os import os
import RNS import RNS
import math import math
+19 -6
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import LXST import LXST
import time 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): def __init__(self, target_frame_ms=40, samplerate=None, codec=None, sink=None, gain=0.0):
self.incoming_frames = {} self.incoming_frames = {}
self.reference_outs = []
self.target_frame_ms = target_frame_ms self.target_frame_ms = target_frame_ms
self.frame_time = self.target_frame_ms/1000 self.frame_time = self.target_frame_ms/1000
self.should_run = False self.should_run = False
@@ -99,6 +102,7 @@ class Mixer(LocalSource, LocalSink):
else: return 10**(self.gain/10) else: return 10**(self.gain/10)
def _mixer_job(self): def _mixer_job(self):
if self.mixer_lock.locked(): return
with self.mixer_lock: with self.mixer_lock:
while self.should_run: while self.should_run:
if self.sink and self.sink.can_receive(): 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: if mixed_frame.max() >= 1.0 or mixed_frame.min() <= -1.0:
RNS.log(f"Signal clipped on {self}", RNS.LOG_WARNING) RNS.log(f"Signal clipped on {self}", RNS.LOG_WARNING)
if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self) try:
else: self.sink.handle_frame(mixed_frame, self) if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self)
else: else: self.sink.handle_frame(mixed_frame, self)
time.sleep(self.frame_time*0.1)
except Exception as e: RNS.log(f"Error while mixing frame on {self}: {e}", RNS.LOG_ERROR)
else: try:
time.sleep(self.frame_time*0.1) 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 @property
def codec(self): def codec(self):
+10 -5
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import time import time
import threading import threading
@@ -23,7 +25,8 @@ class SignallingReceiver():
if self.proxy: self.proxy.signalling_received(signals, source) if self.proxy: self.proxy.signalling_received(signals, source)
def signal(self, signal, destination, immediate=True): 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: if immediate:
signalling_packet = RNS.Packet(destination, mp.packb(signalling_data), create_receipt=False) signalling_packet = RNS.Packet(destination, mp.packb(signalling_data), create_receipt=False)
@@ -52,11 +55,12 @@ class Packetizer(RemoteSink):
self.should_run = False self.should_run = False
self.source = None self.source = None
self.transmit_failure = False self.transmit_failure = False
self.squelched = False
self.__failure_calback = failure_callback self.__failure_calback = failure_callback
def handle_frame(self, frame, source=None): def handle_frame(self, frame, source=None):
if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE: if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE: return
return if self.squelched: return
# TODO: Add inband signalling scheduler # TODO: Add inband signalling scheduler
frame = codec_header_byte(type(self.source.codec))+frame frame = codec_header_byte(type(self.source.codec))+frame
@@ -92,8 +96,9 @@ class Packetizer(RemoteSink):
RNS.log(f"{self} starting", RNS.LOG_DEBUG) RNS.log(f"{self} starting", RNS.LOG_DEBUG)
self.should_run = True self.should_run = True
def stop(self): def stop(self): self.should_run = False
self.should_run = False def squelch(self): self.squelched = True
def unsquelch(self): self.squelched = False
class LinkSource(RemoteSource, SignallingReceiver): class LinkSource(RemoteSource, SignallingReceiver):
def __init__(self, link, signalling_receiver, sink=None): def __init__(self, link, signalling_receiver, sink=None):
+21 -12
View File
@@ -1,3 +1,7 @@
# Copyright 2024-2026, Mark Qvist
import threading
from .Sources import * from .Sources import *
from .Sinks import * from .Sinks import *
from .Codecs import * from .Codecs import *
@@ -8,6 +12,8 @@ class PipelineError(Exception):
pass pass
class Pipeline(): class Pipeline():
release_lock = threading.Lock()
def __init__(self, source, codec, sink, processor = None): 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(source), Source): raise PipelineError("Audio pipeline initialised with invalid source")
if not issubclass(type(sink), Sink) : raise PipelineError("Audio pipeline initialised with invalid sink") 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(sink, Loopback): sink.samplerate = source.samplerate
if isinstance(source, Loopback): source._sink = sink if isinstance(source, Loopback): source._sink = sink
if isinstance(source, Mixer): source._sink = sink
if isinstance(sink, Packetizer): sink.source = source if isinstance(sink, Packetizer): sink.source = source
if isinstance(sink, OpusFileSink): 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 @property
def codec(self): def codec(self):
if self.source: if self.source: return self.source.codec
return self.source.codec else: return None
else:
return None
@codec.setter @codec.setter
def codec(self, codec): def codec(self, codec):
@@ -40,19 +53,15 @@ class Pipeline():
@property @property
def sink(self): def sink(self):
if self.source: if self.source: return self.source.sink
return self.source.sink else: return None
else:
return None
@property @property
def running(self): def running(self):
return self.source.should_run return self.source.should_run
def start(self): def start(self):
if not self.running: if not self.running: self.source.start()
self.source.start()
def stop(self): def stop(self):
if self.running: if self.running: self.source.stop()
self.source.stop()
+119 -48
View File
@@ -1,32 +1,4 @@
# Reticulum License # Copyright 2024-2026, Mark Qvist
#
# 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.
import atexit import atexit
import collections.abc import collections.abc
@@ -448,6 +420,7 @@ class _Stream:
self.AudioManager = activity.getSystemService(autoclass("android.media.AudioManager")) self.AudioManager = activity.getSystemService(autoclass("android.media.AudioManager"))
self.AudioTrack = autoclass("android.media.AudioTrack") self.AudioTrack = autoclass("android.media.AudioTrack")
self.AudioRecord = autoclass("android.media.AudioRecord")
self.AudioFormat = autoclass("android.media.AudioFormat") self.AudioFormat = autoclass("android.media.AudioFormat")
self.AudioDeviceInfo = autoclass("android.media.AudioDeviceInfo") self.AudioDeviceInfo = autoclass("android.media.AudioDeviceInfo")
@@ -586,8 +559,8 @@ class _Stream:
else: raise ValueError(f"Unsupported channel count {channels} on Android audio backend") 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_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_recording = self.AudioRecord.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding)
self.bytes_per_sample = (self.bit_depth//8)*self.channels self.bytes_per_sample = (self.bit_depth//8)*self.channels
self._samplerate = int(self.AudioManager.getProperty(self.AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)) 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) aa_builder.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
self.performance_mode = AudioTrack.PERFORMANCE_MODE_NONE 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() self.audio_attributes = aa_builder.build()
af_builder = AudioFormatBuilder() af_builder = AudioFormatBuilder()
@@ -728,6 +703,11 @@ class _Player(_Stream):
while data.nbytes > 0: while data.nbytes > 0:
samples_bytes = data.ravel().tobytes() samples_bytes = data.ravel().tobytes()
written_bytes = self.audio_track.write(samples_bytes, 0, len(samples_bytes), self._write_mode) 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 written_samples = written_bytes//self.bytes_per_sample
if self._low_latency_activated: if self._low_latency_activated:
@@ -743,6 +723,9 @@ class _Player(_Stream):
written_samples = remaining_frame_samples written_samples = remaining_frame_samples
# TODO: Remove debug # 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.") # 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:] data = data[written_samples:]
@@ -759,40 +742,108 @@ class _Player(_Stream):
# RNS.log(f"{delta} underruns on {self}") # RNS.log(f"{delta} underruns on {self}")
class _Recorder(_Stream): 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): def __init__(self, *args, **kwargs):
super(_Recorder, self).__init__(*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): def _connect_stream(self):
try: try:
AudioSource = autoclass("android.media.MediaRecorder$AudioSource") 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() self.audio_record.startRecording()
if _Recorder.READ_MODE == _Recorder.READ_MODE_FAST: self.__check_read_helper()
except Exception as e: except Exception as e:
RNS.log(f"Error while connecting input audio stream via JNI: {e}", RNS.LOG_ERROR) RNS.log(f"Error while connecting input audio stream via JNI: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e) RNS.trace_exception(e)
def _record_chunk(self): def __check_read_helper(self):
try: try:
audio_data = bytearray(self.min_buffer_recording) service = autoclass("org.kivy.android.PythonService").mService
bytes_read = self.audio_record.read(audio_data, 0, self.min_buffer_recording, self.audio_record.READ_NON_BLOCKING) if service == None: raise AttributeError("No PythonService instance available")
if bytes_read == 0: time.sleep(0.005) 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) except Exception as e: RNS.log(f"{self} audio read helper not available, using legacy read path: {e}", RNS.LOG_DEBUG)
elif bytes_read == self.audio_record.ERROR_BAD_VALUE: RNS.log(f"Bad value error from JNI on {self}", RNS.LOG_ERROR)
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: else:
recorded_samples = numpy.frombuffer(audio_data[:bytes_read], dtype="int16")/self.TYPE_MAP_FACTOR read_bytes = self.min_buffer_recording
return recorded_samples.astype("float32") 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: except Exception as e:
RNS.log(f"Error while reading audio chunk: {e}", RNS.LOG_ERROR) RNS.log(f"Error while reading audio chunk: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return None return None
def record(self, numframes=None): def record(self, numframes=None):
if numframes is None: return numpy.reshape(numpy.concatenate([self.flush().ravel(), self._record_chunk()]), [-1, self.channels]) if numframes is None: return numpy.reshape(numpy.concatenate([self.flush().ravel(), self._record_chunk()]), [-1, self.channels])
else: else:
@@ -803,10 +854,30 @@ class _Recorder(_Stream):
return numpy.reshape(keep, [-1, self.channels]) return numpy.reshape(keep, [-1, self.channels])
else: else:
timeout = time.time()+(numframes/self._samplerate)*8
while captured_frames < numframes: while captured_frames < numframes:
chunk = self._record_chunk() if time.time() > timeout:
captured_data.append(chunk) RNS.log(f"{self} capture timed out at {captured_frames} out of {numframes} frames, emitting silence", RNS.LOG_WARNING)
captured_frames += len(chunk)/self.channels 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) to_split = int(len(chunk) - (captured_frames - numframes) * self.channels)
captured_data[-1], self._pending_chunk = numpy.split(captured_data[-1], [to_split]) captured_data[-1], self._pending_chunk = numpy.split(captured_data[-1], [to_split])
+3 -2
View File
@@ -147,7 +147,8 @@ class _PulseAudio:
import sys import sys
prog_name = sys.argv[0] prog_name = sys.argv[0]
if prog_name == "-c": 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": if prog_name == "-m":
prog_name = sys.argv[1] prog_name = sys.argv[1]
# Usually even with -m, sys.argv[0] will already be a path, # Usually even with -m, sys.argv[0] will already be a path,
@@ -230,7 +231,7 @@ class _PulseAudio:
info.append(info_dict) info.append(info_dict)
self._pa_context_get_source_info_by_name(self.context, id.encode(), callback, _ffi.NULL) 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 @property
def sink_list(self): def sink_list(self):
-1
View File
@@ -1 +0,0 @@
void PyInit_filterlib(void) { }
+42 -7
View File
@@ -1,18 +1,23 @@
# Copyright 2024-2026, Mark Qvist
import LXST import LXST
import time import time
import threading import threading
import os import os
import gc
from LXST.Sinks import LineSink from LXST.Sinks import LineSink
from LXST.Sources import OpusFileSource from LXST.Sources import OpusFileSource
class FilePlayer(): 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._file_path = path
self._playback_device = None self._playback_device = None
self.__finished_callback = None self.__finished_callback = None
self.__release_on_finish = release_on_finish
self.__loop = loop self.__loop = loop
self.__source = None self.__source = None
self.__gain = gain
self.__sink = LineSink(self._playback_device) self.__sink = LineSink(self._playback_device)
self.__raw = LXST.Codecs.Raw() self.__raw = LXST.Codecs.Raw()
self.__loopback = LXST.Sources.Loopback() self.__loopback = LXST.Sources.Loopback()
@@ -20,14 +25,32 @@ class FilePlayer():
self.__input_pipeline = None self.__input_pipeline = None
if path: self.set_source(self._file_path) 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 @property
def running(self): def running(self):
if not self.__source: return False 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 @property
def playing(self): return self.running 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 @property
def finished_callback(self): return self.__finished_callback def finished_callback(self): return self.__finished_callback
@@ -38,17 +61,18 @@ class FilePlayer():
else: self.__finished_callback = callback else: self.__finished_callback = callback
def __callback_job(self): def __callback_job(self):
if self.__finished_callback: if self.__finished_callback or self.__release_on_finish:
time.sleep(0.2) time.sleep(0.2)
while self.running: time.sleep(0.1) 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): def set_source(self, path=None):
if not path: return if not path: return
else: else:
if not os.path.isfile(path): raise OSError(f"File not found: {path}") if not os.path.isfile(path): raise OSError(f"File not found: {path}")
else: 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) self.__input_pipeline = LXST.Pipeline(source=self.__source, codec=self.__raw, sink=self.__loopback)
def loop(self, loop=True): def loop(self, loop=True):
@@ -60,7 +84,7 @@ class FilePlayer():
if not self.running and self.__source: if not self.running and self.__source:
self.__input_pipeline.start() self.__input_pipeline.start()
self.__output_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() threading.Thread(target=self.__callback_job, daemon=True).start()
def stop(self): def stop(self):
@@ -68,4 +92,15 @@ class FilePlayer():
self.__input_pipeline.stop() self.__input_pipeline.stop()
self.__output_pipeline.stop() self.__output_pipeline.stop()
def play(self): self.start() 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
+2
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import LXST import LXST
import time import time
+201 -17
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os import os
import RNS import RNS
import LXST import LXST
@@ -11,23 +13,43 @@ from LXST.Sinks import LineSink
from LXST.Sources import LineSource, OpusFileSource from LXST.Sources import LineSource, OpusFileSource
from LXST.Generators import ToneSource from LXST.Generators import ToneSource
from LXST.Network import SignallingReceiver, Packetizer, LinkSource from LXST.Network import SignallingReceiver, Packetizer, LinkSource
from LXST.Filters import BandPass, AGC from LXST.Filters import BandPass, AGC, EchoSuppressor
PRIMITIVE_NAME = "telephony" PRIMITIVE_NAME = "telephony"
class Profiles(): class Profiles():
BANDWIDTH_ULTRA_LOW = 0x10 BANDWIDTH_ULTRA_LOW = 0x10
BANDWIDTH_VERY_LOW = 0x20 BANDWIDTH_VERY_LOW = 0x20
BANDWIDTH_LOW = 0x30 BANDWIDTH_LOW = 0x30
QUALITY_MEDIUM = 0x40 QUALITY_MEDIUM = 0x40
QUALITY_HIGH = 0x50 QUALITY_HIGH = 0x50
QUALITY_MAX = 0x60 QUALITY_MAX = 0x60
LATENCY_ULTRA_LOW = 0x70 LATENCY_ULTRA_LOW = 0x70
LATENCY_LOW = 0x80 LATENCY_LOW = 0x80
DEFAULT_PROFILE = QUALITY_MEDIUM 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 @staticmethod
def available_profiles(): def available_profiles():
return [Profiles.BANDWIDTH_ULTRA_LOW, return [Profiles.BANDWIDTH_ULTRA_LOW,
@@ -92,6 +114,18 @@ class Profiles():
elif profile == Profiles.LATENCY_ULTRA_LOW: return 10 elif profile == Profiles.LATENCY_ULTRA_LOW: return 10
else: return 60 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 @staticmethod
def next_profile(profile): def next_profile(profile):
profile_list = Profiles.available_profiles() profile_list = Profiles.available_profiles()
@@ -107,6 +141,7 @@ class Signalling():
STATUS_RINGING = 0x04 STATUS_RINGING = 0x04
STATUS_CONNECTING = 0x05 STATUS_CONNECTING = 0x05
STATUS_ESTABLISHED = 0x06 STATUS_ESTABLISHED = 0x06
PREFERRED_MODE = 0xF0
PREFERRED_PROFILE = 0xFF PREFERRED_PROFILE = 0xFF
AUTO_STATUS_CODES = [STATUS_CALLING, STATUS_AVAILABLE, STATUS_RINGING, AUTO_STATUS_CODES = [STATUS_CALLING, STATUS_AVAILABLE, STATUS_RINGING,
STATUS_CONNECTING, STATUS_ESTABLISHED] 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): 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__() super().__init__()
RNS.Reticulum.get_instance().wants_destination_type(f"{APP_NAME}.{PRIMITIVE_NAME}")
self.identity = identity self.identity = identity
self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, PRIMITIVE_NAME) 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) self.destination.set_proof_strategy(RNS.Destination.PROVE_NONE)
@@ -155,6 +191,8 @@ class Telephone(SignallingReceiver):
self.receive_gain = receive_gain self.receive_gain = receive_gain
self.transmit_gain = transmit_gain self.transmit_gain = transmit_gain
self.use_agc = True self.use_agc = True
self.use_bandpass = True
self.use_echo_cancellation = True
self.active_call = None self.active_call = None
self.call_status = Signalling.STATUS_AVAILABLE self.call_status = Signalling.STATUS_AVAILABLE
self._external_busy = False self._external_busy = False
@@ -164,6 +202,7 @@ class Telephone(SignallingReceiver):
self.__busy_callback = None self.__busy_callback = None
self.__rejected_callback = None self.__rejected_callback = None
self.target_frame_time_ms = None self.target_frame_time_ms = None
self.target_buffer_frames = None
self.audio_output = None self.audio_output = None
self.audio_input = None self.audio_input = None
self.dial_tone = None self.dial_tone = None
@@ -178,11 +217,13 @@ class Telephone(SignallingReceiver):
self.transmit_pipeline = None self.transmit_pipeline = None
self.__receive_muted = False self.__receive_muted = False
self.__transmit_muted = False self.__transmit_muted = False
self.__loudspeaker_on = False
self.ringer_lock = threading.Lock() self.ringer_lock = threading.Lock()
self.ringer_output = None self.ringer_output = None
self.ringer_pipeline = None self.ringer_pipeline = None
self.ringtone_path = None self.ringtone_path = None
self.speaker_device = None self.speaker_device = None
self.loudspeaker_device = None
self.microphone_device = None self.microphone_device = None
self.ringer_device = None self.ringer_device = None
self.low_latency_output = False self.low_latency_output = False
@@ -241,6 +282,10 @@ class Telephone(SignallingReceiver):
self.speaker_device = device self.speaker_device = device
RNS.log(f"{self} speaker device set to {device}", RNS.LOG_DEBUG) 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): def set_microphone(self, device):
self.microphone_device = device self.microphone_device = device
RNS.log(f"{self} microphone device set to {device}", RNS.LOG_DEBUG) 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 if disable == True: self.use_agc = False
else: self.use_agc = True 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): def set_low_latency_output(self, enabled):
if enabled: if enabled:
self.low_latency_output = True self.low_latency_output = True
@@ -321,7 +382,9 @@ class Telephone(SignallingReceiver):
link.ring_timeout = False link.ring_timeout = False
link.answered = False link.answered = False
link.is_terminating = False link.is_terminating = False
link.established_at = None
link.profile = None link.profile = None
link.call_mode = None
with self.call_handler_lock: with self.call_handler_lock:
if self.active_call or self.busy: if self.active_call or self.busy:
RNS.log(f"Incoming call, but line is already active, signalling busy", RNS.LOG_DEBUG) 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) self.answer(identity)
threading.Thread(target=cb, daemon=True).start() threading.Thread(target=cb, daemon=True).start()
else: else: self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time)
self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time)
def __link_closed(self, link): def __link_closed(self, link):
if link == self.active_call: if link == self.active_call:
@@ -383,6 +445,13 @@ class Telephone(SignallingReceiver):
if not hasattr(self.active_call, "profile"): return None if not hasattr(self.active_call, "profile"): return None
else: return self.active_call.profile 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 @property
def receive_muted(self): def receive_muted(self):
if not self.active_call: return False if not self.active_call: return False
@@ -397,9 +466,16 @@ class Telephone(SignallingReceiver):
if not self.transmit_mixer: return False if not self.transmit_mixer: return False
else: return self.transmit_mixer.muted else: return self.transmit_mixer.muted
def signal(self, signal, link): @property
if signal in Signalling.AUTO_STATUS_CODES: self.call_status = signal def loudspeaker_on(self):
super().signal(signal, link) 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): def answer(self, identity):
with self.call_handler_lock: with self.call_handler_lock:
@@ -415,6 +491,7 @@ class Telephone(SignallingReceiver):
else: else:
RNS.log(f"Answering call from {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) RNS.log(f"Answering call from {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG)
self.active_call.answered = True self.active_call.answered = True
self.active_call.established_at = time.time()
self.__open_pipelines(identity) self.__open_pipelines(identity)
self.__start_pipelines() self.__start_pipelines()
RNS.log(f"Call setup complete for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG) 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.call_status = Signalling.STATUS_AVAILABLE
self.__receive_muted = False self.__receive_muted = False
self.__transmit_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) 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) 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 self.__transmit_muted = not unmute
if self.transmit_mixer: self.transmit_mixer.unmute(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): def set_receive_gain(self, gain=0.0):
self.receive_gain = float(gain) self.receive_gain = float(gain)
if self.receive_mixer: self.receive_mixer.set_gain(self.receive_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) self.transmit_gain = float(gain)
if self.transmit_mixer: self.transmit_mixer.set_gain(self.transmit_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): def switch_profile(self, profile=None, from_signalling=False):
if self.active_call: if self.active_call:
if self.active_call.profile == profile: return if self.active_call.profile == profile: return
@@ -487,14 +622,18 @@ class Telephone(SignallingReceiver):
self.active_call.profile = profile self.active_call.profile = profile
self.transmit_codec = Profiles.get_codec(self.active_call.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_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) if not from_signalling: self.signal(Signalling.PREFERRED_PROFILE+self.active_call.profile, self.active_call)
self.__reconfigure_transmit_pipeline() 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): def __select_call_profile(self, profile=None):
if profile == None: profile = Profiles.DEFAULT_PROFILE if profile == None: profile = Profiles.DEFAULT_PROFILE
self.active_call.profile = profile self.active_call.profile = profile
self.__select_call_codecs(self.active_call.profile) self.__select_call_codecs(self.active_call.profile)
self.__select_call_frame_time(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) RNS.log(f"Selected call profile 0x{RNS.hexrep(profile, delimit=False)}", RNS.LOG_DEBUG)
def __select_call_codecs(self, profile=None): def __select_call_codecs(self, profile=None):
@@ -504,6 +643,9 @@ class Telephone(SignallingReceiver):
def __select_call_frame_time(self, profile=None): def __select_call_frame_time(self, profile=None):
self.target_frame_time_ms = Profiles.get_frame_time(profile) 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): def __reset_dialling_pipelines(self):
with self.pipeline_lock: with self.pipeline_lock:
if self.audio_output: self.audio_output.stop() if self.audio_output: self.audio_output.stop()
@@ -516,12 +658,37 @@ class Telephone(SignallingReceiver):
self.receive_mixer = None self.receive_mixer = None
self.__prepare_dialling_pipelines() 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): def __prepare_dialling_pipelines(self):
self.__select_call_profile(self.active_call.profile) 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.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.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) 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): def __activate_ring_tone(self):
if self.ringtone_path != None and os.path.isfile(self.ringtone_path): if self.ringtone_path != None and os.path.isfile(self.ringtone_path):
@@ -532,6 +699,7 @@ class Telephone(SignallingReceiver):
def job(): def job():
with self.ringer_lock: 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: 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() if not self.ringer_pipeline.running: self.ringer_pipeline.start()
time.sleep(0.1) 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) 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.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)] filter_chain = []
else: self.active_call.filters = [BandPass(250, 8500)] 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.__prepare_dialling_pipelines()
self.active_call.packetizer = Packetizer(self.active_call, failure_callback=self.__packetizer_failure) 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) 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.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.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) self.signal(Signalling.STATUS_ESTABLISHED, self.active_call)
@@ -645,7 +822,7 @@ class Telephone(SignallingReceiver):
if self.transmit_pipeline: self.transmit_pipeline.stop() if self.transmit_pipeline: self.transmit_pipeline.stop()
RNS.log(f"Audio pipelines stopped", RNS.LOG_DEBUG) 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: with self.call_handler_lock:
if not self.active_call: if not self.active_call:
self.call_status = Signalling.STATUS_CALLING self.call_status = Signalling.STATUS_CALLING
@@ -668,7 +845,9 @@ class Telephone(SignallingReceiver):
self.active_call.is_outgoing = True self.active_call.is_outgoing = True
self.active_call.is_terminating = False self.active_call.is_terminating = False
self.active_call.ring_timeout = False self.active_call.ring_timeout = False
self.active_call.established_at = None
self.active_call.profile = profile 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_call_at(self.active_call, outgoing_call_timeout)
self.__timeout_outgoing_establishment_at(self.active_call, outgoing_establishment_timeout) self.__timeout_outgoing_establishment_at(self.active_call, outgoing_establishment_timeout)
@@ -684,8 +863,7 @@ class Telephone(SignallingReceiver):
for signal in signals: for signal in signals:
if source != self.active_call: RNS.log("Received signalling on non-active call, ignoring", RNS.LOG_DEBUG) if source != self.active_call: RNS.log("Received signalling on non-active call, ignoring", RNS.LOG_DEBUG)
else: else:
if self.active_call.is_incoming and not self.active_call.answered and signal < Signalling.PREFERRED_PROFILE: if self.active_call.is_incoming and not self.active_call.answered and signal < Signalling.PREFERRED_MODE: return
return
elif signal == Signalling.STATUS_BUSY: elif signal == Signalling.STATUS_BUSY:
RNS.log("Remote is busy, terminating", RNS.LOG_DEBUG) RNS.log("Remote is busy, terminating", RNS.LOG_DEBUG)
self.active_call.is_terminating = True self.active_call.is_terminating = True
@@ -705,7 +883,8 @@ class Telephone(SignallingReceiver):
RNS.log("Identification accepted, remote is now ringing", RNS.LOG_DEBUG) RNS.log("Identification accepted, remote is now ringing", RNS.LOG_DEBUG)
self.call_status = signal self.call_status = signal
self.__prepare_dialling_pipelines() 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() if self.active_call and self.active_call.is_outgoing: self.__activate_dial_tone()
elif signal == Signalling.STATUS_CONNECTING: elif signal == Signalling.STATUS_CONNECTING:
RNS.log("Call answered, remote is performing call setup, opening audio pipelines", RNS.LOG_DEBUG) 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() self.__disable_dial_tone()
RNS.log(f"Call setup complete for {RNS.prettyhexrep(self.active_call.get_remote_identity().hash)}", RNS.LOG_DEBUG) RNS.log(f"Call setup complete for {RNS.prettyhexrep(self.active_call.get_remote_identity().hash)}", RNS.LOG_DEBUG)
self.call_status = signal 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 callable(self.__established_callback): self.__established_callback(self.active_call.get_remote_identity())
if self.low_latency_output: self.audio_output.enable_low_latency() if self.low_latency_output: self.audio_output.enable_low_latency()
elif signal >= Signalling.PREFERRED_PROFILE: elif signal >= Signalling.PREFERRED_PROFILE:
profile = 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) if self.active_call and self.call_status == Signalling.STATUS_ESTABLISHED: self.switch_profile(profile, from_signalling=True)
else: self.__select_call_profile(profile) 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): def __str__(self):
return f"<lxst.telephony/{RNS.hexrep(self.identity.hash, delimit=False)}>" return f"<lxst.telephony/{RNS.hexrep(self.identity.hash, delimit=False)}>"
+2
View File
@@ -1 +1,3 @@
# Copyright 2024-2026, Mark Qvist
from .Telephony import Telephone from .Telephony import Telephone
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os import os
import time import time
import threading import threading
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os import os
import time import time
import threading import threading
-131
View File
@@ -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
+29 -3
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import math import math
import time import time
@@ -109,6 +111,16 @@ def get_backend():
Backend = get_backend() Backend = get_backend()
class Sink(): 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 handle_frame(self, frame, source): pass
def can_receive(self, from_source=None): return True def can_receive(self, from_source=None): return True
@@ -133,6 +145,7 @@ class LineSink(LocalSink):
self.autostart_min = self.AUTOSTART_MIN self.autostart_min = self.AUTOSTART_MIN
self.buffer_max_height = self.MAX_FRAMES-3 self.buffer_max_height = self.MAX_FRAMES-3
self.low_latency = low_latency self.low_latency = low_latency
self.streaming = False
self.preferred_samplerate = Backend.SAMPLERATE self.preferred_samplerate = Backend.SAMPLERATE
self.backend = Backend(preferred_device=self.preferred_device, samplerate=self.preferred_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) 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 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): def start(self):
if not self.should_run: if not self.should_run:
@@ -172,6 +187,12 @@ class LineSink(LocalSink):
def stop(self): def stop(self):
self.should_run = False 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): def enable_low_latency(self):
self.__wants_low_latency = True self.__wants_low_latency = True
@@ -189,11 +210,15 @@ class LineSink(LocalSink):
self.underrun_at = None self.underrun_at = None
with self.insert_lock: frame = self.frame_deque.popleft() 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] if frame.shape[1] > self.channels: frame = frame[:, 0:self.channels]
player.play(frame) player.play(frame)
if len(self.frame_deque) > self.buffer_max_height: 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() self.frame_deque.popleft()
else: else:
@@ -201,6 +226,7 @@ class LineSink(LocalSink):
# TODO: Remove debug # TODO: Remove debug
# RNS.log(f"Buffer underrun on {self}", RNS.LOG_DEBUG) # RNS.log(f"Buffer underrun on {self}", RNS.LOG_DEBUG)
self.underrun_at = time.time() self.underrun_at = time.time()
if self.streaming: time.sleep((self.frame_time*self.buffer_max_height)/3.0)
else: else:
if time.time() > self.underrun_at+(self.frame_time*self.frame_timeout): 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) 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:]]) frame = np.hstack([frame, frame[:, -1:]])
if frame.shape[0] < self.samples_per_frame: 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) silence_frame = np.zeros((self.samples_per_frame-frame.shape[0], frame.shape[1]), dtype=frame.dtype)
frame = np.vstack([frame, silence_frame]) frame = np.vstack([frame, silence_frame])
+82 -6
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os import os
import RNS import RNS
import math import math
@@ -118,7 +120,21 @@ def get_backend():
Backend = 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 LocalSource(Source): pass
class RemoteSource(Source): pass class RemoteSource(Source): pass
@@ -159,6 +175,7 @@ class Loopback(LocalSource, LocalSink):
class LineSource(LocalSource): class LineSource(LocalSource):
MAX_FRAMES = 128 MAX_FRAMES = 128
DEFAULT_FRAME_MS = 80 DEFAULT_FRAME_MS = 80
SIGNAL_FAIL_REINIT_THRESHOLD = 1.5
@staticmethod @staticmethod
def linear_gain(gain_db): return 10**(gain_db/10) 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.__gain = self.linear_gain(self.gain)
self.__target_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 filters != None:
if type(filters) == list: self.filters = filters if type(filters) == list: self.filters = filters
else: 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 ease_in_completed = True if self.ease_in <= 0.0 else False
skip_completed = True if self.__skip <= 0.0 else False skip_completed = True if self.__skip <= 0.0 else False
while self.should_run: while self.should_run:
# st = time.perf_counter() # TODO: Remove debug
frame_samples = recorder.record(numframes=self.samples_per_frame) 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 not skip_completed:
if time.time()-started > self.__skip: if time.time()-started > self.__skip:
skip_completed = True skip_completed = True
started = time.time() started = time.time()
else: else:
# ft = 0 # TODO: Remove debug
if self.filters != None: 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) 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.__gain != 1.0: frame_samples *= self.__gain
if self.codec: if self.codec:
frame = self.codec.encode(frame_samples)
if self.sink and self.sink.can_receive(from_source=self): 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: if not ease_in_completed:
d = time.time()-started d = time.time()-started
self.__gain = (d/self.ease_in)*self.__target_gain self.__gain = (d/self.ease_in)*self.__target_gain
@@ -263,13 +312,22 @@ class LineSource(LocalSource):
self.__gain = self.__target_gain self.__gain = self.__target_gain
ease_in_completed = True 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): class OpusFileSource(LocalSource):
MAX_FRAMES = 128 MAX_FRAMES = 128
DEFAULT_FRAME_MS = 100 DEFAULT_FRAME_MS = 100
TYPE_MAP_FACTOR = np.iinfo("int16").max 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.target_frame_ms = target_frame_ms
self.loop = loop self.loop = loop
self.timed = timed self.timed = timed
@@ -278,6 +336,8 @@ class OpusFileSource(LocalSource):
self.ingest_thread = None self.ingest_thread = None
self.next_frame = None self.next_frame = None
self._codec = 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}") if file_path == None: raise TypeError(f"{self} initialised with invalid file path: {file_path}")
elif os.path.isfile(file_path): elif os.path.isfile(file_path):
@@ -296,6 +356,19 @@ class OpusFileSource(LocalSource):
self.codec = codec self.codec = codec
self.sink = sink 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 @property
def codec(self): return self._codec def codec(self): return self._codec
@@ -344,6 +417,7 @@ class OpusFileSource(LocalSource):
fi += 1 fi += 1
fs = (fi-1)*spf; fe = min(fi*spf, sc) fs = (fi-1)*spf; fe = min(fi*spf, sc)
frame_samples = self.samples[fs:fe, :] frame_samples = self.samples[fs:fe, :]
if self.__gain != 1.0: frame_samples *= self.__gain
if len(frame_samples) < 1: if len(frame_samples) < 1:
if self.loop: if self.loop:
RNS.log(f"{self} exhausted file samples, looping...", RNS.LOG_DEBUG) RNS.log(f"{self} exhausted file samples, looping...", RNS.LOG_DEBUG)
@@ -353,8 +427,10 @@ class OpusFileSource(LocalSource):
self.should_run = False self.should_run = False
else: else:
if self.codec: if self.codec:
frame = self.codec.encode(frame_samples)
if self.sink and self.sink.can_receive(from_source=self): 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: else:
time.sleep(self.frame_time*0.1) time.sleep(self.frame_time*0.1)
+2
View File
@@ -1,5 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# Copyright 2024-2026, Mark Qvist
import RNS import RNS
import os import os
import sys import sys
+2
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
APP_NAME = "lxst" APP_NAME = "lxst"
from .Pipeline import Pipeline from .Pipeline import Pipeline
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.4.5" __version__ = "0.6.0"
+17 -2
View File
@@ -21,7 +21,15 @@ create_symlinks:
build_wheel: build_wheel:
cp ./lib/static/* ./LXST/ cp ./lib/static/* ./LXST/
touch ./skip_extensions 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 ./skip_extensions
-@(rm ./LXST/*.so) -@(rm ./LXST/*.so)
-@(rm ./LXST/*.dll) -@(rm ./LXST/*.dll)
@@ -40,11 +48,18 @@ persist_libs:
-cp ./lib/dev/*.so ./lib/static/ -cp ./lib/dev/*.so ./lib/static/
-cp ./lib/dev/*.dll ./lib/static/ -cp ./lib/dev/*.dll ./lib/static/
build_spkg: remove_symlinks build_sdist create_symlinks
release: remove_symlinks build_wheel create_symlinks release: remove_symlinks build_wheel create_symlinks
upload: 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 @echo Ready to publish release, hit enter to continue
@read VOID @read VOID
@echo Uploading to PyPi... @echo Uploading to PyPi...
twine upload dist/* twine upload dist/lxst-*.whl
@echo Release published @echo Release published
+38 -24
View File
@@ -1,8 +1,21 @@
# Lightweight Extensible Signal Transport # 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 - Cross-platform, works on Linux, Android, Windows and Mac
- Provides a variety of ready-to-use primitives, for easily creating applications such as: - 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 - Uses a fully staged signal pipelining, allowing arbitrary stream routing
- Provides built-in signal mixing support for any number of channels - 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 ## 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. 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 ## 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 ## 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 raspi-config # Enable the I2C bus under "Interface Options"
sudo apt install python3-rpi.gpio # Install gpio module system-wide 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
+1
View File
@@ -15,6 +15,7 @@ if loop:
else: else:
player = FilePlayer("./docs/speech_stereo.opus") player = FilePlayer("./docs/speech_stereo.opus")
player.release_on_finish = True
player.start() player.start()
while player.running: time.sleep(0.1) while player.running: time.sleep(0.1)
+10 -5
View File
@@ -2,18 +2,23 @@ import setuptools
from setuptools import setup, Extension from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext from setuptools.command.build_ext import build_ext
import os import os
import sys
import platform import platform
if os.path.isfile("./skip_extensions"): BUILD_EXTENSIONS = False if os.path.isfile("./skip_extensions"): BUILD_EXTENSIONS = False
else: BUILD_EXTENSIONS = True else: BUILD_EXTENSIONS = True
if os.name == "nt": BUILD_EXTENSIONS = False 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() with open("README.md", "r") as fh: long_description = fh.read()
exec(open("LXST/_version.py", "r").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"] c_sources = ["LXST/Filters.c"]
if BUILD_EXTENSIONS: extensions = [ Extension("LXST.filterlib", sources=c_sources, include_dirs=["LXST"], language="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', 'rnphone=LXST.Utilities.rnphone:main',
] ]
}, },
install_requires=["rns>=1.0.4", install_requires=["rns>=1.6.0",
"lxmf>=0.9.3", "lxmf>=1.3.0",
"numpy>=2.3.4", "numpy>=2.3.4",
"pycodec2>=4.1.0", "pycodec2>=4.1.0",
"audioop-lts>=0.2.1;python_version>='3.13'", "audioop-lts>=0.2.1;python_version>='3.13'",