Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/omamobile-modem-sit/bin/omamobile-sit
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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])
Expand Down
12 changes: 9 additions & 3 deletions packages/omamobile-modem-sit/etc/omamobile/modem-sit.conf
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 12 additions & 3 deletions packages/omamobile-modem-sit/lib/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": "..."}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand Down
81 changes: 68 additions & 13 deletions packages/omamobile-modem-sit/lib/voice_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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')
Expand Down Expand Up @@ -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:
Expand Down
40 changes: 36 additions & 4 deletions packages/omamobile-modem-sit/test/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()
Expand Down
7 changes: 7 additions & 0 deletions packages/omamobile-modem-sit/test/test_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Loading