catap 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
catap/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ # ruff: noqa: E402
2
+ """Public API for catap."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import platform
7
+ from importlib.metadata import PackageNotFoundError, version
8
+
9
+ if platform.system() != "Darwin":
10
+ raise ImportError("catap only supports macOS 14.2 or later.")
11
+
12
+ _macos_version = platform.mac_ver()[0]
13
+ if not _macos_version:
14
+ raise ImportError("catap only supports macOS 14.2 or later.")
15
+
16
+ try:
17
+ _macos_version_tuple = tuple(int(part) for part in _macos_version.split("."))
18
+ except ValueError as exc:
19
+ raise ImportError("catap only supports macOS 14.2 or later.") from exc
20
+
21
+ if _macos_version_tuple < (14, 2):
22
+ raise ImportError(
23
+ f"catap requires macOS 14.2 or later. Detected macOS {_macos_version}."
24
+ )
25
+
26
+ from catap.bindings.device import (
27
+ AmbiguousAudioDeviceError,
28
+ AudioDevice,
29
+ AudioDeviceStream,
30
+ find_audio_device_by_name,
31
+ find_audio_device_by_uid,
32
+ list_audio_devices,
33
+ )
34
+ from catap.bindings.hardware import create_process_tap, destroy_process_tap
35
+ from catap.bindings.process import (
36
+ AmbiguousAudioProcessError,
37
+ AudioProcess,
38
+ find_process_by_name,
39
+ list_audio_processes,
40
+ )
41
+ from catap.bindings.tap import (
42
+ AudioTap,
43
+ AudioTapNotFoundError,
44
+ find_tap_by_uid,
45
+ list_audio_taps,
46
+ )
47
+ from catap.bindings.tap_description import TapDescription, TapMuteBehavior
48
+ from catap.recorder import AudioRecorder
49
+ from catap.session import (
50
+ AudioProcessNotFoundError,
51
+ RecordingSession,
52
+ record_process,
53
+ record_system_audio,
54
+ record_tap,
55
+ )
56
+
57
+ try:
58
+ __version__ = version("catap")
59
+ except PackageNotFoundError:
60
+ __version__ = "0.0.0"
61
+
62
+ __all__ = [
63
+ "AmbiguousAudioDeviceError",
64
+ "AmbiguousAudioProcessError",
65
+ "AudioDevice",
66
+ "AudioDeviceStream",
67
+ "AudioProcess",
68
+ "AudioProcessNotFoundError",
69
+ "AudioRecorder",
70
+ "AudioTap",
71
+ "AudioTapNotFoundError",
72
+ "RecordingSession",
73
+ "TapDescription",
74
+ "TapMuteBehavior",
75
+ "create_process_tap",
76
+ "destroy_process_tap",
77
+ "find_audio_device_by_name",
78
+ "find_audio_device_by_uid",
79
+ "find_process_by_name",
80
+ "find_tap_by_uid",
81
+ "list_audio_devices",
82
+ "list_audio_processes",
83
+ "list_audio_taps",
84
+ "record_process",
85
+ "record_system_audio",
86
+ "record_tap",
87
+ ]
catap/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Main entry point for python -m catap."""
2
+
3
+ from catap.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Internal development helpers for catap."""
@@ -0,0 +1,155 @@
1
+ """Generate and optionally play a deterministic helper tone for catap tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import signal
7
+ import tempfile
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from catap import list_audio_devices
12
+ from catap._devtools.tone import TonePlayer, pleasant_tone_sample, write_tone_wav
13
+
14
+
15
+ def _positive_float(value: str) -> float:
16
+ parsed = float(value)
17
+ if parsed <= 0:
18
+ raise argparse.ArgumentTypeError("must be greater than 0")
19
+ return parsed
20
+
21
+
22
+ def _positive_int(value: str) -> int:
23
+ parsed = int(value)
24
+ if parsed <= 0:
25
+ raise argparse.ArgumentTypeError("must be greater than 0")
26
+ return parsed
27
+
28
+
29
+ def _default_output_path() -> Path:
30
+ return Path(tempfile.gettempdir()) / "catap-test-tone.wav"
31
+
32
+
33
+ def _resolve_output_device(device_uid: str | None) -> tuple[int | None, str]:
34
+ if not device_uid:
35
+ return None, "Default Output"
36
+
37
+ for device in list_audio_devices():
38
+ if device.uid == device_uid and device.output_streams:
39
+ return device.audio_object_id, device.name
40
+
41
+ raise LookupError(f"No output-capable device matches UID '{device_uid}'")
42
+
43
+
44
+ def build_parser() -> argparse.ArgumentParser:
45
+ parser = argparse.ArgumentParser(
46
+ description=(
47
+ "Generate a predictable mellow helper tone and optionally play it "
48
+ "through a selected output device so catap always has a known "
49
+ "audio source."
50
+ )
51
+ )
52
+ parser.add_argument(
53
+ "--seconds",
54
+ type=_positive_float,
55
+ default=60.0,
56
+ help="Tone length in seconds (default: 60)",
57
+ )
58
+ parser.add_argument(
59
+ "--frequency",
60
+ type=_positive_float,
61
+ default=220.0,
62
+ help="Tone fundamental in Hz (default: 220)",
63
+ )
64
+ parser.add_argument(
65
+ "--sample-rate",
66
+ type=_positive_int,
67
+ default=44_100,
68
+ help="Sample rate for the generated WAV (default: 44100)",
69
+ )
70
+ parser.add_argument(
71
+ "--channels",
72
+ type=_positive_int,
73
+ default=2,
74
+ help="Channel count for the generated WAV (default: 2)",
75
+ )
76
+ parser.add_argument(
77
+ "--amplitude",
78
+ type=_positive_float,
79
+ default=0.12,
80
+ help="Linear amplitude between 0 and 1 (default: 0.12)",
81
+ )
82
+ parser.add_argument(
83
+ "--output",
84
+ type=Path,
85
+ default=_default_output_path(),
86
+ help="Where to write the helper WAV file",
87
+ )
88
+ parser.add_argument(
89
+ "--device-uid",
90
+ help="Output device UID to use for playback; defaults to the system output",
91
+ )
92
+ parser.add_argument(
93
+ "--write-only",
94
+ action="store_true",
95
+ help="Generate the WAV but do not launch playback",
96
+ )
97
+ return parser
98
+
99
+
100
+ def main(argv: list[str] | None = None) -> int:
101
+ parser = build_parser()
102
+ args = parser.parse_args(argv)
103
+
104
+ if args.amplitude > 1.0:
105
+ parser.error("--amplitude must be between 0 and 1")
106
+
107
+ output_path = write_tone_wav(
108
+ args.output,
109
+ seconds=args.seconds,
110
+ frequency_hz=args.frequency,
111
+ sample_rate=args.sample_rate,
112
+ channels=args.channels,
113
+ amplitude=args.amplitude,
114
+ )
115
+ print(f"Wrote helper tone: {output_path}", flush=True)
116
+
117
+ if args.write_only:
118
+ return 0
119
+
120
+ device_id, device_name = _resolve_output_device(args.device_uid)
121
+ print(f"Playing helper tone on {device_name}", flush=True)
122
+
123
+ stop_requested = False
124
+
125
+ def _request_stop(_signum: int, _frame: object | None) -> None:
126
+ nonlocal stop_requested
127
+ stop_requested = True
128
+
129
+ signal.signal(signal.SIGTERM, _request_stop)
130
+ signal.signal(signal.SIGINT, _request_stop)
131
+
132
+ player = TonePlayer(
133
+ duration_seconds=args.seconds,
134
+ sample_rate=float(args.sample_rate),
135
+ channels=args.channels,
136
+ frequency_hz=args.frequency,
137
+ amplitude=args.amplitude,
138
+ device_id=device_id,
139
+ sample_fn=pleasant_tone_sample,
140
+ apply_fade=True,
141
+ )
142
+ player.start()
143
+
144
+ deadline = time.monotonic() + args.seconds + 0.2
145
+ try:
146
+ while not stop_requested and time.monotonic() < deadline and player.is_playing:
147
+ time.sleep(0.05)
148
+ finally:
149
+ player.stop()
150
+
151
+ return 0
152
+
153
+
154
+ if __name__ == "__main__":
155
+ raise SystemExit(main())
@@ -0,0 +1,220 @@
1
+ """Shared helper-tone primitives for catap development scripts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import math
7
+ import struct
8
+ import warnings
9
+ import wave
10
+ from collections.abc import Callable
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ SampleFn = Callable[[float], float]
15
+
16
+ _TAU = 2.0 * math.pi
17
+
18
+ _OBJC: Any = None
19
+ _AVFOUNDATION_BUNDLE_LOADED = False
20
+ _AVAudioEngine: Any = None
21
+ _AVAudioFormat: Any = None
22
+ _AVAudioPCMBuffer: Any = None
23
+ _AVAudioPlayerNode: Any = None
24
+
25
+
26
+ def fade_gain(frame_index: int, total_frames: int, sample_rate: int) -> float:
27
+ """Return a short edge fade to avoid clicks at buffer boundaries."""
28
+ fade_frames = max(1, min(int(sample_rate * 0.02), total_frames // 2 or 1))
29
+ fade_in = min(1.0, (frame_index + 1) / fade_frames)
30
+ fade_out = min(1.0, (total_frames - frame_index) / fade_frames)
31
+ return min(fade_in, fade_out)
32
+
33
+
34
+ def pure_sine_sample(phase: float) -> float:
35
+ """Return a pure sine-wave sample for the provided phase."""
36
+ return math.sin(phase)
37
+
38
+
39
+ def pleasant_tone_sample(phase: float) -> float:
40
+ """Return a slightly richer helper tone with gentle harmonics."""
41
+ return (
42
+ 0.72 * math.sin(phase)
43
+ + 0.20 * math.sin(phase * 2.0)
44
+ + 0.08 * math.sin(phase * 3.0)
45
+ )
46
+
47
+
48
+ def write_tone_wav(
49
+ path: Path,
50
+ *,
51
+ seconds: float,
52
+ frequency_hz: float,
53
+ sample_rate: int,
54
+ channels: int,
55
+ amplitude: float,
56
+ sample_fn: SampleFn = pleasant_tone_sample,
57
+ apply_fade: bool = True,
58
+ ) -> Path:
59
+ """Write a deterministic stereo tone WAV for helper playback."""
60
+ path.parent.mkdir(parents=True, exist_ok=True)
61
+ total_frames = max(1, int(seconds * sample_rate))
62
+ chunk_frames = 4096
63
+ amplitude_i16 = max(0, min(int(amplitude * 32767), 32767))
64
+ phase_step = _TAU * frequency_hz / sample_rate
65
+ phase = 0.0
66
+ frames_remaining = total_frames
67
+ frame_index = 0
68
+
69
+ with wave.open(str(path), "wb") as wav_file:
70
+ wav_file.setnchannels(channels)
71
+ wav_file.setsampwidth(2)
72
+ wav_file.setframerate(sample_rate)
73
+
74
+ while frames_remaining > 0:
75
+ frame_count = min(chunk_frames, frames_remaining)
76
+ chunk = bytearray()
77
+ for _ in range(frame_count):
78
+ gain = (
79
+ fade_gain(frame_index, total_frames, sample_rate)
80
+ if apply_fade
81
+ else 1.0
82
+ )
83
+ sample = int(amplitude_i16 * gain * sample_fn(phase))
84
+ chunk.extend(struct.pack("<" + "h" * channels, *([sample] * channels)))
85
+ phase += phase_step
86
+ if phase >= _TAU:
87
+ phase -= _TAU
88
+ frame_index += 1
89
+ wav_file.writeframes(chunk)
90
+ frames_remaining -= frame_count
91
+
92
+ return path
93
+
94
+
95
+ def _load_avfoundation() -> None:
96
+ """Load the AVFoundation classes used by the helper tone player."""
97
+ global _OBJC
98
+ global _AVFOUNDATION_BUNDLE_LOADED
99
+ global _AVAudioEngine
100
+ global _AVAudioFormat
101
+ global _AVAudioPCMBuffer
102
+ global _AVAudioPlayerNode
103
+
104
+ if _AVFOUNDATION_BUNDLE_LOADED:
105
+ return
106
+
107
+ import objc
108
+
109
+ _OBJC = objc
110
+ objc.loadBundle( # ty: ignore[unresolved-attribute]
111
+ "AVFoundation",
112
+ globals(),
113
+ bundle_path=objc.pathForFramework(
114
+ "/System/Library/Frameworks/AVFoundation.framework"
115
+ ),
116
+ )
117
+ _AVAudioEngine = objc.lookUpClass("AVAudioEngine") # ty: ignore[unresolved-attribute]
118
+ _AVAudioFormat = objc.lookUpClass("AVAudioFormat") # ty: ignore[unresolved-attribute]
119
+ _AVAudioPCMBuffer = objc.lookUpClass("AVAudioPCMBuffer") # ty: ignore[unresolved-attribute]
120
+ _AVAudioPlayerNode = objc.lookUpClass("AVAudioPlayerNode") # ty: ignore[unresolved-attribute]
121
+ _AVFOUNDATION_BUNDLE_LOADED = True
122
+
123
+
124
+ class TonePlayer:
125
+ """Simple AVAudioEngine-backed tone player for helper scripts."""
126
+
127
+ def __init__(
128
+ self,
129
+ *,
130
+ duration_seconds: float,
131
+ sample_rate: float = 44_100.0,
132
+ channels: int = 2,
133
+ frequency_hz: float = 440.0,
134
+ amplitude: float = 0.08,
135
+ device_id: int | None = None,
136
+ sample_fn: SampleFn = pure_sine_sample,
137
+ apply_fade: bool = False,
138
+ ) -> None:
139
+ _load_avfoundation()
140
+
141
+ self._duration_seconds = duration_seconds
142
+ self._sample_rate = sample_rate
143
+ self._channels = channels
144
+ self._frequency_hz = frequency_hz
145
+ self._amplitude = amplitude
146
+ self._sample_fn = sample_fn
147
+ self._apply_fade = apply_fade
148
+
149
+ self._engine = _AVAudioEngine.alloc().init()
150
+ self._player = _AVAudioPlayerNode.alloc().init()
151
+ self._engine.attachNode_(self._player)
152
+
153
+ self._format = (
154
+ _AVAudioFormat.alloc().initStandardFormatWithSampleRate_channels_(
155
+ self._sample_rate,
156
+ self._channels,
157
+ )
158
+ )
159
+ self._engine.connect_to_format_(
160
+ self._player,
161
+ self._engine.mainMixerNode(),
162
+ self._format,
163
+ )
164
+
165
+ if device_id is not None:
166
+ ok = self._engine.outputNode().AUAudioUnit().setDeviceID_error_(
167
+ device_id,
168
+ None,
169
+ )
170
+ if not ok:
171
+ raise OSError(f"Failed to set helper tone output device {device_id}")
172
+
173
+ frame_count = max(1, int(self._sample_rate * self._duration_seconds))
174
+ self._buffer = _AVAudioPCMBuffer.alloc().initWithPCMFormat_frameCapacity_(
175
+ self._format,
176
+ frame_count,
177
+ )
178
+ self._buffer.setFrameLength_(frame_count)
179
+ self._fill_buffer(frame_count)
180
+
181
+ @property
182
+ def is_playing(self) -> bool:
183
+ return bool(self._player.isPlaying())
184
+
185
+ def _fill_buffer(self, frame_count: int) -> None:
186
+ assert _OBJC is not None
187
+ warnings.filterwarnings("ignore", category=_OBJC.ObjCPointerWarning)
188
+ channel_ptrs = ctypes.cast(
189
+ self._buffer.floatChannelData().pointerAsInteger,
190
+ ctypes.POINTER(ctypes.POINTER(ctypes.c_float)),
191
+ )
192
+ phase_step = _TAU * self._frequency_hz / self._sample_rate
193
+
194
+ for channel_index in range(self._channels):
195
+ channel = ctypes.cast(
196
+ channel_ptrs[channel_index],
197
+ ctypes.POINTER(ctypes.c_float * frame_count),
198
+ ).contents
199
+ phase = 0.0
200
+ for frame_index in range(frame_count):
201
+ gain = (
202
+ fade_gain(frame_index, frame_count, int(self._sample_rate))
203
+ if self._apply_fade
204
+ else 1.0
205
+ )
206
+ channel[frame_index] = self._amplitude * gain * self._sample_fn(phase)
207
+ phase += phase_step
208
+ if phase >= _TAU:
209
+ phase -= _TAU
210
+
211
+ def start(self) -> None:
212
+ ok = self._engine.startAndReturnError_(None)
213
+ if not ok:
214
+ raise OSError("AVAudioEngine failed to start")
215
+ self._player.scheduleBuffer_completionHandler_(self._buffer, None)
216
+ self._player.play()
217
+
218
+ def stop(self) -> None:
219
+ self._player.stop()
220
+ self._engine.stop()
@@ -0,0 +1 @@
1
+ """Low-level Core Audio / CATapDescription bindings."""