Debian Codegraph @

wyoming/audio.py

raw
1 """Audio input/output."""
2
3 import argparse
4 import io
5 import sys
6 import wave
7 from dataclasses import dataclass
8 from typing import Iterable, Optional, Union
9
10 try:
11 # Use built-in audioop until it's removed in Python 3.13
12 import audioop # pylint: disable=deprecated-module
13 except ImportError:
14 from . import pyaudioop as audioop # type: ignore[no-redef]
15
16 from .event import Event, Eventable
17 from .util.dataclasses_json import DataClassJsonMixin
18
19 _CHUNK_TYPE = "audio-chunk"
20 _START_TYPE = "audio-start"
21 _STOP_TYPE = "audio-stop"
22
23
24 @dataclass
25 class AudioFormat(DataClassJsonMixin):
26 """Base class for events with audio format information."""
27
28 rate: int
29 """Hertz"""
30
31 width: int
32 """Bytes"""
33
34 channels: int
35 """Mono = 1"""
36
37
38 @dataclass
39 class AudioChunk(AudioFormat, Eventable):
40 """Chunk of raw PCM audio."""
41
42 audio: bytes
43 """Raw audio"""
44
45 timestamp: Optional[int] = None
46 """Milliseconds"""
47
48 @staticmethod
49 def is_type(event_type: str) -> bool:
50 return event_type == _CHUNK_TYPE
51
52 def event(self) -> Event:
53 return Event(
54 type=_CHUNK_TYPE,
55 data={
56 "rate": self.rate,
57 "width": self.width,
58 "channels": self.channels,
59 "timestamp": self.timestamp,
60 },
61 payload=self.audio,
62 )
63
64 @staticmethod
65 def from_event(event: Event) -> "AudioChunk":
66 return AudioChunk(
67 rate=event.data["rate"],
68 width=event.data["width"],
69 channels=event.data["channels"],
70 audio=event.payload or bytes(),
71 timestamp=event.data.get("timestamp"),
72 )
73
74 @property
75 def samples(self) -> int:
76 return len(self.audio) // (self.width * self.channels)
77
78 @property
79 def seconds(self) -> float:
80 return self.samples / self.rate
81
82 @property
83 def milliseconds(self) -> int:
84 return int(self.seconds * 1_000)
85
86
87 @dataclass
88 class AudioStart(AudioFormat, Eventable):
89 """Audio stream has started."""
90
91 timestamp: Optional[int] = None
92 """Milliseconds"""
93
94 @staticmethod
95 def is_type(event_type: str) -> bool:
96 return event_type == _START_TYPE
97
98 def event(self) -> Event:
99 return Event(
100 type=_START_TYPE,
101 data={
102 "rate": self.rate,
103 "width": self.width,
104 "channels": self.channels,
105 "timestamp": self.timestamp,
106 },
107 )
108
109 @staticmethod
110 def from_event(event: Event) -> "AudioStart":
111 return AudioStart(
112 rate=event.data["rate"],
113 width=event.data["width"],
114 channels=event.data["channels"],
115 timestamp=event.data.get("timestamp"),
116 )
117
118
119 @dataclass
120 class AudioStop(Eventable):
121 """Audio stream has stopped."""
122
123 timestamp: Optional[int] = None
124 """Milliseconds"""
125
126 @staticmethod
127 def is_type(event_type: str) -> bool:
128 return event_type == _STOP_TYPE
129
130 def event(self) -> Event:
131 return Event(
132 type=_STOP_TYPE,
133 data={"timestamp": self.timestamp},
134 )
135
136 @staticmethod
137 def from_event(event: Event) -> "AudioStop":
138 return AudioStop(timestamp=event.data.get("timestamp"))
139
140
141 @dataclass
142 class AudioChunkConverter:
143 """Converts audio chunks using audioop/pyaudioop."""
144
145 rate: Optional[int] = None
146 width: Optional[int] = None
147 channels: Optional[int] = None
148 _ratecv_state = None
149
150 def convert(self, chunk: AudioChunk) -> AudioChunk:
151 """Converts sample rate, width, and channels as necessary."""
152 if (
153 ((self.rate is None) or (chunk.rate == self.rate))
154 and ((self.width is None) or (chunk.width == self.width))
155 and ((self.channels is None) or (chunk.channels == self.channels))
156 ):
157 return chunk
158
159 audio_bytes = chunk.audio
160 width = chunk.width
161
162 if (self.width is not None) and (chunk.width != self.width):
163 # Convert sample width
164 audio_bytes = audioop.lin2lin(audio_bytes, chunk.width, self.width)
165 width = self.width
166
167 channels = chunk.channels
168 if (self.channels is not None) and (chunk.channels != self.channels):
169 # Convert to mono or stereo
170 if self.channels == 1:
171 audio_bytes = audioop.tomono(audio_bytes, width, 1.0, 1.0)
172 elif self.channels == 2:
173 audio_bytes = audioop.tostereo(audio_bytes, width, 1.0, 1.0)
174 else:
175 raise ValueError(f"Cannot convert to channels: {self.channels}")
176
177 channels = self.channels
178
179 rate = chunk.rate
180 if (self.rate is not None) and (chunk.rate != self.rate):
181 # Resample
182 audio_bytes, self._ratecv_state = audioop.ratecv(
183 audio_bytes,
184 width,
185 channels,
186 chunk.rate,
187 self.rate,
188 self._ratecv_state,
189 )
190 rate = self.rate
191
192 return AudioChunk(
193 rate,
194 width,
195 channels,
196 audio_bytes,
197 timestamp=chunk.timestamp,
198 )
199
200
201 def wav_to_chunks(
202 wav_file: wave.Wave_read,
203 samples_per_chunk: int,
204 timestamp: int = 0,
205 start_event: bool = False,
206 stop_event: bool = False,
207 ) -> Iterable[Union[AudioStart, AudioChunk, AudioStop]]:
208 """Splits WAV file into AudioChunks."""
209 rate = wav_file.getframerate()
210 width = wav_file.getsampwidth()
211 channels = wav_file.getnchannels()
212
213 if start_event:
214 yield AudioStart(rate=rate, width=width, channels=channels, timestamp=0)
215
216 audio_bytes = wav_file.readframes(samples_per_chunk)
217 while audio_bytes:
218 chunk = AudioChunk(
219 rate=rate,
220 width=width,
221 channels=channels,
222 audio=audio_bytes,
223 timestamp=timestamp,
224 )
225 yield chunk
226 timestamp += chunk.milliseconds
227 audio_bytes = wav_file.readframes(samples_per_chunk)
228
229 if stop_event:
230 yield AudioStop(timestamp=timestamp)
231
232
233 # -----------------------------------------------------------------------------
234
235
236 def main() -> None:
237 parser = argparse.ArgumentParser()
238 parser.add_argument("--rate", type=int)
239 parser.add_argument("--width", type=int)
240 parser.add_argument("--channels", type=int)
241 parser.add_argument("--samples-per-chunk", type=int, default=1024)
242 args = parser.parse_args()
243
244 converter = AudioChunkConverter(
245 rate=args.rate, width=args.width, channels=args.channels
246 )
247
248 with io.BytesIO(
249 sys.stdin.buffer.read()
250 ) as input_wav_io, io.BytesIO() as output_wav_io:
251 input_wav_file: wave.Wave_read = wave.open(input_wav_io, "rb")
252 output_wav_file: wave.Wave_write = wave.open(output_wav_io, "wb")
253 with input_wav_file, output_wav_file:
254 # Input
255 rate = input_wav_file.getframerate()
256 width = input_wav_file.getsampwidth()
257 channels = input_wav_file.getnchannels()
258
259 # Output
260 output_wav_file.setframerate(args.rate if args.rate is not None else rate)
261 output_wav_file.setsampwidth(
262 args.width if args.width is not None else width
263 )
264 output_wav_file.setnchannels(
265 args.channels if args.channels is not None else channels
266 )
267
268 audio_bytes = input_wav_file.readframes(args.samples_per_chunk)
269 while audio_bytes:
270 chunk = converter.convert(
271 AudioChunk(rate, width, channels, audio_bytes)
272 )
273 output_wav_file.writeframes(chunk.audio)
274 audio_bytes = input_wav_file.readframes(args.samples_per_chunk)
275
276 sys.stdout.buffer.write(output_wav_io.getvalue())
277
278
279 if __name__ == "__main__":
280 main()