Move worker arming rejection and resampler block loops into native code

This commit is contained in:
Cryan209 committed 2026-11-23 14:47:00 +13:00
1 parent d138dc27b5
commit e84e324167
14 files changed
+1001 -33

No files matched your search

+7 -1
View File
@@ -399,7 +399,13 @@ for measured workloads and remaining limits. Eligible native-worker runs also
use native batch-call setup and empty post-run cleanup; see
[native worker wrapper measurements](docs/native-worker-wrapper-performance.md).
`COURIER_X86_NATIVE_WRAPPER=0` retains the Python wrapper without disabling
native CPU execution.
native CPU execution. A further worker arming-rejection gate and native
fixed-rate FIR/polyphase block loops are described in
[native service/resampler performance](docs/native-service-resample-performance.md).
`COURIER_NATIVE_ARM_GATE=0`, `COURIER_NATIVE_FIXED_RESAMPLE=0`, and
`COURIER_NATIVE_POLYPHASE=0` disable those paths independently. The resampler
kernels use only an already-loaded core library; older libraries retain Python
fallbacks. These execution-cost improvements do not establish live-call stability.
It uses `uv` when that is on `PATH` and falls back to `venv` plus `pip`
otherwise. `PYTHON=<interpreter>` chooses the interpreter it builds the
+8
View File
@@ -4133,6 +4133,14 @@ class CourierMachine:
worker_arm[0] = True
uc.native_before_run = before_run
# These are sufficient rejection conditions, not a replacement
# for arm's eligibility/deadline checks. Exact classes only: the
# extension must not bypass a subclass's attribute dispatch.
uc.native_before_run_gate = (
(before_run, worker_arm, self,
('_serial_started', 'online_mode', 'serial_rx'), deque)
if type(self) is CourierMachine and type(bridge) is CourierDspBridge
and os.environ.get('COURIER_NATIVE_ARM_GATE', '1') != '0' else None)
uc.native_after_run = after_run
uc.native_after_run_gate = (
(after_run, *poll.after_run_gate) if poll.after_run_gate is not None else None)
+44 -13
View File
@@ -23,9 +23,13 @@ from __future__ import annotations
import ctypes
import math
import os
import sys
from array import array
from bisect import bisect_left, bisect_right
from operator import mul
from types import BuiltinFunctionType
from . import resample_native
# Input samples each side of the output instant. 64 narrows the transition
# band enough that 8 kHz <-> 9600 Hz stays at 62-75 dB SNR for tones from
@@ -44,7 +48,18 @@ PHASES = 1024
# C-implemented dot product where the interpreter has one (3.12+); the FIR
# below runs it once per output sample.
_dot = getattr(math, "sumprod", None) or (lambda a, b: sum(map(mul, a, b)))
_fallback_dot = lambda a, b: sum(map(mul, a, b))
_dot = getattr(math, "sumprod", None) or _fallback_dot
_REFERENCE_SUM, _REFERENCE_MUL = sum, mul
_FIXED_DOT_MODE = int(_dot is not _fallback_dot)
# Only accelerate known stdlib arithmetic, never an import-time replacement.
# Python 3.12+ sum is compensated even if math.sumprod has been removed.
_REFERENCE_DOT = _dot if (
(type(_dot) is BuiltinFunctionType and _dot.__module__ == 'math'
and _dot.__name__ == 'sumprod') or
(_dot is _fallback_dot and sys.version_info < (3, 12)
and type(sum) is BuiltinFunctionType and sum.__module__ == 'builtins' and sum.__name__ == 'sum'
and type(mul) is BuiltinFunctionType and mul.__module__ == '_operator' and mul.__name__ == 'mul')) else None
def _bessel_i0(x: float) -> float:
@@ -292,6 +307,7 @@ class BandLimitedResampler:
# Output instant, in input samples, relative to _history[HALF_TAPS-1].
self._position = 0.0
self._kernel: list[tuple[float, ...]] | None = None
self._fixed_kernel_key = None
# Keep extra input history for a clock change: its old sample spacing
# must survive until the FIR window has crossed the boundary.
self._recent_input: list[float] = [0.0] * (2 * TAPS)
@@ -416,8 +432,9 @@ class BandLimitedResampler:
if output_rate != self.output_rate or input_rate != self.input_rate:
input_changed = input_rate != self.input_rate
self.input_rate, self.output_rate = input_rate, output_rate
self._kernel = _kernel_for(
CUTOFF * min(input_rate, output_rate) / 2 / input_rate)
cutoff = CUTOFF * min(input_rate, output_rate) / 2 / input_rate
self._kernel = _kernel_for(cutoff)
self._fixed_kernel_key = round(cutoff, 9)
if input_changed:
self._position = 0.0
kernel = self._kernel
@@ -428,16 +445,30 @@ class BandLimitedResampler:
result: list[int] = []
position = self._position
limit = len(history) - TAPS
while position <= limit:
base = int(position)
phase = int((position - base) * PHASES + 0.5)
if phase == PHASES:
base, phase = base + 1, 0
if base > limit:
break
value = _dot(kernel[phase], history[base:base + TAPS])
result.append(max(-32768, min(32767, int(round(value)))))
position += step
native = None
# Amortize block marshalling; tiny conversions keep the scalar loop.
if (type(position) is float and type(step) is float and step > 0
and limit - position >= 31 * step
and sys.implementation.name == 'cpython' and _dot is _REFERENCE_DOT
and (_FIXED_DOT_MODE or (sum is _REFERENCE_SUM and mul is _REFERENCE_MUL))
and self._fixed_kernel_key is not None
and kernel is _KERNELS.get(self._fixed_kernel_key)
and resample_native.fixed_available()):
native = resample_native.fixed(history, _flat_kernel_for(self._fixed_kernel_key),
step, position, _FIXED_DOT_MODE)
if native is not None:
result, position = native
else:
while position <= limit:
base = int(position)
phase = int((position - base) * PHASES + 0.5)
if phase == PHASES:
base, phase = base + 1, 0
if base > limit:
break
value = _dot(kernel[phase], history[base:base + TAPS])
result.append(max(-32768, min(32767, int(round(value)))))
position += step
consumed = len(history) - TAPS
self._history = history[consumed:]
self._position = position - consumed
+110
View File
@@ -0,0 +1,110 @@
"""Optional stateless FIR block kernels on an already loaded core library.
Results are transactional: None declines to the Python loop without committing
stream state. Scratch chunks bound allocation, not audio or output retention.
"""
from array import array
import ctypes as c
import math
import os
_binding = None
def _function(kind):
if (os.environ.get('COURIER_NATIVE_RESAMPLE', '1') == '0' or
os.environ.get('COURIER_NATIVE_' + ('FIXED_RESAMPLE' if kind == 'fixed' else 'POLYPHASE'), '1') == '0'):
return None
from .dsp import loaded_library
library = loaded_library()
if library is None:
return None
global _binding
if _binding is None or _binding[0] is not library:
functions = {}
signatures = {
'fixed': [c.c_void_p, c.c_size_t, c.c_void_p, c.c_size_t,
c.c_double, c.c_double, c.c_void_p, c.c_size_t,
c.c_void_p, c.c_void_p, c.c_uint],
'polyphase': [c.c_void_p, c.c_size_t, c.c_void_p, c.c_size_t,
c.c_uint64, c.c_uint64, c.c_uint64, c.c_int64,
c.c_int64, c.c_int64, c.c_void_p, c.c_size_t,
c.c_void_p, c.c_void_p],
}
for name, signature in signatures.items():
function = getattr(library, 'courier_resample_' + name, None)
if function is not None:
# Packet-sized kernels must not surrender the GIL to a busy
# emulator thread and then wait a switch interval to return.
function = c.PYFUNCTYPE(c.c_size_t, *signature)(
c.cast(function, c.c_void_p).value)
function._library_owner = library
functions[name] = function
_binding = (library, functions)
return _binding[1][kind]
def fixed_available():
return _function('fixed') is not None
def polyphase_available():
return _function('polyphase') is not None
def _collect(function, args, cursor, capacity):
out = array('h', [0]) * capacity
status = c.c_int()
result = []
while True:
before = cursor.value
count = function(*args(before), out.buffer_info()[0], capacity,
c.byref(cursor), c.byref(status))
if status.value == 1:
return None
if status.value not in (0, 2) or count > capacity:
raise RuntimeError('invalid native resampler result')
result.extend(out[:count].tolist())
if status.value == 0:
return result, cursor.value
if count == 0:
raise RuntimeError('native resampler made no progress')
if cursor.value == before:
# A positive but sub-ulp step must retain the reference behavior.
return None
def fixed(history, kernel, step, position, mode):
function = _function('fixed')
if (function is None or type(step) is not float or type(position) is not float
or not (math.isfinite(step) and step > 0 and
math.isfinite(position) and 0 <= position <= 2**52)):
return None
values = array('d', history)
estimate = (len(values) - 128 - position) / step
if not math.isfinite(estimate):
return None
capacity = min(1024, max(1, math.ceil(estimate) + 2))
cursor = c.c_double(position)
# The mode is the last C argument; adapt the shared chunk collector.
def invoke(*args):
return function(*args, mode)
return _collect(invoke, lambda pos: (values.buffer_info()[0], len(values),
kernel.buffer_info()[0], len(kernel), step, pos), cursor, capacity)
def polyphase(history, kernel, up, down, taps, half, origin, output):
function = _function('polyphase')
if (function is None or any(type(v) is not int for v in
(up, down, taps, half, origin, output))
or not (0 < up <= 1024 and 0 < down <= 2**20 and
0 < taps <= 4096 and 0 <= half <= taps and abs(origin) <= 2**52 and
0 <= output <= 2**52 // down)):
return None
values = array('d', history)
newest = origin + len(values) - 1
last = ((newest - half + 1) * up - 1) // down
capacity = min(1024, max(1, last - output + 1))
return _collect(function, lambda index: (values.buffer_info()[0], len(values),
kernel.buffer_info()[0], len(kernel), up, down, taps, half,
origin, index), c.c_int64(output), capacity)
+51 -15
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from array import array
from collections import deque
from dataclasses import asdict, dataclass
from hashlib import md5
@@ -13,7 +14,7 @@ import threading
import time
from .rtp import RtpPlayout, RtpReceiveStats, RtpTransmitStats, parse_rtp
from . import g711_native
from . import g711_native, resample_native
SIP_PORT = 5060
@@ -145,6 +146,15 @@ class PolyphaseResampler:
self._buffer: list[float] = [0.0] * self.taps_per_phase
self._origin = -self.taps_per_phase
self._output = 0
self._native_kernel = None
# Only an acceleration heuristic: never changes sample readiness.
# Amortize interop/table validation over at least 32 outputs and one
# phase table's worth of dot products. Nonstandard numeric rates fall
# back without invoking additional arithmetic callbacks.
self._native_min_buffer = (
self.taps_per_phase + (max(32, self.up) * self.down + self.up - 1) // self.up
if all(type(v) is int for v in (self.up, self.down, self.taps_per_phase))
and self.up > 0 and self.down > 0 else math.inf)
def _design(self) -> list[list[float]]:
"""Return the filter as `up` phases of `taps_per_phase` taps each."""
@@ -181,6 +191,22 @@ class PolyphaseResampler:
phases.append([tap / total for tap in taps])
return phases
def _native_coefficients(self):
# Bound table-validation work for unusual nearly-coprime rates. Custom
# numeric taps keep their Python multiplication semantics.
if (type(self.up) is not int or type(self.taps_per_phase) is not int
or type(self._taps) not in (list, tuple)
or not (0 < self.up <= 1024 and 0 < self.taps_per_phase <= 4096)
or any(type(row) not in (list, tuple) for row in self._taps)):
return None
rows = tuple(tuple(row) for row in self._taps)
if (len(rows) != self.up or any(len(row) != self.taps_per_phase for row in rows)
or any(type(value) is not float for row in rows for value in row)):
return None
if self._native_kernel is None or rows != self._native_kernel[0]:
self._native_kernel = (rows, array('d', (v for row in rows for v in row)))
return self._native_kernel[1]
def convert(self, samples) -> list[int]:
"""Take input samples and return every output sample now determined."""
if self.up == self.down == 1:
@@ -192,20 +218,30 @@ class PolyphaseResampler:
return [int(sample) for sample in samples]
self._buffer.extend(float(sample) for sample in samples)
result: list[int] = []
newest = self._origin + len(self._buffer) - 1
while True:
position = self._output * self.down
base = position // self.up
if base + self._half > newest:
break
taps = self._taps[position % self.up]
total = 0.0
for index, tap in enumerate(taps):
sample = base + self._half - index - self._origin
if 0 <= sample < len(self._buffer):
total += tap * self._buffer[sample]
result.append(max(-32_768, min(32_767, int(round(total)))))
self._output += 1
length = len(self._buffer)
newest = self._origin + length - 1
native = None
if length >= self._native_min_buffer and resample_native.polyphase_available():
kernel = self._native_coefficients()
if kernel is not None:
native = resample_native.polyphase(self._buffer, kernel, self.up, self.down,
self.taps_per_phase, self._half, self._origin, self._output)
if native is not None:
result, self._output = native
else:
while True:
position = self._output * self.down
base = position // self.up
if base + self._half > newest:
break
taps = self._taps[position % self.up]
total = 0.0
for index, tap in enumerate(taps):
sample = base + self._half - index - self._origin
if 0 <= sample < len(self._buffer):
total += tap * self._buffer[sample]
result.append(max(-32_768, min(32_767, int(round(total)))))
self._output += 1
# Drop everything the next output can no longer reach back to.
oldest = (self._output * self.down) // self.up + self._half - self.taps_per_phase + 1
drop = oldest - self._origin
+2
View File
@@ -249,6 +249,8 @@ class Uc:
# Optional (callback identity, native gate function, context). A zero
# gate result means native code already performed the callback's work.
self.native_after_run_gate: tuple[object, int, int] | None = None
# Trusted worker-only rejection gate; extensions without it ignore it.
self.native_before_run_gate = None
self.native_after_io: Callable[[], None] | None = None
self.native_host_base = 0
# Optional filter for native_after_io: a 64 KiB table of ports.
+201
View File
@@ -0,0 +1,201 @@
# Native worker rejection and remaining resampler loops
This follows the [native worker wrapper](native-worker-wrapper-performance.md).
It moves two more bounded kinds of work out of Python, without altering clocks,
service deadlines, RTP packet sizes, media reserves, or acceptance criteria.
It is **not a live-call stability qualification**. The rejection gate saves most
work in boot/command mode with queued AT input; successful data-mode arming is
unchanged. Connected-only speedup is not established by the whole-replay result.
## Worker arming rejection
The native x86 wrapper can skip the internal `before_run` callback when:
- No worker arming request exists. The original callback does nothing here.
- `_serial_started` is exactly `True`: `fast_service_static` must reject.
- Input is queued in an exact ordinary `deque` and `online_mode` is exactly
`False`: `_serial_receive_quiet_until` must return `None`, so
`timer_poll_static` must reject.
Rejected requests are cleared, just as `arm()` clears them before checking
eligibility. No worker snapshot is modified. All other cases still run the
**complete original Python arming checks**, including every device/deadline
boundary. This does not move successful arming, device ownership, or nonempty
post-run publication into C++; those remain further work.
The gate is bound to callback identity. Replacing the callback cannot bypass
it. Registration is restricted to exact `CourierMachine`/`CourierDspBridge`
classes; custom queue types keep their truth callbacks. This is an optional CPU
attribute, not a change to the existing extension argument tuple. Older x86
extensions simply call the original callback. `COURIER_NATIVE_ARM_GATE=0`
disables registration without disabling native execution or empty cleanup.
## Native fixed-rate FIR and polyphase blocks
Two optional C API exports, `courier_resample_fixed` and
`courier_resample_polyphase`, execute the previously Python output loops.
- **Fixed-rate FIR:** retains the original 128-tap/1024-phase coefficients,
floating position additions, nearest phase, history trim, saturation, and
ties-to-even integer rounding. CPython with `math.sumprod` uses the existing
compensated native dot; CPython 3.10/3.11 without it uses separate binary64
products and sequential additions, matching its original `sum(map(mul, ...))`.
Newer CPython without standard `math.sumprod` retains Python's compensated
`sum` fallback; import-time replacement functions are never bypassed.
Volatile product temporaries prohibit accidental FMA contraction in that
latter mode. Non-CPython interpreters and custom `_dot` callbacks keep Python.
- **Rational polyphase:** retains the original tap order, reverse history
indexing, integer phase/output counters, padding, trim, flush, and equal-rate
passthrough. Separate multiply/add semantics are required even on FMA hosts.
Cached native coefficients are checked against the current Python table;
changed tables are rebuilt, and custom numeric taps use Python. More than
1024 phases, more than 4096 taps/phase, or unusually large counters/rate ratios
conservatively use Python, **not different rates or reduced precision**.
- Small blocks keep Python to amortize marshalling and table validation. These
eligibility heuristics do not change sample readiness or output counts.
- Both use an **already-loaded** core library. Neither implicitly builds or
loads the DSP library; missing optional exports preserve Python-only and
older-library operation.
- C calls retain the GIL so a short packet kernel does not surrender it to a
busy emulator thread and wait a switch interval to return. Output scratch is
bounded to 1024 samples/call; larger blocks resume and append **all** output.
This is interop scratch, not an emulated queue or a media-buffer change.
- Input/coefficient arrays have strong Python owners throughout each call.
There are no persistent raw stream-buffer pointers or native stream objects.
Results commit only after successful completion. Nonfinite/unsupported data
declines to the original Python loop, preserving exceptions and partial
stream-state changes. No failures become missing PCM.
Disable independently with `COURIER_NATIVE_FIXED_RESAMPLE=0` and
`COURIER_NATIVE_POLYPHASE=0`. The existing `COURIER_NATIVE_RESAMPLE=0` process
switch also disables these new kernels.
## Measurement method
The actual pre-change source was saved from `d138dc2`. The final control uses
an original-source Python package (including the old CPU constructor), the
separately compiled original x86 binary, and the separately compiled original
DSP C API/resampler header. Unchanged package files are shared by symlink;
bytecode compilation is outside timing. Both libraries use matching compiler
options. Neither candidate-disable controls nor a common newly modified DSP
library alone serve as the final baseline.
The socket-free 300M-instruction replay includes boot, training, CONNECT, and
subsequent NO CARRIER. Every complete report and both recorded WAV hashes must
match. These are whole-replay costs, not connected-only costs.
`tools/benchmark_resample_pipeline.py` measures a **complete offline audio
pipeline**, not just a native dot-product microbenchmark:
```
PCM -> TX resampler -> 160-sample SIP queue/G.711 encode
-> G.711 decode -> RX resampler -> PCM
```
The fixed pipeline runs 48 kHz -> 8 kHz -> 48 kHz; polyphase runs
7200 Hz -> 8 kHz -> 7200 Hz. Each sample processes 30 simulated seconds.
Filter design, compilation, and a one-block warm-up are outside timing.
Wire/PCM hashes, packet/sample counts, pending TX contents, and final counters
and floating stream-state hashes must all match the actual reference source.
For example, after saving the old `resample.py` and `sip.py`:
```sh
python tools/benchmark_resample_pipeline.py --kind fixed --seconds 30 \
--reference-dir /path/to/pre-change/courier_emu
python tools/benchmark_resample_pipeline.py --kind fixed --seconds 30
```
Use alternating pinned child processes (ABBA then BAAB), not these two commands
alone, for a performance decision. The replay intentionally bypasses real RTP;
the separate pipeline exercises resamplers/codecs/queues but not sockets or
real-time scheduling.
### Vmhost replay and pipeline results
Debian CPython 3.11.2, Clang 19.1.7, pinned CPU3 (advertised 4.4 GHz);
allowed CPUs were `[3, 6, 7, 11]`. Do not compare absolute times with the prior
wrapper experiment's CPU5/E-core runs. Compiler options:
- DSP: `-std=c++17 -O3 -fno-semantic-interposition -shared -fPIC`.
- x86: `-std=c++17 -O3 -Wall -Wextra -shared -fPIC -I/usr/include/python3.11`.
Eight complete replay children, ABBA then BAAB, using the full original source
package and both original libraries as the control:
| Median seconds | Actual pre-change | Candidate | Reduction |
| --- | ---: | ---: | ---: |
| Wall | 28.82496 | 28.39733 | 1.48% |
| Process CPU | 28.77712 | 28.34570 | 1.50% |
An earlier eight-run series sharing the candidate DSP library showed 1.87%
lower CPU cost; the stricter full-original comparison above is the headline
result. All alternating series were positive, but the modest gain is
workload/host-specific.
Every full report and both WAVs match, including the canonical hashes:
- RX: `55a7640af4ec1d159334bb39969fbdbb0d82689e5b78959c8c11a641517013c0`
- TX: `6f4b2418571c7bdf0abe2014e5ae1c8a7cc70e430df8be281bfa14b0de93caa1`
A separate rejection-only Clang 14.0.6 ABBA check kept the old resampler/SIP
source in both variants: median CPU 28.89690 -> 28.46931 seconds (**1.48%**).
The replay is dominated by supervisor/retuned-native paths, not the two new
steady-state block kernels. Their benefit is measured separately below.
Separate profiles retain identical full reports and 897,710 native CPU batches
and 741,423 service passes. Python `before_run` calls fall from 897,710 to
271,762 (**625,948 fewer**); `arm` calls fall from 741,423 to 271,762
(**469,661 fewer**). Nonempty `after_run` publication remains at 156,803.
These counts explain the boundary reduction; only the unprofiled paired runs
above establish the execution-cost benefit.
Eight children per pipeline, median process CPU seconds for 30 simulated
seconds, including both directions, marshalling, codec/queue work and hashing:
| Pipeline | Actual pre-change | Native | Speedup |
| --- | ---: | ---: | ---: |
| Fixed FIR | 4.19025 | 0.35149 | 11.92x |
| Polyphase | 0.76958 | 0.12486 | 6.16x |
Every wire/PCM hash and final stream/queue state matches. These are **pipeline
speedups**, not whole-emulator speedups or live-call results.
### Local pipeline result
macOS arm64, CPython 3.13.6, existing Clang build; eight children per pipeline.
Median process CPU seconds (30 simulated seconds, both directions):
| Pipeline | Actual pre-change | Native | Speedup |
| --- | ---: | ---: | ---: |
| Fixed FIR | 1.37950 | 0.52973 | 2.60x |
| Polyphase | 0.63434 | 0.08276 | 7.66x |
The CPython 3.11 reference lacks `math.sumprod`, so its fixed-FIR reference is
substantially more costly. Do not generalize its speedup to newer Python or to
the whole emulator. Equal-rate polyphase passthrough and already-native retuned
FIR loops are not accelerated by these new block kernels.
## Validation and evidence
Differential tests cover fragmented/empty input, fixed rates, phase rounding,
flush, equal-rate passthrough, saturation/ties, large multi-scratch output,
nonfinite exceptions/partial state, coefficient mutations, custom dot/queue
callbacks, unloaded/old libraries, GIL binding, and cancellation vectors which
explicitly distinguish sequential, fused, and compensated arithmetic. Captured
CPU firmware with a synthetic idle DSP is compared against cooperative service
both with and without queued AT input.
491 focused local tests passed, plus 85 tests with the native wrapper and
arming gate explicitly disabled, and 22 timing-analysis/clock-audit tests. Vmhost passed **489 tests with each of the
Clang and GNU builds**, with two skips per compiler: the macOS-only CoreAudio
helper and an optional saved hardware capture. Tests use the existing project
venv (also CPython 3.11.2); benchmark children use distro CPython 3.11.2. A further
300M-instruction compatibility replay using the new Python package with **both
original libraries** retains the complete report and canonical audio too.
Artifacts are under `tmp/tx-timing-followup/service-resample-local-final/` and
the isolated vmhost `perf-service-resample-followup/` directory:
`results-actual-baseline/` holds the final replay comparison; `results-release/`
holds pipeline comparisons, profiles, tests, and source/library manifests. The remote work uses
no real SIP session, PBX changes, or deployment library replacement. After
retrieving the artifacts, CT127 was restored to its original **stopped** state.
+17
View File
@@ -1793,6 +1793,23 @@ std::size_t courier_g711_decode(const uint8_t *in, std::size_t count, int16_t *o
return courier::g711::decode(in, count, out, capacity, law);
}
std::size_t courier_resample_fixed(const double *history, std::size_t length,
const double *kernel, std::size_t kernel_length, double step, double position,
int16_t *out, std::size_t capacity, double *position_out, int *status, unsigned mode)
{
return courier::resample::fixed(history, length, kernel, kernel_length, step,
position, out, capacity, position_out, status, mode);
}
std::size_t courier_resample_polyphase(const double *history, std::size_t length,
const double *kernel, std::size_t kernel_length, uint64_t up, uint64_t down,
uint64_t taps, int64_t half, int64_t origin, int64_t output,
int16_t *out, std::size_t capacity, int64_t *output_out, int *status)
{
return courier::resample::polyphase(history, length, kernel, kernel_length,
up, down, taps, half, origin, output, out, capacity, output_out, status);
}
// Immutable Kaiser coefficients used by Python's resampler kernel builder.
std::size_t courier_resample_windows(double *out, std::size_t capacity, double norm)
{
+98
View File
@@ -75,6 +75,104 @@ inline double sumprod(const double *a, const double *b, long count)
#endif
}
// Match separate Python multiply/add operations, including on FMA targets.
inline double sumprod_sequential(const double *a, const double *b, long count)
{
double total = 0.0;
for (long k = 0; k < count; ++k) {
volatile double product = a[k] * b[k];
total += product;
}
return total;
}
inline int16_t pcm16_even(double value)
{
if (value >= 32767.0) return 32767;
if (value <= -32768.0) return -32768;
double rounded = std::floor(value);
const double fraction = value - rounded;
if (fraction > 0.5 || (fraction == 0.5 && std::fmod(rounded, 2.0) != 0.0))
rounded += 1.0;
return static_cast<int16_t>(rounded);
}
// Stateless block kernels. Status 0: complete, 1: decline to Python, 2: output
// scratch full (resume at the returned position). No stream state is committed.
inline std::size_t fixed(const double *history, std::size_t length,
const double *kernel, std::size_t kernel_length, double step, double position,
int16_t *out, std::size_t capacity, double *position_out, int *status, unsigned mode)
{
if (!status) return 0;
*status = 1;
constexpr double limit_exact = 4503599627370496.0;
if (!history || !kernel || !position_out || (!out && capacity)
|| length < TAPS || uint64_t(length) > UINT64_C(4503599627370496)
|| kernel_length != PHASES * TAPS || mode > 1
|| !std::isfinite(position) || position < 0 || position > limit_exact
|| !std::isfinite(step) || step <= 0) return 0;
const double limit = double(length - TAPS);
std::size_t written = 0;
*status = 0;
while (position <= limit) {
auto base = static_cast<std::size_t>(position);
auto phase = static_cast<long>((position - double(base)) * PHASES + 0.5);
if (phase == PHASES) {
++base; phase = 0;
if (double(base) > limit) break;
}
if (written == capacity) { *status = 2; break; }
const double *taps = kernel + phase * TAPS;
const double value = mode ? sumprod(taps, history + base, TAPS)
: sumprod_sequential(taps, history + base, TAPS);
if (!std::isfinite(value)) { *status = 1; return 0; }
out[written++] = pcm16_even(value);
position += step;
}
*position_out = position;
return written;
}
inline std::size_t polyphase(const double *history, std::size_t length,
const double *kernel, std::size_t kernel_length, uint64_t up, uint64_t down,
uint64_t taps, int64_t half, int64_t origin, int64_t output,
int16_t *out, std::size_t capacity, int64_t *output_out, int *status)
{
if (!status) return 0;
*status = 1;
constexpr int64_t limit = INT64_C(4503599627370496);
if ((!history && length) || !kernel || !output_out || (!out && capacity)
|| !up || up > 1024 || !down || down > (1u << 20)
|| !taps || taps > 4096 || half < 0 || uint64_t(half) > taps
|| kernel_length != up * taps || uint64_t(length) > uint64_t(limit)
|| origin < -limit || origin > limit || output < 0
|| output > limit / int64_t(down)) return 0;
const int64_t newest = origin + int64_t(length) - 1;
std::size_t written = 0;
*status = 0;
while (true) {
if (output > limit / int64_t(down)) { *status = 1; return 0; }
const int64_t position = output * int64_t(down);
const int64_t base = position / int64_t(up);
if (base + half > newest) break;
if (written == capacity) { *status = 2; break; }
const double *row = kernel + (position % int64_t(up)) * int64_t(taps);
double total = 0.0;
for (uint64_t k = 0; k < taps; ++k) {
const int64_t sample = base + half - int64_t(k) - origin;
if (sample >= 0 && uint64_t(sample) < length) {
volatile double product = row[k] * history[sample];
total += product;
}
}
if (!std::isfinite(total)) { *status = 1; return 0; }
out[written++] = pcm16_even(total);
++output;
}
*output_out = output;
return written;
}
constexpr double KAISER_BETA = 8.0;
// resample._bessel_i0, operation for operation. The square is libm's pow, as
+49 -1
View File
@@ -452,6 +452,52 @@ static bool runner_callback(PyObject *function) {
RunnerRef result(PyObject_CallNoArgs(function));
return bool(result);
}
// A worker request which is already false does nothing. While AT input is
// queued outside data mode, _serial_receive_quiet_until is necessarily None;
// timer_poll_static therefore rejects arm. _serial_started independently
// rejects fast_service_static. All other cases keep the full Python checks.
static int worker_before_needed(PyObject *cpu, PyObject *callback) {
RunnerRef gate(PyObject_GetAttrString(cpu,"native_before_run_gate"));
if (!gate) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return -1;
PyErr_Clear();
return 1;
}
if (!PyTuple_Check(gate.p) || PyTuple_GET_SIZE(gate.p)!=5
|| PyTuple_GET_ITEM(gate.p,0)!=callback) return 1;
PyObject *request=PyTuple_GET_ITEM(gate.p,1);
if (!PyList_CheckExact(request) || PyList_GET_SIZE(request)!=1) return 1;
if (PyList_GET_ITEM(request,0)==Py_False) return 0;
if (PyList_GET_ITEM(request,0)!=Py_True) return 1;
PyObject *names=PyTuple_GET_ITEM(gate.p,3);
if (!PyTuple_Check(names) || PyTuple_GET_SIZE(names)!=3) return 1;
RunnerRef machine(PyObject_GenericGetDict(PyTuple_GET_ITEM(gate.p,2),nullptr));
if (!machine) return -1;
PyObject *started=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,0));
if (PyErr_Occurred()) return -1;
bool reject=started==Py_True;
if (!reject) {
PyObject *online=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,1));
if (PyErr_Occurred()) return -1;
if (online==Py_False) {
PyObject *rx=PyDict_GetItemWithError(machine.p,PyTuple_GET_ITEM(names,2));
if (PyErr_Occurred()) return -1;
PyObject *deque_type=PyTuple_GET_ITEM(gate.p,4);
if (rx && reinterpret_cast<PyObject*>(Py_TYPE(rx))==deque_type) {
const Py_ssize_t length=PyObject_Length(rx);
if (length<0) return -1;
reject=length!=0;
}
}
}
if (reject) {
// arm() begins by clearing this request, even when it rejects.
PyList_SetItem(request,0,Py_NewRef(Py_False));
return 0;
}
return 1;
}
static PyObject *run_cpu_python(PyObject *, PyObject *args) {
PyObject *cpu, *wrapper, *keys;
unsigned int count;
@@ -517,7 +563,9 @@ static PyObject *run_cpu_python(PyObject *, PyObject *args) {
// registers, memory and interrupt buffers are obtained after it. Keep every
// borrowed execution buffer alive even if a native I/O callback replaces it.
RunnerRef before(PyObject_GetAttr(cpu,PyTuple_GET_ITEM(keys,RF_BEFORE)));
if (!before || !runner_callback(before.p)) return nullptr;
if (!before) return nullptr;
const int before_needed=before.p==Py_None ? 0 : worker_before_needed(cpu,before.p);
if (before_needed<0 || (before_needed && !runner_callback(before.p))) return nullptr;
RunnerRef state(PyObject_GenericGetDict(cpu,nullptr));
RunnerRef buffers(PyObject_GenericGetDict(wrapper,nullptr));
if (!state || !buffers) return nullptr;
+64
View File
@@ -293,6 +293,70 @@ def test_subclasses_keep_attribute_dispatch_in_python(monkeypatch):
assert CustomRunner(x86.Uc(0, 0))._run_cpu is None
@pytest.mark.parametrize('requested,started,online,queued', [
(r, s, o, q) for r in (False, True) for s in (False, True)
for o in (False, True) for q in (False, True)
])
def test_before_worker_rejection_gate_preserves_requests_and_work(
requested, started, online, queued, monkeypatch):
from collections import deque
results = []
for enabled in (False, True):
cpu, native = setup(monkeypatch, enabled)
request, work, calls = [requested], [], []
machine = SimpleNamespace(_serial_started=started, online_mode=online,
serial_rx=deque([1] if queued else []))
def before():
calls.append('before')
if request[0]:
request[0] = False
if machine._serial_started or (machine.serial_rx and not machine.online_mode):
return
work.append('eligible')
cpu.native_before_run = before
cpu.native_before_run_gate = (
before, request, machine, ('_serial_started', 'online_mode', 'serial_rx'), deque)
native.execute(cpu, 3)
results.append((snapshot(cpu, native), request.copy(), work))
rejected = started or (queued and not online)
assert len(calls) == int(not enabled or (requested and not rejected))
assert results[0] == results[1]
def test_before_gate_does_not_apply_to_replaced_hook(monkeypatch):
from collections import deque
cpu, native = setup(monkeypatch, True)
request, calls = [True], []
machine = SimpleNamespace(_serial_started=True, online_mode=False, serial_rx=deque([1]))
cpu.native_before_run_gate = (
lambda: None, request, machine, ('_serial_started', 'online_mode', 'serial_rx'), deque)
cpu.native_before_run = lambda: calls.append('replacement')
native.execute(cpu, 3)
assert calls == ['replacement'] and request == [True]
def test_before_gate_keeps_custom_queue_truth_callbacks(monkeypatch):
from collections import deque
calls = []
class CustomQueue(deque):
def __len__(self):
calls.append('length')
return super().__len__()
cpu, native = setup(monkeypatch, True)
request = [True]
machine = SimpleNamespace(_serial_started=False, online_mode=False,
serial_rx=CustomQueue([1]))
def before():
calls.append('before')
request[0] = False
bool(machine.serial_rx)
cpu.native_before_run = before
cpu.native_before_run_gate = (
before, request, machine, ('_serial_started', 'online_mode', 'serial_rx'), deque)
native.execute(cpu, 3)
assert calls == ['before', 'length'] and request == [False]
def test_ordinary_cpu_without_worker_gate_keeps_python_wrapper(monkeypatch):
monkeypatch.setenv('COURIER_X86_NATIVE_WRAPPER', '1')
assert x86_native.NativeInterpreter(x86.Uc(0, 0))._run_cpu is None
+246
View File
@@ -0,0 +1,246 @@
from array import array
import math
import random
import struct
from types import SimpleNamespace
import pytest
from courier_emu import dsp, resample, resample_native as native
from courier_emu.sip import PolyphaseResampler
@pytest.fixture(autouse=True, scope='module')
def library():
dsp.load_library()
assert native.fixed_available() and native.polyphase_available()
def doubles(values):
return struct.pack(f'{len(values)}d', *values)
def fixed_state(r):
return (doubles(r._history), doubles(r._recent_input), doubles([r._position]),
r.converted, r.input_rate, r.output_rate)
def poly_state(r):
return doubles(r._buffer), r._origin, r._output
@pytest.mark.parametrize('rates', [(48000, 8000), (8000, 48000), (9600, 8000),
(8000, 9600), (44100, 8000), (8000, 8000),
(8000.31, 8000), (7999.9, 8000)])
def test_fixed_stream_and_state_exact(rates, monkeypatch):
rng = random.Random(39)
chunks = [[rng.randrange(-40000, 40000) for _ in range(n)]
for n in (0, 1, 19, 160, 0, 997, 3, 401, 160)]
runs = []
for enabled in ('0', '1'):
monkeypatch.setenv('COURIER_NATIVE_FIXED_RESAMPLE', enabled)
r = resample.BandLimitedResampler()
runs.append([(r.convert(chunk, *rates), fixed_state(r)) for chunk in chunks])
assert runs[0] == runs[1]
@pytest.mark.parametrize('position', [0., .5 / 1024, 1023.5 / 1024,
math.nextafter(1., 0.), .375, 7.9999])
def test_fixed_phase_round_up_and_boundaries(position, monkeypatch):
runs = []
for enabled in ('0', '1'):
monkeypatch.setenv('COURIER_NATIVE_FIXED_RESAMPLE', enabled)
r = resample.BandLimitedResampler()
r.convert([1], 9600, 8000)
r._position = position
runs.append((r.convert(list(range(160)), 9600, 8000), fixed_state(r)))
assert runs[0] == runs[1]
@pytest.mark.parametrize('rates', [(7200, 8000), (8000, 7200), (48000, 8000),
(8000, 48000), (44100, 8000), (8000, 8000),
(8192, 8000), (8001, 8000)])
def test_polyphase_stream_flush_and_state_exact(rates, monkeypatch):
rng = random.Random(17)
chunks = [[rng.randrange(-40000, 40000) for _ in range(n)]
for n in (0, 1, 19, 160, 0, 997, 3, 401, 160)]
runs = []
for enabled in ('0', '1'):
monkeypatch.setenv('COURIER_NATIVE_POLYPHASE', enabled)
r = PolyphaseResampler(*rates)
result = [(r.convert(chunk), poly_state(r)) for chunk in chunks]
result.append((r.flush(), poly_state(r)))
runs.append(result)
assert runs[0] == runs[1]
@pytest.mark.parametrize('mode', [0, 1])
def test_fixed_ties_even_saturation_and_nonfinite_decline(mode):
weights = array('d', [0.]) * (1024 * 128)
for p in range(1024):
weights[p * 128] = 1.
values = [-32768.5, -32767.5, -2.5, -1.5, -.5, .5, 1.5, 2.5,
32766.5, 32767.5, -1e100, 1e100] + [0.] * 127
result, position = native.fixed(values, weights, 1., 0., mode)
assert result == [max(-32768, min(32767, round(v))) for v in values[:-127]]
assert position == len(result)
values[2] = float('nan')
assert native.fixed(values, weights, 1., 0., mode) is None
assert native.fixed(values, weights, 1., 2**60, mode) is None
assert native.fixed([0.] * 512, weights, 1e-16, 100., mode) is None
def test_polyphase_ties_even_saturation_and_nonfinite_decline():
values = [-32768.5, -32767.5, -2.5, -1.5, -.5, .5, 1.5, 2.5,
32766.5, 32767.5, -1e100, 1e100]
result, index = native.polyphase(values, array('d', [1.]), 1, 1, 1, 0, 0, 0)
assert result == [max(-32768, min(32767, round(v))) for v in values]
assert index == len(values)
values[2] = float('inf')
assert native.polyphase(values, array('d', [1.]), 1, 1, 1, 0, 0, 0) is None
assert native.polyphase(values, array('d', [1.]), 1, 1, 1, 0, 0, 2**60) is None
@pytest.mark.parametrize('kind', ['fixed', 'polyphase'])
def test_scratch_chunk_boundary_does_not_discard_audio(kind, monkeypatch):
rng = random.Random(13)
samples = [rng.randrange(-32000, 32000) for _ in range(12000)]
runs = []
flag = 'COURIER_NATIVE_FIXED_RESAMPLE' if kind == 'fixed' else 'COURIER_NATIVE_POLYPHASE'
for enabled in ('0', '1'):
monkeypatch.setenv(flag, enabled)
if kind == 'fixed':
r = resample.BandLimitedResampler()
result = r.convert(samples, 8000, 48000)
state = fixed_state(r)
else:
r = PolyphaseResampler(8000, 48000)
result = r.convert(samples)
state = poly_state(r)
assert len(result) > 65536
runs.append((result, state))
assert runs[0] == runs[1]
@pytest.mark.parametrize('kind', ['fixed', 'polyphase'])
def test_nonfinite_exception_preserves_partial_stream_state(kind, monkeypatch):
runs = []
flag = 'COURIER_NATIVE_FIXED_RESAMPLE' if kind == 'fixed' else 'COURIER_NATIVE_POLYPHASE'
for enabled in ('0', '1'):
monkeypatch.setenv(flag, enabled)
samples = [1.] * 160
samples[15] = float('nan')
r = resample.BandLimitedResampler() if kind == 'fixed' else PolyphaseResampler(7200, 8000)
with pytest.raises(ValueError) as error:
if kind == 'fixed':
r.convert(samples, 9600, 8000)
else:
r.convert(samples)
runs.append((str(error.value), fixed_state(r) if kind == 'fixed' else poly_state(r)))
assert runs[0] == runs[1]
def test_polyphase_coefficient_mutations_are_observed(monkeypatch):
runs = []
for enabled in ('0', '1'):
monkeypatch.setenv('COURIER_NATIVE_POLYPHASE', enabled)
calls = []
class Tap(float):
def __mul__(self, value):
calls.append(1)
return float(self) * value
r = PolyphaseResampler(7200, 8000)
results = [r.convert([123] * 160)]
r._taps[0][0] += .125
results.append(r.convert([321] * 160))
# Integer/custom numeric taps retain their original Python semantics.
r._taps[1][0] = Tap(1.)
results.append(r.convert([100] * 160))
assert calls
runs.append((results, poly_state(r), len(calls)))
assert runs[0] == runs[1]
def test_small_blocks_do_not_pay_native_marshalling(monkeypatch):
monkeypatch.setattr(native, 'fixed', lambda *args: pytest.fail('tiny native FIR'))
monkeypatch.setattr(native, 'polyphase', lambda *args: pytest.fail('tiny native polyphase'))
fixed, poly = resample.BandLimitedResampler(), PolyphaseResampler(7200, 8000)
assert fixed.convert([3] * 8, 48000, 8000) == [0, 0]
assert poly.convert([3] * 8)
def test_custom_rate_arithmetic_is_not_bypassed(monkeypatch):
runs = []
calls = []
class Step(float):
def __radd__(self, other):
calls.append(1)
return other + float(self)
class Rate(float):
def __truediv__(self, other):
return Step(float(self) / other)
for enabled in ('0', '1'):
calls.clear()
monkeypatch.setenv('COURIER_NATIVE_FIXED_RESAMPLE', enabled)
r = resample.BandLimitedResampler()
result = r.convert([100] * 160, Rate(9600), 8000)
assert len(calls) == len(result)
runs.append((result, fixed_state(r), len(calls)))
assert runs[0] == runs[1]
def test_import_time_custom_sumprod_is_not_bypassed(monkeypatch):
from pathlib import Path
from types import ModuleType
calls = []
reference = getattr(math, 'sumprod', resample._fallback_dot)
def custom(a, b):
calls.append(1)
return reference(a, b)
monkeypatch.setattr(math, 'sumprod', custom, raising=False)
module = ModuleType('courier_emu._resample_custom_dot')
module.__package__ = 'courier_emu'
source = Path(resample.__file__)
exec(compile(source.read_text(), str(source), 'exec'), module.__dict__)
assert module._REFERENCE_DOT is None
result = module.BandLimitedResampler().convert([100] * 160, 9600, 8000)
assert len(calls) == len(result)
def test_custom_fixed_dot_is_not_bypassed(monkeypatch):
calls = []
monkeypatch.setattr(resample, '_dot', lambda a, b: calls.append(1) or 0.)
r = resample.BandLimitedResampler()
assert r.convert([100] * 160, 9600, 8000) == [0] * len(calls)
assert calls
def test_sequential_products_are_not_fused_or_compensated():
# Separate binary64 product/add gives 0; fused/compensated gives -1.
a, b = float(2**27 + 1), float(2**27 - 1)
weights = array('d', [0.]) * (1024 * 128)
for p in range(1024):
weights[p * 128:p * 128 + 2] = array('d', [1., a])
values = [-float(2**54), b] + [0.] * 127
assert native.fixed(values, weights, 1., 0., 0)[0][0] == 0
assert native.fixed(values, weights, 1., 0., 1)[0][0] == -1
assert native.polyphase([b, -float(2**54)], array('d', [1., a]),
1, 1, 2, 1, 0, 0) == ([0], 1)
def test_packet_kernels_keep_the_gil_and_invalid_tables_decline():
import ctypes
for kind in ('fixed', 'polyphase'):
assert native._function(kind)._flags_ & ctypes._FUNCFLAG_PYTHONAPI
assert native.fixed([0.] * 128, array('d', [1.]), 1., 0., 0) is None
assert native.polyphase([0.], array('d', [1.]), 2, 1, 1, 0, 0, 0) is None
def test_missing_symbols_and_unloaded_library_do_not_load_core(monkeypatch):
monkeypatch.setattr(dsp, 'load_library', lambda: pytest.fail('implicit library load'))
for library in (None, SimpleNamespace()):
monkeypatch.setattr(dsp, 'loaded_library', lambda: library)
assert not native.fixed_available()
assert not native.polyphase_available()
assert native.fixed([], array('d'), 1., 0., 0) is None
assert native.polyphase([], array('d'), 1, 1, 1, 0, 0, 0) is None
+6 -3
View File
@@ -19,14 +19,16 @@ class LocalPort:
def close(self):self.state='closed';self.closed=True
def test_native_sip_arm_matches_cooperative_service_at_boot(monkeypatch):
@pytest.mark.parametrize('serial_input', [b'', b'AT\r'])
def test_native_sip_arm_matches_cooperative_service_at_boot(monkeypatch, serial_input):
path=Path(__file__).resolve().parents[1]/'dumps/courier-board-21210-capture-403/courier-board.rom'
if not path.exists():pytest.skip('optional captured original firmware unavailable')
machines=[]
results=[]
for mode in ['0','auto']:
monkeypatch.setenv('COURIER_WORKER_POLL',mode)
machine=CourierMachine(load_image(path),with_dsp=True,sip=LocalPort(),exchange=LineExchange(),board_id=7)
machine=CourierMachine(load_image(path),with_dsp=True,sip=LocalPort(),exchange=LineExchange(),board_id=7,
serial_input=serial_input)
# A synthetic idle DSP loop makes quiet-SIP polling eligible without
# a real call. CPU firmware and all its I/O hooks remain untouched.
bridge=machine.dsp_bridge
@@ -44,7 +46,8 @@ def test_native_sip_arm_matches_cooperative_service_at_boot(monkeypatch):
assert slow._interrupt_stack==fast._interrupt_stack
assert slow.serial==fast.serial
assert fast._worker_poll.state.instruction_base==0
assert fast._worker_poll.state.polls>0
if not serial_input:
assert fast._worker_poll.state.polls>0
assert results[0].dsp_bridge['dsp']==results[1].dsp_bridge['dsp']
for field in ['_instructions','_x86_ticks','_exchange_instructions',
'_codec_instructions','_dsp_cycle_debt']:
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Socket-free PCM -> resample -> RTP codec/queue -> resample pipeline.
Compare pinned alternating child processes, optionally loading the *actual*
pre-change resample.py/sip.py via --reference-dir. No clocks or buffers change.
Compilation, filter design, and a one-block warm-up are outside the measurement.
"""
import argparse
from array import array
from collections import deque
import hashlib
import importlib
import json
import math
from pathlib import Path
import platform
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--kind', choices=('fixed', 'polyphase'), required=True)
parser.add_argument('--seconds', type=int, default=20)
parser.add_argument('--reference-dir', type=Path)
args = parser.parse_args()
if args.seconds <= 0:
parser.error('--seconds must be positive')
from courier_emu.dsp import load_library
load_library()
if args.reference_dir:
for name in ('resample', 'sip'):
module = importlib.import_module('courier_emu.' + name)
source = args.reference_dir / (name + '.py')
exec(compile(source.read_text(), str(source), 'exec'), module.__dict__)
from courier_emu.resample import BandLimitedResampler
from courier_emu.sip import PolyphaseResampler, SipSession, linear_to_ulaw
from courier_emu import g711_native
if not g711_native.available():
raise RuntimeError('benchmark requires native G.711 for both variants')
rate = 48000 if args.kind == 'fixed' else 7200
if args.kind == 'fixed':
tx, rx = BandLimitedResampler(), BandLimitedResampler()
send = lambda values: tx.convert(values, rate, 8000)
receive = lambda values: rx.convert(values, 8000, rate)
else:
tx, rx = PolyphaseResampler(rate, 8000), PolyphaseResampler(8000, rate)
send, receive = tx.convert, rx.convert
session = object.__new__(SipSession) # No SIP socket or network activity.
session._encode = linear_to_ulaw
session._tx_audio = deque()
size = rate // 50
source = [int(23000 * math.sin(2 * math.pi * 697 * n / rate))
+ (n * 7919 % 3001 - 1500) for n in range(rate)]
blocks = [source[n:n + size] for n in range(0, rate, size)]
def process(block, wire, pcm):
packets = count = 0
session._tx_audio.extend(send(block))
while len(session._tx_audio) >= 160:
payload = session._encode_rtp_audio()
decoded = g711_native.decode_octets(payload, 0)
output = receive(decoded)
wire.update(payload)
pcm.update(array('h', output).tobytes())
count += len(output)
packets += 1
return packets, count
wire, pcm = hashlib.sha256(), hashlib.sha256()
process(blocks[0], wire, pcm) # Warm table packing and bindings too.
wire, pcm = hashlib.sha256(), hashlib.sha256()
packets = count = 0
start_cpu, start_wall = time.process_time(), time.perf_counter()
for n in range(args.seconds * 50):
p, c = process(blocks[(n + 1) % len(blocks)], wire, pcm)
packets += p
count += c
elapsed_wall, elapsed_cpu = time.perf_counter() - start_wall, time.process_time() - start_cpu
def state(r):
if args.kind == 'fixed':
values = [r._position, *r._history, *r._recent_input]
counters = [r.converted, r.input_rate, r.output_rate]
else:
values, counters = r._buffer, [r._origin, r._output, r.up, r.down]
return {'counters': counters,
'float_state_sha256': hashlib.sha256(array('d', values).tobytes()).hexdigest()}
print(json.dumps({'kind': args.kind, 'seconds': args.seconds,
'platform': platform.platform(), 'python': sys.version,
'reference_dir': str(args.reference_dir) if args.reference_dir else None,
'wall_seconds': elapsed_wall, 'cpu_seconds': elapsed_cpu,
'result': {'packets': packets, 'pcm_samples': count,
'wire_sha256': wire.hexdigest(), 'pcm_sha256': pcm.hexdigest(),
'tx': state(tx), 'rx': state(rx), 'queued_tx': list(session._tx_audio)}}))
if __name__ == '__main__':
main()