23 Commits
Author SHA1 Message Date
Mark Qvist 6a329bf6d9 Updated readme 2026-11-08 13:59:20 +01:00
Mark Qvist 8409247f37 Clarify no-derivatives licensing 2026-11-08 13:54:19 +01:00
Mark Qvist f868cc4f70 Sync upstream 2026-11-08 13:50:44 +01:00
Mark Qvist 1194c9011f Updated readme 2025-12-28 01:00:21 +01:00
Mark Qvist cf19a2e994 Updated readme 2025-12-28 00:58:57 +01:00
markqvist add440db43 Update README.md 2025-12-22 22:25:38 +01:00
markqvist b1f8229f65 Update README.md 2025-12-22 22:24:52 +01:00
Mark Qvist 05bccbffee Sync upstream 2025-11-27 15:12:24 +01:00
Mark Qvist 1d57d83517 Sync upstream 2025-11-27 15:09:56 +01:00
Mark Qvist 68c2cf489c Sync upstream 2025-11-27 02:17:32 +01:00
Mark Qvist 7d5f390a90 Sync upstream 2025-11-26 11:02:13 +01:00
Mark Qvist 3fd611ecea Sync upstream 2025-11-25 21:20:05 +01:00
Mark Qvist dd0cced5b0 Sync upstream 2025-11-25 11:38:14 +01:00
Mark Qvist 0ae8092914 Sync upstream 2025-11-24 18:08:02 +01:00
Mark Qvist 7794313202 Sync upstream 2025-11-24 16:35:53 +01:00
Mark Qvist a470dca73e Sync upstream 2025-11-24 16:17:25 +01:00
Mark Qvist 906b3612d3 Sync upstream 2025-11-24 15:35:22 +01:00
Mark Qvist eefc35c2f8 Sync upstream 2025-11-24 15:32:26 +01:00
Mark Qvist 55065d3ec3 Sync upstream 2025-11-24 15:30:42 +01:00
Mark Qvist 514b5e7ae6 Sync upstream 2025-11-24 15:28:32 +01:00
Mark Qvist 61a452c6df Sync upstream 2025-11-21 17:41:12 +01:00
Mark Qvist 0f329e5304 Sync upstream 2025-11-21 17:34:28 +01:00
Mark Qvist 5602eeb767 Sync upstream 2025-11-10 02:30:46 +01:00
88 changed files with 7618 additions and 540 deletions

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
# .github/workflows/build-platforms.yml
name: Build Windows and macOS binaries
on:
push:
branches: [ main, master ]
tags: [ 'libs*' ]
pull_request:
branches: [ main, master ]
release:
types: [published]
jobs:
build_windows:
name: Build Windows wheels (Python ${{ matrix.python-version }})
runs-on: windows-2022
strategy:
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install cffi wheel setuptools
- name: Build wheel
run: |
python setup.py bdist_wheel
- name: Upload wheel artifact
uses: actions/upload-artifact@v4
with:
name: windows-wheels-${{ matrix.python-version }}
path: dist/*.whl
build_macos_x86_64:
name: Build macOS x86_64 wheels (Python ${{ matrix.python-version }})
runs-on: macos-13 # Platform for macOS Intel
strategy:
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install cffi wheel setuptools
- name: Build wheel
run: |
python setup.py bdist_wheel
- name: Upload wheel artifact
uses: actions/upload-artifact@v4
with:
name: macos-x86_64-wheels-${{ matrix.python-version }}
path: dist/*.whl
# MACOS BUILDS (Apple Silicon ARM64)
build_macos_arm64:
name: Build macOS ARM64 wheels (Python ${{ matrix.python-version }})
runs-on: macos-14 # Platform for macOS ARM
strategy:
matrix:
python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install cffi wheel setuptools
- name: Build wheel
run: |
python setup.py bdist_wheel
- name: Upload wheel artifact
uses: actions/upload-artifact@v4
with:
name: macos-arm64-wheels-${{ matrix.python-version }}
path: dist/*.whl
collect_artifacts:
name: Collect all wheels
needs: [build_windows, build_macos_x86_64, build_macos_arm64]
runs-on: ubuntu-latest
if: github.event_name == 'release' && github.event.action == 'published'
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: ./artifacts
- name: List all files
run: |
find ./artifacts -type f
- name: Create combined wheel directory
run: |
mkdir -p ./final_wheels
find ./artifacts -name "*.whl" -exec cp {} ./final_wheels/ \;
find ./artifacts -name "*.tar.gz" -exec cp {} ./final_wheels/ \;
- name: Upload to GitHub Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: ./final_wheels/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-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
from .libs.pydub import AudioSegment
@@ -11,6 +13,8 @@ class Codec():
source = None
sink = None
def __str__(self): return f"<LXST/Codec>"
class CodecError(Exception):
pass
@@ -24,6 +28,8 @@ class Null(Codec):
def decode(self, frame):
return frame
def __str__(self): return f"<LXST/NullCodec>"
def resample_bytes(sample_bytes, bitdepth, channels, input_rate, output_rate, normalize=False):
sample_width = bitdepth//8
audio = AudioSegment(
+8 -3
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import time
import math
import struct
@@ -57,7 +59,6 @@ class Codec2(Codec):
elif frame.shape[1] > self.channels:
frame = frame[:, 1]
input_samples = frame*self.TYPE_MAP_FACTOR
input_samples = input_samples.astype(np.int16)
@@ -88,7 +89,9 @@ class Codec2(Codec):
def decode(self, frame_bytes):
frame_header = frame_bytes[0]
frame_bytes = frame_bytes[1:]
frame_mode = self.HEADER_MODES[frame_header]
if frame_header in self.HEADER_MODES: frame_mode = self.HEADER_MODES[frame_header]
else: frame_mode = self.mode
if self.mode != frame_mode:
self.set_mode(frame_mode)
@@ -117,4 +120,6 @@ class Codec2(Codec):
frame_samples = np.zeros((len(decoded_samples), 1), dtype="float32")
frame_samples[:, 0] = decoded_samples
return frame_samples
return frame_samples
def __str__(self): return f"<LXST/Codec2 @ {RNS.prettyspeed(self.mode)}>"
+81 -76
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import io
import RNS
import time
@@ -22,6 +24,19 @@ class Opus(Codec):
PROFILE_AUDIO_HIGH = 0x07
PROFILE_AUDIO_MAX = 0x08
@staticmethod
def profile_name(profile):
if profile == Opus.PROFILE_VOICE_LOW: return "Voice, Low"
elif profile == Opus.PROFILE_VOICE_MEDIUM: return "Voice, Medium"
elif profile == Opus.PROFILE_VOICE_HIGH: return "Voice, High"
elif profile == Opus.PROFILE_VOICE_MAX: return "Voice, Max"
elif profile == Opus.PROFILE_AUDIO_MIN: return "Audio, Min"
elif profile == Opus.PROFILE_AUDIO_LOW: return "Audio, Low"
elif profile == Opus.PROFILE_AUDIO_MEDIUM: return "Audio, Medium"
elif profile == Opus.PROFILE_AUDIO_HIGH: return "Audio, High"
elif profile == Opus.PROFILE_AUDIO_MAX: return "Audio, Max"
else: return "Default"
def __init__(self, profile=PROFILE_VOICE_LOW):
self.frame_quanta_ms = self.FRAME_QUANTA_MS
self.frame_max_ms = self.FRAME_MAX_MS
@@ -40,85 +55,73 @@ class Opus(Codec):
self.output_bitrate = 0
self.set_profile(profile)
@staticmethod
def profile_channels(profile):
if profile == Opus.PROFILE_VOICE_LOW: return 1
elif profile == Opus.PROFILE_VOICE_MEDIUM: return 1
elif profile == Opus.PROFILE_VOICE_HIGH: return 1
elif profile == Opus.PROFILE_VOICE_MAX: return 2
elif profile == Opus.PROFILE_AUDIO_MIN: return 1
elif profile == Opus.PROFILE_AUDIO_LOW: return 1
elif profile == Opus.PROFILE_AUDIO_MEDIUM: return 2
elif profile == Opus.PROFILE_AUDIO_HIGH: return 2
elif profile == Opus.PROFILE_AUDIO_MAX: return 2
else: raise CodecError(f"Unsupported profile")
@staticmethod
def profile_samplerate(profile):
if profile == Opus.PROFILE_VOICE_LOW: return 8000
elif profile == Opus.PROFILE_VOICE_MEDIUM: return 24000
elif profile == Opus.PROFILE_VOICE_HIGH: return 48000
elif profile == Opus.PROFILE_VOICE_MAX: return 48000
elif profile == Opus.PROFILE_AUDIO_MIN: return 8000
elif profile == Opus.PROFILE_AUDIO_LOW: return 12000
elif profile == Opus.PROFILE_AUDIO_MEDIUM: return 24000
elif profile == Opus.PROFILE_AUDIO_HIGH: return 48000
elif profile == Opus.PROFILE_AUDIO_MAX: return 48000
else: raise CodecError(f"Unsupported profile")
@staticmethod
def profile_application(profile):
if profile == Opus.PROFILE_VOICE_LOW: return "voip"
elif profile == Opus.PROFILE_VOICE_MEDIUM: return "voip"
elif profile == Opus.PROFILE_VOICE_HIGH: return "voip"
elif profile == Opus.PROFILE_VOICE_MAX: return "voip"
elif profile == Opus.PROFILE_AUDIO_MIN: return "audio"
elif profile == Opus.PROFILE_AUDIO_LOW: return "audio"
elif profile == Opus.PROFILE_AUDIO_MEDIUM: return "audio"
elif profile == Opus.PROFILE_AUDIO_HIGH: return "audio"
elif profile == Opus.PROFILE_AUDIO_MAX: return "audio"
else: raise CodecError(f"Unsupported profile")
@staticmethod
def profile_bitrate_ceiling(profile):
if profile == Opus.PROFILE_VOICE_LOW: return 6000
elif profile == Opus.PROFILE_VOICE_MEDIUM: return 8000
elif profile == Opus.PROFILE_VOICE_HIGH: return 16000
elif profile == Opus.PROFILE_VOICE_MAX: return 32000
elif profile == Opus.PROFILE_AUDIO_MIN: return 8000
elif profile == Opus.PROFILE_AUDIO_LOW: return 14000
elif profile == Opus.PROFILE_AUDIO_MEDIUM: return 28000
elif profile == Opus.PROFILE_AUDIO_HIGH: return 56000
elif profile == Opus.PROFILE_AUDIO_MAX: return 128000
else: raise CodecError(f"Unsupported profile")
@staticmethod
def max_bytes_per_frame(bitrate_ceiling, frame_duration_ms):
return math.ceil((bitrate_ceiling/8)*(frame_duration_ms/1000))
def set_profile(self, profile):
if profile == self.PROFILE_VOICE_LOW:
self.profile = profile
self.channels = 1
self.input_channels = self.channels
self.output_samplerate = 8000
self.opus_encoder.set_application("voip")
elif profile == self.PROFILE_VOICE_MEDIUM:
self.profile = profile
self.channels = 1
self.input_channels = self.channels
self.output_samplerate = 24000
self.opus_encoder.set_application("voip")
elif profile == self.PROFILE_VOICE_HIGH:
self.profile = profile
self.channels = 1
self.input_channels = self.channels
self.output_samplerate = 48000
self.opus_encoder.set_application("voip")
elif profile == self.PROFILE_VOICE_MAX:
self.profile = profile
self.channels = 2
self.input_channels = self.channels
self.output_samplerate = 48000
self.opus_encoder.set_application("voip")
elif profile == self.PROFILE_AUDIO_MIN:
self.profile = profile
self.channels = 1
self.input_channels = self.channels
self.output_samplerate = 8000
self.opus_encoder.set_application("audio")
elif profile == self.PROFILE_AUDIO_LOW:
self.profile = profile
self.channels = 1
self.input_channels = self.channels
self.output_samplerate = 12000
self.opus_encoder.set_application("audio")
elif profile == self.PROFILE_AUDIO_MEDIUM:
self.profile = profile
self.channels = 2
self.input_channels = self.channels
self.output_samplerate = 24000
self.opus_encoder.set_application("audio")
elif profile == self.PROFILE_AUDIO_HIGH:
self.profile = profile
self.channels = 2
self.input_channels = self.channels
self.output_samplerate = 48000
self.opus_encoder.set_application("audio")
elif profile == self.PROFILE_AUDIO_MAX:
self.profile = profile
self.channels = 2
self.input_channels = self.channels
self.output_samplerate = 48000
self.opus_encoder.set_application("audio")
else:
raise CodecError(f"Unsupported profile configured for {self}")
self.channels = self.profile_channels(profile)
self.input_channels = self.channels
self.output_samplerate = self.profile_samplerate(profile)
self.opus_encoder.set_application(self.profile_application(profile))
self.profile = profile
def update_bitrate(self, frame_duration_ms):
if self.profile == self.PROFILE_VOICE_LOW:
self.bitrate_ceiling = 6000
elif self.profile == self.PROFILE_VOICE_MEDIUM:
self.bitrate_ceiling = 8000
elif self.profile == self.PROFILE_VOICE_HIGH:
self.bitrate_ceiling = 16000
elif self.profile == self.PROFILE_VOICE_MAX:
self.bitrate_ceiling = 32000
elif self.profile == self.PROFILE_AUDIO_MIN:
self.bitrate_ceiling = 8000
elif self.profile == self.PROFILE_AUDIO_LOW:
self.bitrate_ceiling = 14000
elif self.profile == self.PROFILE_AUDIO_MEDIUM:
self.bitrate_ceiling = 28000
elif self.profile == self.PROFILE_AUDIO_HIGH:
self.bitrate_ceiling = 56000
elif self.profile == self.PROFILE_AUDIO_MAX:
self.bitrate_ceiling = 128000
self.bitrate_ceiling = self.profile_bitrate_ceiling(self.profile)
max_bytes_per_frame = self.max_bytes_per_frame(self.bitrate_ceiling, frame_duration_ms)
max_bytes_per_frame = math.ceil((self.bitrate_ceiling/8)*(frame_duration_ms/1000))
configured_bitrate = (max_bytes_per_frame*8)/(frame_duration_ms/1000)
self.opus_encoder.set_max_bytes_per_frame(max_bytes_per_frame)
@@ -176,4 +179,6 @@ class Opus(Codec):
decoded_samples = np.frombuffer(decoded_frame_bytes, dtype="int16")/self.TYPE_MAP_FACTOR
frame_samples = decoded_samples.reshape(len(decoded_samples)//self.channels, self.channels)
return frame_samples
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 numpy as np
from .Codec import Codec
@@ -55,4 +57,6 @@ class Raw(Codec):
frame_samples = frame_samples.reshape(len(frame_samples)//frame_channels, frame_channels)
if not self.channels: self.channels = frame_channels
return frame_samples
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 Codec as Codec
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
+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
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 math
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):
"""
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
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,
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:
from __builtin__ import max as builtin_max
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
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
"""
+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
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():
pass
+71
View File
@@ -0,0 +1,71 @@
// Copyright 2024-2026, Mark Qvist
#include <math.h>
void highpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states, float* last_inputs) {
int i, ch;
for (ch = 0; ch < channels; ch++) { float input_diff = input[ch] - last_inputs[ch]; output[ch] = alpha * (filter_states[ch] + input_diff); }
for (i = 1; i < samples; i++) { for (ch = 0; ch < channels; ch++) { int idx = i * channels + ch; float input_diff = input[idx] - input[idx - channels]; output[idx] = alpha * (output[idx - channels] + input_diff); } }
for (ch = 0; ch < channels; ch++) { int last_idx = (samples - 1) * channels + ch; filter_states[ch] = output[last_idx]; last_inputs[ch] = input[last_idx]; }
}
void lowpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states) {
int i, ch;
float one_minus_alpha = 1.0f - alpha;
for (ch = 0; ch < channels; ch++) { output[ch] = alpha * input[ch] + one_minus_alpha * filter_states[ch]; }
for (i = 1; i < samples; i++) {
for (ch = 0; ch < channels; ch++) { int idx = i * channels + ch; output[idx] = alpha * input[idx] + one_minus_alpha * output[idx - channels]; }
}
for (ch = 0; ch < channels; ch++) { int last_idx = (samples - 1) * channels + ch; filter_states[ch] = output[last_idx]; }
}
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) {
for (int i = 0; i < samples * channels; i++) { output[i] = input[i]; }
int num_blocks = block_target;
int block_size = samples / num_blocks;
if (block_size < 1) block_size = 1;
for (int block = 0; block < num_blocks; block++) {
int block_start = block*block_size;
int block_end = (block + 1)*block_size;
if (block == num_blocks - 1) { block_end = samples; }
if (block_end > samples) { block_end = samples; }
int block_samples = block_end - block_start;
if (block_samples <= 0) continue;
for (int ch = 0; ch < channels; ch++) {
float sum_squares = 0.0f;
for (int i = block_start; i < block_end; i++) { int idx = i * channels + ch; sum_squares += output[idx] * output[idx]; }
float rms = sqrtf(sum_squares / block_samples);
float target_gain;
if (rms > 1e-9f && rms > trigger_level) {
target_gain = target_linear / rms;
if (target_gain > max_gain_linear) { target_gain = max_gain_linear; }
} else { target_gain = current_gain_lin[ch]; }
if (target_gain < current_gain_lin[ch]) {
current_gain_lin[ch] = attack_coeff * target_gain + (1.0f - attack_coeff) * current_gain_lin[ch];
*hold_counter = (int)hold_samples;
} else {
if (*hold_counter > 0) { *hold_counter -= block_samples; }
else { current_gain_lin[ch] = release_coeff * target_gain + (1.0f - release_coeff) * current_gain_lin[ch]; }
}
for (int i = block_start; i < block_end; i++) { int idx = i * channels + ch; output[idx] *= current_gain_lin[ch]; }
}
}
float peak_limit = 0.75f;
for (int ch = 0; ch < channels; ch++) {
float peak = 0.0f;
for (int i = 0; i < samples; i++) { int idx = i * channels + ch; float abs_val = fabsf(output[idx]);
if (abs_val > peak) { peak = abs_val; } }
if (peak > peak_limit) { float scale = peak_limit / peak;
for (int i = 0; i < samples; i++) { int idx = i * channels + ch; output[idx] *= scale; } }
}
}
+4
View File
@@ -0,0 +1,4 @@
EXPORTS
highpass_filter
lowpass_filter
agc_process
+5
View File
@@ -0,0 +1,5 @@
// Copyright 2024-2026, Mark Qvist
void highpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states, float* last_inputs);
void lowpass_filter(float* input, float* output, int samples, int channels, float alpha, float* filter_states);
void agc_process(float* input, float* output, int samples, int channels, float target_linear, float max_gain_linear, float trigger_level, float attack_coeff, float release_coeff, float hold_samples, float* current_gain_lin, int* hold_counter, int block_target);
+1568
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 RNS
import math
+47 -9
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS
import LXST
import time
@@ -15,14 +17,17 @@ class Mixer(LocalSource, LocalSink):
MAX_FRAMES = 8
TYPE_MAP_FACTOR = np.iinfo("int16").max
def __init__(self, target_frame_ms=40, samplerate=None, codec=None, sink=None):
def __init__(self, target_frame_ms=40, samplerate=None, codec=None, sink=None, gain=0.0):
self.incoming_frames = {}
self.reference_outs = []
self.target_frame_ms = target_frame_ms
self.frame_time = self.target_frame_ms/1000
self.should_run = False
self.mixer_thread = None
self.mixer_lock = threading.Lock()
self.insert_lock = threading.Lock()
self.muted = False
self.gain = gain
self.bitdepth = 32
self.channels = None
self.samplerate = None
@@ -44,6 +49,18 @@ class Mixer(LocalSource, LocalSink):
def stop(self):
self.should_run = False
def set_gain(self, gain=None):
if gain == None: self.gain = 0.0
else: self.gain = float(gain)
def mute(self, mute=True):
if mute == True or mute == False: self.muted = mute
else: self.muted = False
def unmute(self, unmute=True):
if unmute == True or unmute == False: self.muted = unmute
else: self.muted = False
def set_source_max_frames(self, source, max_frames):
with self.insert_lock:
if not source in self.incoming_frames: self.incoming_frames[source] = deque(maxlen=max_frames)
@@ -78,7 +95,14 @@ class Mixer(LocalSource, LocalSink):
self.incoming_frames[source].append(frame_samples)
@property
def _mixing_gain(self):
if self.muted: return 0.0
elif self.gain == 0.0: return 1.0
else: return 10**(self.gain/10)
def _mixer_job(self):
if self.mixer_lock.locked(): return
with self.mixer_lock:
while self.should_run:
if self.sink and self.sink.can_receive():
@@ -87,18 +111,32 @@ class Mixer(LocalSource, LocalSink):
for source in self.incoming_frames.copy():
if len(self.incoming_frames[source]) > 0:
next_frame = self.incoming_frames[source].popleft()
if source_count == 0: mixed_frame = next_frame
else: mixed_frame = mixed_frame + next_frame
if source_count == 0: mixed_frame = next_frame*self._mixing_gain
else: mixed_frame = mixed_frame + next_frame*self._mixing_gain
source_count += 1
if source_count > 0:
if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self)
else: self.sink.handle_frame(mixed_frame, self)
else:
time.sleep(self.frame_time*0.1)
mixed_frame = np.clip(mixed_frame, -1.0, 1.0)
if RNS.loglevel >= RNS.LOG_DEBUG:
if mixed_frame.max() >= 1.0 or mixed_frame.min() <= -1.0:
RNS.log(f"Signal clipped on {self}", RNS.LOG_WARNING)
else:
time.sleep(self.frame_time*0.1)
try:
if self.codec: self.sink.handle_frame(self.codec.encode(mixed_frame), self)
else: self.sink.handle_frame(mixed_frame, self)
except Exception as e: RNS.log(f"Error while mixing frame on {self}: {e}", RNS.LOG_ERROR)
try:
for ref in self.reference_outs: ref.handle_reference(mixed_frame, self.samplerate)
except Exception as e: RNS.log(f"Error while handling reference output on {self}: {e}", RNS.LOG_ERROR)
else: time.sleep(self.frame_time*0.1)
else: time.sleep(self.frame_time*0.1)
RNS.log(f"{self} stopped", RNS.LOG_DEBUG)
@property
def codec(self):
+14 -13
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import RNS
import time
import threading
@@ -23,7 +25,8 @@ class SignallingReceiver():
if self.proxy: self.proxy.signalling_received(signals, source)
def signal(self, signal, destination, immediate=True):
signalling_data = {FIELD_SIGNALLING:[signal]}
if type(signal) != list: signalling_data = {FIELD_SIGNALLING: [signal]}
else: signalling_data = {FIELD_SIGNALLING: signal}
if immediate:
signalling_packet = RNS.Packet(destination, mp.packb(signalling_data), create_receipt=False)
@@ -39,10 +42,8 @@ class SignallingReceiver():
if type(unpacked) == dict:
if FIELD_SIGNALLING in unpacked:
signalling = unpacked[FIELD_SIGNALLING]
if type(signalling) == list:
self.signalling_received(signalling, source)
else:
self.signalling_received([signalling], source)
if type(signalling) == list: self.signalling_received(signalling, source)
else: self.signalling_received([signalling], source)
except Exception as e:
RNS.log(f"{self} could not process incoming packet: {e}", RNS.LOG_ERROR)
@@ -54,11 +55,12 @@ class Packetizer(RemoteSink):
self.should_run = False
self.source = None
self.transmit_failure = False
self.squelched = False
self.__failure_calback = failure_callback
def handle_frame(self, frame, source=None):
if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE:
return
if type(self.destination) == RNS.Link and not self.destination.status == RNS.Link.ACTIVE: return
if self.squelched: return
# TODO: Add inband signalling scheduler
frame = codec_header_byte(type(self.source.codec))+frame
@@ -94,8 +96,9 @@ class Packetizer(RemoteSink):
RNS.log(f"{self} starting", RNS.LOG_DEBUG)
self.should_run = True
def stop(self):
self.should_run = False
def stop(self): self.should_run = False
def squelch(self): self.squelched = True
def unsquelch(self): self.squelched = False
class LinkSource(RemoteSource, SignallingReceiver):
def __init__(self, link, signalling_receiver, sink=None):
@@ -128,10 +131,8 @@ class LinkSource(RemoteSource, SignallingReceiver):
else:
decoded_frame = self.codec.decode(frame[1:])
if self.pipeline:
self.sink.handle_frame(decoded_frame, self)
else:
self.sink.handle_frame(decoded_frame, self, decoded=True)
if self.pipeline: self.sink.handle_frame(decoded_frame, self)
else: self.sink.handle_frame(decoded_frame, self, decoded=True)
if FIELD_SIGNALLING in unpacked:
super()._packet(data=None, packet=packet, unpacked=unpacked)
+25 -18
View File
@@ -1,3 +1,7 @@
# Copyright 2024-2026, Mark Qvist
import threading
from .Sources import *
from .Sinks import *
from .Codecs import *
@@ -8,6 +12,8 @@ class PipelineError(Exception):
pass
class Pipeline():
release_lock = threading.Lock()
def __init__(self, source, codec, sink, processor = None):
if not issubclass(type(source), Source): raise PipelineError("Audio pipeline initialised with invalid source")
if not issubclass(type(sink), Sink) : raise PipelineError("Audio pipeline initialised with invalid sink")
@@ -18,19 +24,24 @@ class Pipeline():
self.source.sink = sink
self.codec = codec
if isinstance(sink, Loopback):
sink.samplerate = source.samplerate
if isinstance(source, Loopback):
source._sink = sink
if isinstance(sink, Packetizer):
sink.source = source
if isinstance(sink, Loopback): sink.samplerate = source.samplerate
if isinstance(source, Loopback): source._sink = sink
if isinstance(source, Mixer): source._sink = sink
if isinstance(sink, Packetizer): sink.source = source
if isinstance(sink, OpusFileSink): sink.source = source
def release(self):
if self.release_lock.locked(): return
with self.release_lock:
if not hasattr(self, "released") or not self.released:
self.released = True
self.source = None
self._codec = None
@property
def codec(self):
if self.source:
return self.source.codec
else:
return None
if self.source: return self.source.codec
else: return None
@codec.setter
def codec(self, codec):
@@ -42,19 +53,15 @@ class Pipeline():
@property
def sink(self):
if self.source:
return self.source.sink
else:
return None
if self.source: return self.source.sink
else: return None
@property
def running(self):
return self.source.should_run
def start(self):
if not self.running:
self.source.start()
if not self.running: self.source.start()
def stop(self):
if self.running:
self.source.stop()
if self.running: self.source.stop()
+267 -85
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import atexit
import collections.abc
import time
@@ -81,28 +83,28 @@ class _AndroidAudio:
# Populate device type descriptions from JNI
self.device_type_descriptions = {
adi.TYPE_AUX_LINE: "Aux Line", # 0x13 - API level 23
adi.TYPE_BLUETOOTH_A2DP: "Bluetooth A2DP", # 0x08 - API level 23
adi.TYPE_BLUETOOTH_SCO: "Bluetooth SCO", # 0x07 - API level 23
adi.TYPE_AUX_LINE: "Aux Line", # 0x13 - API level 23
adi.TYPE_BLUETOOTH_A2DP: "Bluetooth A2DP", # 0x08 - API level 23
adi.TYPE_BLUETOOTH_SCO: "Bluetooth SCO", # 0x07 - API level 23
adi.TYPE_BUILTIN_EARPIECE: "Internal Earpiece", # 0x01 - API level 23
adi.TYPE_BUILTIN_MIC: "Internal Microphone", # 0x0f - API level 23
adi.TYPE_BUILTIN_SPEAKER: "Internal Speaker", # 0x02 - API level 23
adi.TYPE_DOCK: "Dock", # 0x0d - API level 23
adi.TYPE_FM: "FM", # 0x0e - API level 23
adi.TYPE_FM_TUNER: "FM Tuner", # 0x10 - API level 23
adi.TYPE_HDMI: "HDMI", # 0x09 - API level 23
adi.TYPE_HDMI_ARC: "HDMI ARC", # 0x0a - API level 23
adi.TYPE_IP: "IP", # 0x14 - API level 23
adi.TYPE_LINE_ANALOG: "Analog Line", # 0x05 - API level 23
adi.TYPE_LINE_DIGITAL: "Digital Line", # 0x06 - API level 23
adi.TYPE_TELEPHONY: "Telephony", # 0x12 - API level 23
adi.TYPE_TV_TUNER: "TV Tuner", # 0x11 - API level 23
adi.TYPE_UNKNOWN: "Unknown", # 0x00 - API level 23
adi.TYPE_USB_ACCESSORY: "USB Accessory", # 0x0c - API level 23
adi.TYPE_USB_DEVICE: "USB Device", # 0x0b - API level 23
adi.TYPE_WIRED_HEADPHONES: "Wired Headphones", # 0x04 - API level 23
adi.TYPE_WIRED_HEADSET: "Wired Headset", # 0x03 - API level 23
adi.TYPE_BUS: "Bus", # 0x15 - API level 24
adi.TYPE_BUILTIN_MIC: "Internal Microphone", # 0x0f - API level 23
adi.TYPE_BUILTIN_SPEAKER: "Internal Speaker", # 0x02 - API level 23
adi.TYPE_DOCK: "Dock", # 0x0d - API level 23
adi.TYPE_FM: "FM", # 0x0e - API level 23
adi.TYPE_FM_TUNER: "FM Tuner", # 0x10 - API level 23
adi.TYPE_HDMI: "HDMI", # 0x09 - API level 23
adi.TYPE_HDMI_ARC: "HDMI ARC", # 0x0a - API level 23
adi.TYPE_IP: "IP", # 0x14 - API level 23
adi.TYPE_LINE_ANALOG: "Analog Line", # 0x05 - API level 23
adi.TYPE_LINE_DIGITAL: "Digital Line", # 0x06 - API level 23
adi.TYPE_TELEPHONY: "Telephony", # 0x12 - API level 23
adi.TYPE_TV_TUNER: "TV Tuner", # 0x11 - API level 23
adi.TYPE_UNKNOWN: "Unknown", # 0x00 - API level 23
adi.TYPE_USB_ACCESSORY: "USB Accessory", # 0x0c - API level 23
adi.TYPE_USB_DEVICE: "USB Device", # 0x0b - API level 23
adi.TYPE_WIRED_HEADPHONES: "Wired Headphones", # 0x04 - API level 23
adi.TYPE_WIRED_HEADSET: "Wired Headset", # 0x03 - API level 23
adi.TYPE_BUS: "Bus", # 0x15 - API level 24
}
if self.android_api_version >= 26:
@@ -115,9 +117,9 @@ class _AndroidAudio:
self.device_type_descriptions[adi.TYPE_BUILTIN_SPEAKER_SAFE] = "Ringer Speaker" # 0x18 - API level 30
if self.android_api_version >= 31:
self.device_type_descriptions[adi.TYPE_BLE_HEADSET] = "BLE Headset" # 0x1a - API level 31
self.device_type_descriptions[adi.TYPE_BLE_SPEAKER] = "BLE Speaker" # 0x1b - API level 31
self.device_type_descriptions[adi.TYPE_HDMI_EARC] = "HDMI EARC" # 0x1d - API level 31
self.device_type_descriptions[adi.TYPE_BLE_HEADSET] = "BLE Headset" # 0x1a - API level 31
self.device_type_descriptions[adi.TYPE_BLE_SPEAKER] = "BLE Speaker" # 0x1b - API level 31
self.device_type_descriptions[adi.TYPE_HDMI_EARC] = "HDMI EARC" # 0x1d - API level 31
self.device_type_descriptions[adi.TYPE_REMOTE_SUBMIX] = "Remote Submix" # 0x19 - API level 31
if self.android_api_version >= 33:
@@ -130,7 +132,10 @@ class _AndroidAudio:
self.device_type_descriptions[adi.TYPE_MULTICHANNEL_GROUP] = "Multichannel Group" # 0x20 - API level 36
added_ids = []
available_devices = self.AudioManager.getAvailableCommunicationDevices()
found_ringer = False
virtual_ringers = []
if self.android_api_version < 31: available_devices = []
else: available_devices = self.AudioManager.getAvailableCommunicationDevices()
for device in available_devices:
try:
device_id = device.getId(); device_type = device.getType(); channel_counts = device.getChannelCounts()
@@ -144,10 +149,11 @@ class _AndroidAudio:
added_ids.append(device_id)
self.available_devices.append(d)
if type_description == "Ringer Speaker": found_ringer = True
if type_description in self.ADD_VIRT_RINGER_TYPES:
d = {"id": device_id+self.VIRTUAL_DEVICE_OFFSET, "name": device.getProductName(), "type": device_type, "type_description": "Ringer Speaker",
"channel_counts": channel_counts, "is_source": device.isSource(), "is_sink": device.isSink(), "is_comms": False, "is_virtual": True}
self.available_devices.append(d)
virtual_ringers.append(d)
except Exception as e:
RNS.log(f"An error occurred while mapping available communications devices: {e}", RNS.LOG_ERROR)
@@ -166,15 +172,27 @@ class _AndroidAudio:
"is_source": device.isSource(), "is_sink": device.isSink(), "is_comms": False, "is_virtual": False}
added_ids.append(device_id)
self.available_devices.append(d)
if type_description == "Ringer Speaker": found_ringer = True
if type_description in self.ADD_VIRT_RINGER_TYPES:
d = {"id": device_id+self.VIRTUAL_DEVICE_OFFSET, "name": device.getProductName(), "type": device_type, "type_description": "Ringer Speaker",
"channel_counts": channel_counts, "is_source": device.isSource(), "is_sink": device.isSink(), "is_comms": False, "is_virtual": True}
virtual_ringers.append(d)
except Exception as e:
RNS.log(f"An error occurred while mapping available audio devices: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
if not found_ringer:
RNS.log(f"No native ringer output available on device", RNS.LOG_DEBUG)
for virtual_ringer in virtual_ringers:
RNS.log(f"Adding virtual ringer {virtual_ringer}", RNS.LOG_DEBUG)
self.available_devices.append(virtual_ringer)
# TODO: Remove debug
# RNS.log(f"Discovered audio devices:", RNS.LOG_DEBUG)
# for d in self.available_devices:
# RNS.log(f" {d}", RNS.LOG_DEBUG)
RNS.log(f"Discovered audio devices:", RNS.LOG_DEBUG)
for d in self.available_devices:
RNS.log(f" {d}", RNS.LOG_DEBUG)
except Exception as e:
RNS.log(f"Error while initializing Android audio backend: {e}", RNS.LOG_ERROR)
@@ -402,6 +420,7 @@ class _Stream:
self.AudioManager = activity.getSystemService(autoclass("android.media.AudioManager"))
self.AudioTrack = autoclass("android.media.AudioTrack")
self.AudioRecord = autoclass("android.media.AudioRecord")
self.AudioFormat = autoclass("android.media.AudioFormat")
self.AudioDeviceInfo = autoclass("android.media.AudioDeviceInfo")
@@ -425,45 +444,110 @@ class _Stream:
# selecting matching sources in the setCommunicationDevice API
if target_device_info["is_sink"]:
target_device_id = target_device_info["id"]
if target_device_info["is_virtual"]: target_device_id -= _audio.VIRTUAL_DEVICE_OFFSET
available_devices = self.AudioManager.getAvailableCommunicationDevices()
for device in available_devices:
device_id = device.getId(); device_type = device.getType()
if target_device_id == device_id:
if _audio.android_api_version >= 34:
RNS.log(f"Running on API level {_audio.android_api_version}, setting via setCommunicationDevice", RNS.LOG_DEBUG)
if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.audio_mode = "communication"
self.enabled_comms = True
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
elif target_device_info["type_description"] == "Ringer Speaker":
self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
self.audio_mode = "ringer"
RNS.log("Enabled ringer audio mode", RNS.LOG_DEBUG)
else:
self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
self.audio_mode = "normal"
RNS.log("Enabled nomal audio mode", RNS.LOG_DEBUG)
if self.AudioManager.setCommunicationDevice(device):
RNS.log(f"Successfully configured communication device to: {device} / {device.getType()}", RNS.LOG_DEBUG)
break
if target_device_info["is_virtual"]:
RNS.log(f"{self} USING VIRTUAL RINGER")
target_device_id -= _audio.VIRTUAL_DEVICE_OFFSET
if _audio.android_api_version < 31:
available_devices = self.AudioManager.getDevices(self.AudioManager.GET_DEVICES_ALL)
comms_devices = []
else:
available_devices = self.AudioManager.getDevices(self.AudioManager.GET_DEVICES_ALL)
comms_devices = self.AudioManager.getAvailableCommunicationDevices()
target_device = None
is_comms_device = False
is_ringer_device = False
for device in comms_devices:
if target_device_id == device.getId():
target_device = device
is_comms_device = True
break
if target_device == None:
for device in available_devices:
if target_device_id == device.getId():
target_device = device
is_comms_device = False
break
device_id = device.getId()
device_type = device.getType()
if target_device_info["type_description"] == "Ringer Speaker":
self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
self.audio_mode = "ringer"
RNS.log("Enabled ringer audio mode", RNS.LOG_DEBUG)
else:
if _audio.android_api_version >= 34:
if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.audio_mode = "communication"
self.enabled_comms = True
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
if is_comms_device:
RNS.log(f"Running on API level {_audio.android_api_version}, setting via setCommunicationDevice", RNS.LOG_DEBUG)
if self.AudioManager.setCommunicationDevice(device):
RNS.log(f"Successfully configured communication device to: {device} / {device.getType()}", RNS.LOG_DEBUG)
else:
RNS.log(f"Running on API level {_audio.android_api_version}, setting via setSpeakerphoneOn", RNS.LOG_DEBUG)
if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.AudioManager.setSpeakerphoneOn(False)
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
else:
# API levels < 34, we'll apparently have to set communications mode
# no matter what, since otherwise the microphone will be muted.
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.AudioManager.setSpeakerphoneOn(True)
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
self.audio_mode = "normal"
RNS.log("Enabled normal audio mode", RNS.LOG_DEBUG)
else:
RNS.log(f"Running on API level {_audio.android_api_version}, setting via setSpeakerphoneOn", RNS.LOG_DEBUG)
if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.AudioManager.setSpeakerphoneOn(False)
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
else:
# API levels < 34, we'll apparently have to set communications mode
# no matter what, since otherwise the microphone will be muted.
self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
self.AudioManager.setSpeakerphoneOn(True)
RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
# for device in available_devices:
# device_id = device.getId(); device_type = device.getType()
# if target_device_id == device_id:
# if _audio.android_api_version >= 34:
# RNS.log(f"Running on API level {_audio.android_api_version}, setting via setCommunicationDevice", RNS.LOG_DEBUG)
# if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
# self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
# self.audio_mode = "communication"
# self.enabled_comms = True
# RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
# elif target_device_info["type_description"] == "Ringer Speaker":
# self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
# self.audio_mode = "ringer"
# RNS.log("Enabled ringer audio mode", RNS.LOG_DEBUG)
# else:
# self.AudioManager.setMode(self.AudioManager.MODE_NORMAL)
# self.audio_mode = "normal"
# RNS.log("Enabled normal audio mode", RNS.LOG_DEBUG)
# if self.AudioManager.setCommunicationDevice(device):
# RNS.log(f"Successfully configured communication device to: {device} / {device.getType()}", RNS.LOG_DEBUG)
# break
# else:
# RNS.log(f"Running on API level {_audio.android_api_version}, setting via setSpeakerphoneOn", RNS.LOG_DEBUG)
# if device_type in _audio.device_type_descriptions and _audio.device_type_descriptions[device_type] in _audio.COMMUNICATION_MODE_TYPES:
# self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
# self.AudioManager.setSpeakerphoneOn(False)
# RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
# else:
# # API levels < 34, we'll apparently have to set communications mode
# # no matter what, since otherwise the microphone will be muted.
# self.AudioManager.setMode(self.AudioManager.MODE_IN_COMMUNICATION)
# self.AudioManager.setSpeakerphoneOn(True)
# RNS.log("Enabled communications audio mode", RNS.LOG_DEBUG)
if self.channels == 1:
self.audio_format_out = self.AudioFormat.CHANNEL_OUT_MONO
@@ -475,8 +559,8 @@ class _Stream:
else: raise ValueError(f"Unsupported channel count {channels} on Android audio backend")
self.min_buffer_playback = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_out, self.audio_encoding);
self.min_buffer_recording = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding);
self.min_buffer_playback = self.AudioTrack.getMinBufferSize(self._samplerate, self.audio_format_out, self.audio_encoding)
self.min_buffer_recording = self.AudioRecord.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding)
self.bytes_per_sample = (self.bit_depth//8)*self.channels
self._samplerate = int(self.AudioManager.getProperty(self.AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE))
@@ -567,7 +651,9 @@ class _Player(_Stream):
aa_builder.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
self.performance_mode = AudioTrack.PERFORMANCE_MODE_NONE
aa_builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_NONE)
if _audio.android_api_version >= 29:
aa_builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_NONE)
self.audio_attributes = aa_builder.build()
af_builder = AudioFormatBuilder()
@@ -617,6 +703,11 @@ class _Player(_Stream):
while data.nbytes > 0:
samples_bytes = data.ravel().tobytes()
written_bytes = self.audio_track.write(samples_bytes, 0, len(samples_bytes), self._write_mode)
if written_bytes < 0:
RNS.log(f"{self} frame write error: {written_bytes}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return
written_samples = written_bytes//self.bytes_per_sample
if self._low_latency_activated:
@@ -632,6 +723,9 @@ class _Player(_Stream):
written_samples = remaining_frame_samples
# TODO: Remove debug
# RNS.log(f"Buffer overrun. Target buffer samples {self._target_buffer_samples}. Needed to write {remaining_frame_samples} samples / {len(samples_bytes)} bytes. Discarding {written_samples} input samples.")
else: time.sleep(0.001) # Yield thread, buffer full inside overrun lock window
if written_bytes == 0 and not self._low_latency_activated: time.sleep(0.001) # Yield thread, buffer full
data = data[written_samples:]
@@ -648,40 +742,108 @@ class _Player(_Stream):
# RNS.log(f"{delta} underruns on {self}")
class _Recorder(_Stream):
READ_MODE_FAST = "fast"
READ_MODE_LEGACY = "legacy"
READ_MODE_FAUX = "faux"
READ_MODE = READ_MODE_FAST
DBG_READ_PACING = 0.0
def __init__(self, *args, **kwargs):
super(_Recorder, self).__init__(*args, **kwargs)
self.AudioRecord = autoclass("android.media.AudioRecord")
self._pending_chunk = numpy.zeros((0, ), dtype='float32')
self._pending_chunk = numpy.zeros((0, ), dtype='float32')
self._helper_service = None
self._helper_ok = False
def _connect_stream(self):
try:
AudioSource = autoclass("android.media.MediaRecorder$AudioSource")
self.min_buffer_recording = self.AudioRecord.getMinBufferSize(self._samplerate, self.audio_format_in, self.audio_encoding)
self.audio_record = self.AudioRecord(AudioSource.VOICE_COMMUNICATION, self._samplerate, self.audio_format_in, self.audio_encoding, self.min_buffer_recording)
buffer_target_ms = 200
buffer_target_samples = int((self._samplerate/1000)*buffer_target_ms)
buffer_target_bytes = buffer_target_samples*self.bytes_per_sample
# RNS.log(f"hz={self._samplerate}, Bps={self.bytes_per_sample}, bd={self.bit_depth}, ch={self.channels}, mbr={self.min_buffer_recording}")
# RNS.log(f"ms={buffer_target_ms}, smpls={buffer_target_samples}, bytes={buffer_target_bytes}")
if buffer_target_bytes < self.min_buffer_recording: buffer_target_bytes = self.min_buffer_recording
self.audio_record = self.AudioRecord(AudioSource.VOICE_COMMUNICATION, self._samplerate, self.audio_format_in, self.audio_encoding, buffer_target_bytes)
self.audio_record.startRecording()
if _Recorder.READ_MODE == _Recorder.READ_MODE_FAST: self.__check_read_helper()
except Exception as e:
RNS.log(f"Error while connecting input audio stream via JNI: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
def _record_chunk(self):
def __check_read_helper(self):
try:
audio_data = bytearray(self.min_buffer_recording)
bytes_read = self.audio_record.read(audio_data, 0, self.min_buffer_recording, self.audio_record.READ_NON_BLOCKING)
if bytes_read == 0: time.sleep(0.005)
service = autoclass("org.kivy.android.PythonService").mService
if service == None: raise AttributeError("No PythonService instance available")
probe = service.audioRecordRead(self.audio_record, 0, self.audio_record.READ_NON_BLOCKING)
if probe == None: raise AttributeError("audioRecordRead returned None for probe")
if len(probe) != 0: raise ValueError("audioRecordRead probe returned unexpected data")
self._helper_service = service
self._helper_ok = True
RNS.log(f"{self} using audio read helper", RNS.LOG_DEBUG)
return
if bytes_read == self.audio_record.ERROR_INVALID_OPERATION: RNS.log(f"Invalid operation error from JNI on {self}", RNS.LOG_ERROR)
elif bytes_read == self.audio_record.ERROR_BAD_VALUE: RNS.log(f"Bad value error from JNI on {self}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"{self} audio read helper not available, using legacy read path: {e}", RNS.LOG_DEBUG)
self._helper_service = None
self._helper_ok = False
def _read_fast(self, read_bytes, read_mode):
result = self._helper_service.audioRecordRead(self.audio_record, int(read_bytes), int(read_mode))
if result == None:
bytes_read = -1
RNS.log(f"{self} audio read error in helper", RNS.LOG_ERROR)
return None
bytes_read = len(result)
if bytes_read == 0: return numpy.zeros((0, ), dtype="float32")
else:
recorded_samples = numpy.frombuffer(result.tostring(), dtype="int16")/self.TYPE_MAP_FACTOR
return recorded_samples.astype("float32")
def _read_legacy(self, read_bytes, read_mode):
audio_data = bytearray(int(read_bytes))
bytes_read = self.audio_record.read(audio_data, 0, read_bytes, read_mode)
if bytes_read == self.audio_record.ERROR_INVALID_OPERATION: RNS.log(f"Invalid operation error from JNI on {self}", RNS.LOG_ERROR)
elif bytes_read == self.audio_record.ERROR_BAD_VALUE: RNS.log(f"Bad value error from JNI on {self}", RNS.LOG_ERROR)
elif bytes_read < 0: RNS.log(f"Audio read error ({bytes_read}) on {self}", RNS.LOG_ERROR)
elif bytes_read == 0: return numpy.zeros((0, ), dtype="float32")
else:
recorded_samples = numpy.frombuffer(audio_data[:bytes_read], dtype="int16")/self.TYPE_MAP_FACTOR
return recorded_samples.astype("float32")
# Debug-only faux-read shim
def _read_faux(self, read_bytes, read_mode):
bytes_read = int(read_bytes)
audio_data = bytes(bytes_read)
time.sleep(bytes_read/self.bytes_per_sample/self._samplerate)
return numpy.zeros((bytes_read//2, ), dtype="float32")
def _record_chunk(self, read_bytes=None):
try:
if read_bytes:
read_mode = self.audio_record.READ_BLOCKING
else:
recorded_samples = numpy.frombuffer(audio_data[:bytes_read], dtype="int16")/self.TYPE_MAP_FACTOR
return recorded_samples.astype("float32")
read_bytes = self.min_buffer_recording
read_mode = self.audio_record.READ_NON_BLOCKING
if _Recorder.READ_MODE == _Recorder.READ_MODE_FAUX: chunk = self._read_faux(read_bytes, read_mode)
elif _Recorder.READ_MODE == _Recorder.READ_MODE_FAST and self._helper_ok: chunk = self._read_fast(read_bytes, read_mode)
else: chunk = self._read_legacy(read_bytes, read_mode)
if _Recorder.DBG_READ_PACING > 0 and _Recorder.READ_MODE != _Recorder.READ_MODE_FAUX: time.sleep(_Recorder.DBG_READ_PACING)
return chunk
except Exception as e:
RNS.log(f"Error while reading audio chunk: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
return None
def record(self, numframes=None):
if numframes is None: return numpy.reshape(numpy.concatenate([self.flush().ravel(), self._record_chunk()]), [-1, self.channels])
else:
@@ -692,10 +854,30 @@ class _Recorder(_Stream):
return numpy.reshape(keep, [-1, self.channels])
else:
timeout = time.time()+(numframes/self._samplerate)*8
while captured_frames < numframes:
chunk = self._record_chunk()
captured_data.append(chunk)
captured_frames += len(chunk)/self.channels
if time.time() > timeout:
RNS.log(f"{self} capture timed out at {captured_frames} out of {numframes} frames, emitting silence", RNS.LOG_WARNING)
self._pending_chunk = numpy.zeros((0, ), dtype="float32")
return numpy.zeros((int(numframes), self.channels), dtype="float32")
try:
m_frames = numframes - captured_frames
m_bytes = m_frames * self.bytes_per_sample
# RNS.log(f"RECORD {m_bytes} bytes ({m_frames} samples) (min {self.min_buffer_recording})") # TODO: Remove
chunk = self._record_chunk(read_bytes=m_bytes)
captured_data.append(chunk)
captured_frames += len(chunk)/self.channels
if captured_frames < numframes:
wait_factor=0.65
m_frames = numframes - captured_frames
st = (m_frames / self._samplerate) * wait_factor
# RNS.log(f"Missing {m_frames}/{numframes} samples, sleeping for {RNS.prettyshorttime(st)}") # TODO: Remove
time.sleep(st)
except Exception as e:
RNS.log(f"Could not acquire audio frame: {e}", RNS.LOG_WARNING)
return None
to_split = int(len(chunk) - (captured_frames - numframes) * self.channels)
captured_data[-1], self._pending_chunk = numpy.split(captured_data[-1], [to_split])
View File
Whitespace-only changes.
+261
View File
@@ -0,0 +1,261 @@
// All files are found in /System/Library/Frameworks
// CoreFoundation/CFBase.h:
typedef unsigned char Boolean;
typedef unsigned char UInt8;
typedef signed char SInt8;
typedef unsigned short UInt16;
typedef signed short SInt16;
typedef unsigned int UInt32;
typedef signed int SInt32;
typedef uint64_t UInt64;
typedef int64_t SInt64;
typedef SInt32 OSStatus;
typedef float Float32;
typedef double Float64;
typedef unsigned short UniChar;
typedef unsigned long UniCharCount;
typedef unsigned char * StringPtr;
typedef const unsigned char * ConstStringPtr;
typedef unsigned char Str255[256];
typedef const unsigned char * ConstStr255Param;
typedef SInt16 OSErr;
typedef SInt16 RegionCode;
typedef SInt16 LangCode;
typedef SInt16 ScriptCode;
typedef UInt32 FourCharCode;
typedef FourCharCode OSType;
typedef UInt8 Byte;
typedef SInt8 SignedByte;
typedef UInt32 UTF32Char;
typedef UInt16 UTF16Char;
typedef UInt8 UTF8Char;
typedef signed long long CFIndex;
typedef const void * CFStringRef;
// CoreFoundation/CFString.h
typedef UInt32 CFStringEncoding;
CFIndex CFStringGetLength(CFStringRef theString);
Boolean CFStringGetCString(CFStringRef theString, char *buffer, CFIndex bufferSize, CFStringEncoding encoding);
// CoreFoundation/CFRunLoop.h
typedef struct __CFRunLoop * CFRunLoopRef;
// CoreAudio/AudioHardwareBase.h
typedef UInt32 AudioObjectID;
typedef UInt32 AudioObjectPropertySelector;
typedef UInt32 AudioObjectPropertyScope;
typedef UInt32 AudioObjectPropertyElement;
struct AudioObjectPropertyAddress
{
AudioObjectPropertySelector mSelector;
AudioObjectPropertyScope mScope;
AudioObjectPropertyElement mElement;
};
typedef struct AudioObjectPropertyAddress AudioObjectPropertyAddress;
// CoreAudio/AudioHardware.h
Boolean AudioObjectHasProperty(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress);
OSStatus AudioObjectGetPropertyDataSize(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32* outDataSize);
OSStatus AudioObjectGetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32* ioDataSize,
void* outData);
OSStatus AudioObjectSetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inQualifierDataSize,
const void* inQualifierData,
UInt32 inDataSize,
const void* inData);
// CoreAudioTypes.h
typedef UInt32 AudioFormatID;
typedef UInt32 AudioFormatFlags;
struct AudioStreamBasicDescription
{
Float64 mSampleRate;
AudioFormatID mFormatID;
AudioFormatFlags mFormatFlags;
UInt32 mBytesPerPacket;
UInt32 mFramesPerPacket;
UInt32 mBytesPerFrame;
UInt32 mChannelsPerFrame;
UInt32 mBitsPerChannel;
UInt32 mReserved;
};
typedef struct AudioStreamBasicDescription AudioStreamBasicDescription;
struct AudioStreamPacketDescription
{
SInt64 mStartOffset;
UInt32 mVariableFramesInPacket;
UInt32 mDataByteSize;
};
typedef struct AudioStreamPacketDescription AudioStreamPacketDescription;
// AudioToolbox/AudioQueue.h
// data structures:
struct SMPTETime
{
SInt16 mSubframes;
SInt16 mSubframeDivisor;
UInt32 mCounter;
UInt32 mType;
UInt32 mFlags;
SInt16 mHours;
SInt16 mMinutes;
SInt16 mSeconds;
SInt16 mFrames;
};
typedef struct SMPTETime SMPTETime;
struct AudioTimeStamp
{
Float64 mSampleTime;
UInt64 mHostTime;
Float64 mRateScalar;
UInt64 mWordClockTime;
SMPTETime mSMPTETime;
UInt32 mFlags;
UInt32 mReserved;
};
typedef struct AudioTimeStamp AudioTimeStamp;
// AudioComponent.h
typedef struct AudioComponentDescription {
OSType componentType;
OSType componentSubType;
OSType componentManufacturer;
UInt32 componentFlags;
UInt32 componentFlagsMask;
} AudioComponentDescription;
typedef struct OpaqueAudioComponent * AudioComponent;
typedef struct ComponentInstanceRecord * AudioComponentInstance;
AudioComponent AudioComponentFindNext(AudioComponent inComponent,
const AudioComponentDescription *inDesc);
OSStatus AudioComponentInstanceNew(AudioComponent inComponent,
AudioComponentInstance *outInstance);
OSStatus AudioComponentInstanceDispose(AudioComponentInstance inInstance);
OSStatus AudioComponentCopyName(AudioComponent inComponent,
CFStringRef *outName);
OSStatus AudioComponentGetDescription(AudioComponent inComponent,
AudioComponentDescription *outDesc);
// AUComponent.h
typedef AudioComponentInstance AudioUnit;
typedef UInt32 AudioUnitPropertyID;
typedef UInt32 AudioUnitScope;
typedef UInt32 AudioUnitElement;
OSStatus AudioUnitInitialize(AudioUnit inUnit);
OSStatus AudioUnitGetPropertyInfo(AudioUnit inUnit,
AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
UInt32 *outDataSize,
Boolean *outWritable);
OSStatus AudioUnitGetProperty(AudioUnit inUnit,
AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
void *outData,
UInt32 *ioDataSize);
OSStatus AudioUnitSetProperty(AudioUnit inUnit,
AudioUnitPropertyID inID,
AudioUnitScope inScope,
AudioUnitElement inElement,
const void *inData,
UInt32 inDataSize);
OSStatus AudioOutputUnitStart(AudioUnit ci);
OSStatus AudioOutputUnitStop(AudioUnit ci);
typedef UInt32 AudioUnitRenderActionFlags;
struct AudioBuffer
{
UInt32 mNumberChannels;
UInt32 mDataByteSize;
void* mData;
};
typedef struct AudioBuffer AudioBuffer;
struct AudioBufferList
{
UInt32 mNumberBuffers;
AudioBuffer mBuffers[]; // this is a variable length array of mNumberBuffers elements
};
typedef struct AudioBufferList AudioBufferList;
OSStatus AudioUnitProcess(AudioUnit inUnit,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inNumberFrames,
AudioBufferList *ioData);
OSStatus AudioUnitRender(AudioUnit inUnit,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp,
UInt32 inOutputBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData);
typedef OSStatus (*AURenderCallback)(void * inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData);
typedef struct AURenderCallbackStruct {
AURenderCallback inputProc;
void *inputProcRefCon;
} AURenderCallbackStruct;
struct AudioValueRange
{
Float64 mMinimum;
Float64 mMaximum;
};
typedef struct AudioValueRange AudioValueRange;
// AudioConverter.h
typedef struct OpaqueAudioConverter * AudioConverterRef;
typedef UInt32 AudioConverterPropertyID;
OSStatus AudioConverterNew(const AudioStreamBasicDescription *inSourceFormat,
const AudioStreamBasicDescription *inDestinationFormat,
AudioConverterRef *outAudioConverter);
OSStatus AudioConverterDispose(AudioConverterRef inAudioConverter);
typedef OSStatus (*AudioConverterComplexInputDataProc)(
AudioConverterRef inAudioConverter,
UInt32 *ioNumberDataPackets,
AudioBufferList *ioData,
AudioStreamPacketDescription **outDataPacketDescription,
void *inUserData);
extern OSStatus AudioConverterFillComplexBuffer(
AudioConverterRef inAudioConverter,
AudioConverterComplexInputDataProc inInputDataProc,
void *inInputDataProcUserData,
UInt32 *ioOutputDataPacketSize,
AudioBufferList *outOutputData,
AudioStreamPacketDescription *outPacketDescription);
extern OSStatus AudioConverterSetProperty(
AudioConverterRef inAudioConverter,
AudioConverterPropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void *inPropertyData);
extern OSStatus AudioConverterGetProperty(
AudioConverterRef inAudioConverter,
AudioConverterPropertyID inPropertyID,
UInt32 *ioPropertyDataSize,
void *outPropertyData);
+185
View File
@@ -0,0 +1,185 @@
# Adapted from Bastian Bechtold's soundcard library, originally released
# under the BSD 3-Clause License
#
# https://github.com/bastibe/SoundCard
#
# Copyright (c) 2016 Bastian Bechtold
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the copyright holder 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 COPYRIGHT
# HOLDER 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.
#
# Modifications and improvements Copyright 2025 Mark Qvist, and released
# under the same BSD 3-Clause License.
kAudioObjectSystemObject = 1
kAudioHardwarePropertyDevices = int.from_bytes(b'dev#', byteorder='big')
kAudioHardwarePropertyDefaultInputDevice = int.from_bytes(b'dIn ', byteorder='big')
kAudioHardwarePropertyDefaultOutputDevice = int.from_bytes(b'dOut', byteorder='big')
kAudioObjectPropertyScopeGlobal = int.from_bytes(b'glob', byteorder='big')
kAudioObjectPropertyScopeInput = int.from_bytes(b'inpt', byteorder='big')
kAudioObjectPropertyScopeOutput = int.from_bytes(b'outp', byteorder='big')
kAudioObjectPropertyScopePlayThrough = int.from_bytes(b'ptru', byteorder='big')
kAudioObjectPropertyName = int.from_bytes(b'lnam', byteorder='big')
kAudioObjectPropertyModelName = int.from_bytes(b'lmod', byteorder='big')
kAudioObjectPropertyManufacturer = int.from_bytes(b'lmak', byteorder='big')
kAudioDevicePropertyNominalSampleRate = int.from_bytes(b'nsrt', byteorder='big')
kAudioDevicePropertyBufferFrameSize = int.from_bytes(b'fsiz', byteorder='big')
kAudioDevicePropertyBufferFrameSizeRange = int.from_bytes(b'fsz#', byteorder='big')
kAudioDevicePropertyUsesVariableBufferFrameSizes = int.from_bytes(b'vfsz', byteorder='big')
kAudioDevicePropertyStreamConfiguration = int.from_bytes(b'slay', byteorder='big')
kCFStringEncodingUTF8 = 0x08000100
kAudioObjectPropertyElementMaster = 0
kAudioUnitType_Output = int.from_bytes(b'auou', byteorder='big')
kAudioUnitManufacturer_Apple = int.from_bytes(b'appl', byteorder='big')
kAudioUnitSubType_GenericOutput = int.from_bytes(b'genr', byteorder='big')
kAudioUnitSubType_HALOutput = int.from_bytes(b'ahal', byteorder='big')
kAudioUnitSubType_DefaultOutput = int.from_bytes(b'def ', byteorder='big')
# The audio unit can do input from the device as well as output to the
# device. Bus 0 is used for the output side, bus 1 is used to get audio
# input from the device.
outputbus = 0
inputbus = 1
def error_number_to_string(num):
if num == kAudioUnitErr_InvalidProperty:
return "The property is not supported"
elif num == kAudioUnitErr_InvalidParameter:
return "The parameter is not supported"
elif num == kAudioUnitErr_InvalidElement:
return "The specified element is not valid"
elif num == kAudioUnitErr_NoConnection:
return "There is no connection (generally an audio unit is asked to render but it has" \
" not input from which to gather data)"
elif num == kAudioUnitErr_FailedInitialization:
return "The audio unit is unable to be initialized"
elif num == kAudioUnitErr_TooManyFramesToProcess:
return "When an audio unit is initialized it has a value which specifies the max" \
" number of frames it will be asked to render at any given time. If an audio" \
" unit is asked to render more than this, this error is returned."
elif num == kAudioUnitErr_InvalidFile:
return "If an audio unit uses external files as a data source, this error is returned" \
" if a file is invalid (Apple's DLS synth returns this error)"
elif num == kAudioUnitErr_UnknownFileType:
return "If an audio unit uses external files as a data source, this error is returned" \
" if a file is invalid (Apple's DLS synth returns this error)"
elif num == kAudioUnitErr_FileNotSpecified:
return "If an audio unit uses external files as a data source, this error is returned" \
" if a file hasn't been set on it (Apple's DLS synth returns this error)"
elif num == kAudioUnitErr_FormatNotSupported:
return "Returned if an input or output format is not supported"
elif num == kAudioUnitErr_Uninitialized:
return "Returned if an operation requires an audio unit to be initialized and it is not."
elif num == kAudioUnitErr_InvalidScope:
return "The specified scope is invalid"
elif num == kAudioUnitErr_PropertyNotWritable:
return "The property cannot be written"
elif num == kAudioUnitErr_CannotDoInCurrentContext:
return "Returned when an audio unit is in a state where it can't perform the requested" \
" action now - but it could later. Its usually used to guard a render operation" \
" when a reconfiguration of its internal state is being performed."
elif num == kAudioUnitErr_InvalidPropertyValue:
return "The property is valid, but the value of the property being provided is not"
elif num == kAudioUnitErr_PropertyNotInUse:
return "Returned when a property is valid, but it hasn't been set to a valid value at this time."
elif num == kAudioUnitErr_Initialized:
return "Indicates the operation cannot be performed because the audio unit is initialized."
elif num == kAudioUnitErr_InvalidOfflineRender:
return "Used to indicate that the offline render operation is invalid. For instance," \
" when the audio unit needs to be pre-flighted, but it hasn't been."
elif num == kAudioUnitErr_Unauthorized:
return "Returned by either Open or Initialize, this error is used to indicate that the" \
" audio unit is not authorised, that it cannot be used. A host can then present" \
" a UI to notify the user the audio unit is not able to be used in its current state."
elif num == kAudioComponentErr_InstanceInvalidated:
return "the component instance's implementation is not available, most likely because the process" \
" that published it is no longer running"
else:
return "error number {}".format(num)
kAudioUnitErr_InvalidProperty = -10879
kAudioUnitErr_InvalidParameter = -10878
kAudioUnitErr_InvalidElement = -10877
kAudioUnitErr_NoConnection = -10876
kAudioUnitErr_FailedInitialization = -10875
kAudioUnitErr_TooManyFramesToProcess = -10874
kAudioUnitErr_InvalidFile = -10871
kAudioUnitErr_UnknownFileType = -10870
kAudioUnitErr_FileNotSpecified = -10869
kAudioUnitErr_FormatNotSupported = -10868
kAudioUnitErr_Uninitialized = -10867
kAudioUnitErr_InvalidScope = -10866
kAudioUnitErr_PropertyNotWritable = -10865
kAudioUnitErr_CannotDoInCurrentContext = -10863
kAudioUnitErr_InvalidPropertyValue = -10851
kAudioUnitErr_PropertyNotInUse = -10850
kAudioUnitErr_Initialized = -10849
kAudioUnitErr_InvalidOfflineRender = -10848
kAudioUnitErr_Unauthorized = -10847
kAudioComponentErr_InstanceInvalidated = -66749
kAudioUnitErr_RenderTimeout = -66745
kAudioOutputUnitProperty_CurrentDevice = 2000
kAudioOutputUnitProperty_EnableIO = 2003 # scope output, element 0 == output,
kAudioOutputUnitProperty_HasIO = 2006 # scope input, element 1 == input
kAudioOutputUnitProperty_IsRunning = 2001
kAudioOutputUnitProperty_ChannelMap = 2002
kAudioFormatLinearPCM = int.from_bytes(b'lpcm', byteorder='big')
kAudioFormatFlagIsFloat = 0x1
kAudioUnitProperty_StreamFormat = 8
kAudioUnitProperty_CPULoad = 6
kAudioUnitProperty_Latency = 12
kAudioUnitProperty_SupportedNumChannels = 13
kAudioUnitProperty_MaximumFramesPerSlice = 14
kAudioUnitProperty_SetRenderCallback = 23
kAudioOutputUnitProperty_SetInputCallback = 2005
kAudioUnitProperty_StreamFormat = 8
kAudioUnitProperty_SampleRate = 2
kAudioUnitProperty_ContextName = 25
kAudioUnitProperty_ElementName = 30
kAudioUnitProperty_NickName = 54
kAudioUnitRenderAction_PreRender = 1 << 2
kAudioUnitRenderAction_PostRender = 1 << 3
kAudioUnitRenderAction_OutputIsSilence = 1 << 4
kAudioOfflineUnitRenderAction_Preflight = 1 << 5
kAudioOfflineUnitRenderAction_Render = 1 << 6
kAudioOfflineUnitRenderAction_Complete = 1 << 7
kAudioUnitRenderAction_PostRenderError = 1 << 8
kAudioUnitRenderAction_DoNotCheckRenderArgs = 1 << 9
kAudioUnitScope_Global = 0 # The context for audio unit characteristics that apply to the audio unit as a whole
kAudioUnitScope_Input = 1 # The context for audio data coming into an audio unit
kAudioUnitScope_Output = 2 # The context for audio data leaving an audio unit
+945
View File
@@ -0,0 +1,945 @@
# Adapted from Bastian Bechtold's soundcard library, originally released
# under the BSD 3-Clause License
#
# https://github.com/bastibe/SoundCard
#
# Copyright (c) 2016 Bastian Bechtold
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the copyright holder 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 COPYRIGHT
# HOLDER 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.
#
# Modifications and improvements Copyright 2025 Mark Qvist, and released
# under the same BSD 3-Clause License.
import os
import cffi
import numpy
import collections
import time
import re
import math
import threading
import warnings
_ffi = cffi.FFI()
_package_dir, _ = os.path.split(__file__)
with open(os.path.join(_package_dir, 'coreaudio.h'), 'rt') as f:
_ffi.cdef(f.read())
_ca = _ffi.dlopen('CoreAudio')
_au = _ffi.dlopen('AudioUnit')
import LXST.Platforms.darwin.coreaudioconstants as _cac
def all_speakers():
"""A list of all connected speakers."""
device_ids = _CoreAudio.get_property(
_cac.kAudioObjectSystemObject,
_cac.kAudioHardwarePropertyDevices,
"AudioObjectID")
return [_Speaker(id=d) for d in device_ids
if _Speaker(id=d).channels > 0]
def all_microphones(include_loopback=False):
"""A list of all connected microphones."""
# macOS does not support loopback recording functionality
if include_loopback:
warnings.warn("macOS does not support loopback recording functionality", Warning)
device_ids = _CoreAudio.get_property(
_cac.kAudioObjectSystemObject,
_cac.kAudioHardwarePropertyDevices,
"AudioObjectID")
return [_Microphone(id=d) for d in device_ids
if _Microphone(id=d).channels > 0]
def default_speaker():
"""The default speaker of the system."""
device_id, = _CoreAudio.get_property(
_cac.kAudioObjectSystemObject,
_cac.kAudioHardwarePropertyDefaultOutputDevice,
"AudioObjectID")
return _Speaker(id=device_id)
def get_speaker(id):
"""Get a specific speaker by a variety of means.
id can be an a CoreAudio id, a substring of the speaker name, or a
fuzzy-matched pattern for the speaker name.
"""
return _match_device(id, all_speakers())
def default_microphone():
"""The default microphone of the system."""
device_id, = _CoreAudio.get_property(
_cac.kAudioObjectSystemObject,
_cac.kAudioHardwarePropertyDefaultInputDevice,
"AudioObjectID")
return _Microphone(id=device_id)
def get_microphone(id, include_loopback=False):
"""Get a specific microphone by a variety of means.
id can be a CoreAudio id, a substring of the microphone name, or a
fuzzy-matched pattern for the microphone name.
"""
return _match_device(id, all_microphones(include_loopback))
def _match_device(id, devices):
"""Find id in a list of devices.
id can be a CoreAudio id, a substring of the device name, or a
fuzzy-matched pattern for the microphone name.
"""
devices_by_id = {device.id: device for device in devices}
devices_by_name = {device.name: device for device in devices}
if id in devices_by_id:
return devices_by_id[id]
# try substring match:
for name, device in devices_by_name.items():
if id in name:
return device
# try fuzzy match:
pattern = '.*'.join(id)
for name, device in devices_by_name.items():
if re.match(pattern, name):
return device
raise IndexError('no device with id {}'.format(id))
def get_name():
raise NotImplementedError()
def set_name(name):
raise NotImplementedError()
class _Soundcard:
"""A soundcard. This is meant to be subclassed.
Properties:
- `name`: the name of the soundcard
"""
def __init__(self, *, id):
self._id = id
@property
def id(self):
return self._id
@property
def name(self):
name = _CoreAudio.get_property(
self._id, _cac.kAudioObjectPropertyName, 'CFStringRef')
return _CoreAudio.CFString_to_str(name)
class _Speaker(_Soundcard):
"""A soundcard output. Can be used to play audio.
Use the `play` method to play one piece of audio, or use the
`player` method to get a context manager for playing continuous
audio.
Properties:
- `channels`: either the number of channels to play, or a list
of channel indices. Index -1 is silence, and subsequent numbers
are channel numbers (left, right, center, ...)
- `name`: the name of the soundcard
"""
@property
def channels(self):
bufferlist = _CoreAudio.get_property(
self._id,
_cac.kAudioDevicePropertyStreamConfiguration,
'AudioBufferList', scope=_cac.kAudioObjectPropertyScopeOutput)
if bufferlist and bufferlist[0].mNumberBuffers > 0:
return bufferlist[0].mBuffers[0].mNumberChannels
else:
return 0
def __repr__(self):
return '<Speaker {} ({} channels)>'.format(self.name, self.channels)
def player(self, samplerate, channels=None, blocksize=None):
if channels is None:
channels = self.channels
return _Player(self._id, samplerate, channels, blocksize)
def play(self, data, samplerate, channels=None, blocksize=None):
if channels is None and len(data.shape) == 2:
channels = data.shape[1]
elif channels is None:
channels = self.channels
with self.player(samplerate, channels, blocksize) as p:
p.play(data)
class _Microphone(_Soundcard):
"""A soundcard input. Can be used to record audio.
Use the `record` method to record a piece of audio, or use the
`recorder` method to get a context manager for recording
continuous audio.
Properties:
- `channels`: either the number of channels to record, or a list
of channel indices. Index -1 is silence, and subsequent numbers
are channel numbers (left, right, center, ...)
- `name`: the name of the soundcard
"""
@property
def isloopback(self):
return False
@property
def channels(self):
bufferlist = _CoreAudio.get_property(
self._id,
_cac.kAudioDevicePropertyStreamConfiguration,
'AudioBufferList', scope=_cac.kAudioObjectPropertyScopeInput)
if bufferlist and bufferlist[0].mNumberBuffers > 0:
return bufferlist[0].mBuffers[0].mNumberChannels
else:
return 0
def __repr__(self):
return '<Microphone {} ({} channels)>'.format(self.name, self.channels)
def recorder(self, samplerate, channels=None, blocksize=None):
if channels is None:
channels = self.channels
return _Recorder(self._id, samplerate, channels, blocksize)
def record(self, numframes, samplerate, channels=None, blocksize=None):
if channels is None:
channels = self.channels
with self.recorder(samplerate, channels, blocksize) as p:
return p.record(numframes)
class _CoreAudio:
"""A helper class for interacting with CoreAudio."""
@staticmethod
def get_property(target, selector, ctype, scope=_cac.kAudioObjectPropertyScopeGlobal):
"""Get a CoreAudio property.
This might include things like a list of available sound
cards, or various meta data about those sound cards.
Arguments:
- `target`: The AudioObject that the property belongs to
- `selector`: The Selector for this property
- `scope`: The Scope for this property
- `ctype`: The type of the property
Returns:
A list of objects of type `ctype`
"""
prop = _ffi.new("AudioObjectPropertyAddress*",
{'mSelector': selector,
'mScope': scope,
'mElement': _cac.kAudioObjectPropertyElementMaster})
has_prop = _ca.AudioObjectHasProperty(target, prop)
assert has_prop == 1, 'Core Audio does not have the requested property'
size = _ffi.new("UInt32*")
err = _ca.AudioObjectGetPropertyDataSize(target, prop, 0, _ffi.NULL, size)
assert err == 0, "Can't get Core Audio property size"
num_values = int(size[0]//_ffi.sizeof(ctype))
prop_data = _ffi.new(ctype+'[]', num_values)
err = _ca.AudioObjectGetPropertyData(target, prop, 0, _ffi.NULL,
size, prop_data)
assert err == 0, "Can't get Core Audio property data"
return prop_data
@staticmethod
def set_property(target, selector, prop_data, scope=_cac.kAudioObjectPropertyScopeGlobal):
"""Set a CoreAudio property.
This is typically a piece of meta data about a sound card.
Arguments:
- `target`: The AudioObject that the property belongs to
- `selector`: The Selector for this property
- `scope`: The Scope for this property
- `prop_data`: The new property value
"""
prop = _ffi.new("AudioObjectPropertyAddress*",
{'mSelector': selector,
'mScope': scope,
'mElement': _cac.kAudioObjectPropertyElementMaster})
err = _ca.AudioObjectSetPropertyData(target, prop, 0, _ffi.NULL,
_ffi.sizeof(_ffi.typeof(prop_data).item.cname), prop_data)
assert err == 0, "Can't set Core Audio property data"
@staticmethod
def CFString_to_str(cfstrptr):
"""Converts a CFStringRef to a Python str."""
# Multiply by 4, the maximum number of bytes used per character in UTF-8.
str_length = _ca.CFStringGetLength(cfstrptr[0]) * 4
str_buffer = _ffi.new('char[]', str_length+1)
err = _ca.CFStringGetCString(cfstrptr[0], str_buffer, str_length+1, _cac.kCFStringEncodingUTF8)
assert err == 1, "Could not decode string"
return _ffi.string(str_buffer).decode()
class _Player:
"""A context manager for an active output stream.
Audio playback is available as soon as the context manager is
entered. Audio data can be played using the `play` method.
Successive calls to `play` will queue up the audio one piece after
another. If no audio is queued up, this will play silence.
This context manager can only be entered once, and can not be used
after it is closed.
"""
def __init__(self, id, samplerate, channels, blocksize=None):
self._au = _AudioUnit("output", id, samplerate, channels, blocksize)
def __enter__(self):
self._queue = collections.deque()
@_ffi.callback("AURenderCallback")
def render_callback(userdata, actionflags, timestamp,
busnumber, numframes, bufferlist):
for bufferidx in range(bufferlist.mNumberBuffers):
dest = bufferlist.mBuffers[bufferidx]
channels = dest.mNumberChannels
bytes_written = 0
to_write = dest.mDataByteSize
while bytes_written < to_write:
if self._queue:
data = self._queue.popleft()
srcbuffer = _ffi.from_buffer(data)
numbytes = min(len(srcbuffer), to_write-bytes_written)
_ffi.memmove(dest.mData+bytes_written, srcbuffer, numbytes)
if numbytes < len(srcbuffer):
leftover = data[numbytes//4//channels:]
self._queue.appendleft(leftover)
bytes_written += numbytes
else:
src = bytearray(to_write-bytes_written)
_ffi.memmove(dest.mData+bytes_written, src, len(src))
bytes_written += len(src)
return 0
self._au.set_callback(render_callback)
self._au.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self._au.close()
def play(self, data, wait=True):
"""Play some audio data.
Internally, all data is handled as float32 and with the
appropriate number of channels. For maximum performance,
provide data as a `frames × channels` float32 numpy array.
If single-channel or one-dimensional data is given, this data
will be played on all available channels.
This function will return *before* all data has been played,
so that additional data can be provided for gapless playback.
The amount of buffering can be controlled through the
blocksize of the player object.
If data is provided faster than it is played, later pieces
will be queued up and played one after another.
"""
data = numpy.asarray(data, dtype="float32", order='C')
data[data>1] = 1
data[data<-1] = -1
if data.ndim == 1:
data = data[:, None] # force 2d
if data.ndim != 2:
raise TypeError('data must be 1d or 2d, not {}d'.format(data.ndim))
if data.shape[1] == 1 and self._au.channels != 1:
data = numpy.tile(data, [1, self._au.channels])
if data.shape[1] != self._au.channels:
raise TypeError('second dimension of data must be equal to the number of channels, not {}'.format(data.shape[1]))
idx = 0
while idx < len(data)-self._au.blocksize:
self._queue.append(data[idx:idx+self._au.blocksize])
idx += self._au.blocksize
self._queue.append(data[idx:])
while self._queue and wait:
time.sleep(0.001)
class _AudioUnit:
"""Communication helper with AudioUnits.
This provides an abstraction over a single AudioUnit. Can be used
as soon as it instatiated.
Properties:
- `enableinput`, `enableoutput`: set up the AudioUnit for playback
or recording. It is not possible to record and play at the same
time.
- `device`: The numeric ID of the underlying CoreAudio device.
- `blocksize`: The amount of buffering in the AudioUnit. Values
outside of `blocksizerange` will be silently clamped to that
range.
- `blocksizerange`: The minimum and maximum possible block size.
- `samplerate`: The sampling rate of the CoreAudio device. This
will lead to errors if changed in a recording AudioUnit.
- `channels`: The number of channels of the AudioUnit.
"""
def __init__(self, iotype, device, samplerate, channels, blocksize):
self._iotype = iotype
desc = _ffi.new(
"AudioComponentDescription*",
dict(componentType=_cac.kAudioUnitType_Output,
componentSubType=_cac.kAudioUnitSubType_HALOutput,
componentFlags=0,
componentFlagsMask=0,
componentManufacturer=_cac.kAudioUnitManufacturer_Apple))
audiocomponent = _au.AudioComponentFindNext(_ffi.NULL, desc)
if not audiocomponent:
raise RuntimeError("could not find audio component")
self.ptr = _ffi.new("AudioComponentInstance*")
status = _au.AudioComponentInstanceNew(audiocomponent, self.ptr)
if status:
raise RuntimeError(_cac.error_number_to_string(status))
if iotype == 'input':
self.enableinput = True
self.enableoutput = False
self._au_scope = _cac.kAudioUnitScope_Output
self._au_element = 1
elif iotype == 'output':
self.enableinput = False
self.enableoutput = True
self._au_scope = _cac.kAudioUnitScope_Input
self._au_element = 0
self.device = device
blocksize = blocksize or self.blocksize
# Input AudioUnits can't use non-native sample rates.
# Therefore, if a non-native sample rate is requested, use a
# resampled block size and resample later, manually:
if iotype == 'input':
# Get the input device format
curr_device_format = self._get_property(_cac.kAudioUnitProperty_StreamFormat,
_cac.kAudioUnitScope_Input,
1,
"AudioStreamBasicDescription")
self.samplerate = curr_device_format[0].mSampleRate
self.resample = self.samplerate/samplerate
else:
self.resample = 1
self.samplerate = samplerate
# there are two maximum block sizes for some reason:
maxblocksize = min(self.blocksizerange[1],
self.maxblocksize)
if self.blocksizerange[0] <= blocksize <= maxblocksize:
self.blocksize = blocksize
else:
raise TypeError("blocksize must be between {} and {}"
.format(self.blocksizerange[0],
maxblocksize))
if isinstance(channels, collections.abc.Iterable):
if iotype == 'output':
# invert channel map and fill with -1 ([2, 0] -> [1, -1, 0]):
self.channels = len([c for c in channels if c >= 0])
channelmap = [-1]*(max(channels)+1)
for idx, c in enumerate(channels):
channelmap[c] = idx
self.channelmap = channelmap
else:
self.channels = len(channels)
self.channelmap = channels
elif isinstance(channels, int):
self.channels = channels
else:
raise TypeError('channels must be iterable or integer')
self._set_channels(self.channels)
def _set_property(self, property, scope, element, data):
if '[]' in _ffi.typeof(data).cname:
num_values = len(data)
else:
num_values = 1
status = _au.AudioUnitSetProperty(self.ptr[0],
property, scope, element,
data, _ffi.sizeof(_ffi.typeof(data).item.cname)*num_values)
if status != 0:
raise RuntimeError(_cac.error_number_to_string(status))
def _get_property(self, property, scope, element, type):
datasize = _ffi.new("UInt32*")
status = _au.AudioUnitGetPropertyInfo(self.ptr[0],
property, scope, element,
datasize, _ffi.NULL)
num_values = datasize[0]//_ffi.sizeof(type)
data = _ffi.new(type + '[{}]'.format(num_values))
status = _au.AudioUnitGetProperty(self.ptr[0],
property, scope, element,
data, datasize)
if status != 0:
raise RuntimeError(_cac.error_number_to_string(status))
# return trivial data trivially
if num_values == 1 and (type == "UInt32" or type == "Float64"):
return data[0]
else: # everything else, return the cdata, to keep it alive
return data
@property
def device(self):
return self._get_property(
_cac.kAudioOutputUnitProperty_CurrentDevice,
_cac.kAudioUnitScope_Global, 0, "UInt32")
@device.setter
def device(self, dev):
data = _ffi.new("UInt32*", dev)
self._set_property(
_cac.kAudioOutputUnitProperty_CurrentDevice,
_cac.kAudioUnitScope_Global, 0, data)
@property
def enableinput(self):
return self._get_property(
_cac.kAudioOutputUnitProperty_EnableIO,
_cac.kAudioUnitScope_Input, 1, "UInt32")
@enableinput.setter
def enableinput(self, yesno):
data = _ffi.new("UInt32*", yesno)
self._set_property(
_cac.kAudioOutputUnitProperty_EnableIO,
_cac.kAudioUnitScope_Input, 1, data)
@property
def enableoutput(self):
return self._get_property(
_cac.kAudioOutputUnitProperty_EnableIO,
_cac.kAudioUnitScope_Output, 0, "UInt32")
@enableoutput.setter
def enableoutput(self, yesno):
data = _ffi.new("UInt32*", yesno)
self._set_property(
_cac.kAudioOutputUnitProperty_EnableIO,
_cac.kAudioUnitScope_Output, 0, data)
@property
def samplerate(self):
return self._get_property(
_cac.kAudioUnitProperty_SampleRate,
self._au_scope, self._au_element, "Float64")
@samplerate.setter
def samplerate(self, samplerate):
data = _ffi.new("Float64*", samplerate)
self._set_property(
_cac.kAudioUnitProperty_SampleRate,
self._au_scope, self._au_element, data)
def _set_channels(self, channels):
streamformat = _ffi.new(
"AudioStreamBasicDescription*",
dict(mSampleRate=self.samplerate,
mFormatID=_cac.kAudioFormatLinearPCM,
mFormatFlags=_cac.kAudioFormatFlagIsFloat,
mFramesPerPacket=1,
mChannelsPerFrame=channels,
mBitsPerChannel=32,
mBytesPerPacket=channels * 4,
mBytesPerFrame=channels * 4))
self._set_property(
_cac.kAudioUnitProperty_StreamFormat,
self._au_scope, self._au_element, streamformat)
@property
def maxblocksize(self):
maxblocksize = self._get_property(
_cac.kAudioUnitProperty_MaximumFramesPerSlice,
_cac.kAudioUnitScope_Global, 0, "UInt32")
assert maxblocksize
return maxblocksize
@property
def channelmap(self):
scope = {2: 1, 1: 2}[self._au_scope]
map = self._get_property(
_cac.kAudioOutputUnitProperty_ChannelMap,
scope, self._au_element,
"SInt32")
last_meaningful = max(idx for idx, c in enumerate(map) if c != -1)
return list(map[0:last_meaningful+1])
@channelmap.setter
def channelmap(self, map):
scope = {2: 1, 1: 2}[self._au_scope]
cmap = _ffi.new("SInt32[]", map)
self._set_property(
_cac.kAudioOutputUnitProperty_ChannelMap,
scope, self._au_element,
cmap)
@property
def blocksizerange(self):
framesizerange = _CoreAudio.get_property(
self.device,
_cac.kAudioDevicePropertyBufferFrameSizeRange,
'AudioValueRange', scope=_cac.kAudioObjectPropertyScopeOutput)
assert framesizerange
return framesizerange[0].mMinimum, framesizerange[0].mMaximum
@property
def blocksize(self):
framesize = _CoreAudio.get_property(
self.device,
_cac.kAudioDevicePropertyBufferFrameSize,
'UInt32', scope=_cac.kAudioObjectPropertyScopeOutput)
assert framesize
return framesize[0]
@blocksize.setter
def blocksize(self, blocksize):
framesize = _ffi.new("UInt32*", blocksize)
status = _CoreAudio.set_property(
self.device,
_cac.kAudioDevicePropertyBufferFrameSize,
framesize, scope=_cac.kAudioObjectPropertyScopeOutput)
def set_callback(self, callback):
"""Set a callback function for the AudioUnit. """
if self._iotype == 'input':
callbacktype = _cac.kAudioOutputUnitProperty_SetInputCallback
elif self._iotype == 'output':
callbacktype = _cac.kAudioUnitProperty_SetRenderCallback
self._callback = callback
callbackstruct = _ffi.new(
"AURenderCallbackStruct*",
dict(inputProc=callback,
inputProcRefCon=_ffi.NULL))
self._set_property(
callbacktype,
_cac.kAudioUnitScope_Global, 0, callbackstruct)
def start(self):
"""Start processing audio, and start calling the callback."""
status = _au.AudioUnitInitialize(self.ptr[0])
if status:
raise RuntimeError(_cac.error_number_to_string(status))
status = _au.AudioOutputUnitStart(self.ptr[0])
if status:
raise RuntimeError(_cac.error_number_to_string(status))
def close(self):
"""Stop processing audio, and stop calling the callback."""
status = _au.AudioOutputUnitStop(self.ptr[0])
if status:
raise RuntimeError(_cac.error_number_to_string(status))
status = _au.AudioComponentInstanceDispose(self.ptr[0])
if status:
raise RuntimeError(_cac.error_number_to_string(status))
del self.ptr
# Here's how to do it: http://atastypixel.com/blog/using-remoteio-audio-unit/
# https://developer.apple.com/library/content/technotes/tn2091/_index.html
class _Resampler:
def __init__(self, fromsamplerate, tosamplerate, channels):
self.fromsamplerate = fromsamplerate
self.tosamplerate = tosamplerate
self.channels = channels
fromstreamformat = _ffi.new(
"AudioStreamBasicDescription*",
dict(mSampleRate=self.fromsamplerate,
mFormatID=_cac.kAudioFormatLinearPCM,
mFormatFlags=_cac.kAudioFormatFlagIsFloat,
mFramesPerPacket=1,
mChannelsPerFrame=self.channels,
mBitsPerChannel=32,
mBytesPerPacket=self.channels * 4,
mBytesPerFrame=self.channels * 4))
tostreamformat = _ffi.new(
"AudioStreamBasicDescription*",
dict(mSampleRate=self.tosamplerate,
mFormatID=_cac.kAudioFormatLinearPCM,
mFormatFlags=_cac.kAudioFormatFlagIsFloat,
mFramesPerPacket=1,
mChannelsPerFrame=self.channels,
mBitsPerChannel=32,
mBytesPerPacket=self.channels * 4,
mBytesPerFrame=self.channels * 4))
self.audioconverter = _ffi.new("AudioConverterRef*")
_au.AudioConverterNew(fromstreamformat, tostreamformat, self.audioconverter)
@_ffi.callback("AudioConverterComplexInputDataProc")
def converter_callback(converter, numberpackets, bufferlist, desc, userdata):
return self.converter_callback(converter, numberpackets, bufferlist, desc, userdata)
self._converter_callback = converter_callback
self.queue = []
self.blocksize = 512
self.outbuffer = _ffi.new("AudioBufferList*", [1, 1])
self.outbuffer.mNumberBuffers = 1
self.outbuffer.mBuffers[0].mNumberChannels = self.channels
self.outbuffer.mBuffers[0].mDataByteSize = self.blocksize*4*self.channels
self.outdata = _ffi.new("Float32[]", self.blocksize*self.channels)
self.outbuffer.mBuffers[0].mData = self.outdata
self.outsize = _ffi.new("UInt32*")
def converter_callback(self, converter, numberpackets, bufferlist, desc, userdata):
numframes = min(numberpackets[0], len(self.todo), self.blocksize)
raw_data = self.todo[:numframes].tobytes()
_ffi.memmove(self.outdata, raw_data, len(raw_data))
bufferlist[0].mBuffers[0].mDataByteSize = len(raw_data)
bufferlist[0].mBuffers[0].mData = self.outdata
numberpackets[0] = numframes
self.todo = self.todo[numframes:]
if len(self.todo) == 0 and numframes == 0:
return -1
return 0
def resample(self, data):
self.todo = numpy.array(data, dtype='float32')
while len(self.todo) > 0:
self.outsize[0] = self.blocksize
# Set outbuffer each iteration to avoid mDataByteSize decreasing over time
self.outbuffer.mNumberBuffers = 1
self.outbuffer.mBuffers[0].mNumberChannels = self.channels
self.outbuffer.mBuffers[0].mDataByteSize = self.blocksize*4*self.channels
self.outbuffer.mBuffers[0].mData = self.outdata
status = _au.AudioConverterFillComplexBuffer(self.audioconverter[0],
self._converter_callback,
_ffi.NULL,
self.outsize,
self.outbuffer,
_ffi.NULL)
if status != 0 and status != -1:
raise RuntimeError('error during sample rate conversion:', status)
array = numpy.frombuffer(_ffi.buffer(self.outdata), dtype='float32').copy()
self.queue.append(array[:self.outsize[0]*self.channels])
converted_data = numpy.concatenate(self.queue)
self.queue.clear()
return converted_data.reshape([-1, self.channels])
def __del__(self):
_au.AudioConverterDispose(self.audioconverter[0])
class _Recorder:
"""A context manager for an active input stream.
Audio recording is available as soon as the context manager is
entered. Recorded audio data can be read using the `record`
method. If no audio data is available, `record` will block until
the requested amount of audio data has been recorded.
This context manager can only be entered once, and can not be used
after it is closed.
"""
def __init__(self, id, samplerate, channels, blocksize=None):
self._au = _AudioUnit("input", id, samplerate, channels, blocksize)
self._resampler = _Resampler(self._au.samplerate, samplerate, self._au.channels)
self._record_event = threading.Event()
def __enter__(self):
self._queue = collections.deque()
self._pending_chunk = numpy.zeros([0, self._au.channels], dtype='float32')
channels = self._au.channels
au = self._au.ptr[0]
@_ffi.callback("AURenderCallback")
def input_callback(userdata, actionflags, timestamp,
busnumber, numframes, bufferlist):
bufferlist = _ffi.new("AudioBufferList*", [1, 1])
bufferlist.mNumberBuffers = 1
bufferlist.mBuffers[0].mNumberChannels = channels
bufferlist.mBuffers[0].mDataByteSize = numframes * 4 * channels
bufferlist.mBuffers[0].mData = _ffi.NULL
status = _au.AudioUnitRender(au,
actionflags,
timestamp,
busnumber,
numframes,
bufferlist)
# special case if output is silence:
if (actionflags[0] == _cac.kAudioUnitRenderAction_OutputIsSilence
and status == _cac.kAudioUnitErr_CannotDoInCurrentContext):
actionflags[0] = 0 # reset actionflags
status = 0 # reset error code
data = numpy.zeros([numframes, channels], 'float32')
else:
data = numpy.frombuffer(_ffi.buffer(bufferlist.mBuffers[0].mData,
bufferlist.mBuffers[0].mDataByteSize),
dtype='float32')
data = data.reshape([-1, bufferlist.mBuffers[0].mNumberChannels]).copy()
if status != 0:
print('error during recording:', status)
self._queue.append(data)
self._record_event.set()
return status
self._au.set_callback(input_callback)
self._au.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self._au.close()
def _record_chunk(self):
"""Record one chunk of audio data, as returned by core audio
The data will be returned as a 1D numpy array, which will be used by
the `record` method. This function is the interface of the `_Recorder`
object with core audio.
"""
while not self._queue:
self._record_event.wait()
self._record_event.clear()
block = self._queue.popleft()
# perform sample rate conversion:
if self._au.resample != 1:
block = self._resampler.resample(block)
return block
def record(self, numframes=None):
"""Record a block of audio data.
The data will be returned as a frames × channels float32 numpy array.
This function will wait until numframes frames have been recorded.
If numframes is given, it will return exactly `numframes` frames,
and buffer the rest for later.
If numframes is None, it will return whatever the audio backend
has available right now.
Use this if latency must be kept to a minimum, but be aware that
block sizes can change at the whims of the audio backend.
If using `record` with `numframes=None` after using `record` with a
required `numframes`, the last buffered frame will be returned along
with the new recorded block.
(If you want to empty the last buffered frame instead, use `flush`)
"""
if numframes is None:
blocks = [self._pending_chunk, self._record_chunk()]
self._pending_chunk = numpy.zeros([0, self._au.channels], dtype='float32')
else:
blocks = [self._pending_chunk]
self._pending_chunk = numpy.zeros([0, self._au.channels], dtype='float32')
recorded_frames = len(blocks[0])
while recorded_frames < numframes:
block = self._record_chunk()
blocks.append(block)
recorded_frames += len(block)
if recorded_frames > numframes:
to_split = -(recorded_frames-numframes)
blocks[-1], self._pending_chunk = numpy.split(blocks[-1], [to_split])
data = numpy.concatenate(blocks, axis=0)
return data
def flush(self):
"""Return the last pending chunk
After using the record method, this will return the last incomplete
chunk and delete it.
"""
last_chunk = numpy.reshape(self._pending_chunk, [-1, self._au.channels])
self._pending_chunk = numpy.zeros([0, self._au.channels], dtype='float32')
return last_chunk
View File
Whitespace-only changes.
+419
View File
@@ -0,0 +1,419 @@
typedef enum pa_stream_direction {
PA_STREAM_NODIRECTION,
PA_STREAM_PLAYBACK,
PA_STREAM_RECORD,
PA_STREAM_UPLOAD
} pa_stream_direction_t;
typedef enum pa_sample_format {
PA_SAMPLE_U8,
PA_SAMPLE_ALAW,
PA_SAMPLE_ULAW,
PA_SAMPLE_S16LE,
PA_SAMPLE_S16BE,
PA_SAMPLE_FLOAT32LE,
PA_SAMPLE_FLOAT32BE,
PA_SAMPLE_S32LE,
PA_SAMPLE_S32BE,
PA_SAMPLE_S24LE,
PA_SAMPLE_S24BE,
PA_SAMPLE_S24_32LE,
PA_SAMPLE_S24_32BE,
PA_SAMPLE_MAX,
PA_SAMPLE_INVALID = -1
} pa_sample_format_t;
typedef struct pa_sample_spec {
pa_sample_format_t format;
uint32_t rate;
uint8_t channels;
} pa_sample_spec;
typedef enum pa_channel_position {
PA_CHANNEL_POSITION_INVALID = -1,
PA_CHANNEL_POSITION_MONO = 0,
PA_CHANNEL_POSITION_FRONT_LEFT,
PA_CHANNEL_POSITION_FRONT_RIGHT,
PA_CHANNEL_POSITION_FRONT_CENTER,
PA_CHANNEL_POSITION_LEFT = PA_CHANNEL_POSITION_FRONT_LEFT,
PA_CHANNEL_POSITION_RIGHT = PA_CHANNEL_POSITION_FRONT_RIGHT,
PA_CHANNEL_POSITION_CENTER = PA_CHANNEL_POSITION_FRONT_CENTER,
PA_CHANNEL_POSITION_REAR_CENTER,
PA_CHANNEL_POSITION_REAR_LEFT,
PA_CHANNEL_POSITION_REAR_RIGHT,
PA_CHANNEL_POSITION_LFE,
PA_CHANNEL_POSITION_SUBWOOFER = PA_CHANNEL_POSITION_LFE,
PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER,
PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER,
PA_CHANNEL_POSITION_SIDE_LEFT,
PA_CHANNEL_POSITION_SIDE_RIGHT,
PA_CHANNEL_POSITION_AUX0,
PA_CHANNEL_POSITION_AUX1,
PA_CHANNEL_POSITION_AUX2,
PA_CHANNEL_POSITION_AUX3,
PA_CHANNEL_POSITION_AUX4,
PA_CHANNEL_POSITION_AUX5,
PA_CHANNEL_POSITION_AUX6,
PA_CHANNEL_POSITION_AUX7,
PA_CHANNEL_POSITION_AUX8,
PA_CHANNEL_POSITION_AUX9,
PA_CHANNEL_POSITION_AUX10,
PA_CHANNEL_POSITION_AUX11,
PA_CHANNEL_POSITION_AUX12,
PA_CHANNEL_POSITION_AUX13,
PA_CHANNEL_POSITION_AUX14,
PA_CHANNEL_POSITION_AUX15,
PA_CHANNEL_POSITION_AUX16,
PA_CHANNEL_POSITION_AUX17,
PA_CHANNEL_POSITION_AUX18,
PA_CHANNEL_POSITION_AUX19,
PA_CHANNEL_POSITION_AUX20,
PA_CHANNEL_POSITION_AUX21,
PA_CHANNEL_POSITION_AUX22,
PA_CHANNEL_POSITION_AUX23,
PA_CHANNEL_POSITION_AUX24,
PA_CHANNEL_POSITION_AUX25,
PA_CHANNEL_POSITION_AUX26,
PA_CHANNEL_POSITION_AUX27,
PA_CHANNEL_POSITION_AUX28,
PA_CHANNEL_POSITION_AUX29,
PA_CHANNEL_POSITION_AUX30,
PA_CHANNEL_POSITION_AUX31,
PA_CHANNEL_POSITION_TOP_CENTER,
PA_CHANNEL_POSITION_TOP_FRONT_LEFT,
PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
PA_CHANNEL_POSITION_TOP_FRONT_CENTER,
PA_CHANNEL_POSITION_TOP_REAR_LEFT,
PA_CHANNEL_POSITION_TOP_REAR_RIGHT,
PA_CHANNEL_POSITION_TOP_REAR_CENTER,
PA_CHANNEL_POSITION_MAX
} pa_channel_position_t;
#define PA_CHANNELS_MAX 32U
typedef struct pa_channel_map {
uint8_t channels;
pa_channel_position_t map[PA_CHANNELS_MAX];
} pa_channel_map;
typedef enum pa_channel_map_def {
PA_CHANNEL_MAP_AIFF,
PA_CHANNEL_MAP_ALSA,
PA_CHANNEL_MAP_AUX,
PA_CHANNEL_MAP_WAVEEX,
PA_CHANNEL_MAP_OSS,
PA_CHANNEL_MAP_DEF_MAX,
PA_CHANNEL_MAP_DEFAULT = PA_CHANNEL_MAP_AIFF
} pa_channel_map_def_t;
pa_channel_map* pa_channel_map_init_extend(pa_channel_map *m, unsigned channels, pa_channel_map_def_t def);
int pa_channel_map_valid(const pa_channel_map *map);
const char* pa_channel_position_to_string(pa_channel_position_t pos);
typedef struct pa_buffer_attr {
uint32_t maxlength;
uint32_t tlength;
uint32_t prebuf;
uint32_t minreq;
uint32_t fragsize;
} pa_buffer_attr;
typedef struct pa_simple pa_simple;
pa_simple* pa_simple_new(
const char *server,
const char *name,
pa_stream_direction_t dir,
const char *dev,
const char *stream_name,
const pa_sample_spec *ss,
const pa_channel_map *map,
const pa_buffer_attr *attr,
int *error
);
typedef struct pa_mainloop pa_mainloop;
pa_mainloop *pa_mainloop_new(void);
void pa_mainloop_free(pa_mainloop* m);
int pa_mainloop_run(pa_mainloop *m, int *retval);
void pa_mainloop_quit(pa_mainloop *m, int retval);
typedef struct pa_threaded_mainloop pa_threaded_mainloop;
pa_threaded_mainloop *pa_threaded_mainloop_new(void);
int pa_threaded_mainloop_start(pa_threaded_mainloop *m);
void pa_threaded_mainloop_stop(pa_threaded_mainloop *m);
void pa_threaded_mainloop_free(pa_threaded_mainloop *m);
void pa_threaded_mainloop_lock(pa_threaded_mainloop *m);
void pa_threaded_mainloop_unlock(pa_threaded_mainloop *m);
typedef struct pa_mainloop_api pa_mainloop_api;
pa_mainloop_api* pa_mainloop_get_api(pa_mainloop*m);
pa_mainloop_api *pa_threaded_mainloop_get_api(pa_threaded_mainloop *m);
typedef struct pa_context pa_context;
pa_context *pa_context_new(pa_mainloop_api *mainloop, const char *name);
void pa_context_unref(pa_context *c);
typedef enum pa_context_flags {PA_CONTEXT_NOFLAGS = 0} pa_context_flags_t;
typedef struct pa_spawn_api pa_spawn_api;
int pa_context_connect(pa_context *c, const char *server, pa_context_flags_t flags, const pa_spawn_api *api);
void pa_context_disconnect(pa_context *c);
int pa_context_errno(const pa_context *c);
typedef enum pa_context_state {
PA_CONTEXT_UNCONNECTED,
PA_CONTEXT_CONNECTING,
PA_CONTEXT_AUTHORIZING,
PA_CONTEXT_SETTING_NAME,
PA_CONTEXT_READY,
PA_CONTEXT_FAILED,
PA_CONTEXT_TERMINATED
} pa_context_state_t;
pa_context_state_t pa_context_get_state(pa_context *c);
typedef struct pa_operation pa_operation;
pa_operation *pa_operation_ref(pa_operation *o);
void pa_operation_unref(pa_operation *o);
typedef enum pa_operation_state {
PA_OPERATION_RUNNING,
PA_OPERATION_DONE,
PA_OPERATION_CANCELLED
} pa_operation_state_t;
pa_operation_state_t pa_operation_get_state(pa_operation *o);
typedef enum pa_sink_state { /* enum serialized in u8 */
PA_SINK_INVALID_STATE = -1,
PA_SINK_RUNNING = 0,
PA_SINK_IDLE = 1,
PA_SINK_SUSPENDED = 2
} pa_sink_state_t;
typedef struct pa_proplist pa_proplist;
const char *pa_proplist_gets(pa_proplist *p, const char *key);
typedef enum pa_encoding {
PA_ENCODING_ANY,
PA_ENCODING_PCM,
PA_ENCODING_AC3_IEC61937,
PA_ENCODING_EAC3_IEC61937,
PA_ENCODING_MPEG_IEC61937,
PA_ENCODING_DTS_IEC61937,
PA_ENCODING_MPEG2_AAC_IEC61937,
PA_ENCODING_MAX,
PA_ENCODING_INVALID = -1,
} pa_encoding_t;
typedef struct pa_format_info {
pa_encoding_t encoding;
pa_proplist *plist;
} pa_format_info;
typedef struct pa_sink_port_info {
const char *name;
const char *description;
uint32_t priority;
int available;
} pa_sink_port_info;
typedef uint32_t pa_volume_t;
typedef struct pa_cvolume {
uint8_t channels;
pa_volume_t values[PA_CHANNELS_MAX];
} pa_cvolume;
typedef uint64_t pa_usec_t;
typedef enum pa_sink_flags {
PA_SINK_NOFLAGS = 0x0000,
PA_SINK_HW_VOLUME_CTRL = 0x0001,
PA_SINK_LATENCY = 0x0002,
PA_SINK_HARDWARE = 0x0004,
PA_SINK_NETWORK = 0x0008,
PA_SINK_HW_MUTE_CTRL = 0x0010,
PA_SINK_DECIBEL_VOLUME = 0x0020,
PA_SINK_FLAT_VOLUME = 0x0040,
PA_SINK_DYNAMIC_LATENCY = 0x0080,
PA_SINK_SET_FORMATS = 0x0100
} pa_sink_flags_t;
typedef struct pa_sink_info {
const char *name;
uint32_t index;
const char *description;
pa_sample_spec sample_spec;
pa_channel_map channel_map;
uint32_t owner_module;
pa_cvolume volume;
int mute;
uint32_t monitor_source;
const char *monitor_source_name;
pa_usec_t latency;
const char *driver;
pa_sink_flags_t flags;
pa_proplist *proplist;
pa_usec_t configured_latency;
pa_volume_t base_volume;
pa_sink_state_t state;
uint32_t n_volume_steps;
uint32_t card;
uint32_t n_ports;
pa_sink_port_info** ports;
pa_sink_port_info* active_port;
uint8_t n_formats;
pa_format_info **formats;
} pa_sink_info;
typedef struct pa_source_port_info {
const char *name;
const char *description;
uint32_t priority;
int available;
} pa_source_port_info;
typedef enum pa_source_flags {
PA_SOURCE_NOFLAGS = 0x0000,
PA_SOURCE_HW_VOLUME_CTRL = 0x0001,
PA_SOURCE_LATENCY = 0x0002,
PA_SOURCE_HARDWARE = 0x0004,
PA_SOURCE_NETWORK = 0x0008,
PA_SOURCE_HW_MUTE_CTRL = 0x0010,
PA_SOURCE_DECIBEL_VOLUME = 0x0020,
PA_SOURCE_DYNAMIC_LATENCY = 0x0040,
PA_SOURCE_FLAT_VOLUME = 0x0080
} pa_source_flags_t;
typedef enum pa_source_state {
PA_SOURCE_INVALID_STATE = -1,
PA_SOURCE_RUNNING = 0,
PA_SOURCE_IDLE = 1,
PA_SOURCE_SUSPENDED = 2
} pa_source_state_t;
typedef struct pa_source_info {
const char *name;
uint32_t index;
const char *description;
pa_sample_spec sample_spec;
pa_channel_map channel_map;
uint32_t owner_module;
pa_cvolume volume;
int mute;
uint32_t monitor_of_sink;
const char *monitor_of_sink_name;
pa_usec_t latency;
const char *driver;
pa_source_flags_t flags; //
pa_proplist *proplist;
pa_usec_t configured_latency;
pa_volume_t base_volume;
pa_source_state_t state; //
uint32_t n_volume_steps;
uint32_t card;
uint32_t n_ports;
pa_source_port_info** ports;
pa_source_port_info* active_port;
uint8_t n_formats;
pa_format_info **formats;
} pa_source_info;
typedef void (*pa_sink_info_cb_t)(pa_context *c, const pa_sink_info *i, int eol, void *userdata);
pa_operation* pa_context_get_sink_info_list(pa_context *c, pa_sink_info_cb_t cb, void *userdata);
pa_operation* pa_context_get_sink_info_by_name(pa_context *c, const char *name, pa_sink_info_cb_t cb, void *userdata);
typedef void (*pa_source_info_cb_t)(pa_context *c, const pa_source_info *i, int eol, void *userdata);
pa_operation* pa_context_get_source_info_list(pa_context *c, pa_source_info_cb_t cb, void *userdata);
pa_operation* pa_context_get_source_info_by_name(pa_context *c, const char *name, pa_source_info_cb_t cb, void *userdata);
typedef void (*pa_context_notify_cb)(pa_context *c, void *userdata);
pa_operation* pa_context_drain(pa_context *c, pa_context_notify_cb cb, void *userdata);
typedef void (*pa_context_success_cb_t)(pa_context *c, int success, void *userdata);
pa_operation* pa_context_set_name(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata);
uint32_t pa_context_get_index(const pa_context *s);
typedef struct pa_client_info {
uint32_t index;
const char *name;
uint32_t owner_module;
const char *driver;
pa_proplist *proplist;
} pa_client_info;
typedef void (*pa_client_info_cb_t) (pa_context *c, const pa_client_info*i, int eol, void *userdata);
pa_operation* pa_context_get_client_info(pa_context *c, uint32_t idx, pa_client_info_cb_t cb, void *userdata);
typedef struct pa_server_info {
const char *user_name;
const char *host_name;
const char *server_version;
const char *server_name;
pa_sample_spec sample_spec;
const char *default_sink_name;
const char *default_source_name;
uint32_t cookie;
pa_channel_map channel_map;
} pa_server_info;
typedef void (*pa_server_info_cb_t) (pa_context *c, const pa_server_info*i, void *userdata);
pa_operation* pa_context_get_server_info(pa_context *c, pa_server_info_cb_t cb, void *userdata);
int pa_sample_spec_valid(const pa_sample_spec *spec);
typedef struct pa_stream pa_stream;
pa_stream* pa_stream_new(pa_context *c, const char *name, const pa_sample_spec *ss, const pa_channel_map *map);
void pa_stream_unref(pa_stream *s);
typedef enum pa_stream_flags {
PA_STREAM_NOFLAGS = 0x0000,
PA_STREAM_START_CORKED = 0x0001,
PA_STREAM_INTERPOLATE_TIMING = 0x0002,
PA_STREAM_NOT_MONOTONIC = 0x0004,
PA_STREAM_AUTO_TIMING_UPDATE = 0x0008,
PA_STREAM_NO_REMAP_CHANNELS = 0x0010,
PA_STREAM_NO_REMIX_CHANNELS = 0x0020,
PA_STREAM_FIX_FORMAT = 0x0040,
PA_STREAM_FIX_RATE = 0x0080,
PA_STREAM_FIX_CHANNELS = 0x0100,
PA_STREAM_DONT_MOVE = 0x0200,
PA_STREAM_VARIABLE_RATE = 0x0400,
PA_STREAM_PEAK_DETECT = 0x0800,
PA_STREAM_START_MUTED = 0x1000,
PA_STREAM_ADJUST_LATENCY = 0x2000,
PA_STREAM_EARLY_REQUESTS = 0x4000,
PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND = 0x8000,
PA_STREAM_START_UNMUTED = 0x10000,
PA_STREAM_FAIL_ON_SUSPEND = 0x20000,
PA_STREAM_RELATIVE_VOLUME = 0x40000,
PA_STREAM_PASSTHROUGH = 0x80000
} pa_stream_flags_t;
int pa_stream_connect_playback(pa_stream *s, const char *dev, const pa_buffer_attr *attr, pa_stream_flags_t flags, const pa_cvolume *volume, pa_stream *sync_stream);
int pa_stream_connect_record(pa_stream *s, const char *dev, const pa_buffer_attr *attr, pa_stream_flags_t flags);
int pa_stream_disconnect(pa_stream *s);
typedef void (*pa_stream_success_cb_t) (pa_stream*s, int success, void *userdata);
pa_operation* pa_stream_cork(pa_stream *s, int b, pa_stream_success_cb_t cb, void *userdata);
pa_operation* pa_stream_drain(pa_stream *s, pa_stream_success_cb_t cb, void *userdata);
size_t pa_stream_writable_size(pa_stream *p);
size_t pa_stream_readable_size(pa_stream *p);
typedef void (*pa_free_cb_t)(void *p);
typedef enum pa_seek_mode {
PA_SEEK_RELATIVE = 0,
PA_SEEK_ABSOLUTE = 1,
PA_SEEK_RELATIVE_ON_READ = 2,
PA_SEEK_RELATIVE_END = 3
} pa_seek_mode_t;
int pa_stream_write(pa_stream *p, const void *data, size_t nbytes, pa_free_cb_t free_cb, int64_t offset, pa_seek_mode_t seek);
int pa_stream_peek(pa_stream *p, const void **data, size_t *nbytes);
int pa_stream_drop(pa_stream *p);
int pa_stream_get_latency(pa_stream *s, pa_usec_t *r_usec, int *negative);
const pa_channel_map* pa_stream_get_channel_map(pa_stream *s);
const pa_buffer_attr* pa_stream_get_buffer_attr(pa_stream *s);
typedef enum pa_stream_state {
PA_STREAM_UNCONNECTED,
PA_STREAM_CREATING,
PA_STREAM_READY,
PA_STREAM_FAILED,
PA_STREAM_TERMINATED
} pa_stream_state_t;
pa_stream_state_t pa_stream_get_state(pa_stream *p);
typedef void(*pa_stream_request_cb_t)(pa_stream *p, size_t nbytes, void *userdata);
void pa_stream_set_read_callback(pa_stream *p, pa_stream_request_cb_t cb, void *userdata);
pa_operation* pa_stream_update_timing_info(pa_stream *s, pa_stream_success_cb_t cb, void *userdata);
+945
View File
@@ -0,0 +1,945 @@
# Adapted from Bastian Bechtold's soundcard library, originally released
# under the BSD 3-Clause License
#
# https://github.com/bastibe/SoundCard
#
# Copyright (c) 2016 Bastian Bechtold
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the copyright holder 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 COPYRIGHT
# HOLDER 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.
#
# Modifications and improvements Copyright 2025 Mark Qvist, and released
# under the same BSD 3-Clause License.
import os
import atexit
import collections.abc
import time
import re
import threading
import warnings
import numpy
import cffi
_ffi = cffi.FFI()
_package_dir, _ = os.path.split(__file__)
with open(os.path.join(_package_dir, "pulseaudio.h"), "rt") as f: _ffi.cdef(f.read())
# Try explicit file name, if the general does not work (e.g. on nixos)
try: _pa = _ffi.dlopen("pulse")
except OSError: _pa = _ffi.dlopen("libpulse.so")
# First, we need to define a global _PulseAudio proxy for interacting
# with the C API:
def _lock(func):
"""Call a pulseaudio function while holding the mainloop lock."""
def func_with_lock(*args, **kwargs):
self = args[0]
with self._lock_mainloop():
return func(*args[1:], **kwargs)
return func_with_lock
def _lock_and_block(func):
"""Call a pulseaudio function while holding the mainloop lock, and
block until the operation has finished.
Use this for pulseaudio functions that return a `pa_operation *`.
"""
def func_with_lock(*args, **kwargs):
self = args[0]
with self._lock_mainloop():
operation = func(*args[1:], **kwargs)
self._block_operation(operation)
self._pa_operation_unref(operation)
return func_with_lock
def channel_name_map():
"""
Return a dict containing the channel position index for every channel position name string.
"""
channel_indices = {
_ffi.string(_pa.pa_channel_position_to_string(idx)).decode("utf-8"): idx for idx in
range(_pa.PA_CHANNEL_POSITION_MAX)
}
# Append alternative names for front-left, front-right, front-center and lfe according to
# the PulseAudio definitions.
channel_indices.update({"left": _pa.PA_CHANNEL_POSITION_LEFT,
"right": _pa.PA_CHANNEL_POSITION_RIGHT,
"center": _pa.PA_CHANNEL_POSITION_CENTER,
"subwoofer": _pa.PA_CHANNEL_POSITION_SUBWOOFER})
# The values returned from Pulseaudio contain 1 for "left", 2 for "right" and so on.
# SoundCard"s channel indices for "left" start at 0. Therefore, we have to decrement all values.
channel_indices = {key: value - 1 for (key, value) in channel_indices.items()}
return channel_indices
class _PulseAudio:
"""Proxy for communcation with Pulseaudio.
This holds the pulseaudio main loop, and a pulseaudio context.
Together, these provide the building blocks for interacting with
pulseaudio.
This can be used to query the pulseaudio server for sources,
sinks, and server information, and provides thread-safe access to
the main pulseaudio functions.
Any function that would return a `pa_operation *` in pulseaudio
will block until the operation has finished.
"""
def __init__(self):
# these functions are called before the mainloop starts, so we
# don't need to hold the lock:
self.mainloop = _pa.pa_threaded_mainloop_new()
self.mainloop_api = _pa.pa_threaded_mainloop_get_api(self.mainloop)
self.context = _pa.pa_context_new(self.mainloop_api, self._infer_program_name().encode())
_pa.pa_context_connect(self.context, _ffi.NULL, _pa.PA_CONTEXT_NOFLAGS, _ffi.NULL)
_pa.pa_threaded_mainloop_start(self.mainloop)
while self._pa_context_get_state(self.context) in (_pa.PA_CONTEXT_UNCONNECTED, _pa.PA_CONTEXT_CONNECTING, _pa.PA_CONTEXT_AUTHORIZING, _pa.PA_CONTEXT_SETTING_NAME):
time.sleep(0.001)
assert self._pa_context_get_state(self.context)==_pa.PA_CONTEXT_READY
@staticmethod
def _infer_program_name():
"""Get current progam name.
Will handle `./script.py`, `python path/to/script.py`,
`python -m module.submodule` and `python -c "code(x=y)"`.
See https://docs.python.org/3/using/cmdline.html#interface-options
"""
import sys
prog_name = sys.argv[0]
if prog_name == "-c":
if len(sys.argv) > 1: return sys.argv[1][:30] + "..."
else: return f"lxst_application_{os.getpid()}"
if prog_name == "-m":
prog_name = sys.argv[1]
# Usually even with -m, sys.argv[0] will already be a path,
# so do the following outside the above check
main_str = "/__main__.py"
if prog_name.endswith(main_str):
prog_name = prog_name[:-len(main_str)]
# Not handled: sys.argv[0] == "-"
return os.path.basename(prog_name)
def _shutdown(self):
operation = self._pa_context_drain(self.context, _ffi.NULL, _ffi.NULL)
self._block_operation(operation)
self._pa_context_disconnect(self.context)
self._pa_context_unref(self.context)
# no more mainloop locking necessary from here on:
_pa.pa_threaded_mainloop_stop(self.mainloop)
_pa.pa_threaded_mainloop_free(self.mainloop)
def _block_operation(self, operation):
"""Wait until the operation has finished."""
if operation == _ffi.NULL:
return
while self._pa_operation_get_state(operation) == _pa.PA_OPERATION_RUNNING:
time.sleep(0.001)
@property
def name(self):
"""Return application name stored in client proplist"""
idx = self._pa_context_get_index(self.context)
if idx < 0: # PA_INVALID_INDEX == -1
raise RuntimeError("Could not get client index of PulseAudio context.")
name = None
@_ffi.callback("pa_client_info_cb_t")
def callback(context, client_info, eol, userdata):
nonlocal name
if not eol:
name = _ffi.string(client_info.name).decode("utf-8")
self._pa_context_get_client_info(self.context, idx, callback, _ffi.NULL)
assert name is not None
return name
@name.setter
def name(self, name):
rv = None
@_ffi.callback("pa_context_success_cb_t")
def callback(context, success, userdata):
nonlocal rv
rv = success
self._pa_context_set_name(self.context, name.encode(), callback, _ffi.NULL)
assert rv is not None
if rv == 0:
raise RuntimeError("Setting PulseAudio context name failed")
@property
def source_list(self):
"""Return a list of dicts of information about available sources."""
info = []
@_ffi.callback("pa_source_info_cb_t")
def callback(context, source_info, eol, userdata):
if not eol:
info.append(dict(name=_ffi.string(source_info.description).decode("utf-8"),
id=_ffi.string(source_info.name).decode("utf-8")))
self._pa_context_get_source_info_list(self.context, callback, _ffi.NULL)
return info
def source_info(self, id):
"""Return a dictionary of information about a specific source."""
info = []
@_ffi.callback("pa_source_info_cb_t")
def callback(context, source_info, eol, userdata):
if not eol:
info_dict = dict(latency=source_info.latency,
configured_latency=source_info.configured_latency,
channels=source_info.sample_spec.channels,
name=_ffi.string(source_info.description).decode("utf-8"))
for prop in ["device.class", "device.api", "device.bus"]:
data = _pa.pa_proplist_gets(source_info.proplist, prop.encode())
info_dict[prop] = _ffi.string(data).decode("utf-8") if data else None
info.append(info_dict)
self._pa_context_get_source_info_by_name(self.context, id.encode(), callback, _ffi.NULL)
return info[0] if len(info) else None
@property
def sink_list(self):
"""Return a list of dicts of information about available sinks."""
info = []
@_ffi.callback("pa_sink_info_cb_t")
def callback(context, sink_info, eol, userdata):
if not eol:
info.append((dict(name=_ffi.string(sink_info.description).decode("utf-8"),
id=_ffi.string(sink_info.name).decode("utf-8"))))
self._pa_context_get_sink_info_list(self.context, callback, _ffi.NULL)
return info
def sink_info(self, id):
"""Return a dictionary of information about a specific sink."""
info = []
@_ffi.callback("pa_sink_info_cb_t")
def callback(context, sink_info, eol, userdata):
if not eol:
info_dict = dict(latency=sink_info.latency,
configured_latency=sink_info.configured_latency,
channels=sink_info.sample_spec.channels,
name=_ffi.string(sink_info.description).decode("utf-8"))
for prop in ["device.class", "device.api", "device.bus"]:
data = _pa.pa_proplist_gets(sink_info.proplist, prop.encode())
info_dict[prop] = _ffi.string(data).decode("utf-8") if data else None
info.append(info_dict)
self._pa_context_get_sink_info_by_name(self.context, id.encode(), callback, _ffi.NULL)
return info[0]
@property
def server_info(self):
"""Return a dictionary of information about the server."""
info = {}
@_ffi.callback("pa_server_info_cb_t")
def callback(context, server_info, userdata):
info["server version"] = _ffi.string(server_info.server_version).decode("utf-8")
info["server name"] = _ffi.string(server_info.server_name).decode("utf-8")
info["default sink id"] = _ffi.string(server_info.default_sink_name).decode("utf-8")
info["default source id"] = _ffi.string(server_info.default_source_name).decode("utf-8")
self._pa_context_get_server_info(self.context, callback, _ffi.NULL)
return info
def _lock_mainloop(self):
"""Context manager for locking the mainloop.
Hold this lock before calling any pulseaudio function while
the mainloop is running.
"""
class Lock():
def __enter__(self_):
_pa.pa_threaded_mainloop_lock(self.mainloop)
def __exit__(self_, exc_type, exc_value, traceback):
_pa.pa_threaded_mainloop_unlock(self.mainloop)
return Lock()
# create thread-safe versions of all used pulseaudio functions:
_pa_context_get_source_info_list = _lock_and_block(_pa.pa_context_get_source_info_list)
_pa_context_get_source_info_by_name = _lock_and_block(_pa.pa_context_get_source_info_by_name)
_pa_context_get_sink_info_list = _lock_and_block(_pa.pa_context_get_sink_info_list)
_pa_context_get_sink_info_by_name = _lock_and_block(_pa.pa_context_get_sink_info_by_name)
_pa_context_get_client_info = _lock_and_block(_pa.pa_context_get_client_info)
_pa_context_get_server_info = _lock_and_block(_pa.pa_context_get_server_info)
_pa_context_get_index = _lock(_pa.pa_context_get_index)
_pa_context_get_state = _lock(_pa.pa_context_get_state)
_pa_context_set_name = _lock_and_block(_pa.pa_context_set_name)
_pa_context_drain = _lock(_pa.pa_context_drain)
_pa_context_disconnect = _lock(_pa.pa_context_disconnect)
_pa_context_unref = _lock(_pa.pa_context_unref)
_pa_context_errno = _lock(_pa.pa_context_errno)
_pa_operation_get_state = _lock(_pa.pa_operation_get_state)
_pa_operation_unref = _lock(_pa.pa_operation_unref)
_pa_stream_get_state = _lock(_pa.pa_stream_get_state)
_pa_sample_spec_valid = _lock(_pa.pa_sample_spec_valid)
_pa_stream_new = _lock(_pa.pa_stream_new)
_pa_stream_get_channel_map = _lock(_pa.pa_stream_get_channel_map)
_pa_stream_drain = _lock_and_block(_pa.pa_stream_drain)
_pa_stream_disconnect = _lock(_pa.pa_stream_disconnect)
_pa_stream_unref = _lock(_pa.pa_stream_unref)
_pa_stream_connect_record = _lock(_pa.pa_stream_connect_record)
_pa_stream_readable_size = _lock(_pa.pa_stream_readable_size)
_pa_stream_peek = _lock(_pa.pa_stream_peek)
_pa_stream_drop = _lock(_pa.pa_stream_drop)
_pa_stream_connect_playback = _lock(_pa.pa_stream_connect_playback)
_pa_stream_update_timing_info = _lock_and_block(_pa.pa_stream_update_timing_info)
_pa_stream_get_latency = _lock(_pa.pa_stream_get_latency)
_pa_stream_writable_size = _lock(_pa.pa_stream_writable_size)
_pa_stream_write = _lock(_pa.pa_stream_write)
_pa_stream_set_read_callback = _pa.pa_stream_set_read_callback
_pulse = _PulseAudio()
atexit.register(_pulse._shutdown)
def all_speakers():
"""A list of all connected speakers.
Returns
-------
speakers : list(_Speaker)
"""
return [_Speaker(id=s["id"]) for s in _pulse.sink_list]
def default_speaker():
"""The default speaker of the system.
Returns
-------
speaker : _Speaker
"""
name = _pulse.server_info["default sink id"]
return get_speaker(name)
def get_speaker(id):
"""Get a specific speaker by a variety of means.
Parameters
----------
id : int or str
can be a backend id string (Windows, Linux) or a device id int (MacOS), a substring of the
speaker name, or a fuzzy-matched pattern for the speaker name.
Returns
-------
speaker : _Speaker
"""
speakers = _pulse.sink_list
return _Speaker(id=_match_soundcard(id, speakers)["id"])
def all_microphones(include_loopback=False, exclude_monitors=True):
"""A list of all connected microphones.
By default, this does not include loopbacks (virtual microphones
that record the output of a speaker).
Parameters
----------
include_loopback : bool
allow recording of speaker outputs
exclude_monitors : bool
deprecated version of ``include_loopback``
Returns
-------
microphones : list(_Microphone)
"""
if not exclude_monitors:
warnings.warn("The exclude_monitors flag is being replaced by the include_loopback flag", DeprecationWarning)
include_loopback = not exclude_monitors
mics = [_Microphone(id=m["id"]) for m in _pulse.source_list]
if not include_loopback:
return [m for m in mics if m._get_info()["device.class"] != "monitor"]
else:
return mics
def default_microphone():
"""The default microphone of the system.
Returns
-------
microphone : _Microphone
"""
name = _pulse.server_info["default source id"]
return get_microphone(name, include_loopback=True)
def get_microphone(id, include_loopback=False, exclude_monitors=True):
"""Get a specific microphone by a variety of means.
By default, this does not include loopbacks (virtual microphones
that record the output of a speaker).
Parameters
----------
id : int or str
can be a backend id string (Windows, Linux) or a device id int (MacOS), a substring of the
speaker name, or a fuzzy-matched pattern for the speaker name.
include_loopback : bool
allow recording of speaker outputs
exclude_monitors : bool
deprecated version of ``include_loopback``
Returns
-------
microphone : _Microphone
"""
if not exclude_monitors:
warnings.warn("The exclude_monitors flag is being replaced by the include_loopback flag", DeprecationWarning)
include_loopback = not exclude_monitors
microphones = _pulse.source_list
return _Microphone(id=_match_soundcard(id, microphones, include_loopback)["id"])
def _match_soundcard(id, soundcards, include_loopback=False):
"""Find id in a list of soundcards.
id can be a pulseaudio id, a substring of the microphone name, or
a fuzzy-matched pattern for the microphone name.
"""
if not include_loopback:
soundcards_by_id = {soundcard["id"]: soundcard for soundcard in soundcards
if not "monitor" in soundcard["id"]}
soundcards_by_name = {soundcard["name"]: soundcard for soundcard in soundcards
if not "monitor" in soundcard["id"]}
else:
soundcards_by_id = {soundcard["id"]: soundcard for soundcard in soundcards}
soundcards_by_name = {soundcard["name"]: soundcard for soundcard in soundcards}
if id in soundcards_by_id:
return soundcards_by_id[id]
# try substring match:
for name, soundcard in soundcards_by_name.items():
if id in name:
return soundcard
# try fuzzy match:
pattern = ".*".join(id)
for name, soundcard in soundcards_by_name.items():
if re.match(pattern, name):
return soundcard
raise IndexError("no soundcard with id {}".format(id))
def get_name():
"""Get application name.
.. note::
Currently only works on Linux.
Returns
-------
name : str
"""
return _pulse.name
def set_name(name):
"""Set application name.
.. note::
Currently only works on Linux.
Parameters
----------
name : str
The application using the soundcard
will be identified by the OS using this name.
"""
_pulse.name = name
class _SoundCard:
def __init__(self, *, id):
self._id = id
@property
def channels(self):
"""int or list(int): Either the number of channels, or a list of
channel indices. Index -1 is the mono mixture of all channels,
and subsequent numbers are channel numbers (left, right,
center, ...)
"""
return self._get_info()["channels"]
@property
def id(self):
"""object: A backend-dependent unique ID."""
return self._id
@property
def name(self):
"""str: The human-readable name of the soundcard."""
return self._get_info()["name"]
def _get_info(self):
return _pulse.source_info(self._id)
class _Speaker(_SoundCard):
"""A soundcard output. Can be used to play audio.
Use the :func:`play` method to play one piece of audio, or use the
:func:`player` method to get a context manager for playing continuous
audio.
Multiple calls to :func:`play` play immediately and concurrently,
while the :func:`player` schedules multiple pieces of audio one
after another.
"""
def __repr__(self):
return "<Speaker {} ({} channels)>".format(self.name, self.channels)
def player(self, samplerate, channels=None, blocksize=None):
"""Create Player for playing audio.
Parameters
----------
samplerate : int
The desired sampling rate in Hz
channels : {int, list(int)}, optional
Play on these channels. For example, ``[0, 3]`` will play
stereo data on the physical channels one and four.
Defaults to use all available channels.
On Linux, channel ``-1`` is the mono mix of all channels.
On macOS, channel ``-1`` is silence.
blocksize : int
Will play this many samples at a time. Choose a lower
block size for lower latency and more CPU usage.
exclusive_mode : bool, optional
Windows only: open sound card in exclusive mode, which
might be necessary for short block lengths or high
sample rates or optimal performance. Default is ``False``.
Returns
-------
player : _Player
"""
if channels is None:
channels = self.channels
return _Player(self._id, samplerate, channels, blocksize)
def play(self, data, samplerate, channels=None, blocksize=None):
"""Play some audio data.
Parameters
----------
data : numpy array
The audio data to play. Must be a *frames x channels* Numpy array.
samplerate : int
The desired sampling rate in Hz
channels : {int, list(int)}, optional
Play on these channels. For example, ``[0, 3]`` will play
stereo data on the physical channels one and four.
Defaults to use all available channels.
On Linux, channel ``-1`` is the mono mix of all channels.
On macOS, channel ``-1`` is silence.
blocksize : int
Will play this many samples at a time. Choose a lower
block size for lower latency and more CPU usage.
"""
if channels is None:
channels = self.channels
with _Player(self._id, samplerate, channels, blocksize) as s:
s.play(data)
def _get_info(self):
return _pulse.sink_info(self._id)
class _Microphone(_SoundCard):
"""A soundcard input. Can be used to record audio.
Use the :func:`record` method to record one piece of audio, or use
the :func:`recorder` method to get a context manager for recording
continuous audio.
Multiple calls to :func:`record` record immediately and
concurrently, while the :func:`recorder` schedules multiple pieces
of audio to be recorded one after another.
"""
def __repr__(self):
if self.isloopback:
return "<Loopback {} ({} channels)>".format(self.name, self.channels)
else:
return "<Microphone {} ({} channels)>".format(self.name, self.channels)
@property
def isloopback(self):
"""bool : Whether this microphone is recording a speaker."""
return self._get_info()["device.class"] == "monitor"
def recorder(self, samplerate, channels=None, blocksize=None):
"""Create Recorder for recording audio.
Parameters
----------
samplerate : int
The desired sampling rate in Hz
channels : {int, list(int)}, optional
Record on these channels. For example, ``[0, 3]`` will record
stereo data from the physical channels one and four.
Defaults to use all available channels.
On Linux, channel ``-1`` is the mono mix of all channels.
On macOS, channel ``-1`` is silence.
blocksize : int
Will record this many samples at a time. Choose a lower
block size for lower latency and more CPU usage.
exclusive_mode : bool, optional
Windows only: open sound card in exclusive mode, which
might be necessary for short block lengths or high
sample rates or optimal performance. Default is ``False``.
Returns
-------
recorder : _Recorder
"""
if channels is None:
channels = self.channels
return _Recorder(self._id, samplerate, channels, blocksize)
def record(self, numframes, samplerate, channels=None, blocksize=None):
"""Record some audio data.
Parameters
----------
numframes: int
The number of frames to record.
samplerate : int
The desired sampling rate in Hz
channels : {int, list(int)}, optional
Record on these channels. For example, ``[0, 3]`` will record
stereo data from the physical channels one and four.
Defaults to use all available channels.
On Linux, channel ``-1`` is the mono mix of all channels.
On macOS, channel ``-1`` is silence.
blocksize : int
Will record this many samples at a time. Choose a lower
block size for lower latency and more CPU usage.
Returns
-------
data : numpy array
The recorded audio data. Will be a *frames x channels* Numpy array.
"""
if channels is None:
channels = self.channels
with _Recorder(self._id, samplerate, channels, blocksize) as r:
return r.record(numframes)
class _Stream:
"""A context manager for an active audio stream.
This class is meant to be subclassed. Children must implement the
`_connect_stream` method which takes a `pa_buffer_attr*` struct,
and connects an appropriate stream.
This context manager can only be entered once, and can not be used
after it is closed.
"""
def __init__(self, id, samplerate, channels, blocksize=None, name="outputstream"):
self._id = id
self._samplerate = samplerate
self._name = name
self._blocksize = blocksize
self.channels = channels
def __enter__(self):
samplespec = _ffi.new("pa_sample_spec*")
samplespec.format = _pa.PA_SAMPLE_FLOAT32LE
samplespec.rate = self._samplerate
if isinstance(self.channels, collections.abc.Iterable):
samplespec.channels = len(self.channels)
elif isinstance(self.channels, int):
samplespec.channels = self.channels
else:
raise TypeError("channels must be iterable or integer")
if not _pulse._pa_sample_spec_valid(samplespec):
raise RuntimeError("invalid sample spec")
# pam and channelmap refer to the same object, but need different
# names to avoid garbage collection trouble on the Python/C boundary
pam = _ffi.new("pa_channel_map*")
channelmap = _pa.pa_channel_map_init_extend(pam, samplespec.channels, _pa.PA_CHANNEL_MAP_DEFAULT)
if isinstance(self.channels, collections.abc.Iterable):
for idx, ch in enumerate(self.channels):
if isinstance(ch, int):
channelmap.map[idx] = ch + 1
else:
channel_name_to_index = channel_name_map()
channelmap.map[idx] = channel_name_to_index[ch] + 1
if not _pa.pa_channel_map_valid(channelmap):
raise RuntimeError("invalid channel map")
self.stream = _pulse._pa_stream_new(_pulse.context, self._name.encode(), samplespec, channelmap)
if not self.stream:
errno = _pulse._pa_context_errno(_pulse.context)
raise RuntimeError("stream creation failed with error ", errno)
bufattr = _ffi.new("pa_buffer_attr*")
bufattr.maxlength = 2**32-1 # max buffer length
numchannels = self.channels if isinstance(self.channels, int) else len(self.channels)
bufattr.fragsize = self._blocksize*numchannels*4 if self._blocksize else 2**32-1 # recording block sys.getsizeof()
bufattr.minreq = 2**32-1 # start requesting more data at this bytes
bufattr.prebuf = 2**32-1 # start playback after this bytes are available
bufattr.tlength = self._blocksize*numchannels*4 if self._blocksize else 2**32-1 # buffer length in bytes on server
self._connect_stream(bufattr)
while _pulse._pa_stream_get_state(self.stream) not in [_pa.PA_STREAM_READY, _pa.PA_STREAM_FAILED]:
time.sleep(0.01)
if _pulse._pa_stream_get_state(self.stream) == _pa.PA_STREAM_FAILED:
raise RuntimeError("Stream creation failed. Stream is in status {}"
.format(_pulse._pa_stream_get_state(self.stream)))
channel_map = _pulse._pa_stream_get_channel_map(self.stream)
self.channels = int(channel_map.channels)
return self
def __exit__(self, exc_type, exc_value, traceback):
if isinstance(self, _Player): # only playback streams need to drain
_pulse._pa_stream_drain(self.stream, _ffi.NULL, _ffi.NULL)
_pulse._pa_stream_disconnect(self.stream)
while _pulse._pa_stream_get_state(self.stream) not in (_pa.PA_STREAM_TERMINATED, _pa.PA_STREAM_FAILED):
time.sleep(0.01)
_pulse._pa_stream_unref(self.stream)
@property
def latency(self):
"""float : Latency of the stream in seconds (only available on Linux)"""
_pulse._pa_stream_update_timing_info(self.stream, _ffi.NULL, _ffi.NULL)
microseconds = _ffi.new("pa_usec_t*")
_pulse._pa_stream_get_latency(self.stream, microseconds, _ffi.NULL)
return microseconds[0] / 1000000 # 1_000_000 (3.5 compat)
class _Player(_Stream):
"""A context manager for an active output stream.
Audio playback is available as soon as the context manager is
entered. Audio data can be played using the :func:`play` method.
Successive calls to :func:`play` will queue up the audio one piece
after another. If no audio is queued up, this will play silence.
This context manager can only be entered once, and can not be used
after it is closed.
"""
def _connect_stream(self, bufattr):
_pulse._pa_stream_connect_playback(self.stream, self._id.encode(), bufattr, _pa.PA_STREAM_ADJUST_LATENCY,
_ffi.NULL, _ffi.NULL)
def play(self, data):
"""Play some audio data.
Internally, all data is handled as ``float32`` and with the
appropriate number of channels. For maximum performance,
provide data as a *frames × channels* float32 numpy array.
If single-channel or one-dimensional data is given, this data
will be played on all available channels.
This function will return *before* all data has been played,
so that additional data can be provided for gapless playback.
The amount of buffering can be controlled through the
blocksize of the player object.
If data is provided faster than it is played, later pieces
will be queued up and played one after another.
Parameters
----------
data : numpy array
The audio data to play. Must be a *frames x channels* Numpy array.
"""
data = numpy.array(data, dtype="float32", order="C")
if data.ndim == 1:
data = data[:, None] # force 2d
if data.ndim != 2:
raise TypeError("data must be 1d or 2d, not {}d".format(data.ndim))
if data.shape[1] == 1 and self.channels != 1:
data = numpy.tile(data, [1, self.channels])
if data.shape[1] != self.channels:
raise TypeError("second dimension of data must be equal to the number of channels, not {}".format(data.shape[1]))
while data.nbytes > 0:
nwrite = _pulse._pa_stream_writable_size(self.stream) // (4 * self.channels) # 4 bytes per sample
if nwrite == 0:
time.sleep(0.001)
continue
bytes = data[:nwrite].ravel().tobytes()
_pulse._pa_stream_write(self.stream, bytes, len(bytes), _ffi.NULL, 0, _pa.PA_SEEK_RELATIVE)
data = data[nwrite:]
class _Recorder(_Stream):
"""A context manager for an active input stream.
Audio recording is available as soon as the context manager is
entered. Recorded audio data can be read using the :func:`record`
method. If no audio data is available, :func:`record` will block until
the requested amount of audio data has been recorded.
This context manager can only be entered once, and can not be used
after it is closed.
"""
def __init__(self, *args, **kwargs):
super(_Recorder, self).__init__(*args, **kwargs)
self._pending_chunk = numpy.zeros((0, ), dtype="float32")
self._record_event = threading.Event()
def _connect_stream(self, bufattr):
_pulse._pa_stream_connect_record(self.stream, self._id.encode(), bufattr, _pa.PA_STREAM_ADJUST_LATENCY)
@_ffi.callback("pa_stream_request_cb_t")
def read_callback(stream, nbytes, userdata):
self._record_event.set()
self._callback = read_callback
_pulse._pa_stream_set_read_callback(self.stream, read_callback, _ffi.NULL)
def _record_chunk(self):
'''Record one chunk of audio data, as returned by pulseaudio
The data will be returned as a 1D numpy array, which will be used by
the `record` method. This function is the interface of the `_Recorder`
object with pulseaudio
'''
data_ptr = _ffi.new("void**")
nbytes_ptr = _ffi.new("size_t*")
readable_bytes = _pulse._pa_stream_readable_size(self.stream)
while not readable_bytes:
if not self._record_event.wait(timeout=1):
if _pulse._pa_stream_get_state(self.stream) == _pa.PA_STREAM_FAILED:
raise RuntimeError("Recording failed, stream is in status FAILED")
self._record_event.clear()
readable_bytes = _pulse._pa_stream_readable_size(self.stream)
data_ptr[0] = _ffi.NULL
nbytes_ptr[0] = 0
_pulse._pa_stream_peek(self.stream, data_ptr, nbytes_ptr)
if data_ptr[0] != _ffi.NULL:
buffer = _ffi.buffer(data_ptr[0], nbytes_ptr[0])
chunk = numpy.frombuffer(buffer, dtype="float32").copy()
if data_ptr[0] == _ffi.NULL and nbytes_ptr[0] != 0:
chunk = numpy.zeros(nbytes_ptr[0]//4, dtype="float32")
if nbytes_ptr[0] > 0:
_pulse._pa_stream_drop(self.stream)
return chunk
def record(self, numframes=None):
"""Record a block of audio data.
The data will be returned as a *frames × channels* float32
numpy array. This function will wait until ``numframes``
frames have been recorded. If numframes is given, it will
return exactly ``numframes`` frames, and buffer the rest for
later.
If ``numframes`` is None, it will return whatever the audio
backend has available right now. Use this if latency must be
kept to a minimum, but be aware that block sizes can change at
the whims of the audio backend.
If using :func:`record` with ``numframes=None`` after using
:func:`record` with a required ``numframes``, the last
buffered frame will be returned along with the new recorded
block. (If you want to empty the last buffered frame instead,
use :func:`flush`)
Parameters
----------
numframes : int, optional
The number of frames to record.
Returns
-------
data : numpy array
The recorded audio data. Will be a *frames x channels* Numpy array.
"""
if numframes is None:
return numpy.reshape(numpy.concatenate([self.flush().ravel(), self._record_chunk()]),
[-1, self.channels])
else:
captured_data = [self._pending_chunk]
captured_frames = self._pending_chunk.shape[0] / self.channels
if captured_frames >= numframes:
keep, self._pending_chunk = numpy.split(self._pending_chunk,
[int(numframes * self.channels)])
return numpy.reshape(keep, [-1, self.channels])
else:
while captured_frames < numframes:
chunk = self._record_chunk()
captured_data.append(chunk)
captured_frames += len(chunk)/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])
return numpy.reshape(numpy.concatenate(captured_data), [-1, self.channels])
def flush(self):
"""Return the last pending chunk.
After using the :func:`record` method, this will return the
last incomplete chunk and delete it.
Returns
-------
data : numpy array
The recorded audio data. Will be a *frames x channels* Numpy array.
"""
last_chunk = numpy.reshape(self._pending_chunk, [-1, self.channels])
self._pending_chunk = numpy.zeros((0, ), dtype="float32")
return last_chunk
View File
Whitespace-only changes.
+256
View File
@@ -0,0 +1,256 @@
// see um/winnt.h:
typedef long HRESULT;
typedef wchar_t *LPWSTR;
typedef long long LONGLONG;
// originally, struct=interface, see um/combaseapi.h
// see shared/rpcndr.h:
typedef unsigned char byte;
// see shared/guiddef.h:
typedef struct {
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
byte Data4[ 8 ];
} GUID;
typedef GUID IID;
typedef IID *LPIID;
// see um/mmdeviceapi.h:
typedef struct IMMDeviceEnumerator IMMDeviceEnumerator;
typedef struct IMMDeviceCollection IMMDeviceCollection;
typedef struct IMMDevice IMMDevice;
typedef struct IMMNotificationClient IMMNotificationClient;
// see um/mfidl.h:
typedef struct IMFMediaSink IMFMediaSink;
// see um/mfobjects.h:
typedef struct IMFAttributes IMFAttributes;
// see um/Unknwn.h:
typedef struct IUnknown IUnknown;
typedef IUnknown *LPUNKNOWN;
// see shared/wtypes.h:
typedef unsigned long DWORD;
typedef const char *LPCSTR;
// see shared/WTypesbase.h:
typedef void *LPVOID;
typedef LPCSTR LPCOLESTR;
typedef IID *REFIID;
// see um/combaseapi.h:
HRESULT CoCreateInstance(const GUID* rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, const GUID* riid, LPVOID * ppv);
HRESULT IIDFromString(LPCOLESTR lpsz, LPIID lpiid);
HRESULT CoInitializeEx(LPVOID pvReserved, DWORD dwCoInit);
void CoTaskMemFree(LPVOID pv);
LPVOID CoTaskMemAlloc(size_t cb);
void CoUninitialize(void);
// see um/mmdeviceapi.h:
typedef enum EDataFlow {eRender, eCapture, eAll, EDataFlow_enum_count} EDataFlow;
typedef enum ERole {eConsole, eMultimedia, eCommunications, ERole_enum_count} ERole;
typedef struct IMMDeviceEnumeratorVtbl
{
HRESULT ( __stdcall *QueryInterface )(IMMDeviceEnumerator * This, const GUID *riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IMMDeviceEnumerator * This);
ULONG ( __stdcall *Release )(IMMDeviceEnumerator * This);
HRESULT ( __stdcall *EnumAudioEndpoints )(IMMDeviceEnumerator * This, EDataFlow dataFlow, DWORD dwStateMask, IMMDeviceCollection **ppDevices);
HRESULT ( __stdcall *GetDefaultAudioEndpoint )(IMMDeviceEnumerator * This, EDataFlow dataFlow, ERole role, IMMDevice **ppEndpoint);
HRESULT ( __stdcall *GetDevice )(IMMDeviceEnumerator * This, LPCWSTR pwstrId, IMMDevice **ppDevice);
/* I hope I won't need these
HRESULT ( __stdcall *RegisterEndpointNotificationCallback )(IMMDeviceEnumerator * This, IMMNotificationClient *pClient);
HRESULT ( __stdcall *UnregisterEndpointNotificationCallback )(IMMDeviceEnumerator * This, IMMNotificationClient *pClient);
*/
} IMMDeviceEnumeratorVtbl;
struct IMMDeviceEnumerator
{
const struct IMMDeviceEnumeratorVtbl *lpVtbl;
};
typedef struct IMMDeviceCollectionVtbl
{
HRESULT ( __stdcall *QueryInterface )(IMMDeviceCollection * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IMMDeviceCollection * This);
ULONG ( __stdcall *Release )(IMMDeviceCollection * This);
HRESULT ( __stdcall *GetCount )(IMMDeviceCollection * This, UINT *pcDevices);
HRESULT ( __stdcall *Item )(IMMDeviceCollection * This, UINT nDevice, IMMDevice **ppDevice);
} IMMDeviceCollectionVtbl;
struct IMMDeviceCollection
{
const struct IMMDeviceCollectionVtbl *lpVtbl;
};
// um/propsys.h
typedef struct IPropertyStore IPropertyStore;
// um/combaseapi.h
typedef struct tag_inner_PROPVARIANT PROPVARIANT;
// shared/wtypes.h
typedef unsigned short VARTYPE;
// um/propidl.h
struct tag_inner_PROPVARIANT {
VARTYPE vt;
WORD wReserved1;
WORD wReserved2;
WORD wReserved3;
void * data;
};
void PropVariantInit(PROPVARIANT *p);
HRESULT PropVariantClear(PROPVARIANT *p);
typedef struct IMMDeviceVtbl {
HRESULT ( __stdcall *QueryInterface )(IMMDevice * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IMMDevice * This);
ULONG ( __stdcall *Release )(IMMDevice * This);
HRESULT ( __stdcall *Activate )(IMMDevice * This, REFIID iid, DWORD dwClsCtx, PROPVARIANT *pActivationParams, void **ppInterface);
HRESULT ( __stdcall *OpenPropertyStore )(IMMDevice * This, DWORD stgmAccess, IPropertyStore **ppProperties);
HRESULT ( __stdcall *GetId )(IMMDevice * This, LPWSTR *ppstrId);
HRESULT ( __stdcall *GetState )(IMMDevice * This, DWORD *pdwState);
} IMMDeviceVtbl;
struct IMMDevice {
const struct IMMDeviceVtbl *lpVtbl;
};
// um/propkeydef.h
typedef struct {
GUID fmtid;
DWORD pid;
} PROPERTYKEY;
const PROPERTYKEY PKEY_Device_FriendlyName = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
const PROPERTYKEY PKEY_AudioEngine_DeviceFormat = {{0xf19f064d, 0x82c, 0x4e27, {0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c}}, 0};
typedef struct IPropertyStoreVtbl {
HRESULT ( __stdcall *QueryInterface )(IPropertyStore * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IPropertyStore * This);
ULONG ( __stdcall *Release )(IPropertyStore * This);
HRESULT ( __stdcall *GetCount )(IPropertyStore * This, DWORD *cProps);
HRESULT ( __stdcall *GetAt )(IPropertyStore * This, DWORD iProp, PROPERTYKEY *pkey);
HRESULT ( __stdcall *GetValue )(IPropertyStore * This, const PROPERTYKEY *key, PROPVARIANT *pv);
HRESULT ( __stdcall *SetValue )(IPropertyStore * This, const PROPERTYKEY *key, const PROPVARIANT *propvar);
HRESULT ( __stdcall *Commit )(IPropertyStore * This);
} IPropertyStoreVtbl;
struct IPropertyStore {
const struct IPropertyStoreVtbl *lpVtbl;
};
// shared/WTypesbase.h
typedef struct tagBLOB {
ULONG cbSize;
BYTE *pBlobData;
} BLOB;
typedef struct tag_inner_BLOB_PROPVARIANT BLOB_PROPVARIANT;
struct tag_inner_BLOB_PROPVARIANT {
VARTYPE vt;
WORD wReserved1;
WORD wReserved2;
WORD wReserved3;
BLOB blob;
};
typedef struct WAVEFORMATEX {
WORD wFormatTag; /* format type */
WORD nChannels; /* number of channels (i.e. mono, stereo...) */
DWORD nSamplesPerSec; /* sample rate */
DWORD nAvgBytesPerSec; /* for buffer estimation */
WORD nBlockAlign; /* block size of data */
WORD wBitsPerSample; /* Number of bits per sample of mono data */
WORD cbSize; /* The count in bytes of the size of
extra information (after cbSize) */
} WAVEFORMATEX;
typedef struct {
WAVEFORMATEX Format;
union {
WORD wValidBitsPerSample; /* bits of precision */
WORD wSamplesPerBlock; /* valid if wBitsPerSample==0 */
WORD wReserved; /* If neither applies, set to zero. */
} Samples;
DWORD dwChannelMask; /* which channels are */
/* present in stream */
GUID SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
// um/AudioSessionTypes.h
typedef enum _AUDCLNT_SHAREMODE
{
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_SHAREMODE_EXCLUSIVE
} AUDCLNT_SHAREMODE;
// um/dsound.h
typedef const GUID *LPCGUID;
// um/Audioclient.h
typedef LONGLONG REFERENCE_TIME;
typedef struct IAudioClient IAudioClient;
typedef struct IAudioClientVtbl {
HRESULT ( __stdcall *QueryInterface )(IAudioClient * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IAudioClient * This);
ULONG ( __stdcall *Release )(IAudioClient * This);
HRESULT ( __stdcall *Initialize )(IAudioClient * This, AUDCLNT_SHAREMODE ShareMode, DWORD StreamFlags, REFERENCE_TIME hnsBufferDuration, REFERENCE_TIME hnsPeriodicity, const WAVEFORMATEXTENSIBLE *pFormat, LPCGUID AudioSessionGuid);
HRESULT ( __stdcall *GetBufferSize )(IAudioClient * This, UINT32 *pNumBufferFrames);
HRESULT ( __stdcall *GetStreamLatency )(IAudioClient * This, REFERENCE_TIME *phnsLatency);
HRESULT ( __stdcall *GetCurrentPadding )(IAudioClient * This, UINT32 *pNumPaddingFrames);
HRESULT ( __stdcall *IsFormatSupported )(IAudioClient * This, AUDCLNT_SHAREMODE ShareMode, const WAVEFORMATEXTENSIBLE *pFormat, WAVEFORMATEXTENSIBLE **ppClosestMatch);
HRESULT ( __stdcall *GetMixFormat )(IAudioClient * This, WAVEFORMATEXTENSIBLE **ppDeviceFormat);
HRESULT ( __stdcall *GetDevicePeriod )(IAudioClient * This, REFERENCE_TIME *phnsDefaultDevicePeriod, REFERENCE_TIME *phnsMinimumDevicePeriod);
HRESULT ( __stdcall *Start )(IAudioClient * This);
HRESULT ( __stdcall *Stop )(IAudioClient * This);
HRESULT ( __stdcall *Reset )(IAudioClient * This);
HRESULT ( __stdcall *SetEventHandle )(IAudioClient * This, HANDLE eventHandle);
HRESULT ( __stdcall *GetService )(IAudioClient * This, REFIID riid, void **ppv);
} IAudioClientVtbl;
struct IAudioClient {
const struct IAudioClientVtbl *lpVtbl;
};
typedef struct IAudioRenderClient IAudioRenderClient;
typedef struct IAudioRenderClientVtbl {
HRESULT ( __stdcall *QueryInterface )(IAudioRenderClient * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IAudioRenderClient * This);
ULONG ( __stdcall *Release )(IAudioRenderClient * This);
HRESULT ( __stdcall *GetBuffer )(IAudioRenderClient * This, UINT32 NumFramesRequested, BYTE **ppData);
HRESULT ( __stdcall *ReleaseBuffer )(IAudioRenderClient * This, UINT32 NumFramesWritten, DWORD dwFlags);
} IAudioRenderClientVtbl;
struct IAudioRenderClient {
const struct IAudioRenderClientVtbl *lpVtbl;
};
typedef enum _AUDCLNT_BUFFERFLAGS {
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY = 0x1,
AUDCLNT_BUFFERFLAGS_SILENT = 0x2,
AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR = 0x4
};
typedef struct IAudioCaptureClient IAudioCaptureClient;
typedef struct IAudioCaptureClientVtbl {
HRESULT ( __stdcall *QueryInterface )(IAudioCaptureClient * This, REFIID riid, void **ppvObject);
ULONG ( __stdcall *AddRef )(IAudioCaptureClient * This);
ULONG ( __stdcall *Release )(IAudioCaptureClient * This);
HRESULT ( __stdcall *GetBuffer )(IAudioCaptureClient * This, BYTE **ppData, UINT32 *pNumFramesToRead, DWORD *pdwFlags, UINT64 *pu64DevicePosition, UINT64 *pu64QPCPosition);
HRESULT ( __stdcall *ReleaseBuffer )(IAudioCaptureClient * This, UINT32 NumFramesRead);
HRESULT ( __stdcall *GetNextPacketSize )(IAudioCaptureClient * This, UINT32 *pNumFramesInNextPacket);
} IAudioCaptureClientVtbl;
struct IAudioCaptureClient {
const struct IAudioCaptureClientVtbl *lpVtbl;
};
+641
View File
@@ -0,0 +1,641 @@
# Adapted from Bastian Bechtold's soundcard library, originally released
# under the BSD 3-Clause License
#
# https://github.com/bastibe/SoundCard
#
# Copyright (c) 2016 Bastian Bechtold
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of the copyright holder 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 COPYRIGHT
# HOLDER 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.
#
# Modifications and improvements Copyright 2025 Mark Qvist, and released
# under the same BSD 3-Clause License.
import os
import cffi
import re
import time
import struct
import collections
import platform
import warnings
import threading
import numpy
import RNS
_ffi = cffi.FFI()
_package_dir, _ = os.path.split(__file__)
with open(os.path.join(_package_dir, 'mediafoundation.h'), 'rt') as f: _ffi.cdef(f.read())
try: _ole32 = _ffi.dlopen('ole32')
except OSError:
try: _ole32 = _ffi.dlopen('ole32.dll')
except: raise SystemError("LXST Could not load OLE32 DLL for WASAPI integration")
def tid(): return threading.get_native_id()
com_thread_ids = []
class _COMLibrary:
def __init__(self):
self._lock = threading.Lock()
self.init_com()
def init_com(self):
with self._lock:
if tid() in com_thread_ids: return
else:
com_thread_ids.append(tid())
COINIT_MULTITHREADED = 0x0
RNS.log(f"COM init from thread {tid()}", RNS.LOG_EXTREME)
if platform.win32_ver()[0] == "8": raise OSError("Unsupported Windows version")
else: hr = _ole32.CoInitializeEx(_ffi.NULL, COINIT_MULTITHREADED)
try:
self.check_error(hr)
self.com_loaded = True
except RuntimeError as e:
# Error 0x80010106 - COM already initialized
RPC_E_CHANGED_MODE = 0x80010106
if hr + 2 ** 32 == RPC_E_CHANGED_MODE: self.com_loaded = False
else: raise e
def release_com(self):
with self._lock:
if tid() in com_thread_ids:
com_thread_ids.remove(tid())
RNS.log(f"COM release from thread {tid()}", RNS.LOG_EXTREME)
if _ole32 != None: _ole32.CoUninitialize()
else: RNS.log(f"OLE32 instance was None at de-init for thread {tid()}", RNS.LOG_DEBUG)
def __del__(self): self.release_com()
@staticmethod
def check_error(hresult):
S_OK = 0
E_NOINTERFACE = 0x80004002
E_POINTER = 0x80004003
E_OUTOFMEMORY = 0x8007000e
E_INVALIDARG = 0x80070057
CO_E_NOTINITIALIZED = 0x800401f0
AUDCLNT_E_UNSUPPORTED_FORMAT = 0x88890008
if hresult == S_OK: return
elif hresult+2**32 == E_NOINTERFACE: raise RuntimeError("The specified class does not implement the requested interface, or the controlling IUnknown does not expose the requested interface.")
elif hresult+2**32 == E_POINTER: raise RuntimeError("An argument is NULL")
elif hresult+2**32 == E_INVALIDARG: raise RuntimeError("Invalid argument")
elif hresult+2**32 == E_OUTOFMEMORY: raise RuntimeError("Out of memory")
elif hresult+2**32 == AUDCLNT_E_UNSUPPORTED_FORMAT: raise RuntimeError("Unsupported format")
elif hresult+2**32 == CO_E_NOTINITIALIZED: raise RuntimeError(f"Windows COM context not initialized in {tid()}")
else: raise RuntimeError("Error {}".format(hex(hresult+2**32)))
@staticmethod
def release(ppObject):
if ppObject[0] != _ffi.NULL:
ppObject[0][0].lpVtbl.Release(ppObject[0])
ppObject[0] = _ffi.NULL
_com = _COMLibrary()
def all_speakers():
with _DeviceEnumerator() as enum:
return [_Speaker(dev) for dev in enum.all_devices('speaker')]
def default_speaker():
with _DeviceEnumerator() as enum:
return _Speaker(enum.default_device('speaker'))
def get_speaker(id):
return _match_device(id, all_speakers())
def all_microphones(include_loopback=False):
with _DeviceEnumerator() as enum:
if include_loopback:
return [_Microphone(dev, isloopback=True) for dev in enum.all_devices('speaker')] + [_Microphone(dev) for dev in enum.all_devices('microphone')]
else:
return [_Microphone(dev) for dev in enum.all_devices('microphone')]
def default_microphone():
with _DeviceEnumerator() as enum:
return _Microphone(enum.default_device('microphone'))
def get_microphone(id, include_loopback=False):
return _match_device(id, all_microphones(include_loopback))
def _match_device(id, devices):
devices_by_id = {device.id: device for device in devices}
devices_by_name = {device.name: device for device in devices}
if id in devices_by_id: return devices_by_id[id]
# Try substring match:
for name, device in devices_by_name.items():
if id in name: return device
# Try fuzzy match:
pattern = '.*'.join(id)
for name, device in devices_by_name.items():
if re.match(pattern, name): return device
raise IndexError('No device with id {}'.format(id))
def _str2wstr(string):
return _ffi.new('int16_t[]', [ord(s) for s in string]+[0])
def _guidof(uuid_str):
IID = _ffi.new('LPIID')
uuid = _str2wstr(uuid_str)
hr = _ole32.IIDFromString(_ffi.cast("char*", uuid), IID)
_com.check_error(hr)
return IID
def get_name(): raise NotImplementedError()
def set_name(name): raise NotImplementedError()
class _DeviceEnumerator:
# See shared/WTypesbase.h and um/combaseapi.h:
def __init__(self):
_com.init_com()
self._ptr = _ffi.new('IMMDeviceEnumerator **')
IID_MMDeviceEnumerator = _guidof("{BCDE0395-E52F-467C-8E3D-C4579291692E}")
IID_IMMDeviceEnumerator = _guidof("{A95664D2-9614-4F35-A746-DE8DB63617E6}")
CLSCTX_ALL = 23
hr = _ole32.CoCreateInstance(IID_MMDeviceEnumerator, _ffi.NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, _ffi.cast("void **", self._ptr))
_com.check_error(hr)
def __enter__(self):
_com.init_com()
return self
def __exit__(self, exc_type, exc_value, traceback): _com.release(self._ptr)
def __del__(self): _com.release(self._ptr)
def _device_id(self, device_ptr):
ppId = _ffi.new('LPWSTR *')
hr = device_ptr[0][0].lpVtbl.GetId(device_ptr[0], ppId)
_com.check_error(hr)
return _ffi.string(ppId[0])
def all_devices(self, kind):
if kind == 'speaker': data_flow = 0 # render
elif kind == 'microphone': data_flow = 1 # capture
else: raise TypeError('Invalid kind: {}'.format(kind))
DEVICE_STATE_ACTIVE = 0x1
ppDevices = _ffi.new('IMMDeviceCollection **')
hr = self._ptr[0][0].lpVtbl.EnumAudioEndpoints(self._ptr[0], data_flow, DEVICE_STATE_ACTIVE, ppDevices);
_com.check_error(hr)
for ppDevice in _DeviceCollection(ppDevices):
device = _Device(self._device_id(ppDevice))
_com.release(ppDevice)
yield device
def default_device(self, kind):
if kind == 'speaker': data_flow = 0 # render
elif kind == 'microphone': data_flow = 1 # capture
else: raise TypeError('Invalid kind: {}'.format(kind))
ppDevice = _ffi.new('IMMDevice **')
eConsole = 0
hr = self._ptr[0][0].lpVtbl.GetDefaultAudioEndpoint(self._ptr[0], data_flow, eConsole, ppDevice);
_com.check_error(hr)
device = _Device(self._device_id(ppDevice))
_com.release(ppDevice)
return device
def device_ptr(self, devid):
ppDevice = _ffi.new('IMMDevice **')
devid = _str2wstr(devid)
hr = self._ptr[0][0].lpVtbl.GetDevice(self._ptr[0], _ffi.cast('wchar_t *', devid), ppDevice);
_com.check_error(hr)
return ppDevice
class _DeviceCollection:
def __init__(self, ptr):
_com.init_com()
self._ptr = ptr
def __del__(self): _com.release(self._ptr)
def __len__(self):
pCount = _ffi.new('UINT *')
hr = self._ptr[0][0].lpVtbl.GetCount(self._ptr[0], pCount)
_com.check_error(hr)
return pCount[0]
def __getitem__(self, idx):
if idx >= len(self):
raise StopIteration()
ppDevice = _ffi.new('IMMDevice **')
hr = self._ptr[0][0].lpVtbl.Item(self._ptr[0], idx, ppDevice)
_com.check_error(hr)
return ppDevice
class _PropVariant:
def __init__(self):
_com.init_com()
self.ptr = _ole32.CoTaskMemAlloc(_ffi.sizeof('PROPVARIANT'))
self.ptr = _ffi.cast("PROPVARIANT *", self.ptr)
def __del__(self):
hr = _ole32.PropVariantClear(self.ptr)
_com.check_error(hr)
class _Device:
def __init__(self, id):
_com.init_com()
self._id = id
def _device_ptr(self):
with _DeviceEnumerator() as enum:
return enum.device_ptr(self._id)
@property
def id(self): return self._id
@property
def name(self):
# um/coml2api.h:
ppPropertyStore = _ffi.new('IPropertyStore **')
ptr = self._device_ptr()
hr = ptr[0][0].lpVtbl.OpenPropertyStore(ptr[0], 0, ppPropertyStore)
_com.release(ptr)
_com.check_error(hr)
propvariant = _PropVariant()
# um/functiondiscoverykeys_devpkey.h and https://msdn.microsoft.com/en-us/library/windows/desktop/dd370812(v=vs.85).aspx
PKEY_Device_FriendlyName = _ffi.new("PROPERTYKEY *",
[[0xa45c254e, 0xdf1c, 0x4efd, [0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0]],
14])
hr = ppPropertyStore[0][0].lpVtbl.GetValue(ppPropertyStore[0], PKEY_Device_FriendlyName, propvariant.ptr)
_com.check_error(hr)
if propvariant.ptr[0].vt != 31:
raise RuntimeError('Property was expected to be a string, but is not a string')
data = _ffi.cast("short*", propvariant.ptr[0].data)
for idx in range(256):
if data[idx] == 0: break
devicename = struct.pack('h' * idx, *data[0:idx]).decode('utf-16')
_com.release(ppPropertyStore)
return devicename
@property
def channels(self):
# um/coml2api.h:
ppPropertyStore = _ffi.new('IPropertyStore **')
ptr = self._device_ptr()
hr = ptr[0][0].lpVtbl.OpenPropertyStore(ptr[0], 0, ppPropertyStore)
_com.release(ptr)
_com.check_error(hr)
propvariant = _PropVariant()
# um/functiondiscoverykeys_devpkey.h and https://msdn.microsoft.com/en-us/library/windows/desktop/dd370812(v=vs.85).aspx
PKEY_AudioEngine_DeviceFormat = _ffi.new("PROPERTYKEY *",
[[0xf19f064d, 0x82c, 0x4e27, [0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c]],
0])
hr = ppPropertyStore[0][0].lpVtbl.GetValue(ppPropertyStore[0], PKEY_AudioEngine_DeviceFormat, propvariant.ptr)
_com.release(ppPropertyStore)
_com.check_error(hr)
if propvariant.ptr[0].vt != 65:
raise RuntimeError('Property was expected to be a blob, but is not a blob')
pPropVariantBlob = _ffi.cast("BLOB_PROPVARIANT *", propvariant.ptr)
assert pPropVariantBlob[0].blob.cbSize == 40
waveformat = _ffi.cast("WAVEFORMATEX *", pPropVariantBlob[0].blob.pBlobData)
channels = waveformat[0].nChannels
return channels
def _audio_client(self):
CLSCTX_ALL = 23
ppAudioClient = _ffi.new("IAudioClient **")
IID_IAudioClient = _guidof("{1CB9AD4C-DBFA-4C32-B178-C2F568A703B2}")
ptr = self._device_ptr()
hr = ptr[0][0].lpVtbl.Activate(ptr[0], IID_IAudioClient, CLSCTX_ALL, _ffi.NULL, _ffi.cast("void**", ppAudioClient))
_com.release(ptr)
_com.check_error(hr)
return ppAudioClient
class _Speaker(_Device):
def __init__(self, device): self._id = device._id
def __repr__(self): return '<Speaker {} ({} channels)>'.format(self.name,self.channels)
def player(self, samplerate, channels=None, blocksize=None, exclusive_mode=False):
if channels is None: channels = self.channels
return _Player(self._audio_client(), samplerate, channels, blocksize, False, exclusive_mode)
def play(self, data, samplerate, channels=None, blocksize=None):
with self.player(samplerate, channels, blocksize) as p: p.play(data)
class _Microphone(_Device):
def __init__(self, device, isloopback=False):
self._id = device._id
self.isloopback = isloopback
def __repr__(self):
if self.isloopback: return '<Loopback {} ({} channels)>'.format(self.name,self.channels)
else: return '<Microphone {} ({} channels)>'.format(self.name,self.channels)
def recorder(self, samplerate, channels=None, blocksize=None, exclusive_mode=False):
if channels is None: channels = self.channels
return _Recorder(self._audio_client(), samplerate, channels, blocksize, self.isloopback, exclusive_mode)
def record(self, numframes, samplerate, channels=None, blocksize=None):
with self.recorder(samplerate, channels, blocksize) as r: return r.record(numframes)
class _AudioClient:
def __init__(self, ptr, samplerate, channels, blocksize, isloopback, exclusive_mode=False):
self._ptr = ptr
if isinstance(channels, int): self.channelmap = list(range(channels))
elif isinstance(channels, collections.abc.Iterable): self.channelmap = channels
else: raise TypeError('Channels must be iterable or integer')
if list(range(len(set(self.channelmap)))) != sorted(list(set(self.channelmap))):
raise TypeError('Due to limitations of WASAPI, channel maps on Windows must be a combination of `range(0, x)`.')
if blocksize is None: blocksize = self.deviceperiod[0]*samplerate
ppMixFormat = _ffi.new('WAVEFORMATEXTENSIBLE**') # See: https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible
hr = self._ptr[0][0].lpVtbl.GetMixFormat(self._ptr[0], ppMixFormat)
_com.check_error(hr)
# It's a WAVEFORMATEXTENSIBLE with room for KSDATAFORMAT_SUBTYPE_IEEE_FLOAT:
# Note: Some devices may not return 0xFFFE format, but WASAPI should handle conversion
if ppMixFormat[0][0].Format.wFormatTag == 0xFFFE:
assert ppMixFormat[0][0].Format.cbSize == 22
# The data format is float32:
# These values were found empirically, and I don't know why they work.
# The program crashes if these values are different
assert ppMixFormat[0][0].SubFormat.Data1 == 0x100000
assert ppMixFormat[0][0].SubFormat.Data2 == 0x0080
assert ppMixFormat[0][0].SubFormat.Data3 == 0xaa00
assert [int(x) for x in ppMixFormat[0][0].SubFormat.Data4[0:4]] == [0, 56, 155, 113]
# the last four bytes seem to vary randomly
else:
# Device doesn't return WAVEFORMATEXTENSIBLE, but WASAPI will handle conversion
# Just skip the assertions and let WASAPI convert
pass
channels = len(set(self.channelmap))
channelmask = 0
for ch in self.channelmap: channelmask |= 1<<ch
ppMixFormat[0][0].Format.nChannels=channels
ppMixFormat[0][0].Format.nSamplesPerSec=int(samplerate)
ppMixFormat[0][0].Format.nAvgBytesPerSec=int(samplerate) * channels * 4
ppMixFormat[0][0].Format.nBlockAlign=channels * 4
ppMixFormat[0][0].Format.wBitsPerSample=32
ppMixFormat[0][0].Samples=dict(wValidBitsPerSample=32)
# does not work:
# ppMixFormat[0][0].dwChannelMask=channelmask
# See: https://docs.microsoft.com/en-us/windows/win32/coreaudio/exclusive-mode-streams
# nopersist, see: https://docs.microsoft.com/en-us/windows/win32/coreaudio/audclnt-streamflags-xxx-constants
streamflags = 0x00080000
if exclusive_mode:
sharemode = _ole32.AUDCLNT_SHAREMODE_EXCLUSIVE
periodicity = 0 # 0 uses default, must set value if using AUDCLNT_STREAMFLAGS_EVENTCALLBACK (0x00040000)
if isloopback: raise RuntimeError("Loopback mode and exclusive mode are incompatible.")
else:
sharemode = _ole32.AUDCLNT_SHAREMODE_SHARED
# resample | remix | better-SRC
# rateadjust | autoconvPCM | SRC default quality
streamflags |= 0x00100000 | 0x80000000 | 0x08000000 # These flags are only relevant/permitted for shared mode
periodicity = 0 # Always 0 for shared mode
if isloopback: streamflags |= 0x00020000 # Loopback only allowed for shared mode
bufferduration = int(blocksize/samplerate * 10000000) # in hecto-nanoseconds (1000_000_0)
hr = self._ptr[0][0].lpVtbl.Initialize(self._ptr[0], sharemode, streamflags, bufferduration, periodicity, ppMixFormat[0], _ffi.NULL)
_com.check_error(hr)
_ole32.CoTaskMemFree(ppMixFormat[0])
# save samplerate for later
self.samplerate = samplerate
# placeholder for the last time we had audio input available
self._idle_start_time = None
@property
def buffersize(self):
pBufferSize = _ffi.new("UINT32*")
hr = self._ptr[0][0].lpVtbl.GetBufferSize(self._ptr[0], pBufferSize)
_com.check_error(hr)
return pBufferSize[0]
@property
def deviceperiod(self):
pDefaultPeriod = _ffi.new("REFERENCE_TIME*")
pMinimumPeriod = _ffi.new("REFERENCE_TIME*")
hr = self._ptr[0][0].lpVtbl.GetDevicePeriod(self._ptr[0], pDefaultPeriod, pMinimumPeriod)
_com.check_error(hr)
return pDefaultPeriod[0]/10_000_000, pMinimumPeriod[0]/10_000_000
@property
def currentpadding(self):
pPadding = _ffi.new("UINT32*")
hr = self._ptr[0][0].lpVtbl.GetCurrentPadding(self._ptr[0], pPadding)
_com.check_error(hr)
return pPadding[0]
class _Player(_AudioClient):
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd316756(v=vs.85).aspx
def _render_client(self):
iid = _guidof("{F294ACFC-3146-4483-A7BF-ADDCA7C260E2}")
ppRenderClient = _ffi.new("IAudioRenderClient**")
hr = self._ptr[0][0].lpVtbl.GetService(self._ptr[0], iid, _ffi.cast("void**", ppRenderClient))
_com.check_error(hr)
return ppRenderClient
def _render_buffer(self, numframes):
data = _ffi.new("BYTE**")
hr = self._ppRenderClient[0][0].lpVtbl.GetBuffer(self._ppRenderClient[0], numframes, data)
_com.check_error(hr)
return data
def _render_release(self, numframes):
hr = self._ppRenderClient[0][0].lpVtbl.ReleaseBuffer(self._ppRenderClient[0], numframes, 0)
_com.check_error(hr)
def _render_available_frames(self):
return self.buffersize-self.currentpadding
def __enter__(self):
_com.init_com()
self._ppRenderClient = self._render_client()
hr = self._ptr[0][0].lpVtbl.Start(self._ptr[0])
_com.check_error(hr)
return self
def __exit__(self, exc_type, exc_value, traceback):
hr = self._ptr[0][0].lpVtbl.Stop(self._ptr[0])
_com.check_error(hr)
_com.release(self._ppRenderClient)
_com.release(self._ptr)
_com.release_com()
def play(self, data):
data = numpy.array(data, dtype='float32', order='C')
if data.ndim == 1: data = data[:, None] # force 2d
if data.ndim != 2: raise TypeError('Data must be 1d or 2d, not {}d'.format(data.ndim))
if data.shape[1] == 1 and len(set(self.channelmap)) != 1: data = numpy.tile(data, [1, len(set(self.channelmap))])
# Internally, channel numbers are always ascending:
sortidx = sorted(range(len(self.channelmap)), key=lambda k: self.channelmap[k])
data = data[:, sortidx]
if data.shape[1] != len(set(self.channelmap)):
raise TypeError('second dimension of data must be equal to the number of channels, not {}'.format(data.shape[1]))
while data.nbytes > 0:
towrite = self._render_available_frames()
if towrite == 0:
time.sleep(0.001)
continue
bytes = data[:towrite].ravel().tobytes()
buffer = self._render_buffer(towrite)
_ffi.memmove(buffer[0], bytes, len(bytes))
self._render_release(towrite)
data = data[towrite:]
class _Recorder(_AudioClient):
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd370800(v=vs.85).aspx
def _capture_client(self):
iid = _guidof("{C8ADBD64-E71E-48a0-A4DE-185C395CD317}")
ppCaptureClient = _ffi.new("IAudioCaptureClient**")
hr = self._ptr[0][0].lpVtbl.GetService(self._ptr[0], iid, _ffi.cast("void**", ppCaptureClient))
_com.check_error(hr)
return ppCaptureClient
def _capture_buffer(self):
data = _ffi.new("BYTE**")
toread = _ffi.new('UINT32*')
flags = _ffi.new('DWORD*')
hr = self._ppCaptureClient[0][0].lpVtbl.GetBuffer(self._ppCaptureClient[0], data, toread, flags, _ffi.NULL, _ffi.NULL)
_com.check_error(hr)
return data[0], toread[0], flags[0]
def _capture_release(self, numframes):
hr = self._ppCaptureClient[0][0].lpVtbl.ReleaseBuffer(self._ppCaptureClient[0], numframes)
_com.check_error(hr)
def _capture_available_frames(self):
pSize = _ffi.new("UINT32*")
hr = self._ppCaptureClient[0][0].lpVtbl.GetNextPacketSize(self._ppCaptureClient[0], pSize)
_com.check_error(hr)
return pSize[0]
def __enter__(self):
_com.init_com()
self._ppCaptureClient = self._capture_client()
hr = self._ptr[0][0].lpVtbl.Start(self._ptr[0])
_com.check_error(hr)
self._pending_chunk = numpy.zeros([0], dtype='float32')
self._is_first_frame = True
return self
def __exit__(self, exc_type, exc_value, traceback):
hr = self._ptr[0][0].lpVtbl.Stop(self._ptr[0])
_com.check_error(hr)
_com.release(self._ppCaptureClient)
_com.release(self._ptr)
_com.release_com()
def _record_chunk(self):
while self._capture_available_frames() == 0:
# Some sound cards indicate silence by not making any
# frames available. If that is the case, we need to
# estimate the number of zeros to return, by measuring the
# silent time:
if self._idle_start_time is None: self._idle_start_time = time.perf_counter_ns()
default_block_length, minimum_block_length = self.deviceperiod
time.sleep(minimum_block_length/4)
elapsed_time_ns = time.perf_counter_ns() - self._idle_start_time
# Waiting times shorter than a block length or so are
# normal, and not indicative of a silent sound card. If
# the waiting times get longer however, we must assume
# that there is no audio data forthcoming, and return
# zeros instead:
if elapsed_time_ns / 1_000_000_000 > default_block_length * 4:
num_frames = int(self.samplerate * elapsed_time_ns / 1_000_000_000)
num_channels = len(set(self.channelmap))
self._idle_start_time += elapsed_time_ns
return numpy.zeros([num_frames * num_channels], dtype='float32')
self._idle_start_time = None
data_ptr, nframes, flags = self._capture_buffer()
if data_ptr != _ffi.NULL:
# Convert the raw CFFI buffer into a standard bytes object to ensure compatibility
# with modern NumPy versions (fromstring binary mode was removed). Using frombuffer
# on bytes plus .copy() guarantees a writable float32 array for downstream processing.
buf = bytes(_ffi.buffer(data_ptr, nframes * 4 * len(set(self.channelmap))))
chunk = numpy.frombuffer(buf, dtype=numpy.float32).copy()
else: raise RuntimeError('Could not create capture buffer')
# See https://learn.microsoft.com/en-us/windows/win32/api/audioclient/ne-audioclient-_audclnt_bufferflags
if flags & _ole32.AUDCLNT_BUFFERFLAGS_SILENT: chunk[:] = 0
if self._is_first_frame:
# On first run, clear data discontinuity error, as it will always be set:
flags &= ~_ole32.AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY
self._is_first_frame = False
if flags & _ole32.AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY: pass
# Ignore _ole32.AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR, since we don't use time stamps.
if nframes > 0:
self._capture_release(nframes)
return chunk
else:
return numpy.zeros([0], dtype='float32')
def record(self, numframes=None):
if numframes is None:
recorded_data = [self._pending_chunk, self._record_chunk()]
self._pending_chunk = numpy.zeros([0], dtype='float32')
else:
recorded_frames = len(self._pending_chunk)
recorded_data = [self._pending_chunk]
self._pending_chunk = numpy.zeros([0], dtype='float32')
required_frames = numframes*len(set(self.channelmap))
while recorded_frames < required_frames:
chunk = self._record_chunk()
if len(chunk) == 0:
# No data forthcoming: return zeros
chunk = numpy.zeros(required_frames-recorded_frames, dtype='float32')
recorded_data.append(chunk)
recorded_frames += len(chunk)
if recorded_frames > required_frames:
to_split = -int(recorded_frames-required_frames)
recorded_data[-1], self._pending_chunk = numpy.split(recorded_data[-1], [to_split])
data = numpy.reshape(numpy.concatenate(recorded_data), [-1, len(set(self.channelmap))])
return data[:, self.channelmap]
def flush(self):
last_chunk = numpy.reshape(self._pending_chunk, [-1, len(set(self.channelmap))])
self._pending_chunk = numpy.zeros([0], dtype='float32')
return last_chunk
+106
View File
@@ -0,0 +1,106 @@
# Copyright 2024-2026, Mark Qvist
import LXST
import time
import threading
import os
import gc
from LXST.Sinks import LineSink
from LXST.Sources import OpusFileSource
class FilePlayer():
def __init__(self, path=None, device=None, loop=False, gain=0.0, release_on_finish=False):
self._file_path = path
self._playback_device = None
self.__finished_callback = None
self.__release_on_finish = release_on_finish
self.__loop = loop
self.__source = None
self.__gain = gain
self.__sink = LineSink(self._playback_device)
self.__raw = LXST.Codecs.Raw()
self.__loopback = LXST.Sources.Loopback()
self.__output_pipeline = LXST.Pipeline(source=self.__loopback, codec=self.__raw, sink=self.__sink)
self.__input_pipeline = None
if path: self.set_source(self._file_path)
@property
def gain(self): return self.__gain
@gain.setter
def gain(self, db):
try: db = float(db)
except: raise TypeError("Invalid gain type, must be decibel as a floating point number")
self.__gain = db
if self.__source: self.__source.gain = self.__gain
@property
def running(self):
if not self.__source: return False
else: return self.__source.should_run or len(self.__sink.frame_deque)
@property
def playing(self): return self.running
@property
def release_on_finish(self): return self.__release_on_finish
@release_on_finish.setter
def release_on_finish(self, value):
if type(value) != bool: raise TypeError("Provided value is not bool")
else: self.__release_on_finish = value
@property
def finished_callback(self): return self.__finished_callback
@finished_callback.setter
def finished_callback(self, callback):
if callback == None: self.__finished_callback = None
elif not callable(callback): raise TypeError("Provided callback is not callable")
else: self.__finished_callback = callback
def __callback_job(self):
if self.__finished_callback or self.__release_on_finish:
time.sleep(0.2)
while self.running: time.sleep(0.1)
if self.__finished_callback: self.__finished_callback(self)
if self.__release_on_finish: self.release()
def set_source(self, path=None):
if not path: return
else:
if not os.path.isfile(path): raise OSError(f"File not found: {path}")
else:
self.__source = OpusFileSource(path, loop=self.__loop, gain=self.gain)
self.__input_pipeline = LXST.Pipeline(source=self.__source, codec=self.__raw, sink=self.__loopback)
def loop(self, loop=True):
if loop == True: self.__loop = True
else: self.__loop = False
if self.__source: self.__source.loop = self.__loop
def start(self):
if not self.running and self.__source:
self.__input_pipeline.start()
self.__output_pipeline.start()
if self.__finished_callback or self.__release_on_finish:
threading.Thread(target=self.__callback_job, daemon=True).start()
def stop(self):
if self.running and self.__source:
self.__input_pipeline.stop()
self.__output_pipeline.stop()
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
+55
View File
@@ -0,0 +1,55 @@
# Copyright 2024-2026, Mark Qvist
import RNS
import LXST
import time
import os
from LXST.Sources import LineSource
from LXST.Sinks import OpusFileSink
from LXST.Filters import BandPass, AGC
class FileRecorder():
def __init__(self, path=None, device=None, profile=LXST.Codecs.Opus.PROFILE_AUDIO_MAX,
gain=0.0, ease_in=0.125, skip=0.075, filters=[BandPass(25, 24000)]):
self._file_path = path
self._record_device = device
self.__profile = profile
self.__source = None
self.__sink = OpusFileSink(path=self._file_path, profile=profile)
self.__null = LXST.Codecs.Null()
self.__filters = filters
self.__ease_in = ease_in
self.__skip = skip
self.__gain = gain
self.set_source(device)
@property
def running(self):
if not self.__source: return False
else: return self.__source.should_run
@property
def recording(self): return self.running
def set_source(self, device=None):
self._record_device = device
self.__source = LineSource(preferred_device=self._record_device, target_frame_ms=20, codec=self.__null, sink=self.__sink,
gain=self.__gain, ease_in=self.__ease_in, skip=self.__skip, filters=self.__filters)
self.__sink.source = self.__source
def set_output_path(self, path):
self._file_path = path
self.__sink.__output_path = path
def start(self):
if self.__source:
self.__source.start()
def stop(self):
if self.__source:
self.__source.stop()
while self.__sink.frames_waiting: time.sleep(0.1)
self.__sink.stop()
def record(self):
self.start()
+493 -89
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os
import RNS
import LXST
@@ -11,9 +13,126 @@ from LXST.Sinks import LineSink
from LXST.Sources import LineSource, OpusFileSource
from LXST.Generators import ToneSource
from LXST.Network import SignallingReceiver, Packetizer, LinkSource
from LXST.Filters import BandPass, AGC, EchoSuppressor
PRIMITIVE_NAME = "telephony"
class Profiles():
BANDWIDTH_ULTRA_LOW = 0x10
BANDWIDTH_VERY_LOW = 0x20
BANDWIDTH_LOW = 0x30
QUALITY_MEDIUM = 0x40
QUALITY_HIGH = 0x50
QUALITY_MAX = 0x60
LATENCY_ULTRA_LOW = 0x70
LATENCY_LOW = 0x80
DEFAULT_PROFILE = QUALITY_MEDIUM
MODE_FULL_DUPLEX = 0x01
MODE_HALF_DUPLEX = 0x02
DEFAULT_MODE = MODE_FULL_DUPLEX
@staticmethod
def available_modes():
return [Profiles.MODE_FULL_DUPLEX,
Profiles.MODE_HALF_DUPLEX]
@staticmethod
def mode_name(profile):
if profile == Profiles.MODE_FULL_DUPLEX: return "Full Duplex"
elif profile == Profiles.MODE_HALF_DUPLEX: return "Half Duplex"
else: return "Default"
@staticmethod
def mode_abbrevation(profile):
if profile == Profiles.MODE_FULL_DUPLEX: return "FDX"
elif profile == Profiles.MODE_HALF_DUPLEX: return "HDX"
else: return "DFLT"
@staticmethod
def available_profiles():
return [Profiles.BANDWIDTH_ULTRA_LOW,
Profiles.BANDWIDTH_VERY_LOW,
Profiles.BANDWIDTH_LOW,
Profiles.QUALITY_MEDIUM,
Profiles.QUALITY_HIGH,
Profiles.QUALITY_MAX,
Profiles.LATENCY_LOW,
Profiles.LATENCY_ULTRA_LOW]
@staticmethod
def profile_index(profile):
if profile in Profiles.available_profiles(): return Profiles.available_profiles().index(profile)
else: return None
@staticmethod
def profile_name(profile):
if profile == Profiles.BANDWIDTH_ULTRA_LOW: return "Ultra Low Bandwidth"
elif profile == Profiles.BANDWIDTH_VERY_LOW: return "Very Low Bandwidth"
elif profile == Profiles.BANDWIDTH_LOW: return "Low Bandwidth"
elif profile == Profiles.QUALITY_MEDIUM: return "Medium Quality"
elif profile == Profiles.QUALITY_HIGH: return "High Quality"
elif profile == Profiles.QUALITY_MAX: return "Super High Quality"
elif profile == Profiles.LATENCY_LOW: return "Low Latency"
elif profile == Profiles.LATENCY_ULTRA_LOW: return "Ultra Low Latency"
else: return "Default"
@staticmethod
def profile_abbrevation(profile):
if profile == Profiles.BANDWIDTH_ULTRA_LOW: return "ULBW"
elif profile == Profiles.BANDWIDTH_VERY_LOW: return "VLBW"
elif profile == Profiles.BANDWIDTH_LOW: return "LBW"
elif profile == Profiles.QUALITY_MEDIUM: return "MQ"
elif profile == Profiles.QUALITY_HIGH: return "HQ"
elif profile == Profiles.QUALITY_MAX: return "SHQ"
elif profile == Profiles.LATENCY_LOW: return "LL"
elif profile == Profiles.LATENCY_ULTRA_LOW: return "ULL"
else: return "DFLT"
@staticmethod
def get_codec(profile):
if profile == Profiles.BANDWIDTH_ULTRA_LOW: return Codec2(mode=Codec2.CODEC2_700C)
elif profile == Profiles.BANDWIDTH_VERY_LOW: return Codec2(mode=Codec2.CODEC2_1600)
elif profile == Profiles.BANDWIDTH_LOW: return Codec2(mode=Codec2.CODEC2_3200)
elif profile == Profiles.QUALITY_MEDIUM: return Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
elif profile == Profiles.QUALITY_HIGH: return Opus(profile=Opus.PROFILE_VOICE_HIGH)
elif profile == Profiles.QUALITY_MAX: return Opus(profile=Opus.PROFILE_VOICE_MAX)
elif profile == Profiles.LATENCY_LOW: return Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
elif profile == Profiles.LATENCY_ULTRA_LOW: return Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
else: return Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
@staticmethod
def get_frame_time(profile):
if profile == Profiles.BANDWIDTH_ULTRA_LOW: return 400
elif profile == Profiles.BANDWIDTH_VERY_LOW: return 320
elif profile == Profiles.BANDWIDTH_LOW: return 200
elif profile == Profiles.QUALITY_MEDIUM: return 60
elif profile == Profiles.QUALITY_HIGH: return 60
elif profile == Profiles.QUALITY_MAX: return 60
elif profile == Profiles.LATENCY_LOW: return 20
elif profile == Profiles.LATENCY_ULTRA_LOW: return 10
else: return 60
@staticmethod
def get_buffer_frames(profile):
if profile == Profiles.BANDWIDTH_ULTRA_LOW: return 2
elif profile == Profiles.BANDWIDTH_VERY_LOW: return 2
elif profile == Profiles.BANDWIDTH_LOW: return 2
elif profile == Profiles.QUALITY_MEDIUM: return 5
elif profile == Profiles.QUALITY_HIGH: return 5
elif profile == Profiles.QUALITY_MAX: return 5
elif profile == Profiles.LATENCY_LOW: return 3
elif profile == Profiles.LATENCY_ULTRA_LOW: return 2
else: return 5
@staticmethod
def next_profile(profile):
profile_list = Profiles.available_profiles()
if profile in profile_list:
return profile_list[(Profiles.profile_index(profile)+1)%len(profile_list)]
else: return None
class Signalling():
STATUS_BUSY = 0x00
STATUS_REJECTED = 0x01
@@ -22,12 +141,15 @@ class Signalling():
STATUS_RINGING = 0x04
STATUS_CONNECTING = 0x05
STATUS_ESTABLISHED = 0x06
PREFERRED_MODE = 0xF0
PREFERRED_PROFILE = 0xFF
AUTO_STATUS_CODES = [STATUS_CALLING, STATUS_AVAILABLE, STATUS_RINGING,
STATUS_CONNECTING, STATUS_ESTABLISHED]
STATUS_CONNECTING, STATUS_ESTABLISHED]
class Telephone(SignallingReceiver):
RING_TIME = 60
WAIT_TIME = 70
CONNECT_TIME = 5
DIAL_TONE_FREQUENCY = 382
DIAL_TONE_EASE_MS = 3.14159
JOB_INTERVAL = 5
@@ -36,8 +158,21 @@ class Telephone(SignallingReceiver):
ALLOW_ALL = 0xFF
ALLOW_NONE = 0xFE
def __init__(self, identity, ring_time=RING_TIME, wait_time=WAIT_TIME, auto_answer=None, allowed=ALLOW_ALL):
@staticmethod
def available_outputs(): return LXST.Sinks.Backend().all_speakers()
@staticmethod
def available_inputs(): return LXST.Sources.Backend().all_microphones()
@staticmethod
def default_output(): return LXST.Sinks.Backend().default_speaker()
@staticmethod
def default_input(): return LXST.Sources.Backend().default_microphone()
def __init__(self, identity, ring_time=RING_TIME, wait_time=WAIT_TIME, auto_answer=None, allowed=ALLOW_ALL, receive_gain=0.0, transmit_gain=0.0):
super().__init__()
RNS.Reticulum.get_instance().wants_destination_type(f"{APP_NAME}.{PRIMITIVE_NAME}")
self.identity = identity
self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, PRIMITIVE_NAME)
self.destination.set_proof_strategy(RNS.Destination.PROVE_NONE)
@@ -48,33 +183,47 @@ class Telephone(SignallingReceiver):
self.call_handler_lock = threading.Lock()
self.pipeline_lock = threading.Lock()
self.caller_pipeline_open_lock = threading.Lock()
self.establishment_timeout = self.CONNECT_TIME
self.links = {}
self.ring_time = ring_time
self.wait_time = wait_time
self.auto_answer = auto_answer
self.receive_gain = receive_gain
self.transmit_gain = transmit_gain
self.use_agc = True
self.use_bandpass = True
self.use_echo_cancellation = True
self.active_call = None
self.call_status = Signalling.STATUS_AVAILABLE
self._external_busy = False
self.__ringing_callback = None
self.__established_callback = None
self.__ended_callback = None
self.__busy_callback = None
self.__rejected_callback = None
self.target_frame_time_ms = None
self.target_buffer_frames = None
self.audio_output = None
self.audio_input = None
self.dial_tone = None
self.dial_tone_frequency = self.DIAL_TONE_FREQUENCY
self.dial_tone_ease_ms = self.DIAL_TONE_EASE_MS
self.busy_tone_seconds = 4.25
self.transmit_codec = None
self.receive_codec = None
self.receive_mixer = None
self.transmit_mixer = None
self.receive_pipeline = None
self.transmit_pipeline = None
self.__receive_muted = False
self.__transmit_muted = False
self.__loudspeaker_on = False
self.ringer_lock = threading.Lock()
self.ringer_output = None
self.ringer_pipeline = None
self.ringtone_path = None
self.speaker_device = None
self.loudspeaker_device = None
self.microphone_device = None
self.ringer_device = None
self.low_latency_output = False
@@ -100,6 +249,9 @@ class Telephone(SignallingReceiver):
if type(blocked) == list or blocked == None: self.blocked = blocked
else: raise TypeError(f"Invalid type for blocked callers: {type(blocked)}")
def set_connect_timeout(self, timeout):
self.establishment_timeout = timeout
def set_announce_interval(self, announce_interval):
if not type(announce_interval) == int: raise TypeError(f"Invalid type for announce interval: {announce_interval}")
else:
@@ -118,10 +270,22 @@ class Telephone(SignallingReceiver):
if not callable(callback): raise TypeError(f"Invalid callback, {callback} is not callable")
self.__ended_callback = callback
def set_busy_callback(self, callback):
if not callable(callback): raise TypeError(f"Invalid callback, {callback} is not callable")
self.__busy_callback = callback
def set_rejected_callback(self, callback):
if not callable(callback): raise TypeError(f"Invalid callback, {callback} is not callable")
self.__rejected_callback = callback
def set_speaker(self, device):
self.speaker_device = device
RNS.log(f"{self} speaker device set to {device}", RNS.LOG_DEBUG)
def set_loudspeaker(self, device):
self.loudspeaker_device = device
RNS.log(f"{self} loudspeaker device set to {device}", RNS.LOG_DEBUG)
def set_microphone(self, device):
self.microphone_device = device
RNS.log(f"{self} microphone device set to {device}", RNS.LOG_DEBUG)
@@ -130,11 +294,38 @@ class Telephone(SignallingReceiver):
self.ringer_device = device
RNS.log(f"{self} ringer device set to {device}", RNS.LOG_DEBUG)
def set_ringtone(self, ringtone_path, gain=1.0):
def set_ringtone(self, ringtone_path, gain=0.0):
self.ringtone_path = ringtone_path
self.ringtone_gain = gain
RNS.log(f"{self} ringtone set to {self.ringtone_path}", RNS.LOG_DEBUG)
def set_busy_tone_time(self, seconds=4.25):
self.busy_tone_seconds = seconds
def enable_agc(self, enable=True):
if enable == True: self.use_agc = True
else: self.use_agc = False
def disable_agc(self, disable=True):
if disable == True: self.use_agc = False
else: self.use_agc = True
def enable_bandpass(self, enable=True):
if enable == True: self.use_bandpass = True
else: self.use_bandpass = False
def disable_bandpass(self, disable=True):
if disable == True: self.use_bandpass = False
else: self.use_bandpass = True
def enable_echo_cancellation(self, enable=True):
if enable == True: self.use_echo_cancellation = True
else: self.use_echo_cancellation = False
def disable_echo_cancellation(self, disable=True):
if disable == True: self.use_echo_cancellation = False
else: self.use_echo_cancellation = True
def set_low_latency_output(self, enabled):
if enabled:
self.low_latency_output = True
@@ -159,9 +350,7 @@ class Telephone(SignallingReceiver):
def __timeout_incoming_call_at(self, call, timeout):
def job():
while time.time()<timeout and self.active_call == call:
time.sleep(0.25)
while time.time()<timeout and self.active_call == call: time.sleep(0.25)
if self.active_call == call and self.call_status < Signalling.STATUS_ESTABLISHED:
RNS.log(f"Ring timeout on call from {RNS.prettyhexrep(self.active_call.hash)}, hanging up", RNS.LOG_DEBUG)
self.active_call.ring_timeout = True
@@ -171,19 +360,31 @@ class Telephone(SignallingReceiver):
def __timeout_outgoing_call_at(self, call, timeout):
def job():
while time.time()<timeout and self.active_call == call:
time.sleep(0.25)
while time.time()<timeout and self.active_call == call: time.sleep(0.25)
if self.active_call == call and self.call_status < Signalling.STATUS_ESTABLISHED:
RNS.log(f"Timeout on outgoing call to {RNS.prettyhexrep(self.active_call.hash)}, hanging up", RNS.LOG_DEBUG)
self.hangup()
threading.Thread(target=job, daemon=True).start()
def __timeout_outgoing_establishment_at(self, call, timeout):
def job():
while time.time()<timeout and self.active_call == call: time.sleep(0.25)
if self.active_call == call and self.call_status < Signalling.STATUS_RINGING:
RNS.log(f"Timeout on outgoing connection establishment to {RNS.prettyhexrep(self.active_call.hash)}, hanging up", RNS.LOG_DEBUG)
self.hangup()
threading.Thread(target=job, daemon=True).start()
def __incoming_link_established(self, link):
link.is_incoming = True
link.is_outgoing = False
link.ring_timeout = False
link.is_incoming = True
link.is_outgoing = False
link.ring_timeout = False
link.answered = False
link.is_terminating = False
link.established_at = None
link.profile = None
link.call_mode = None
with self.call_handler_lock:
if self.active_call or self.busy:
RNS.log(f"Incoming call, but line is already active, signalling busy", RNS.LOG_DEBUG)
@@ -210,6 +411,7 @@ class Telephone(SignallingReceiver):
else:
RNS.log(f"Caller identified as {RNS.prettyhexrep(identity.hash)}, ringing", RNS.LOG_DEBUG)
self.active_call = link
self.handle_signalling_from(self.active_call)
self.__reset_dialling_pipelines()
self.signal(Signalling.STATUS_RINGING, self.active_call)
self.__activate_ring_tone()
@@ -221,27 +423,59 @@ class Telephone(SignallingReceiver):
self.answer(identity)
threading.Thread(target=cb, daemon=True).start()
else:
self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time)
else: self.__timeout_incoming_call_at(self.active_call, time.time()+self.ring_time)
def __link_closed(self, link):
if link == self.active_call:
RNS.log(f"Remote for {RNS.prettyhexrep(link.get_remote_identity().hash)} hung up", RNS.LOG_DEBUG)
self.hangup()
if not self.active_call.is_terminating: self.hangup()
def set_busy(self, busy):
self._external_busy = busy
@property
def busy(self):
if self.call_status != Signalling.STATUS_AVAILABLE:
return True
if self.call_status != Signalling.STATUS_AVAILABLE: return True
else: return self._external_busy
@property
def active_profile(self):
if not self.active_call: return None
else:
return self._external_busy
if not hasattr(self.active_call, "profile"): return None
else: return self.active_call.profile
@property
def active_mode(self):
if not self.active_call: return None
else:
if not hasattr(self.active_call, "call_mode"): return None
else: return self.active_call.call_mode
@property
def receive_muted(self):
if not self.active_call: return False
else:
if not self.receive_mixer: return False
else: return self.receive_mixer.muted
@property
def transmit_muted(self):
if not self.active_call: return False
else:
if not self.transmit_mixer: return False
else: return self.transmit_mixer.muted
def signal(self, signal, link):
if signal in Signalling.AUTO_STATUS_CODES: self.call_status = signal
super().signal(signal, link)
@property
def loudspeaker_on(self):
return self.__loudspeaker_on
def signal(self, signals, link):
if type(signals) != list: signals = [signals]
for signal in signals:
if signal in Signalling.AUTO_STATUS_CODES: self.call_status = signal
super().signal(signals, link)
def answer(self, identity):
with self.call_handler_lock:
@@ -256,6 +490,8 @@ class Telephone(SignallingReceiver):
return False
else:
RNS.log(f"Answering call from {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG)
self.active_call.answered = True
self.active_call.established_at = time.time()
self.__open_pipelines(identity)
self.__start_pipelines()
RNS.log(f"Call setup complete for {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG)
@@ -263,7 +499,7 @@ class Telephone(SignallingReceiver):
if self.low_latency_output: self.audio_output.enable_low_latency()
return True
def hangup(self):
def hangup(self, reason=None):
if self.active_call:
with self.call_handler_lock:
terminating_call = self.active_call; self.active_call = None
@@ -275,46 +511,140 @@ class Telephone(SignallingReceiver):
if terminating_call.status == RNS.Link.ACTIVE: terminating_call.teardown()
self.__stop_pipelines()
self.receive_mixer = None
self.transmit_mixer = None
self.receive_pipeline = None
self.receive_mixer = None
self.transmit_mixer = None
self.receive_pipeline = None
self.transmit_pipeline = None
self.audio_output = None
self.dial_tone = None
self.call_status = Signalling.STATUS_AVAILABLE
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)
self.audio_output = None
self.dial_tone = None
self.call_status = Signalling.STATUS_AVAILABLE
self.__receive_muted = False
self.__transmit_muted = False
self.__loudspeaker_on = False
if remote_identity: RNS.log(f"Call with {RNS.prettyhexrep(remote_identity.hash)} terminated", RNS.LOG_DEBUG)
else: RNS.log(f"Outgoing call could not be connected, link establishment failed", RNS.LOG_DEBUG)
if callable(self.__ended_callback): self.__ended_callback(remote_identity)
if reason == None:
if callable(self.__ended_callback): self.__ended_callback(remote_identity)
elif reason == Signalling.STATUS_BUSY:
if callable(self.__busy_callback): self.__busy_callback(remote_identity)
elif callable(self.__ended_callback): self.__ended_callback(remote_identity)
elif reason == Signalling.STATUS_REJECTED:
if callable(self.__rejected_callback): self.__rejected_callback(remote_identity)
elif callable(self.__ended_callback): self.__ended_callback(remote_identity)
def mute_receive(self):
pass
def mute_receive(self, mute=True):
self.__receive_muted = mute
if self.receive_mixer: self.receive_mixer.mute(mute)
def mute_transmit(self):
pass
def unmute_receive(self, unmute=True):
self.__receive_muted = not unmute
if self.receive_mixer: self.receive_mixer.unmute(unmute)
def select_call_codecs(self):
def mute_transmit(self, mute=True):
self.__transmit_muted = mute
if self.transmit_mixer: self.transmit_mixer.mute(mute)
def unmute_transmit(self, unmute=True):
self.__transmit_muted = not unmute
if self.transmit_mixer: self.transmit_mixer.unmute(unmute)
def enable_loudspeaker(self, enable=True):
was_on = self.__loudspeaker_on
self.__loudspeaker_on = enable
if was_on != self.__loudspeaker_on: self.__update_audio_output()
def disable_loudspeaker(self, disable=True):
was_on = self.__loudspeaker_on
self.__loudspeaker_on = not disable
if was_on != self.__loudspeaker_on: self.__update_audio_output()
def pause_agc(self, pause=True):
if self.active_call and hasattr(self.active_call, "filter_agc"):
if pause: self.active_call.filter_agc.paused = True
else: self.active_call.filter_agc.paused = False
def resume_agc(self, resume=True):
if self.active_call and hasattr(self.active_call, "filter_agc"):
if resume: self.active_call.filter_agc.paused = False
else: self.active_call.filter_agc.paused = True
def squelch_transmit(self, squelch=True):
self.pause_agc(squelch)
if self.active_call and hasattr(self.active_call, "packetizer"):
if squelch: self.active_call.packetizer.squelch()
else: self.active_call.packetizer.unsquelch()
def unsquelch_transmit(self, unsquelch=True):
self.resume_agc(unsquelch)
if self.active_call and hasattr(self.active_call, "packetizer"):
if unsquelch: self.active_call.packetizer.unsquelch()
else: self.active_call.packetizer.squelch()
def set_receive_gain(self, gain=0.0):
self.receive_gain = float(gain)
if self.receive_mixer: self.receive_mixer.set_gain(self.receive_gain)
def set_transmit_gain(self, gain=0.0):
self.transmit_gain = float(gain)
if self.transmit_mixer: self.transmit_mixer.set_gain(self.transmit_gain)
def disable_remote_mode_follow(self):
if not self.active_call: return False
else:
self.active_call.mode_switch_disabled = True
return True
def switch_mode(self, mode=None, from_signalling=False):
if self.active_call:
if from_signalling and hasattr(self.active_call, "mode_switch_disabled"): return
if self.active_call.call_mode == mode: return
elif not mode in Profiles.available_modes(): return
else:
if self.call_status == Signalling.STATUS_ESTABLISHED:
self.active_call.call_mode = mode
if not from_signalling: self.signal(Signalling.PREFERRED_MODE+self.active_call.call_mode, self.active_call)
self.__select_call_mode(mode)
def __select_call_mode(self, mode=None):
if mode == None: mode = Profiles.DEFAULT_MODE
self.active_call.call_mode = mode
if hasattr(self.active_call, "packetizer"):
if self.active_call.call_mode == Profiles.MODE_HALF_DUPLEX: self.active_call.packetizer.squelch()
elif self.active_call.call_mode == Profiles.MODE_FULL_DUPLEX: self.active_call.packetizer.unsquelch()
RNS.log(f"Selected call mode 0x{RNS.hexrep(mode, delimit=False)}", RNS.LOG_DEBUG)
def switch_profile(self, profile=None, from_signalling=False):
if self.active_call:
if self.active_call.profile == profile: return
else:
if self.call_status == Signalling.STATUS_ESTABLISHED:
self.active_call.profile = profile
self.transmit_codec = Profiles.get_codec(self.active_call.profile)
self.target_frame_time_ms = Profiles.get_frame_time(self.active_call.profile)
self.target_buffer_frames = Profiles.get_buffer_frames(self.active_call.profile)
if not from_signalling: self.signal(Signalling.PREFERRED_PROFILE+self.active_call.profile, self.active_call)
self.__reconfigure_transmit_pipeline()
self.receive_mixer.set_source_max_frames(self.active_call.audio_source, self.target_buffer_frames)
self.__update_output_buffer_targets()
def __select_call_profile(self, profile=None):
if profile == None: profile = Profiles.DEFAULT_PROFILE
self.active_call.profile = profile
self.__select_call_codecs(self.active_call.profile)
self.__select_call_frame_time(self.active_call.profile)
self.__select_call_buffer_frames(self.active_call.profile)
RNS.log(f"Selected call profile 0x{RNS.hexrep(profile, delimit=False)}", RNS.LOG_DEBUG)
def __select_call_codecs(self, profile=None):
self.receive_codec = Null()
# self.transmit_codec = Codec2(mode=Codec2.CODEC2_700C)
# self.transmit_codec = Codec2(mode=Codec2.CODEC2_1600)
# self.transmit_codec = Codec2(mode=Codec2.CODEC2_3200)
# self.transmit_codec = Opus(profile=Opus.PROFILE_VOICE_LOW)
self.transmit_codec = Opus(profile=Opus.PROFILE_VOICE_MEDIUM)
# self.transmit_codec = Opus(profile=Opus.PROFILE_VOICE_HIGH)
# self.transmit_codec = Opus(profile=Opus.PROFILE_VOICE_MAX)
# self.transmit_codec = Opus(profile=Opus.PROFILE_AUDIO_MIN)
# self.transmit_codec = Opus(profile=Opus.PROFILE_AUDIO_LOW)
# self.transmit_codec = Opus(profile=Opus.PROFILE_AUDIO_MEDIUM)
# self.transmit_codec = Opus(profile=Opus.PROFILE_AUDIO_HIGH)
# self.transmit_codec = Opus(profile=Opus.PROFILE_AUDIO_MAX)
# self.transmit_codec = Raw()
self.transmit_codec = Profiles.get_codec(profile)
def select_call_frame_time(self):
self.target_frame_time_ms = 60
return self.target_frame_time_ms
def __select_call_frame_time(self, profile=None):
self.target_frame_time_ms = Profiles.get_frame_time(profile)
def __select_call_buffer_frames(self, profile=None):
self.target_buffer_frames = Profiles.get_buffer_frames(self.active_call.profile)
def __reset_dialling_pipelines(self):
with self.pipeline_lock:
@@ -328,23 +658,48 @@ class Telephone(SignallingReceiver):
self.receive_mixer = None
self.__prepare_dialling_pipelines()
def __update_output_buffer_targets(self):
if self.audio_output and self.target_buffer_frames:
if self.audio_output.buffer_max_height != self.target_buffer_frames:
self.audio_output.buffer_max_height = self.target_buffer_frames+1
RNS.log(f"Updated {self.audio_output} buffer size to {self.audio_output.buffer_max_height} frames", RNS.LOG_DEBUG)
if self.audio_output.autostart_min != self.target_buffer_frames:
self.audio_output.autostart_min = max(1, self.target_buffer_frames-2)
RNS.log(f"Updated {self.audio_output} buffer trigger height to {self.audio_output.autostart_min} frames", RNS.LOG_DEBUG)
self.audio_output.streaming = True
self.audio_output.wait_for_frames()
def __prepare_dialling_pipelines(self):
self.select_call_frame_time()
self.select_call_codecs()
if self.audio_output == None: self.audio_output = LineSink(preferred_device=self.speaker_device)
if self.receive_mixer == None: self.receive_mixer = Mixer(target_frame_ms=self.target_frame_time_ms)
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)
self.__select_call_profile(self.active_call.profile)
self.__select_call_mode(self.active_call.call_mode)
if self.audio_output == None: self.audio_output = LineSink(preferred_device=self.speaker_device) if not self.__loudspeaker_on else LineSink(preferred_device=self.loudspeaker_device)
if self.receive_mixer == None: self.receive_mixer = Mixer(target_frame_ms=self.target_frame_time_ms, gain=self.receive_gain)
if self.dial_tone == None: self.dial_tone = ToneSource(frequency=self.dial_tone_frequency, gain=0.0, ease_time_ms=self.dial_tone_ease_ms, target_frame_ms=self.target_frame_time_ms, codec=Null(), sink=self.receive_mixer)
if self.receive_pipeline == None: self.receive_pipeline = Pipeline(source=self.receive_mixer, codec=Null(), sink=self.audio_output)
self.__update_output_buffer_targets()
def __update_audio_output(self):
if self.active_call and self.audio_output and self.receive_pipeline and self.receive_mixer:
with self.pipeline_lock:
previous_output = self.audio_output
previous_pipeline = self.receive_pipeline
self.audio_output = LineSink(preferred_device=self.speaker_device) if not self.__loudspeaker_on else LineSink(preferred_device=self.loudspeaker_device)
self.receive_pipeline = Pipeline(source=self.receive_mixer, codec=Null(), sink=self.audio_output)
self.receive_pipeline.start()
previous_pipeline.stop()
previous_output.stop()
self.receive_mixer.start()
def __activate_ring_tone(self):
if self.ringtone_path != None and os.path.isfile(self.ringtone_path):
if not self.ringer_pipeline:
if not self.ringer_output: self.ringer_output = LineSink(preferred_device=self.ringer_device)
self.ringer_source = OpusFileSource(self.ringtone_path, loop=True, target_frame_ms=60)
self.ringer_source = OpusFileSource(self.ringtone_path, loop=True, target_frame_ms=60)
self.ringer_pipeline = Pipeline(source=self.ringer_source, codec=Null(), sink=self.ringer_output)
def job():
with self.ringer_lock:
time.sleep(0.5)
while self.active_call and self.active_call.is_incoming and self.call_status == Signalling.STATUS_RINGING:
if not self.ringer_pipeline.running: self.ringer_pipeline.start()
time.sleep(0.1)
@@ -352,15 +707,16 @@ class Telephone(SignallingReceiver):
threading.Thread(target=job, daemon=True).start()
def __play_busy_tone(self):
if self.audio_output == None or self.receive_mixer == None or self.dial_tone == None: self.__reset_dialling_pipelines()
with self.pipeline_lock:
window = 0.5; started = time.time()
while time.time()-started < 4.25:
elapsed = (time.time()-started)%window
if elapsed > 0.25: self.__enable_dial_tone()
else: self.__mute_dial_tone()
time.sleep(0.005)
time.sleep(0.5)
if self.busy_tone_seconds > 0:
if self.audio_output == None or self.receive_mixer == None or self.dial_tone == None: self.__reset_dialling_pipelines()
with self.pipeline_lock:
window = 0.5; started = time.time()
while time.time()-started < self.busy_tone_seconds:
elapsed = (time.time()-started)%window
if elapsed > 0.25: self.__enable_dial_tone()
else: self.__mute_dial_tone()
time.sleep(0.005)
time.sleep(0.5)
def __activate_dial_tone(self):
def job():
@@ -388,6 +744,23 @@ class Telephone(SignallingReceiver):
if self.dial_tone and self.dial_tone.running:
self.dial_tone.stop()
def __reconfigure_transmit_pipeline(self):
if self.transmit_pipeline and self.call_status == Signalling.STATUS_ESTABLISHED:
self.audio_input.stop()
self.transmit_mixer.stop()
self.transmit_pipeline.stop()
self.transmit_mixer = Mixer(target_frame_ms=self.target_frame_time_ms, gain=self.transmit_gain)
self.audio_input = LineSource(preferred_device=self.microphone_device, target_frame_ms=self.target_frame_time_ms, codec=Raw(),
sink=self.transmit_mixer, filters=self.active_call.filters, skip=0.075, ease_in=0.0)
self.transmit_pipeline = Pipeline(source=self.transmit_mixer, codec=self.transmit_codec, sink=self.active_call.packetizer)
self.transmit_mixer.mute(self.__transmit_muted)
self.transmit_mixer.start()
self.audio_input.start()
self.transmit_pipeline.start()
def __open_pipelines(self, identity):
with self.pipeline_lock:
if not self.active_call.get_remote_identity() == identity:
@@ -400,15 +773,30 @@ class Telephone(SignallingReceiver):
RNS.log(f"Opening audio pipelines for call with {RNS.prettyhexrep(identity.hash)}", RNS.LOG_DEBUG)
if self.active_call.is_incoming: self.signal(Signalling.STATUS_CONNECTING, self.active_call)
filter_chain = []
if self.use_bandpass: filter_chain.append(BandPass(250, 8500))
if self.use_agc: self.active_call.filter_agc = AGC(target_level=-15.0)
if self.use_agc: filter_chain.append(self.active_call.filter_agc)
if self.use_echo_cancellation:
self.active_call.echo_suppressor = EchoSuppressor()
self.receive_mixer.reference_outs = [self.active_call.echo_suppressor]
filter_chain.append(self.active_call.echo_suppressor)
self.active_call.filters = filter_chain
self.__prepare_dialling_pipelines()
self.transmit_mixer = Mixer(target_frame_ms=self.target_frame_time_ms)
self.audio_input = LineSource(preferred_device=self.microphone_device, target_frame_ms=self.target_frame_time_ms, codec=Raw(), sink=self.transmit_mixer)
self.transmit_pipeline = Pipeline(source=self.transmit_mixer,
codec=self.transmit_codec,
sink=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.audio_input = LineSource(preferred_device=self.microphone_device, target_frame_ms=self.target_frame_time_ms, codec=Raw(),
sink=self.transmit_mixer, filters=self.active_call.filters, skip=0.075, ease_in=0.225)
self.transmit_pipeline = Pipeline(source=self.transmit_mixer, codec=self.transmit_codec, sink=self.active_call.packetizer)
self.active_call.audio_source = LinkSource(link=self.active_call, signalling_receiver=self, sink=self.receive_mixer)
self.receive_mixer.set_source_max_frames(self.active_call.audio_source, 2)
self.receive_mixer.set_source_max_frames(self.active_call.audio_source, self.target_buffer_frames)
self.signal(Signalling.STATUS_ESTABLISHED, self.active_call)
@@ -434,29 +822,34 @@ class Telephone(SignallingReceiver):
if self.transmit_pipeline: self.transmit_pipeline.stop()
RNS.log(f"Audio pipelines stopped", RNS.LOG_DEBUG)
def call(self, identity):
def call(self, identity, profile=None, mode=None):
with self.call_handler_lock:
if not self.active_call:
self.call_status = Signalling.STATUS_CALLING
outgoing_call_timeout = time.time()+self.wait_time
outgoing_establishment_timeout = time.time()+self.establishment_timeout
call_destination = RNS.Destination(identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, PRIMITIVE_NAME)
if not RNS.Transport.has_path(call_destination.hash):
RNS.log(f"No path known for call to {RNS.prettyhexrep(call_destination.hash)}, requesting path...", RNS.LOG_DEBUG)
RNS.Transport.request_path(call_destination.hash)
while not RNS.Transport.has_path(call_destination.hash) and time.time() < outgoing_call_timeout: time.sleep(0.2)
if not RNS.Transport.has_path(call_destination.hash) and time.time() >= outgoing_call_timeout:
self.hangup()
if not RNS.Transport.has_path(call_destination.hash) and time.time() >= outgoing_call_timeout: self.hangup()
else:
RNS.log(f"Establishing link with {RNS.prettyhexrep(call_destination.hash)}...", RNS.LOG_DEBUG)
self.active_call = RNS.Link(call_destination,
established_callback=self.__outgoing_link_established,
closed_callback=self.__outgoing_link_closed)
self.active_call.is_incoming = False
self.active_call.is_outgoing = True
self.active_call.ring_timeout = False
self.active_call.is_incoming = False
self.active_call.is_outgoing = True
self.active_call.is_terminating = False
self.active_call.ring_timeout = False
self.active_call.established_at = None
self.active_call.profile = profile
self.active_call.call_mode = mode
self.__timeout_outgoing_call_at(self.active_call, outgoing_call_timeout)
self.__timeout_outgoing_establishment_at(self.active_call, outgoing_establishment_timeout)
def __outgoing_link_established(self, link):
RNS.log(f"Link established for call with {link.get_remote_identity()}", RNS.LOG_DEBUG)
@@ -468,19 +861,20 @@ class Telephone(SignallingReceiver):
def signalling_received(self, signals, source):
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:
if signal == Signalling.STATUS_BUSY:
if self.active_call.is_incoming and not self.active_call.answered and signal < Signalling.PREFERRED_MODE: return
elif signal == Signalling.STATUS_BUSY:
RNS.log("Remote is busy, terminating", RNS.LOG_DEBUG)
self.active_call.is_terminating = True
self.__play_busy_tone()
self.__disable_dial_tone()
self.hangup()
self.hangup(reason=Signalling.STATUS_BUSY)
elif signal == Signalling.STATUS_REJECTED:
RNS.log("Remote rejected call, terminating", RNS.LOG_DEBUG)
self.__play_busy_tone()
self.__disable_dial_tone()
self.hangup()
self.hangup(reason=Signalling.STATUS_REJECTED)
elif signal == Signalling.STATUS_AVAILABLE:
RNS.log("Line available, sending identification", RNS.LOG_DEBUG)
self.call_status = signal
@@ -489,8 +883,9 @@ class Telephone(SignallingReceiver):
RNS.log("Identification accepted, remote is now ringing", RNS.LOG_DEBUG)
self.call_status = signal
self.__prepare_dialling_pipelines()
if self.active_call and self.active_call.is_outgoing:
self.__activate_dial_tone()
self.signal([Signalling.PREFERRED_PROFILE+self.active_call.profile,
Signalling.PREFERRED_MODE+self.active_call.call_mode], self.active_call)
if self.active_call and self.active_call.is_outgoing: self.__activate_dial_tone()
elif signal == Signalling.STATUS_CONNECTING:
RNS.log("Call answered, remote is performing call setup, opening audio pipelines", RNS.LOG_DEBUG)
self.call_status = signal
@@ -505,8 +900,17 @@ class Telephone(SignallingReceiver):
self.__disable_dial_tone()
RNS.log(f"Call setup complete for {RNS.prettyhexrep(self.active_call.get_remote_identity().hash)}", RNS.LOG_DEBUG)
self.call_status = signal
self.active_call.established_at = time.time()
if callable(self.__established_callback): self.__established_callback(self.active_call.get_remote_identity())
if self.low_latency_output: self.audio_output.enable_low_latency()
elif signal >= Signalling.PREFERRED_PROFILE:
profile = signal - Signalling.PREFERRED_PROFILE
if self.active_call and self.call_status == Signalling.STATUS_ESTABLISHED: self.switch_profile(profile, from_signalling=True)
else: self.__select_call_profile(profile)
elif signal >= Signalling.PREFERRED_MODE:
mode = signal - Signalling.PREFERRED_MODE
if self.active_call and self.call_status == Signalling.STATUS_ESTABLISHED: self.switch_mode(mode, from_signalling=True)
else: self.__select_call_mode(mode)
def __str__(self):
return f"<lxst.telephony/{RNS.hexrep(self.identity.hash, delimit=False)}>"
+2
View File
@@ -1 +1,3 @@
# Copyright 2024-2026, Mark Qvist
from .Telephony import Telephone
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os
import time
import threading
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os
import time
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
+181 -18
View File
@@ -1,14 +1,19 @@
# Copyright 2024-2026, Mark Qvist
import RNS
import math
import time
import threading
import numpy as np
from collections import deque
from LXST.Codecs import Opus
from LXST.Codecs.Codec import resample_bytes, resample
class LinuxBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from .Platforms.linux import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
@@ -17,7 +22,10 @@ class LinuxBackend():
else: self.device = soundcard.default_speaker()
RNS.log(f"Using output device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_speakers(self): return self.soundcard.all_speakers()
def default_speaker(self): return self.soundcard.default_speaker()
def flush(self): self.device.flush()
def get_player(self, samples_per_frame=None, low_latency=None):
return self.device.player(samplerate=self.samplerate, blocksize=samples_per_frame)
@@ -37,7 +45,10 @@ class AndroidBackend():
else: self.device = soundcard.default_speaker()
RNS.log(f"Using output device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_speakers(self): return self.soundcard.all_speakers()
def default_speaker(self): return self.soundcard.default_speaker()
def flush(self): self.device.flush()
def get_player(self, samples_per_frame=None, low_latency=None):
return self.device.player(samplerate=self.samplerate, blocksize=samples_per_frame, low_latency=low_latency)
@@ -48,7 +59,7 @@ class DarwinBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from .Platforms.darwin import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
@@ -57,7 +68,10 @@ class DarwinBackend():
else: self.device = soundcard.default_speaker()
RNS.log(f"Using output device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_speakers(self): return self.soundcard.all_speakers()
def default_speaker(self): return self.soundcard.default_speaker()
def flush(self): self.device.flush()
def get_player(self, samples_per_frame=None, low_latency=None):
return self.device.player(samplerate=self.samplerate, blocksize=samples_per_frame)
@@ -68,25 +82,24 @@ class WindowsBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from pythoncom import CoInitializeEx, CoUninitialize
self.com_init = CoInitializeEx
self.com_release = CoUninitialize
self.samplerate = samplerate
self.soundcard = soundcard
from .Platforms.windows import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
try: self.device = self.soundcard.get_speaker(preferred_device)
except: self.device = soundcard.default_speaker()
else: self.device = soundcard.default_speaker()
RNS.log(f"Using output device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_speakers(self): return self.soundcard.all_speakers()
def default_speaker(self): return self.soundcard.default_speaker()
def flush(self): self.device.flush()
def get_player(self, samples_per_frame=None, low_latency=None):
self.com_init(0)
return self.device.player(samplerate=self.samplerate, blocksize=samples_per_frame)
def release_player(self): self.com_release()
def release_player(self): pass
def get_backend():
if RNS.vendor.platformutils.is_linux(): return LinuxBackend
@@ -98,6 +111,16 @@ def get_backend():
Backend = get_backend()
class Sink():
release_lock = threading.Lock()
def release(self):
if self.release_lock.locked(): return
with self.release_lock:
if not hasattr(self, "released") or not self.released:
self.released = True
self.should_run = False
self.frame_deque = None
self.backend = None
def handle_frame(self, frame, source): pass
def can_receive(self, from_source=None): return True
@@ -111,7 +134,6 @@ class LineSink(LocalSink):
def __init__(self, preferred_device=None, autodigest=True, low_latency=False):
self.preferred_device = preferred_device
self.frame_deque = deque(maxlen=self.MAX_FRAMES)
self.should_run = False
self.digest_thread = None
self.digest_lock = threading.Lock()
@@ -123,6 +145,7 @@ class LineSink(LocalSink):
self.autostart_min = self.AUTOSTART_MIN
self.buffer_max_height = self.MAX_FRAMES-3
self.low_latency = low_latency
self.streaming = False
self.preferred_samplerate = Backend.SAMPLERATE
self.backend = Backend(preferred_device=self.preferred_device, samplerate=self.preferred_samplerate)
@@ -151,7 +174,9 @@ class LineSink(LocalSink):
RNS.log(f"{self} starting at {self.samples_per_frame} samples per frame, {self.channels} channels", RNS.LOG_DEBUG)
if self.autodigest and not self.should_run:
if len(self.frame_deque) >= self.autostart_min: self.start()
if len(self.frame_deque) >= self.autostart_min:
RNS.log(f"Auto-digest buffer height of {self.autostart_min} reached on {self}, starting", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.start()
def start(self):
if not self.should_run:
@@ -162,6 +187,12 @@ class LineSink(LocalSink):
def stop(self):
self.should_run = False
def wait_for_frames(self):
if len(self.frame_deque) < self.autostart_min:
self.stop()
self.autodigest = True
RNS.log(f"{self} waiting for frames before re-engaging output", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def enable_low_latency(self):
self.__wants_low_latency = True
@@ -179,11 +210,15 @@ class LineSink(LocalSink):
self.underrun_at = None
with self.insert_lock: frame = self.frame_deque.popleft()
if self.channels != self.backend.device.channels:
RNS.log(f"Underlying device for {self} re-configured channel map mid-stream (from {self.channels} to {self.backend.device.channels})", RNS.LOG_WARNING)
self.channels = self.backend.device.channels
if frame.shape[1] > self.channels: frame = frame[:, 0:self.channels]
player.play(frame)
if len(self.frame_deque) > self.buffer_max_height:
RNS.log(f"Buffer lag on {self} (height {len(self.frame_deque)}), dropping one frame", RNS.LOG_DEBUG)
RNS.log(f"Buffer lag on {self} (height {len(self.frame_deque)}), dropping one frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.frame_deque.popleft()
else:
@@ -191,6 +226,7 @@ class LineSink(LocalSink):
# TODO: Remove debug
# RNS.log(f"Buffer underrun on {self}", RNS.LOG_DEBUG)
self.underrun_at = time.time()
if self.streaming: time.sleep((self.frame_time*self.buffer_max_height)/3.0)
else:
if time.time() > self.underrun_at+(self.frame_time*self.frame_timeout):
RNS.log(f"No frames available on {self}, stopping playback", RNS.LOG_DEBUG)
@@ -207,4 +243,131 @@ class LineSink(LocalSink):
self.backend.release_player()
class PacketSink(RemoteSink): pass
class OpusFileSink(LocalSink):
MAX_FRAMES = 64
AUTOSTART_MIN = 1
FINALIZE_TIMEOUT = 2
TYPE_MAP_FACTOR = np.iinfo("int16").max
def __init__(self, path=None, autodigest=True, profile=Opus.PROFILE_AUDIO_MAX):
self.should_run = False
self.digest_thread = None
self.digest_lock = threading.Lock()
self.insert_lock = threading.Lock()
self.frame_deque = deque(maxlen=self.MAX_FRAMES)
self.autodigest = autodigest
self.autostart_min = self.AUTOSTART_MIN
self.buffer_max_height = self.MAX_FRAMES
self.profile = profile
self.bitdepth = 32
self.samplerate = None
self.output_samplerate = Opus.profile_samplerate(self.profile)
self.channels = Opus.profile_channels(self.profile)
self.application = Opus.profile_application(self.profile)
self.bitrate_ceiling = Opus.profile_bitrate_ceiling(self.profile)
self.max_bytes_per_frame = None
self.samples_per_frame = None
self.frame_time = None
self.output_latency = 0
self.max_latency = 0
self.underrun_at = None
self.samples_written = 0
self.__recording_stopped = False
self.__finalized = False
self.__opus_writer = None
self.__encoder = None
self.__output_path = path
@property
def frames_waiting(self): return len(self.frame_deque)
def can_receive(self, from_source=None):
with self.insert_lock:
if self.__recording_stopped: return False
if len(self.frame_deque) < self.buffer_max_height: return True
else: return False
def handle_frame(self, frame, source=None):
with self.insert_lock:
self.frame_deque.append(frame)
if self.samples_per_frame == None:
self.samplerate = source.samplerate
self.samples_per_frame = frame.shape[0]
self.frame_time = self.samples_per_frame*(1/self.samplerate)
if not self.channels: self.channels = frame.shape[1]
RNS.log(f"{self} starting at {self.samples_per_frame} samples per frame, {self.channels} channels", RNS.LOG_DEBUG)
if self.autodigest and not self.should_run:
if len(self.frame_deque) >= self.autostart_min: self.start()
def start(self):
if not self.should_run:
self.should_run = True
self.digest_thread = threading.Thread(target=self.__digest_job, daemon=True)
self.digest_thread.start()
def stop(self):
if self.should_run:
self.__recording_stopped = True
timeout = time.time()+self.FINALIZE_TIMEOUT
while len(self.frame_deque) > 0 and time.time() < timeout: time.sleep(0.05)
self.should_run = False
while self.__finalized == False: time.sleep(0.05)
self.__opus_writer.close()
self.__opus_writer = None
def __digest_job(self):
with self.digest_lock:
from .Codecs.libs.pyogg import OpusBufferedEncoder
from .Codecs.libs.pyogg import OggOpusWriter
if not self.__output_path: raise ValueError("No recording file path configured")
self.max_bytes_per_frame = Opus.max_bytes_per_frame(self.bitrate_ceiling, self.frame_time*1000)
self.__encoder = OpusBufferedEncoder()
self.__encoder.set_application(self.application)
self.__encoder.set_sampling_frequency(self.samplerate)
self.__encoder.set_channels(self.channels)
self.__encoder.set_frame_size(int(self.frame_time*1000))
self.__encoder.set_max_bytes_per_frame(self.max_bytes_per_frame)
self.__opus_writer = OggOpusWriter(self.__output_path, self.__encoder)
final_silence_frames = 10
while self.should_run or final_silence_frames > 0:
frames_ready = len(self.frame_deque) or (self.should_run == False and final_silence_frames)
if frames_ready:
self.output_latency = len(self.frame_deque)*self.frame_time
self.max_latency = self.buffer_max_height*self.frame_time
self.underrun_at = None
if self.should_run:
with self.insert_lock: frame = self.frame_deque.popleft()
else:
final_silence_frames -= 1
frame = np.zeros((self.samples_per_frame, self.channels), dtype="float32")
if frame.shape[1] > self.channels: frame = frame[:, 0:self.channels]
elif frame.shape[1] < self.channels:
for i in range(self.channels - frame.shape[1]):
frame = np.hstack([frame, frame[:, -1:]])
if frame.shape[0] < self.samples_per_frame:
RNS.log("Insufficient frame data, padding with silence", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
silence_frame = np.zeros((self.samples_per_frame-frame.shape[0], frame.shape[1]), dtype=frame.dtype)
frame = np.vstack([frame, silence_frame])
self.samples_written += frame.shape[0]
if self.samplerate != 48000:
frame = resample(frame, self.bitdepth, self.channels, self.samplerate, self.output_samplerate)
input_samples = frame*self.TYPE_MAP_FACTOR
input_samples = input_samples.astype(np.int16)
self.__opus_writer.write(bytearray(input_samples.tobytes()))
if len(self.frame_deque) > self.buffer_max_height: RNS.log(f"Buffer lag on {self} (height {len(self.frame_deque)})", RNS.LOG_DEBUG)
else:
if self.underrun_at == None: self.underrun_at = time.time()
else: time.sleep(self.frame_time*0.1)
self.__finalized = True
+141 -26
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
import os
import RNS
import math
@@ -13,7 +15,7 @@ class LinuxBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from .Platforms.linux import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
@@ -24,7 +26,10 @@ class LinuxBackend():
self.bitdepth = 32
RNS.log(f"Using input device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_microphones(self): return self.soundcard.all_microphones()
def default_microphone(self): return self.soundcard.default_microphone()
def flush(self): self.device.flush()
def get_recorder(self, samples_per_frame):
return self.device.recorder(samplerate=self.SAMPLERATE, blocksize=samples_per_frame)
@@ -46,7 +51,10 @@ class AndroidBackend():
self.bitdepth = 32
RNS.log(f"Using input device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_microphones(self): return self.soundcard.all_microphones()
def default_microphone(self): return self.soundcard.default_microphone()
def flush(self): self.device.flush()
def get_recorder(self, samples_per_frame):
return self.device.recorder(samplerate=self.SAMPLERATE, blocksize=samples_per_frame)
@@ -57,7 +65,7 @@ class DarwinBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from .Platforms.darwin import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
@@ -68,7 +76,10 @@ class DarwinBackend():
self.bitdepth = 32
RNS.log(f"Using input device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_microphones(self): return self.soundcard.all_microphones()
def default_microphone(self): return self.soundcard.default_microphone()
def flush(self): self.device.flush()
def get_recorder(self, samples_per_frame):
return self.device.recorder(samplerate=self.SAMPLERATE, blocksize=samples_per_frame)
@@ -79,12 +90,9 @@ class WindowsBackend():
SAMPLERATE = 48000
def __init__(self, preferred_device=None, samplerate=SAMPLERATE):
import soundcard
from pythoncom import CoInitializeEx, CoUninitialize
self.com_init = CoInitializeEx
self.com_release = CoUninitialize
self.samplerate = samplerate
self.soundcard = soundcard
from .Platforms.windows import soundcard
self.samplerate = samplerate
self.soundcard = soundcard
if preferred_device:
try: self.device = self.soundcard.get_microphone(preferred_device)
except: self.device = self.soundcard.default_microphone()
@@ -93,13 +101,15 @@ class WindowsBackend():
self.bitdepth = 32
RNS.log(f"Using input device {self.device}", RNS.LOG_DEBUG)
def flush(self): self.recorder.flush()
def all_microphones(self): return self.soundcard.all_microphones()
def default_microphone(self): return self.soundcard.default_microphone()
def flush(self): self.device.flush()
def get_recorder(self, samples_per_frame):
self.com_init(0)
return self.device.recorder(samplerate=self.SAMPLERATE, blocksize=samples_per_frame)
def release_recorder(self): self.com_release()
def release_recorder(self): pass
def get_backend():
if RNS.vendor.platformutils.is_linux(): return LinuxBackend
@@ -110,7 +120,21 @@ def get_backend():
Backend = get_backend()
class Source(): pass
class Source():
release_lock = threading.Lock()
def release(self):
if self.release_lock.locked(): return
with self.release_lock:
if not hasattr(self, "released") or not self.released:
self.released = True
self.should_run = False
self.frame_deque = None
self.codec = None
self._sink = None
self._source = None
self._filters = None
self.backend = None
class LocalSource(Source): pass
class RemoteSource(Source): pass
@@ -151,8 +175,12 @@ class Loopback(LocalSource, LocalSink):
class LineSource(LocalSource):
MAX_FRAMES = 128
DEFAULT_FRAME_MS = 80
SIGNAL_FAIL_REINIT_THRESHOLD = 1.5
def __init__(self, preferred_device=None, target_frame_ms=DEFAULT_FRAME_MS, codec=None, sink=None):
@staticmethod
def linear_gain(gain_db): return 10**(gain_db/10)
def __init__(self, preferred_device=None, target_frame_ms=DEFAULT_FRAME_MS, codec=None, sink=None, filters=None, gain=0.0, ease_in=0.0, skip=0.0):
self.preferred_device = preferred_device
self.frame_deque = deque(maxlen=self.MAX_FRAMES)
self.target_frame_ms = target_frame_ms
@@ -165,6 +193,23 @@ class LineSource(LocalSource):
self._codec = None
self.codec = codec
self.sink = sink
self.filters = None
self.ease_in = ease_in
self.gain = gain
self.__skip = skip
self.__gain = self.linear_gain(self.gain)
self.__target_gain = self.__gain
self.__check_signal = RNS.vendor.platformutils.is_android()
self.__signal_failed = None
self.__signal_ok = False
self.__must_reinit = False
if filters != None:
if type(filters) == list: self.filters = filters
else: self.filters = [filters]
if self.ease_in != 0.0: self.__gain = 0.0
@property
def codec(self): return self._codec
@@ -216,19 +261,73 @@ class LineSource(LocalSource):
else: backend_samples_per_frame = None
with self.backend.get_recorder(samples_per_frame=backend_samples_per_frame) as recorder:
started = time.time()
ease_in_completed = True if self.ease_in <= 0.0 else False
skip_completed = True if self.__skip <= 0.0 else False
while self.should_run:
# st = time.perf_counter() # TODO: Remove debug
frame_samples = recorder.record(numframes=self.samples_per_frame)
if self.codec:
frame = self.codec.encode(frame_samples)
if self.sink and self.sink.can_receive(from_source=self):
self.sink.handle_frame(frame, self)
# rt = time.perf_counter()-st # TODO: Remove debug
if self.__check_signal and not self.__signal_ok:
if np.all(frame_samples == 0):
if not self.__signal_failed: self.__signal_failed = time.time()
else:
self.__signal_ok = True
RNS.log(f"Input signal detected on {self}", RNS.LOG_DEBUG)
if not self.__signal_ok and self.__signal_failed:
fail_duration = time.time()-self.__signal_failed
RNS.log(f"No signal for {RNS.prettyshorttime(fail_duration)} on {self}", RNS.LOG_DEBUG)
if fail_duration > self.SIGNAL_FAIL_REINIT_THRESHOLD:
RNS.log(f"Scheduling re-init on {self}", RNS.LOG_DEBUG)
self.__must_reinit = True
self.stop()
if not skip_completed:
if time.time()-started > self.__skip:
skip_completed = True
started = time.time()
else:
# ft = 0 # TODO: Remove debug
if self.filters != None:
# st = time.perf_counter() # TODO: Remove debug
for f in self.filters: frame_samples = f.handle_frame(frame_samples, self.samplerate)
# ft = time.perf_counter()-st # TODO: Remove debug
if self.__gain != 1.0: frame_samples *= self.__gain
if self.codec:
if self.sink and self.sink.can_receive(from_source=self):
try:
# st = time.perf_counter() # TODO: Remove debug
frame = self.codec.encode(frame_samples)
self.sink.handle_frame(frame, self)
# et = time.perf_counter()-st # TODO: Remove debug
except Exception as e: RNS.log(f"Encode error on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
# RNS.log(f"REC/FLT/SNK: {RNS.prettyshorttime(rt)} / {RNS.prettyshorttime(ft)}, / {RNS.prettyshorttime(et)}", RNS.LOG_DEBUG) # TODO: Remove debug
if not ease_in_completed:
d = time.time()-started
self.__gain = (d/self.ease_in)*self.__target_gain
if self.__gain >= self.__target_gain:
self.__gain = self.__target_gain
ease_in_completed = True
if self.__must_reinit:
self.__must_reinit = False
self.__signal_ok = False
self.__signal_failed = None
self.start()
class OpusFileSource(LocalSource):
MAX_FRAMES = 128
DEFAULT_FRAME_MS = 70
DEFAULT_FRAME_MS = 100
TYPE_MAP_FACTOR = np.iinfo("int16").max
def __init__(self, file_path, target_frame_ms=DEFAULT_FRAME_MS, loop=False, codec=None, sink=None, timed=False):
@staticmethod
def linear_gain(gain_db): return 10**(gain_db/10)
def __init__(self, file_path, target_frame_ms=DEFAULT_FRAME_MS, loop=False, codec=None, sink=None, timed=False, gain=0.0):
self.target_frame_ms = target_frame_ms
self.loop = loop
self.timed = timed
@@ -237,6 +336,8 @@ class OpusFileSource(LocalSource):
self.ingest_thread = None
self.next_frame = None
self._codec = None
self._gain_db = gain
self.__gain = self.linear_gain(self._gain_db)
if file_path == None: raise TypeError(f"{self} initialised with invalid file path: {file_path}")
elif os.path.isfile(file_path):
@@ -255,6 +356,19 @@ class OpusFileSource(LocalSource):
self.codec = codec
self.sink = sink
@property
def running(self): return self.should_run
@property
def gain(self): return self._gain_db
@gain.setter
def gain(self, db):
try: db = float(db)
except: raise TypeError("Invalid gain type, must be decibel as a floating point number")
self._gain_db = db
self.__gain = self.linear_gain(self._gain_db)
@property
def codec(self): return self._codec
@@ -303,6 +417,7 @@ class OpusFileSource(LocalSource):
fi += 1
fs = (fi-1)*spf; fe = min(fi*spf, sc)
frame_samples = self.samples[fs:fe, :]
if self.__gain != 1.0: frame_samples *= self.__gain
if len(frame_samples) < 1:
if self.loop:
RNS.log(f"{self} exhausted file samples, looping...", RNS.LOG_DEBUG)
@@ -312,10 +427,10 @@ class OpusFileSource(LocalSource):
self.should_run = False
else:
if self.codec:
frame = self.codec.encode(frame_samples)
if self.sink and self.sink.can_receive(from_source=self):
self.sink.handle_frame(frame, self)
try:
frame = self.codec.encode(frame_samples)
self.sink.handle_frame(frame, self)
except Exception as e: RNS.log(f"Encode error on {self}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else:
time.sleep(self.frame_time*0.1)
class PacketSource(RemoteSource): pass
+2
View File
@@ -1,5 +1,7 @@
#!/usr/bin/env python3
# Copyright 2024-2026, Mark Qvist
import RNS
import os
import sys
+2
View File
@@ -1,3 +1,5 @@
# Copyright 2024-2026, Mark Qvist
APP_NAME = "lxst"
from .Pipeline import Pipeline
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.4.0"
__version__ = "0.6.0"
+33
View File
@@ -0,0 +1,33 @@
This repository is a public mirror. All potential future development is happening elsewhere.
I am stepping back from all public-facing interaction with this project. Reticulum has always been primarily my work, and continuing in the current public, internet-facing model is no longer sustainable.
The software remains available for use as-is. Occasional updates may appear at unpredictable intervals, but there will be no support, no responses to issues, no discussions, and no community management in this or any other public venue. If it doesn't work for you, it doesn't work. That is the entire extent of available troubleshooting assistance I can offer you.
If you've followed this project for a while, you already know what this means. You know who designed, wrote and tested this, and you know how many years of my life it took. You'll also know about both my particular challenges and strengths, and how I believe anything worth building needs to be built and maintained with our own hands.
Seven months ago, I said I needed to step back, that I was exhausted, and that I needed to recover. I believed a public resolve would be enough to effectuate that, but while striving to get just a few more useful features and protocols out, the unproductive requests and demands also ramped up, and I got pulled back into the same patterns and draining interactions that I'd explicitly said I couldn't sustain anymore.
So here's what you might have already guessed: I'm done playing the game by rules I can't win at.
Everything you need is right here, and by any sensible measure, it's done. Anyone who wants to invest the time, skill and persistence can build on it, or completely re-imagine it with different priorities. That was always the point.
The people who actually contributed - you know who you are, and you know I mean it when I say: Thank you. All of you who've used this to build something real - that was the goal, and you did it without needing me to hold your hand.
The rest of you: You have what you need. Use it or don't. I am not going to be the person who explains it to you anymore.
This is not a temporary break. It's not "see you after some rest", but a recognition that the current model is fundamentally incompatible with my life, my health, and my reality.
If you want to support continued work, you can do so at the donation links listed in this repository. But please understand, that this is not purchasing support or guaranteeing updates. It is support for work that happens on my timeline, according to my capacity, which at the moment is not what it was.
If you want Reticulum to continue evolving, you have the power to make that happen. The protocol is public domain. The code is open source. Everything you need is right here. I've provided the tools, but building what comes next is not my responsibility anymore. It's yours.
To the small group of people who has actually been here, and understood what this work was and what it cost - you already know where to find me if it actually matters.
To everyone else: This is where we part ways. No hard feelings. It's just time.
---
असतो मा सद्गमय
तमसो मा ज्योतिर्गमय
मृत्योर्मा अमृतं गमय
+39 -4
View File
@@ -2,8 +2,9 @@ all: release
clean:
@echo Cleaning...
-rm -r ./build
-rm -r ./dist
-rm -rf ./build
-rm -rf ./dist
-rm -r ./LXST/__pycache__
remove_symlinks:
@echo Removing symlinks for build...
@@ -18,13 +19,47 @@ create_symlinks:
-ln -s ../LXST/ ./examples/LXST
build_wheel:
python3 setup.py sdist bdist_wheel
cp ./lib/static/* ./LXST/
touch ./skip_extensions
python3 setup.py bdist_wheel
rm ./skip_extensions
-@(rm ./LXST/*.so)
-@(rm ./LXST/*.dll)
build_sdist:
cp ./lib/static/* ./LXST/
touch ./skip_extensions
python3 setup.py sdist
rm ./skip_extensions
-@(rm ./LXST/*.so)
-@(rm ./LXST/*.dll)
windll:
cl /LD LXST/Filters.c LXST/Filters.def /Fefilterlib.dll
mv ./filterlib.dll ./lib/dev/
rm ./filterlib.exp
rm ./filterlib.lib
rm ./filterlib.obj
native_libs:
./march_build.sh
persist_libs:
-cp ./lib/dev/*.so ./lib/static/
-cp ./lib/dev/*.dll ./lib/static/
build_spkg: remove_symlinks build_sdist create_symlinks
release: remove_symlinks build_wheel create_symlinks
upload:
@echo Ready to publish release over Reticulum
@read VOID
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/lxst create $$(python setup.py --getversion):dist --name lxst
upload-pip:
@echo Ready to publish release, hit enter to continue
@read VOID
@echo Uploading to PyPi...
twine upload dist/*
twine upload dist/lxst-*.whl
@echo Release published
+42 -3
View File
@@ -1,5 +1,20 @@
# Lightweight Extensible Signal Transport
> [!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.
*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
@@ -31,15 +46,39 @@ LXST is a simple and flexible real-time streaming format and delivery protocol t
- Uses a fully staged signal pipelining, allowing arbitrary stream routing
- Provides built-in signal mixing support for any number of channels
User-facing clients built on LXST include:
- [Sideband](https://unsigned.io/sideband)
- [MeshChatX](https://meshchatx.com/)
- [Partyline](https://github.com/RFnexus/partyline)
- [Columba](https://github.com/torlando-tech/columba)
- [Ratspeak](https://github.com/ratspeak/)
- [rnphone](https://reticulum.network/manual/software.html#reticulum-network-telephone)
- [LXST Phone](https://github.com/kc1awv/lxst_phone)
## Transport Encryption
LXST uses encryption provided by [Reticulum](https://reticulum.network), and thus provides end-to-end encryption, guaranteed data integrity and authenticity, as well as forward secrecy by default.
## Project Status & License
This software is in a very early alpha state, and will change rapidly with ongoing development. Consider no APIs stable. Consider everything explosive. Not all features are implemented. Nothing is documented. For a fully functional LXST program, take a look at [Sideband](https://github.com/markqvist/Sideband) or the included `rnphone` program, which provides telephony service over Reticulum. Everything else will currently be a voyage of your own making.
This software and its interfaces will change rapidly with ongoing development. Consider no APIs stable. Consider everything explosive. Not all features are implemented. Nothing is documented. For a fully functional LXST program, take a look at [Sideband](https://github.com/markqvist/Sideband) or the included `rnphone` program, which provides telephony service over Reticulum. Everything else will currently be a voyage of your own making.
While under early development, 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 use and deploy LXST freely for non-commercial, personal and humanitarian purposes, including in your own programs. At this point, no derivatives are allowed without an explicit license.
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
@@ -59,4 +98,4 @@ sudo apt install python3-pyaudio codec2
pip install smbus2 --break-system-packages # Install smbus module if not already installed
sudo raspi-config # Enable the I2C bus under "Interface Options"
sudo apt install python3-rpi.gpio # Install gpio module system-wide
```
```
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
# This script is used to run the binary wheel builds
# inside docker containers for multi-arch compilation
set -e -x
yum install -y gcc gcc-c++ make codec2-devel codec2
PYTHON_VERSIONS=(
"cp311-cp311"
"cp312-cp312"
"cp313-cp313"
"cp314-cp314"
)
for PY_TAG in "${PYTHON_VERSIONS[@]}"; do
PYBIN="/opt/python/${PY_TAG}/bin"
if [ ! -d "$PYBIN" ]; then
echo "Python version not found: $PYBIN"
continue
fi
echo "Building with: $PYBIN"
"${PYBIN}/pip" install cffi
"${PYBIN}/pip" wheel /io/ -w wheelhouse/
done
+23
View File
@@ -0,0 +1,23 @@
import sys
import time
import select
from LXST.Primitives.Players import FilePlayer
loop = False
if loop:
player = FilePlayer("./docs/speech_stereo.opus", loop=True)
player.start()
while player.running:
i, o, e = select.select([sys.stdin], [], [], 1.0)
if (i): player.stop()
else:
player = FilePlayer("./docs/speech_stereo.opus")
player.release_on_finish = True
player.start()
while player.running: time.sleep(0.1)
print("Playback finished")
+24
View File
@@ -0,0 +1,24 @@
import sys
import time
import select
from LXST.Primitives.Recorders import FileRecorder
filename = "recording.opus"
# With default profile (maximum quality)
recorder = FileRecorder(filename)
# Or, with specific profile
# from LXST.Codecs import Opus
# recorder = FileRecorder(filename, profile=Opus.PROFILE_VOICE_MEDIUM)
recorder.start()
print("Recording started")
try: input()
except KeyboardInterrupt: pass
recorder.stop()
print(f"Recording saved to {filename}")
time.sleep(0.2)
+23
View File
@@ -0,0 +1,23 @@
import RNS
import LXST
import sys
import time
from LXST.Filters import BandPass, AGC
target_frame_ms = 40
raw = LXST.Codecs.Raw()
filters = [BandPass(200, 8500), AGC()]
line_sink = LXST.Sinks.LineSink()
mixer = LXST.Mixer(target_frame_ms=target_frame_ms, sink=line_sink)
line_source = LXST.Sources.LineSource(target_frame_ms=target_frame_ms, codec=raw, sink=mixer, filters=filters)
mixer.start()
line_source.start()
print("Hit enter stop"); input()
line_source.stop()
time.sleep(0.5)
Executable
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
TARGET_DIR="${1:-./lib/dev}"
mkdir -p "$TARGET_DIR"
echo "Copying native libraries to $TARGET_DIR..."
find ./build -name "filterlib*.*" -type f \( -name "*.so" -o -name "*.dll" -o -name "*.dylib" \) -exec cp {} "$TARGET_DIR/" \;
echo "Done. Copied files:"
ls -lh "$TARGET_DIR/"
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
docker run --rm -v $(pwd):/io quay.io/pypa/manylinux_2_34_x86_64 /io/build_wheels.sh
docker run --rm -v $(pwd):/io quay.io/pypa/manylinux_2_34_aarch64 /io/build_wheels.sh
docker run --rm -v $(pwd):/io quay.io/pypa/manylinux_2_39_riscv64 /io/build_wheels.sh
# docker run --rm -v $(pwd):/io quay.io/pypa/manylinux_2_31_armv7l /io/build_wheels.sh
# docker run --rm -v $(pwd):/io quay.io/pypa/musllinux_1_2_x86_64 /io/build_wheels.sh
# docker run --rm -v $(pwd):/io quay.io/pypa/musllinux_1_2_aarch64 /io/build_wheels.sh
# docker run --rm -v $(pwd):/io quay.io/pypa/musllinux_1_2_armv7l /io/build_wheels.sh
# docker run --rm -v $(pwd):/io quay.io/pypa/musllinux_1_2_riscv64 /io/build_wheels.sh
./fetch_libs.sh
+3 -1
View File
@@ -1,3 +1,5 @@
soundcard
rns
lxmf
cffi
numpy
pycodec2
+37 -7
View File
@@ -1,10 +1,29 @@
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import os
import sys
import platform
with open("README.md", "r") as fh:
long_description = fh.read()
if os.path.isfile("./skip_extensions"): BUILD_EXTENSIONS = False
else: BUILD_EXTENSIONS = True
if os.name == "nt": BUILD_EXTENSIONS = False
with open("README.md", "r") as fh: long_description = fh.read()
exec(open("LXST/_version.py", "r").read())
if "--getversion" in sys.argv:
print(__version__, end="")
exit(0)
if BUILD_EXTENSIONS: print(f"Building LXST with native extensions...")
else: print(f"Building LXST without native extensions...")
c_sources = ["LXST/Filters.c"]
if BUILD_EXTENSIONS: extensions = [ Extension("LXST.filterlib", sources=c_sources, include_dirs=["LXST"], language="c"), ]
else: extensions = []
packages = setuptools.find_packages(exclude=[])
packages.append("LXST.Utilities")
packages.append("LXST.Primitives.hardware")
@@ -16,6 +35,15 @@ package_data = {
"Codecs/libs/pyogg/libs/win_amd64/*",
"Codecs/libs/pyogg/libs/macos/*",
"Sounds/*",
],
"LXST": [
"Filters.h",
"Filters.c",
"filterlib*.so",
"filterlib*.dll",
"Platforms/linux/pulseaudio.h",
"Platforms/darwin/coreaudio.h",
"Platforms/windows/mediafoundation.h",
]
}
@@ -30,6 +58,8 @@ setuptools.setup(
url="https://git.unsigned.io/markqvist/lxst",
packages=packages,
package_data=package_data,
ext_modules=extensions,
cmdclass={"build_ext": build_ext},
classifiers=[
"Programming Language :: Python :: 3",
"License :: Other/Proprietary License",
@@ -40,11 +70,11 @@ setuptools.setup(
'rnphone=LXST.Utilities.rnphone:main',
]
},
install_requires=["rns>=1.0.1",
"lxmf>=0.9.1",
"soundcard>=0.4.5",
install_requires=["rns>=1.6.0",
"lxmf>=1.3.0",
"numpy>=2.3.4",
"pycodec2>=4.1.0",
"audioop-lts>=0.2.1;python_version>='3.13'"],
python_requires=">=3.7",
"audioop-lts>=0.2.1;python_version>='3.13'",
"cffi>=2.0.0"],
python_requires=">=3.11",
)