duotape 0.1.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.
Files changed (78) hide show
  1. duotape/__init__.py +3 -0
  2. duotape/__main__.py +5 -0
  3. duotape/after_session.py +258 -0
  4. duotape/audio_devices.py +191 -0
  5. duotape/audio_recorder.py +232 -0
  6. duotape/button_notice.py +265 -0
  7. duotape/call_guard.py +188 -0
  8. duotape/cli.py +1150 -0
  9. duotape/config.py +570 -0
  10. duotape/crash_recovery.py +259 -0
  11. duotape/data/duotape-control.lua +185 -0
  12. duotape/data/duotape.desktop.in +19 -0
  13. duotape/data/gnome-shortcut.sh +135 -0
  14. duotape/data/icons/duotape-idle.svg +4 -0
  15. duotape/data/icons/duotape-recording-warning.svg +15 -0
  16. duotape/data/icons/duotape-recording.svg +4 -0
  17. duotape/data/icons/duotape-warning.svg +15 -0
  18. duotape/data/icons/duotape-working.svg +16 -0
  19. duotape/data/icons/duotape.svg +5 -0
  20. duotape/desktop_entry.py +140 -0
  21. duotape/desktop_exec.py +89 -0
  22. duotape/desktop_install.py +237 -0
  23. duotape/desktop_uninstall.py +324 -0
  24. duotape/discard.py +265 -0
  25. duotape/discard_command.py +192 -0
  26. duotape/doctor.py +480 -0
  27. duotape/doctor_report.py +90 -0
  28. duotape/doctor_system.py +226 -0
  29. duotape/doctor_tray.py +77 -0
  30. duotape/file_manager.py +118 -0
  31. duotape/file_opener.py +179 -0
  32. duotape/fs_utils.py +154 -0
  33. duotape/job_files.py +102 -0
  34. duotape/launcher_location.py +66 -0
  35. duotape/level_meter.py +184 -0
  36. duotape/listening_copy.py +259 -0
  37. duotape/listening_copy_job.py +185 -0
  38. duotape/media_descriptors.py +78 -0
  39. duotape/notifications.py +404 -0
  40. duotape/obs_backend.py +337 -0
  41. duotape/obs_collection.py +187 -0
  42. duotape/obs_encoder.py +125 -0
  43. duotape/obs_installation.py +285 -0
  44. duotape/obs_leftover.py +149 -0
  45. duotape/obs_setup.py +340 -0
  46. duotape/obs_stop.py +273 -0
  47. duotape/obs_tray_window.py +267 -0
  48. duotape/package_data.py +36 -0
  49. duotape/pipewire_graph.py +267 -0
  50. duotape/preflight.py +76 -0
  51. duotape/recording_folder.py +199 -0
  52. duotape/resident_runtime.py +367 -0
  53. duotape/runtime_paths.py +109 -0
  54. duotape/session.py +1865 -0
  55. duotape/session_bus.py +52 -0
  56. duotape/session_bus_checks.py +122 -0
  57. duotape/session_control.py +177 -0
  58. duotape/session_request.py +60 -0
  59. duotape/session_state.py +200 -0
  60. duotape/systemd_units.py +268 -0
  61. duotape/tool_versions.py +69 -0
  62. duotape/transcription.py +522 -0
  63. duotape/transcription_job.py +100 -0
  64. duotape/transcription_phase.py +115 -0
  65. duotape/tray.py +544 -0
  66. duotape/tray_command.py +165 -0
  67. duotape/tray_menu.py +170 -0
  68. duotape/tray_protocol.py +27 -0
  69. duotape/tray_resident.py +455 -0
  70. duotape/unit_watch.py +459 -0
  71. duotape/watchdog.py +244 -0
  72. duotape/wireplumber.py +112 -0
  73. duotape-0.1.0.dist-info/METADATA +691 -0
  74. duotape-0.1.0.dist-info/RECORD +78 -0
  75. duotape-0.1.0.dist-info/WHEEL +4 -0
  76. duotape-0.1.0.dist-info/entry_points.txt +2 -0
  77. duotape-0.1.0.dist-info/licenses/LICENSE +202 -0
  78. duotape-0.1.0.dist-info/licenses/NOTICE +2 -0
