diff --git a/packages/omamobile-modem-sit/bin/omamobile-sit b/packages/omamobile-modem-sit/bin/omamobile-sit index 9b86a4185..65d62b714 100755 --- a/packages/omamobile-modem-sit/bin/omamobile-sit +++ b/packages/omamobile-modem-sit/bin/omamobile-sit @@ -9,6 +9,8 @@ omamobile-sit hangup [ID] the current call (or call ID) omamobile-sit dtmf KEYS [ID] touch tones in the active call omamobile-sit mute on|off the microphone during a call + omamobile-sit speaker on|off the loudspeaker or the earpiece during a + call (Pixel 9a only) omamobile-sit sms send NUMBER TEXT one SMS (several parts if needed) omamobile-sit sms list [--json] received, not yet deleted omamobile-sit sms delete ID @@ -120,6 +122,9 @@ def main(argv): if cmd == 'mute' and rest in (['on'], ['off']): request('audio', what='mute', value=rest[0]) return 0 + if cmd == 'speaker' and rest in (['on'], ['off']): + print('loudspeaker' if request('audio', what='speaker', value=rest[0])['speaker'] else 'earpiece') + return 0 if cmd == 'sms' and rest[:1] == ['send'] and len(rest) == 3: key = uuid.uuid4().hex result = request('sms-send', timeout=300, request_id=key, number=rest[1], text=rest[2]) diff --git a/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf b/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf index 8379e6d9b..27482aaf6 100644 --- a/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf +++ b/packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf @@ -149,11 +149,17 @@ group = wheel # reports that mode; with earpiece = no, refused unless the service runs at # stage media or c8 with the top amplifier at analog 6 or less and both # within the media stage's ceilings (digital 737, analog 10). -# On the Pixel 9a, call audio selects an experimental TAS2572 speakerphone -# route instead, held muted until both gains read back -20 dB after PCM -# startup. +# On the Pixel 9a, call audio selects an experimental TAS2572 route instead, +# held muted until both gains read back what was written after PCM startup +# (see "output" below). #card = none earpiece = yes +# Pixel 9a only: where a call starts, "speaker" (the default: both +# amplifiers at -20 dB, the loudspeaker) or "earpiece" (the top amplifier +# alone at -20 dB, the bottom at 0). "omamobile-sit speaker on|off" switches +# during a call. Every other phone ignores this key; on the 9a an unknown +# value is logged and the call starts on the loudspeaker. +#output = speaker # Microphone gain above stock's 130 cB during calls: 6 (default, judged # louder and clean in calls on the 7 Pro) or 0 (stock). The 9a always uses # stock's 130 cB, with no boost. diff --git a/packages/omamobile-modem-sit/lib/service.py b/packages/omamobile-modem-sit/lib/service.py index cc7494869..b842f44f7 100644 --- a/packages/omamobile-modem-sit/lib/service.py +++ b/packages/omamobile-modem-sit/lib/service.py @@ -13,6 +13,7 @@ {"action": "accept"|"hangup"|"delete-call", "id": "..."} {"action": "dtmf", "id": "...", "keys": "12#"} {"action": "audio", "what": "mute", "value": "on"|"off"} + {"action": "audio", "what": "speaker", "value": "on"|"off"} loudspeaker | earpiece (tegu) {"action": "sms-send", "request_id": <32 hex>, "number": "...", "text": "..."} {"action": "sms-status", "request_id": ...} | {"action": "sms-list"} {"action": "sms-delete", "id": "..."} @@ -362,7 +363,8 @@ def audio_start(self): # in the status's audio error, as with [audio] card = none. try: self.audio = VoiceAudio(mic_boost_db=audio.getint('mic_boost_db', 6), card=card, - earpiece=audio.getboolean('earpiece', True)) + earpiece=audio.getboolean('earpiece', True), + output=audio.get('output', 'speaker').strip().lower()) self.audio.__enter__() except (OSError, RuntimeError, ValueError, subprocess.TimeoutExpired) as error: self.audio = None @@ -754,9 +756,13 @@ def status(self, *, public=False): unread = self.db.execute('SELECT COUNT(*) FROM received WHERE consumed=0').fetchone()[0] return dict(modem=modem, calls=calls, sms=dict(unread=unread), updated=int(time.time())) received = [r[0] for r in self.db.execute('SELECT id FROM received WHERE consumed=0 ORDER BY rowid')] + # The loudspeaker and the switch are facts of the tegu route alone: + # every other phone's call plays in its earpiece and can't switch. + tegu = getattr(self.audio, 'tegu', False) is True return dict(modem=modem, calls=calls, sms=dict(received=['sit:' + i for i in received]), audio=dict(available=True, running=self.audio is not None, mute=self.muted, - speaker=getattr(self.audio, 'tegu', False) is True, speaker_available=False, error=self.audio_error)) + speaker=tegu and getattr(self.audio, 'output', 'speaker') == 'speaker', + speaker_available=tegu, error=self.audio_error)) def subscribe(self, connection): """Keep an authorised connection for status events; refuse beyond @@ -971,7 +977,10 @@ def dispatch(self, request): if self.audio is None: raise RuntimeError('No call audio is running') if request.get('what') == 'speaker': - raise RuntimeError('Speakerphone routing is not configured yet') + if request.get('value') not in ('on', 'off'): + raise ValueError('Invalid audio command') + self.audio.set_output('speaker' if request['value'] == 'on' else 'earpiece') + return self.status()['audio'] if request.get('what') != 'mute' or request.get('value') not in ('on', 'off'): raise ValueError('Invalid audio command') self.muted = request['value'] == 'on' diff --git a/packages/omamobile-modem-sit/lib/voice_audio.py b/packages/omamobile-modem-sit/lib/voice_audio.py index 4b6ff2070..37b6fd09a 100644 --- a/packages/omamobile-modem-sit/lib/voice_audio.py +++ b/packages/omamobile-modem-sit/lib/voice_audio.py @@ -16,8 +16,11 @@ stage's (digital <= 737, analog <= 10, AGENTS.md). The built-in default routes no call audio; a device package whose route is verified sets [audio] card = auto in its defaults (paths.DEVICE_DEFAULTS). Tegu instead -uses its TAS2572 speakerphone path, muted until both amplifiers read back a -conservative gain after PCM start. +uses its TAS2572 path, muted until both amplifiers read back what was +written after PCM start: the loudspeaker (both amplifiers at a conservative +gain) or, with [audio] output = earpiece, the earpiece (the top amplifier +alone, the bottom at 0). set_output switches between the two during a call +under the same rule. """ import ctypes as C import os @@ -64,6 +67,13 @@ ('MIC HW Gain At High Power Mode (cB)', '130'), ('MIC Record Soft Gain (dB)', '0'), ('TDM_0_RX Mixer EP5', '1'), ('EP4 TX Mixer INTERNAL_MIC_TX', '1')) +# Call-audio outputs on the 9a's TAS2572 route, as the TEGU_GAINS pair (top, +# bottom): the top amplifier is the earpiece, the bottom the loudspeaker +# (this module's docstring). "earpiece" mutes the bottom's digital volume so +# only the top (earpiece) sounds; "speaker" runs both at the conservative +# gain. Switched live during a call (set_output), the sink muted across the +# change, and the original gains come back from `saved` when the call ends. +TEGU_OUTPUTS = {'speaker': (TEGU_GAIN, TEGU_GAIN), 'earpiece': (TEGU_GAIN, '0')} class AudioRefused(RuntimeError): @@ -106,7 +116,10 @@ class VoiceAudio: # without earpiece mode (no service installed, or [audio] earpiece = no) earpiece_cmd = None - def __init__(self, *, mic_boost_db=6, card=None, earpiece=True): + # The call-audio output to start a call on (set_output switches it live). + output = 'speaker' + + def __init__(self, *, mic_boost_db=6, card=None, earpiece=True, output='speaker'): if mic_boost_db not in (0, 6): raise ValueError('unsupported voice microphone boost') self.mic_boost_db = mic_boost_db @@ -118,6 +131,15 @@ def __init__(self, *, mic_boost_db=6, card=None, earpiece=True): # The protection service's earpiece mode is the 7 Pro's CS35L41 # route; the 9a's TAS2572 route sets its own gains. self.earpiece_cmd = None + # [audio] output is the tegu route's key and is read here only: + # on every other phone it is ignored, whatever it says, so a + # mistyped value there can't take a call's audio away. On the + # 9a an unknown value is logged and the call starts on the + # loudspeaker, as without the key. + if output in TEGU_OUTPUTS: + self.output = output + else: + print('Unknown [audio] output', repr(str(output)[:32]) + '; using speaker', flush=True) self.saved = [] self.pcms = [] self.alsa = C.CDLL('libasound.so.2') @@ -285,22 +307,55 @@ def tegu_enter(self): self.check(self.alsa.snd_pcm_start(pcm), 'start') # The codec profile resets gain at playback start. These must # happen afterwards, while the modem downlink remains muted. - for name in TEGU_GAINS: - self.mixer('cset', name, TEGU_GAIN) - for name in TEGU_GAINS: - try: - gain = self.mixer_value(name) - except (OSError, RuntimeError, subprocess.TimeoutExpired) as error: - raise AudioRefused('tegu call audio refused: TAS gain read-back unavailable') from error - if gain != TEGU_GAIN: - raise AudioRefused('tegu call audio refused: TAS gain read-back mismatch') + # The configured output's gains (the earpiece's when asked + # for), so the call's first moment is already on that output. + self.tegu_gains(TEGU_OUTPUTS[self.output], 'tegu call audio refused') self.mixer('cset', 'Incall Sink Mute', '0') - print('AoC tegu speakerphone prepared at conservative TAS gain', flush=True) + print('AoC tegu', 'speakerphone' if self.output == 'speaker' else self.output, + 'prepared at conservative TAS gain', flush=True) return self except BaseException: self.__exit__(None, None, None) raise + def set_output(self, output): + """Switch call audio between the loudspeaker and the earpiece during + a call. Wired for the tegu TAS2572 route only. The sink is muted + across the gain change (no pop) and stays muted if the change + can't be confirmed; the top amplifier (the earpiece) always sounds + and the bottom (the loudspeaker) is muted for the earpiece; the + original gains return from `saved` when the call ends.""" + if output not in TEGU_OUTPUTS: + raise ValueError('unsupported call audio output: ' + str(output)) + if not getattr(self, 'tegu', False): + raise RuntimeError('call audio output switching is only wired for the tegu route') + if not self.pcms: + raise RuntimeError('no call audio is running') + # The tegu route's rule holds here too: the call sink is unmuted + # only once both gains read back what was written. A failed write or + # a mismatch leaves the sink muted and raises; the output isn't + # changed, and a repeat of the command can try again. + self.mixer('cset', 'Incall Sink Mute', '1') + if self.mixer_value('Incall Sink Mute') not in ('1', 'on'): + raise AudioRefused('call audio output refused: sink mute read-back mismatch') + self.tegu_gains(TEGU_OUTPUTS[output], 'call audio output refused') + self.mixer('cset', 'Incall Sink Mute', '0') + self.output = output + print('AoC tegu call audio switched to the', 'loudspeaker' if output == 'speaker' else output, flush=True) + + def tegu_gains(self, values, refusal): + """Write the (top, bottom) Speaker Digital Volume and read both + back; AudioRefused unless each reads what was written.""" + for name, value in zip(TEGU_GAINS, values): + self.mixer('cset', name, value) + for name, value in zip(TEGU_GAINS, values): + try: + gain = self.mixer_value(name) + except (OSError, RuntimeError, subprocess.TimeoutExpired) as error: + raise AudioRefused(refusal + ': TAS gain read-back unavailable') from error + if gain != value: + raise AudioRefused(refusal + ': TAS gain read-back mismatch') + def __exit__(self, *args): failures = [] if getattr(self, 'tegu', False) and self.saved: diff --git a/packages/omamobile-modem-sit/test/test_service.py b/packages/omamobile-modem-sit/test/test_service.py index 742ab50f4..4ce4758a1 100644 --- a/packages/omamobile-modem-sit/test/test_service.py +++ b/packages/omamobile-modem-sit/test/test_service.py @@ -10,6 +10,7 @@ from unittest.mock import Mock, MagicMock, patch import paths import service as app_service +from voice_audio import VoiceAudio class ServiceTests(unittest.TestCase): def setUp(self): @@ -76,11 +77,42 @@ def test_refused_tegu_gain_does_not_fail_call_signalling(self): self.assertEqual([c.args[0] for c in self.client.request.call_args_list], [0x0000, 0x0d00]) self.assertIsNone(self.service.audio) - def test_tegu_route_is_reported_as_speakerphone(self): - self.service.audio = MagicMock(tegu=True) - self.assertTrue(self.service.status()['audio']['speaker']) - self.service.audio.tegu = False + def test_call_audio_output_is_reported_and_switchable_on_tegu(self): + self.service.audio = MagicMock(tegu=True, output='speaker', pcms=[1]) + status = self.service.status()['audio'] + self.assertTrue(status['speaker']) # the loudspeaker + self.assertTrue(status['speaker_available']) # the tegu route can switch + self.service.audio.output = 'earpiece' self.assertFalse(self.service.status()['audio']['speaker']) + self.service.audio = None + off = self.service.status()['audio'] + self.assertFalse(off['speaker'] or off['speaker_available']) + + def test_a_route_other_than_tegu_reports_the_earpiece_and_no_switch(self): + # The 7 Pro's call plays in its earpiece (the CS35L41 earpiece mode) + # whatever [audio] output says, and that default is "speaker". + for output in ('speaker', 'earpiece'): + self.service.audio = MagicMock(tegu=False, output=output, pcms=[1]) + status = self.service.status()['audio'] + self.assertFalse(status['speaker'], output) + self.assertFalse(status['speaker_available'], output) + self.assertTrue(status['running']) + # A real route object away from the tegu card has no tegu attribute set true. + audio = VoiceAudio.__new__(VoiceAudio) + audio.tegu = False + self.service.audio = audio + self.assertEqual(audio.output, 'speaker') + self.assertFalse(self.service.status()['audio']['speaker']) + + def test_speaker_command_switches_the_output_and_rejects_bad_values(self): + self.service.audio = MagicMock(tegu=True, output='speaker', pcms=[1]) + self.service.dispatch(dict(action='audio', what='speaker', value='off')) + self.service.audio.set_output.assert_called_once_with('earpiece') + self.service.audio.set_output.reset_mock() + self.service.dispatch(dict(action='audio', what='speaker', value='on')) + self.service.audio.set_output.assert_called_once_with('speaker') + with self.assertRaises(ValueError): + self.service.dispatch(dict(action='audio', what='speaker', value='maybe')) def test_failed_radio_off_still_requires_reboot_without_claiming_release(self): self.client.request.side_effect = TimeoutError() diff --git a/packages/omamobile-modem-sit/test/test_sim.py b/packages/omamobile-modem-sit/test/test_sim.py index 8f520527c..6ec7b3f10 100644 --- a/packages/omamobile-modem-sit/test/test_sim.py +++ b/packages/omamobile-modem-sit/test/test_sim.py @@ -275,6 +275,13 @@ def test_subscription_follows_calls_and_messages(self): self.cli('answer') self.next_status(reader, lambda s: s['calls'][0]['state'] == 'active') self.cli('dtmf', '1#') + # The speaker command reaches sitd; this configuration routes no call + # audio ([audio] card = none), so it is refused and the call goes on. + refused = subprocess.run([sys.executable, str(BIN / 'omamobile-sit'), 'speaker', 'off'], env=self.env, + capture_output=True, text=True, timeout=60) + self.assertNotEqual(refused.returncode, 0) + self.assertIn('No call audio is running', refused.stderr) + self.assertEqual(json.loads(self.cli('status', '--json'))['calls'][0]['state'], 'active') self.control('remote-hangup') self.next_status(reader, lambda s: s['calls'][0]['state'] == 'terminated') self.control('wap-push') diff --git a/packages/omamobile-modem-sit/test/test_voice_audio.py b/packages/omamobile-modem-sit/test/test_voice_audio.py index aa4033c43..d95e9f1bd 100644 --- a/packages/omamobile-modem-sit/test/test_voice_audio.py +++ b/packages/omamobile-modem-sit/test/test_voice_audio.py @@ -4,7 +4,7 @@ import shutil import tempfile import unittest -from unittest.mock import patch +from unittest.mock import MagicMock, patch import paths import voice_audio from voice_audio import VoiceAudio @@ -441,6 +441,133 @@ def test_failed_close_keeps_sink_muted(self): audio.__exit__(None, None, None) self.assertEqual(controls['Incall Sink Mute'], '1') + def test_set_output_switches_the_loudspeaker_and_the_earpiece_and_restores(self): + audio, events, controls, original = self.fixture() + with audio: + self.assertEqual(audio.output, 'speaker') + audio.set_output('earpiece') + self.assertEqual(audio.output, 'earpiece') + self.assertEqual(controls['Bottom Speaker Digital Volume'], '0') # loudspeaker muted + self.assertEqual(controls['Top Speaker Digital Volume'], voice_audio.TEGU_GAIN) + self.assertEqual(controls['Incall Sink Mute'], '0') # unmuted after the switch + audio.set_output('speaker') + self.assertEqual(controls['Bottom Speaker Digital Volume'], voice_audio.TEGU_GAIN) + self.assertEqual(controls, original) # the call's end restores the pre-call gains + with self.assertRaises(ValueError): + audio.set_output('headset') + + def test_a_configured_earpiece_output_starts_the_call_on_the_earpiece(self): + audio, events, controls, original = self.fixture() + audio.output = 'earpiece' + with audio: + self.assertEqual(controls['Bottom Speaker Digital Volume'], '0') + self.assertEqual(controls['Top Speaker Digital Volume'], voice_audio.TEGU_GAIN) + self.assertEqual(audio.output, 'earpiece') + # Never a moment on the loudspeaker: the bottom amplifier is + # written once, to 0, both gains are read back, and the one + # unmute comes after that. + bottom = [e for e in events if e[:2] == ('cset', 'Bottom Speaker Digital Volume')] + self.assertEqual([e[2] for e in bottom], ['0']) + unmutes = [i for i, e in enumerate(events) if e == ('cset', 'Incall Sink Mute', '0')] + self.assertEqual(len(unmutes), 1) + read_back = [i for i, e in enumerate(events) + if e[0] == 'cget' and e[1] in voice_audio.TEGU_GAINS and i > events.index(bottom[0])] + self.assertEqual(len(read_back), 2) + self.assertLess(max(read_back), unmutes[0]) + self.assertEqual(controls, original) + + def test_a_configured_earpiece_start_is_refused_when_its_gain_does_not_read_back(self): + audio, events, controls, original = self.fixture() + audio.output = 'earpiece' + inner = audio.mixer + def lying(action, name, value=None): + if action == 'cget' and name == 'Bottom Speaker Digital Volume' and controls[name] == '0': + return ' : values=180\n' + return inner(action, name, value) + audio.mixer = lying + with self.assertRaisesRegex(voice_audio.AudioRefused, 'tegu call audio refused: TAS gain read-back mismatch'): + audio.__enter__() + # Unmuted only by the restore at the end (the sink's pre-call value, + # written last), never while the call route was up. + unmutes = [i for i, e in enumerate(events) if e == ('cset', 'Incall Sink Mute', '0')] + self.assertEqual(unmutes, [len(events) - 1]) + self.assertEqual(controls, original) + + def test_set_output_leaves_the_sink_muted_when_a_gain_write_fails(self): + audio, events, controls, original = self.fixture() + with audio: + inner = audio.mixer + def failing(action, name, value=None): + if action == 'cset' and name == 'Bottom Speaker Digital Volume' and value == '0': + raise RuntimeError('mixer failed') + return inner(action, name, value) + audio.mixer = failing + with self.assertRaisesRegex(RuntimeError, 'mixer failed'): + audio.set_output('earpiece') + self.assertEqual(controls['Incall Sink Mute'], '1') # never unmuted on unconfirmed gains + self.assertEqual(audio.output, 'speaker') # and the output isn't claimed + # A repeat that goes through unmutes again. + audio.mixer = inner + audio.set_output('earpiece') + self.assertEqual((controls['Incall Sink Mute'], audio.output), ('0', 'earpiece')) + self.assertEqual(controls, original) + + def test_set_output_leaves_the_sink_muted_on_a_gain_read_back_mismatch(self): + for broken, message in ((' : values=180\n', 'read-back mismatch'), + (' : values=unavailable\n', 'read-back unavailable')): + audio, events, controls, original = self.fixture() + with audio: + inner = audio.mixer + def lying(action, name, value=None, broken=broken): + if action == 'cget' and name == 'Bottom Speaker Digital Volume': + return broken + return inner(action, name, value) + audio.mixer = lying + with self.assertRaisesRegex(voice_audio.AudioRefused, 'call audio output refused: TAS gain ' + message): + audio.set_output('earpiece') + self.assertEqual(controls['Incall Sink Mute'], '1') + self.assertEqual(audio.output, 'speaker') + audio.mixer = inner + self.assertEqual(controls, original) + + def test_set_output_checks_the_sink_mute_before_changing_a_gain(self): + audio, events, controls, original = self.fixture() + with audio: + inner = audio.mixer + def deaf(action, name, value=None): + if action == 'cset' and name == 'Incall Sink Mute' and value == '1': + return '' + return inner(action, name, value) + audio.mixer = deaf + with self.assertRaisesRegex(voice_audio.AudioRefused, 'sink mute read-back mismatch'): + audio.set_output('earpiece') + self.assertEqual(controls['Bottom Speaker Digital Volume'], voice_audio.TEGU_GAIN) + audio.mixer = inner + self.assertEqual(controls, original) + + def test_an_unknown_output_is_checked_on_the_tegu_route_only(self): + # [audio] output is the 9a's key. A mistyped value must not cost any + # phone its call audio: ignored away from the tegu card, and on it + # logged, with the call starting on the loudspeaker. + for tegu, value, expected, warned in ((False, 'earpeice', 'speaker', False), + (False, 'earpiece', 'speaker', False), + (True, 'earpeice', 'speaker', True), + (True, 'earpiece', 'earpiece', False), + (True, 'speaker', 'speaker', False)): + with patch.object(voice_audio, 'is_tegu_card', return_value=tegu), \ + patch.object(voice_audio.C, 'CDLL', return_value=MagicMock()), \ + patch.object(voice_audio.shutil, 'which', return_value=None), \ + patch('builtins.print') as printed: + audio = VoiceAudio(card=3, output=value) # must not raise + self.assertEqual((audio.tegu, audio.output), (tegu, expected), (tegu, value)) + log = ' '.join(' '.join(map(str, call.args)) for call in printed.call_args_list) + self.assertEqual('Unknown [audio] output' in log, warned, (tegu, value)) + + def test_set_output_needs_a_running_route(self): + audio, _, _, _ = self.fixture() # pcms not opened yet + with self.assertRaisesRegex(RuntimeError, 'no call audio is running'): + audio.set_output('earpiece') + class EarpieceUnitTests(unittest.TestCase): def test_the_mode_goes_through_the_units_when_installed(self): audio = VoiceAudio.__new__(VoiceAudio) diff --git a/packages/omamobile-modem-sit/version b/packages/omamobile-modem-sit/version index faa71045f..5d8b11af8 100644 --- a/packages/omamobile-modem-sit/version +++ b/packages/omamobile-modem-sit/version @@ -1 +1 @@ -0.3.43 +0.3.45