Debian Codegraph @

wyoming/snd.py

raw
1 """Audio output to speakers."""
2
3 import asyncio
4 import contextlib
5 import logging
6 from asyncio.subprocess import Process
7 from dataclasses import dataclass
8 from typing import List, Optional
9
10 from .audio import AudioChunk, AudioChunkConverter
11 from .client import AsyncClient
12 from .event import Event, Eventable
13
14 _LOGGER = logging.getLogger(__name__)
15
16 _PLAYED_TYPE = "played"
17
18
19 @dataclass
20 class Played(Eventable):
21 """Audio has finished playing."""
22
23 @staticmethod
24 def is_type(event_type: str) -> bool:
25 return event_type == _PLAYED_TYPE
26
27 def event(self) -> Event:
28 return Event(type=_PLAYED_TYPE)
29
30 @staticmethod
31 def from_event(event: Event) -> "Played":
32 return Played()
33
34
35 class SndProcessAsyncClient(AsyncClient, contextlib.AbstractAsyncContextManager):
36 """Context manager for sending output audio to an external program."""
37
38 def __init__(
39 self,
40 rate: int,
41 width: int,
42 channels: int,
43 program: str,
44 program_args: List[str],
45 ) -> None:
46 super().__init__()
47
48 self.rate = rate
49 self.width = width
50 self.channels = channels
51 self.program = program
52 self.program_args = program_args
53
54 self._proc: Optional[Process] = None
55 self._chunk_converter = AudioChunkConverter(rate, width, channels)
56
57 async def connect(self) -> None:
58 self._proc = await asyncio.create_subprocess_exec(
59 self.program, *self.program_args, stdin=asyncio.subprocess.PIPE
60 )
61
62 async def disconnect(self) -> None:
63 assert self._proc is not None
64 assert self._proc.stdin is not None
65
66 try:
67 if self._proc.returncode is None:
68 # Terminate process gracefully
69 self._proc.stdin.close()
70 await self._proc.wait()
71 except ProcessLookupError:
72 # Expected when process has already exited
73 pass
74 except Exception:
75 _LOGGER.exception("Unexpected error stopping process: %s", self.program)
76 finally:
77 self._proc = None
78
79 async def __aenter__(self) -> "SndProcessAsyncClient":
80 await self.connect()
81 return self
82
83 async def __aexit__(self, exc_type, exc, tb):
84 await self.disconnect()
85
86 async def read_event(self) -> Optional[Event]:
87 """Client is write-only."""
88
89 async def write_event(self, event: Event) -> None:
90 assert self._proc is not None
91 assert self._proc.stdin is not None
92
93 if not AudioChunk.is_type(event.type):
94 return
95
96 chunk = AudioChunk.from_event(event)
97
98 # Convert sample rate/width/channels if necessary
99 chunk = self._chunk_converter.convert(chunk)
100
101 self._proc.stdin.write(chunk.audio)
102 await self._proc.stdin.drain()