duotape/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """duotape: a start-anytime local meeting recorder for Linux."""
2
+
3
+ __version__ = "0.1.0"
duotape/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m duotape``."""
2
+
3
+ from duotape.cli import run_and_exit
4
+
5
+ run_and_exit()
@@ -0,0 +1,258 @@
1
+ """What runs after a session ends, from the unit's ``ExecStopPost`` (so it runs even if the supervisor crashed).
2
+
3
+ It reports an unclean end. A session that left only the command line's "starting" mark ended before the supervisor
4
+ could write anything. systemd says which way, in the ``$SERVICE_RESULT`` it gives every ``ExecStopPost`` command:
5
+ ``success`` when the unit ended by its own stop signal (a stop that landed while the supervisor was still being
6
+ loaded), anything else when it died by itself.
7
+
8
+ After an unclean end it also does what the supervisor's stop would have done with OBS (``crash_recovery``): it
9
+ stops OBS's recording and collects its file into the meeting folder before the report, and closes OBS after it.
10
+
11
+ A session whose status says a discard was confirmed (``is_discard_requested``) is finished as a discard instead: its
12
+ files are deleted by ``discard.delete_recording_files`` (the video only once OBS confirmed its recording stopped, by a
13
+ fresh report or by no OBS being left after it was closed, and never moved), and the end is announced as a clean
14
+ discard's is, led by ``CRASHED_DISCARD_NOTE`` when anything is left.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable, Mapping
20
+ from pathlib import Path
21
+
22
+ from duotape.audio_recorder import ME_TRACK, THEM_TRACK
23
+ from duotape.config import VIDEO_MODE
24
+ from duotape.crash_recovery import CollectedVideo, CrashedVideo, LocatedVideo
25
+ from duotape.discard import CRASHED_DISCARD_NOTE, DiscardOutcome, delete_recording_files, discard_end_notice
26
+ from duotape.notifications import Urgency, notify_once
27
+ from duotape.obs_stop import (
28
+ NO_VIDEO_FILE_FOUND_AFTER_A_CRASH,
29
+ OBS_MAY_BE_RECORDING_PROBLEM,
30
+ OBS_STILL_OPEN_PROBLEM,
31
+ )
32
+ from duotape.package_data import ICON_IDLE, ICON_WARNING
33
+ from duotape.runtime_paths import RuntimePaths
34
+ from duotape.session_state import (
35
+ CANCELLED_BODY,
36
+ CANCELLED_SUMMARY,
37
+ SessionPhase,
38
+ SessionStatus,
39
+ read_status,
40
+ write_status,
41
+ )
42
+ from duotape.systemd_units import SESSION_UNIT
43
+
44
+ UNCLEAN_PHASES = (SessionPhase.STARTING, SessionPhase.RECORDING, SessionPhase.STOPPING)
45
+ SERVICE_RESULT_ENV_VAR = "SERVICE_RESULT"
46
+ STOPPED_ON_REQUEST_SERVICE_RESULT = "success"
47
+
48
+ Notify = Callable[..., None]
49
+
50
+
51
+ def run_after_session(
52
+ paths: RuntimePaths,
53
+ *,
54
+ environment: Mapping[str, str],
55
+ crashed_video: CrashedVideo,
56
+ notify: Notify = notify_once,
57
+ ) -> int:
58
+ """Report a session that ended without reaching an end state of its own; return the exit code.
59
+
60
+ A session whose status says a discard was confirmed is finished as a discard instead of being reported (see
61
+ ``_finish_a_crashed_discard``).
62
+
63
+ Parameters
64
+ ----------
65
+ paths
66
+ The runtime files (the status, and the files shared with OBS).
67
+ environment
68
+ The after-session step's environment, in which systemd puts ``$SERVICE_RESULT``.
69
+ crashed_video
70
+ Collects the video (or, for a discard, locates it) and closes OBS. It has no default, so that no caller reaches
71
+ a real OBS by leaving it out.
72
+ notify
73
+ Shows a notification (replaced in tests).
74
+
75
+ Returns
76
+ -------
77
+ int
78
+ Always 0.
79
+ """
80
+ status = read_status(paths.status_file)
81
+ if status is None or status.phase not in UNCLEAN_PHASES:
82
+ return 0
83
+ if status.is_discard_requested:
84
+ # Confirmed by the user before the stop began, so a crash never turns it back into a saved recording. It
85
+ # closes OBS itself: whether OBS is gone is part of what decides whether the video may be deleted.
86
+ _finish_a_crashed_discard(paths, status, crashed_video, notify)
87
+ return 0
88
+ status.phase = _unclean_end_phase(status.folder, environment)
89
+ # Saved before the video is collected: on a network mount that stopped answering, collecting can hang until
90
+ # systemd kills this step, which should then cost only the notification and closing OBS (the next start does).
91
+ write_status(paths.status_file, status)
92
+ collected_video = crashed_video.collect(status)
93
+ _report_unclean_end(status.folder, status.phase, notify, collected_video)
94
+ # Until OBS records, the status says audio, and OBS can take half a minute to load, so this runs whatever the
95
+ # mode. It closes only an OBS in duotape's own unit, which an audio-only session never starts, and none while
96
+ # OBS's report says it records.
97
+ crashed_video.close_obs()
98
+ return 0
99
+
100
+
101
+ def _finish_a_crashed_discard(
102
+ paths: RuntimePaths, status: SessionStatus, crashed_video: CrashedVideo, notify: Notify
103
+ ) -> None:
104
+ """Finish the discard a crash interrupted, by the same rules as the supervisor's, and say what is left.
105
+
106
+ Parameters
107
+ ----------
108
+ paths
109
+ The runtime files (the status, the level files, and the files shared with OBS).
110
+ status
111
+ The crashed session's status, with its discard confirmed.
112
+ crashed_video
113
+ Stops OBS's recording, says where its video is (it is never moved), and closes OBS.
114
+ notify
115
+ Shows the notification.
116
+ """
117
+ # Saved before anything is touched, as for a crash that is not a discard: a hung mount costs only the notice.
118
+ status.phase = SessionPhase.CANCELLED
119
+ status.warnings = [CRASHED_DISCARD_NOTE]
120
+ write_status(paths.status_file, status)
121
+ located_video = crashed_video.stop_and_locate(status)
122
+ # As the supervisor does: stop, close OBS, then decide. A fresh report that says OBS is not recording confirms the
123
+ # stop, and so does no OBS being left after closing it; a stale report alone confirms nothing.
124
+ is_obs_gone = crashed_video.close_obs()
125
+ is_stop_confirmed = located_video.is_stop_confirmed or is_obs_gone
126
+ outcome = _delete_the_crashed_recording(paths, status, located_video, is_stop_confirmed)
127
+ items_left = _items_left_by_a_crashed_discard(status, located_video, is_stop_confirmed, is_obs_gone, outcome)
128
+ if status.folder and not Path(status.folder).exists():
129
+ status.folder = "" # `duotape status` must not point at a folder that is gone
130
+ status.warnings = items_left
131
+ write_status(paths.status_file, status)
132
+ end_notice = discard_end_notice(items_left)
133
+ notify(end_notice.summary, end_notice.body, end_notice.urgency, icon=end_notice.icon)
134
+
135
+
136
+ def _items_left_by_a_crashed_discard(
137
+ status: SessionStatus,
138
+ located_video: LocatedVideo,
139
+ is_stop_confirmed: bool,
140
+ is_obs_gone: bool,
141
+ outcome: DiscardOutcome,
142
+ ) -> list[str]:
143
+ """Return what a crashed discard left, led by ``CRASHED_DISCARD_NOTE``; empty only when nothing is left.
144
+
145
+ Parameters
146
+ ----------
147
+ status
148
+ The crashed session's status.
149
+ located_video
150
+ Where the video is.
151
+ is_stop_confirmed
152
+ Whether OBS's recording is known to have stopped.
153
+ is_obs_gone
154
+ Whether no OBS was left in duotape's unit after closing it.
155
+ outcome
156
+ What the deletion left behind.
157
+
158
+ Returns
159
+ -------
160
+ list[str]
161
+ One sentence per item, in the supervisor's order: the note, then OBS's sentences (it may still be recording,
162
+ when the stop is unconfirmed and no file is known; no video file was found; OBS is still open after a confirmed
163
+ stop), then what the deletion left.
164
+ """
165
+ obs_items: list[str] = []
166
+ if status.mode == VIDEO_MODE:
167
+ if not is_stop_confirmed and located_video.file is None:
168
+ obs_items.append(OBS_MAY_BE_RECORDING_PROBLEM)
169
+ if located_video.file is None:
170
+ obs_items.append(NO_VIDEO_FILE_FOUND_AFTER_A_CRASH)
171
+ if is_stop_confirmed and not is_obs_gone and not located_video.is_recording_started_by_hand:
172
+ obs_items.append(OBS_STILL_OPEN_PROBLEM)
173
+ items = [*obs_items, *outcome.left_behind]
174
+ return [CRASHED_DISCARD_NOTE, *items] if items else []
175
+
176
+
177
+ def _delete_the_crashed_recording(
178
+ paths: RuntimePaths, status: SessionStatus, located_video: LocatedVideo, is_stop_confirmed: bool
179
+ ) -> DiscardOutcome:
180
+ """Delete the crashed recording's own files by their known names (``discard.delete_recording_files``).
181
+
182
+ Parameters
183
+ ----------
184
+ paths
185
+ The runtime files, for the level files.
186
+ status
187
+ The crashed session's status, for the meeting folder.
188
+ located_video
189
+ Where OBS wrote the video.
190
+ is_stop_confirmed
191
+ Whether OBS's recording is known to have stopped: the video is deleted where it is only then, and only named
192
+ otherwise.
193
+
194
+ Returns
195
+ -------
196
+ DiscardOutcome
197
+ What was left behind.
198
+ """
199
+ video_to_delete = located_video.file if is_stop_confirmed else None
200
+ video_left_unconfirmed = None if is_stop_confirmed else located_video.file
201
+ return delete_recording_files(
202
+ Path(status.folder) if status.folder else None,
203
+ video_to_delete,
204
+ video_left_unconfirmed=video_left_unconfirmed,
205
+ level_files=[paths.levels_file(THEM_TRACK), paths.levels_file(ME_TRACK)],
206
+ )
207
+
208
+
209
+ def _unclean_end_phase(folder: str, environment: Mapping[str, str]) -> SessionPhase:
210
+ """Return the phase a session ended in that never reached an end state of its own.
211
+
212
+ Parameters
213
+ ----------
214
+ folder
215
+ The meeting folder from the status, empty when the supervisor ended before it had one.
216
+ environment
217
+ The after-session step's environment, in which systemd puts ``$SERVICE_RESULT``.
218
+
219
+ Returns
220
+ -------
221
+ SessionPhase
222
+ Cancelled when it was stopped on request before it had a meeting folder (so before anything was recorded),
223
+ failed otherwise.
224
+ """
225
+ # Only the command line's "starting" mark exists: the supervisor ended before it had a meeting folder.
226
+ if not folder and environment.get(SERVICE_RESULT_ENV_VAR) == STOPPED_ON_REQUEST_SERVICE_RESULT:
227
+ return SessionPhase.CANCELLED
228
+ return SessionPhase.FAILED
229
+
230
+
231
+ def _report_unclean_end(folder: str, phase: SessionPhase, notify: Notify, collected_video: CollectedVideo) -> None:
232
+ """Tell the user how a session ended that never reached an end state of its own.
233
+
234
+ Parameters
235
+ ----------
236
+ folder
237
+ The meeting folder from the status, empty when the supervisor ended before it had one.
238
+ phase
239
+ The phase it ended in (``_unclean_end_phase``).
240
+ notify
241
+ Shows the notification.
242
+ collected_video
243
+ Where the session's video ended up, so a video left outside the meeting folder can be named.
244
+ """
245
+ if folder:
246
+ body = f"duotape exited before saving cleanly. What was recorded is in {folder}."
247
+ if collected_video.left_file is not None:
248
+ body += f" The screen video is still at {collected_video.left_file}."
249
+ notify("Recording stopped unexpectedly", body, Urgency.CRITICAL, icon=ICON_WARNING)
250
+ elif phase is SessionPhase.CANCELLED:
251
+ notify(CANCELLED_SUMMARY, CANCELLED_BODY, icon=ICON_IDLE)
252
+ else:
253
+ notify(
254
+ "Recording did not start",
255
+ f"duotape stopped before it could record anything. See 'journalctl --user -u {SESSION_UNIT}'.",
256
+ Urgency.CRITICAL,
257
+ icon=ICON_WARNING,
258
+ )
@@ -0,0 +1,191 @@
1
+ """Choosing what a session records: one speaker (whose monitor is the far side) and one microphone.
2
+
3
+ duotape records the devices the system or the config names, and never changes a profile or a default device. A
4
+ Bluetooth headset whose microphone is recorded is switched to call mode by WirePlumber itself, for as long as
5
+ something records from it, and back afterwards.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Iterable
11
+ from dataclasses import dataclass
12
+
13
+ from duotape.config import Settings
14
+ from duotape.pipewire_graph import AudioDevice, AudioNode, PipeWireGraph, foreign_streams
15
+
16
+ DEFAULT_DEVICE = "default"
17
+ SPEAKER_ROLE = "speaker"
18
+ MICROPHONE_ROLE = "microphone"
19
+ # Form factors of devices worn on the head; PipeWire's Bluetooth support names a speaker "speaker", "portable",
20
+ # "hifi" or "car". "hands-free" and "handsfree" are both in its list.
21
+ PERSONAL_FORM_FACTORS = ("headset", "headphone", "hands-free", "handsfree")
22
+ PERSONAL_NAME_HINTS = ("headphone", "headset")
23
+ # PipeWire's names for a Bluetooth headset's call profiles (HFP/HSP): "headset-head-unit", and its codec variants
24
+ # such as "headset-head-unit-msbc".
25
+ CALL_PROFILE_PREFIX = "headset-head-unit"
26
+
27
+
28
+ class DeviceResolutionError(RuntimeError):
29
+ """Raised when there is no usable speaker or microphone to record."""
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ResolvedDevices:
34
+ """The devices one session records.
35
+
36
+ Attributes
37
+ ----------
38
+ speaker
39
+ The sink whose monitor carries the far side.
40
+ microphone
41
+ The source that carries the user's voice.
42
+ speaker_is_personal
43
+ Whether the speaker is headphones or a headset; if not, the microphone also picks up the far side.
44
+ recording_switches_the_speakers_headset
45
+ Whether recording the microphone will make WirePlumber switch the Bluetooth headset that is also the
46
+ speaker to call mode; WirePlumber before 0.5.13 then replaces the speaker node.
47
+ """
48
+
49
+ speaker: AudioNode
50
+ microphone: AudioNode
51
+ speaker_is_personal: bool
52
+ recording_switches_the_speakers_headset: bool
53
+
54
+
55
+ def _has_role(node: AudioNode, role: str) -> bool:
56
+ """Return whether a node can serve as the speaker or the microphone, whichever ``role`` names."""
57
+ return node.is_speaker if role == SPEAKER_ROLE else node.is_microphone
58
+
59
+
60
+ def _choose_node(graph: PipeWireGraph, configured_name: str, default_name: str | None, role: str) -> AudioNode:
61
+ node_name = default_name if configured_name == DEFAULT_DEVICE else configured_name
62
+ if not node_name:
63
+ raise DeviceResolutionError(f"no default {role}: connect or select one in the sound settings")
64
+ node = graph.node_by_name(node_name)
65
+ if node is None or not _has_role(node, role):
66
+ raise DeviceResolutionError(f"the {role} '{node_name}' is not available")
67
+ return node
68
+
69
+
70
+ def choose_nodes(graph: PipeWireGraph, settings: Settings) -> tuple[AudioNode, AudioNode]:
71
+ """Pick the speaker and microphone from the settings, falling back to the current defaults.
72
+
73
+ Parameters
74
+ ----------
75
+ graph
76
+ The current graph.
77
+ settings
78
+ ``speaker`` and ``microphone`` are node names or ``"default"``.
79
+
80
+ Returns
81
+ -------
82
+ tuple[AudioNode, AudioNode]
83
+ The speaker and the microphone.
84
+
85
+ Raises
86
+ ------
87
+ DeviceResolutionError
88
+ If a default is missing or a configured node does not exist.
89
+ """
90
+ speaker = _choose_node(graph, settings.speaker, graph.default_sink_name, SPEAKER_ROLE)
91
+ microphone = _choose_node(graph, settings.microphone, graph.default_source_name, MICROPHONE_ROLE)
92
+ return speaker, microphone
93
+
94
+
95
+ def is_personal_output(graph: PipeWireGraph, node: AudioNode) -> bool:
96
+ """Return whether a speaker node is headphones or a headset (so the microphone does not hear the far side)."""
97
+ device = graph.device_by_id(node.device_id) if node.device_id is not None else None
98
+ if device is not None and device.form_factor in PERSONAL_FORM_FACTORS:
99
+ return True
100
+ searchable_text = f"{node.name} {node.description}".casefold()
101
+ return any(hint in searchable_text for hint in PERSONAL_NAME_HINTS)
102
+
103
+
104
+ def bluetooth_headset_of(graph: PipeWireGraph, node: AudioNode) -> AudioDevice | None:
105
+ """Return the Bluetooth device a speaker or microphone node belongs to, or None (a virtual or wired node)."""
106
+ device = graph.device_by_id(node.device_id) if node.device_id is not None else None
107
+ return device if device is not None and device.is_bluetooth else None
108
+
109
+
110
+ def is_speaker_on_the_microphones_headset(graph: PipeWireGraph, speaker: AudioNode, microphone: AudioNode) -> bool:
111
+ """Return whether the microphone is a Bluetooth headset's and the speaker is the same headset's."""
112
+ headset = bluetooth_headset_of(graph, microphone)
113
+ return headset is not None and speaker.device_id == headset.id
114
+
115
+
116
+ def _recording_switches_the_speakers_headset(graph: PipeWireGraph, speaker: AudioNode, microphone: AudioNode) -> bool:
117
+ """Return whether recording the microphone will make WirePlumber switch the speaker's headset to call mode.
118
+
119
+ It will when the microphone and the speaker are one headset's, the headset is not in a call profile yet, and
120
+ nothing records from its microphone yet (anything that did would have had WirePlumber switch it already).
121
+ """
122
+ headset = bluetooth_headset_of(graph, microphone)
123
+ if headset is None or speaker.device_id != headset.id:
124
+ return False
125
+ is_in_call_mode = (headset.active_profile or "").startswith(CALL_PROFILE_PREFIX)
126
+ return not is_in_call_mode and not graph.streams_capturing_from(microphone.id)
127
+
128
+
129
+ def apps_capturing_a_microphone(
130
+ graph: PipeWireGraph, ignored_apps: Iterable[str], own_process_ids: Iterable[int]
131
+ ) -> list[str]:
132
+ """Return the names of the other applications capturing from any microphone, sorted and each named once.
133
+
134
+ Parameters
135
+ ----------
136
+ graph
137
+ The current graph.
138
+ ignored_apps
139
+ Application names that never count, compared case-insensitively.
140
+ own_process_ids
141
+ Process ids of duotape's own recorders.
142
+
143
+ Returns
144
+ -------
145
+ list[str]
146
+ The applications that count as a call.
147
+ """
148
+ ignored = tuple(ignored_apps)
149
+ own_ids = set(own_process_ids)
150
+ capturing_apps = {
151
+ stream.application_name
152
+ for node in graph.nodes
153
+ if node.is_microphone
154
+ for stream in foreign_streams(graph.streams_capturing_from(node.id), ignored, own_ids)
155
+ }
156
+ return sorted(capturing_apps, key=str.casefold)
157
+
158
+
159
+ def is_call_in_progress(graph: PipeWireGraph, ignored_apps: Iterable[str], own_process_ids: Iterable[int]) -> bool:
160
+ """Return whether any other application is capturing from any microphone, i.e. a call is probably running."""
161
+ return bool(apps_capturing_a_microphone(graph, ignored_apps, own_process_ids))
162
+
163
+
164
+ def resolve_devices(settings: Settings, *, read_graph: Callable[[], PipeWireGraph]) -> ResolvedDevices:
165
+ """Decide what to record, from the settings and the current defaults; nothing is changed.
166
+
167
+ Parameters
168
+ ----------
169
+ settings
170
+ The configured speaker and microphone, or ``"default"``.
171
+ read_graph
172
+ Takes a snapshot of the audio graph.
173
+
174
+ Returns
175
+ -------
176
+ ResolvedDevices
177
+ The speaker and microphone to record.
178
+
179
+ Raises
180
+ ------
181
+ DeviceResolutionError
182
+ If no usable speaker or microphone exists.
183
+ """
184
+ graph = read_graph()
185
+ speaker, microphone = choose_nodes(graph, settings)
186
+ return ResolvedDevices(
187
+ speaker,
188
+ microphone,
189
+ speaker_is_personal=is_personal_output(graph, speaker),
190
+ recording_switches_the_speakers_headset=_recording_switches_the_speakers_headset(graph, speaker, microphone),
191
+ )
@@ -0,0 +1,232 @@
1
+ """The audio recorder: the far side (the speaker's monitor) and the microphone as two independent FLAC streams.
2
+
3
+ One ffmpeg process reads both PipeWire nodes through the PulseAudio API. Each input has its own filter graph and its
4
+ own wall-clock timestamps, so a dropout leaves a gap instead of shifting the rest of the track. ffmpeg would start
5
+ each input at zero on its own, dropping the time between opening the two, so the microphone is synced to the far
6
+ side's clock (``-isync``): the two tracks stay in step, to within the devices' latency. The inputs are not
7
+ independent, though: ffmpeg 7 and later read them in step, so a device that stops delivering audio holds up the other
8
+ track too (``watchdog`` reports it). A side branch of each graph meters the input once a second into a levels file.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import signal
15
+ import subprocess
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ from duotape.fs_utils import PRIVATE_FILE_MODE, set_mode_where_supported
20
+ from duotape.media_descriptors import create_for_writing, descriptor_url_arguments, open_for_reading
21
+
22
+ SAMPLE_RATE_HZ = 48000
23
+ METER_WINDOW_SAMPLES = SAMPLE_RATE_HZ # one level per second
24
+ RMS_LEVEL_KEY = "lavfi.astats.Overall.RMS_level"
25
+ PULSE_CLIENT_NAME = "duotape"
26
+ # ffmpeg exits 0, or 255 when it finished the file after the SIGINT that stops it.
27
+ CLEAN_EXIT_CODES = (0, 255)
28
+ THEM_TRACK = "them"
29
+ ME_TRACK = "me"
30
+ # The order of ffmpeg's inputs: the far side first, as the clock the microphone is synced to.
31
+ THEM_INPUT_INDEX = 0
32
+ ME_INPUT_INDEX = 1
33
+ # How much of ffmpeg's log is quoted when it exits unexpectedly: its last lines say why.
34
+ LOG_TAIL_LINES = 5
35
+ # Characters with a meaning in a filter option value (level 1) and in a filtergraph description (level 2).
36
+ OPTION_VALUE_SPECIAL_CHARACTERS = "\\':"
37
+ FILTERGRAPH_SPECIAL_CHARACTERS = "\\'[],;"
38
+
39
+
40
+ class AudioRecorderError(RuntimeError):
41
+ """Raised when the audio recorder cannot be started."""
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class AudioRecordingPlan:
46
+ """What the audio recorder reads and writes.
47
+
48
+ Attributes
49
+ ----------
50
+ output_file
51
+ The ``.mka`` to write: stream 0 = Them (far side), stream 1 = Me (microphone).
52
+ speaker_monitor
53
+ The PulseAudio source name of the speaker's monitor, ``<sink node name>.monitor``.
54
+ microphone
55
+ The microphone's node name.
56
+ their_levels_file, my_levels_file
57
+ Where each track's per-second RMS level is printed.
58
+ """
59
+
60
+ output_file: Path
61
+ speaker_monitor: str
62
+ microphone: str
63
+ their_levels_file: Path
64
+ my_levels_file: Path
65
+
66
+
67
+ def _escape(value: str, special_characters: str) -> str:
68
+ return "".join(f"\\{character}" if character in special_characters else character for character in value)
69
+
70
+
71
+ def escape_filter_value(value: str) -> str:
72
+ """Escape a filter option value (such as a file path) for use inside a ``-filter_complex`` description."""
73
+ option_level_escaped = _escape(value, OPTION_VALUE_SPECIAL_CHARACTERS)
74
+ return _escape(option_level_escaped, FILTERGRAPH_SPECIAL_CHARACTERS)
75
+
76
+
77
+ def _track_filter_graph(input_index: int, output_label: str, levels_file: Path) -> str:
78
+ """Pass one input through to ``[output_label]`` and meter it once a second into ``levels_file``."""
79
+ meter_label = f"meter{input_index}"
80
+ meter_chain = (
81
+ f"[{meter_label}]asetnsamples=n={METER_WINDOW_SAMPLES},astats=metadata=1:reset=1,"
82
+ f"ametadata=mode=print:key={RMS_LEVEL_KEY}:file={escape_filter_value(str(levels_file))}:direct=1,anullsink"
83
+ )
84
+ return f"[{input_index}:a]asplit=2[{output_label}][{meter_label}];{meter_chain}"
85
+
86
+
87
+ def _pulse_input(source_name: str, stream_name: str) -> list[str]:
88
+ return [
89
+ "-f", "pulse",
90
+ "-name", PULSE_CLIENT_NAME,
91
+ "-stream_name", stream_name,
92
+ "-sample_rate", str(SAMPLE_RATE_HZ),
93
+ "-channels", "1",
94
+ "-i", source_name,
95
+ ] # fmt: skip
96
+
97
+
98
+ def build_ffmpeg_command(plan: AudioRecordingPlan, output_descriptor: int) -> list[str]:
99
+ """Build the recorder's ffmpeg argv (never run through a shell, so node names pass through unchanged).
100
+
101
+ ffmpeg writes ``plan.output_file`` through ``output_descriptor``, which it inherits: the file's path holds the
102
+ meeting's title, and every local user can read a process's arguments.
103
+ """
104
+ return [
105
+ "ffmpeg", "-hide_banner", "-nostdin", "-loglevel", "warning",
106
+ *_pulse_input(plan.speaker_monitor, THEM_TRACK),
107
+ "-isync", str(THEM_INPUT_INDEX), *_pulse_input(plan.microphone, ME_TRACK),
108
+ "-filter_complex", _track_filter_graph(THEM_INPUT_INDEX, THEM_TRACK, plan.their_levels_file),
109
+ "-filter_complex", _track_filter_graph(ME_INPUT_INDEX, ME_TRACK, plan.my_levels_file),
110
+ "-map", f"[{THEM_TRACK}]", "-map", f"[{ME_TRACK}]",
111
+ "-c:a", "flac",
112
+ "-metadata:s:a:0", "title=Them",
113
+ "-metadata:s:a:1", "title=Me",
114
+ "-f", MATROSKA_FORMAT, *descriptor_url_arguments(output_descriptor),
115
+ ] # fmt: skip
116
+
117
+
118
+ class AudioRecorder:
119
+ """Runs and supervises the ffmpeg audio recorder.
120
+
121
+ Parameters
122
+ ----------
123
+ plan
124
+ What to record and where.
125
+ log_file
126
+ Where ffmpeg's warnings and errors go (owner-only).
127
+ """
128
+
129
+ def __init__(self, plan: AudioRecordingPlan, log_file: Path) -> None:
130
+ self.plan = plan
131
+ self._log_file = log_file
132
+ self._process: subprocess.Popen[bytes] | None = None
133
+
134
+ def start(self) -> None:
135
+ """Start recording.
136
+
137
+ Raises
138
+ ------
139
+ AudioRecorderError
140
+ If ffmpeg is missing or cannot be started.
141
+ """
142
+ try:
143
+ # Created owner-only, so the log is private even where chmod is refused (a FAT or exFAT drive).
144
+ log_descriptor = os.open(self._log_file, os.O_WRONLY | os.O_CREAT | os.O_APPEND, PRIVATE_FILE_MODE)
145
+ log_handle = os.fdopen(log_descriptor, "ab")
146
+ with log_handle, create_for_writing(self.plan.output_file) as output_descriptor:
147
+ set_mode_where_supported(self._log_file, PRIVATE_FILE_MODE)
148
+ command = build_ffmpeg_command(self.plan, output_descriptor)
149
+ self._process = subprocess.Popen(
150
+ command,
151
+ stdin=subprocess.DEVNULL,
152
+ stdout=log_handle,
153
+ stderr=log_handle,
154
+ pass_fds=(output_descriptor,),
155
+ )
156
+ except FileNotFoundError as err:
157
+ raise AudioRecorderError("ffmpeg is not installed") from err
158
+ except OSError as err:
159
+ raise AudioRecorderError(f"could not start ffmpeg: {err}") from err
160
+
161
+ @property
162
+ def pid(self) -> int | None:
163
+ """The ffmpeg process id, once started."""
164
+ return self._process.pid if self._process else None
165
+
166
+ def log_tail(self, max_lines: int = LOG_TAIL_LINES) -> str:
167
+ """Return the last lines ffmpeg logged (an empty string when there is no log or it cannot be read)."""
168
+ try:
169
+ log_lines = self._log_file.read_text(encoding="utf-8", errors="replace").splitlines()
170
+ except OSError:
171
+ return ""
172
+ return "\n".join(log_lines[-max_lines:])
173
+
174
+ def is_alive(self) -> bool:
175
+ """Return whether ffmpeg is still running."""
176
+ return self._process is not None and self._process.poll() is None
177
+
178
+ @property
179
+ def returncode(self) -> int | None:
180
+ """Ffmpeg's exit status, once it has exited."""
181
+ return self._process.poll() if self._process else None
182
+
183
+ def wait(self, timeout_s: float) -> int | None:
184
+ """Wait for ffmpeg to exit; return its exit status, or None if it is still running after the timeout."""
185
+ if self._process is None:
186
+ return None
187
+ try:
188
+ return self._process.wait(timeout=timeout_s)
189
+ except subprocess.TimeoutExpired:
190
+ return None
191
+
192
+ def interrupt(self) -> None:
193
+ """Ask ffmpeg to finish the file and exit (SIGINT, as on Ctrl-C)."""
194
+ if self.is_alive() and self._process is not None:
195
+ self._process.send_signal(signal.SIGINT)
196
+
197
+ def kill(self) -> None:
198
+ """Stop ffmpeg at once; the file may lack its final index but stays readable."""
199
+ if self.is_alive() and self._process is not None:
200
+ self._process.kill()
201
+
202
+
203
+ FFPROBE_TIMEOUT_S = 30
204
+ MATROSKA_FORMAT = "matroska"
205
+
206
+
207
+ def count_audio_streams(recording: Path) -> int:
208
+ """Return how many audio streams a recording has (0 when it is missing or unreadable)."""
209
+ probe_command = [
210
+ "ffprobe",
211
+ "-v",
212
+ "error",
213
+ "-select_streams",
214
+ "a",
215
+ "-show_entries",
216
+ "stream=index",
217
+ "-of",
218
+ "csv=p=0",
219
+ ]
220
+ try:
221
+ with open_for_reading(recording) as recording_descriptor:
222
+ probe = subprocess.run(
223
+ [*probe_command, *descriptor_url_arguments(recording_descriptor)],
224
+ capture_output=True,
225
+ text=True,
226
+ check=True,
227
+ timeout=FFPROBE_TIMEOUT_S,
228
+ pass_fds=(recording_descriptor,),
229
+ )
230
+ except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):
231
+ return 0
232
+ return len([line for line in probe.stdout.splitlines() if line.strip()])