hydrogen-mcp-server 0.3.1__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.
@@ -0,0 +1 @@
1
+ """FastMCP integration for Hydrogen."""
hydrogen_mcp/audio.py ADDED
@@ -0,0 +1,482 @@
1
+ """Read-only facts about audio files: container headers and PCM peak level.
2
+
3
+ Covers every format Hydrogen renders: WAV, Wave64, AIFF, AU, CAF, FLAC, Ogg Vorbis,
4
+ Opus, MP3 and VOC. Nothing is decoded, so peak level exists for PCM and float data only.
5
+ """
6
+
7
+ import sys
8
+ from array import array
9
+ from collections.abc import Iterator
10
+ from math import isfinite, log10
11
+ from pathlib import Path
12
+ from struct import unpack
13
+ from typing import BinaryIO
14
+
15
+ PCM = 1
16
+ IEEE_FLOAT = 3
17
+ EXTENSIBLE = 0xFFFE
18
+ RF64_SIZE = 0xFFFFFFFF
19
+ HEADER_BYTES = 4096
20
+ MAX_CHUNKS = 10_000
21
+ MAX_FRAME_BYTES = 1024
22
+ MAX_PEAK_BYTES = 512 * 1024 * 1024
23
+ SCAN_BYTES = 1 << 20
24
+ OGG_PAGE_BYTES = 65_307
25
+ OPUS_RATE = 48_000
26
+ MAX_MP3_SCAN_BYTES = 256 * 1024 * 1024
27
+ VOC_MAGIC = b"Creative Voice File\x1a"
28
+ AU_ENCODINGS = {
29
+ 1: ("mu-law", 1),
30
+ 2: ("pcm", 1),
31
+ 3: ("pcm", 2),
32
+ 4: ("pcm", 3),
33
+ 5: ("pcm", 4),
34
+ 6: ("float", 4),
35
+ 7: ("float", 8),
36
+ 27: ("a-law", 1),
37
+ }
38
+ MP3_RATES = {
39
+ 3: (44_100, 48_000, 32_000),
40
+ 2: (22_050, 24_000, 16_000),
41
+ 0: (11_025, 12_000, 8000),
42
+ }
43
+ MP3_KBPS = {
44
+ True: (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320),
45
+ False: (0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160),
46
+ }
47
+ Details = dict[str, object]
48
+
49
+
50
+ def _details(
51
+ kind: str, encoding: str, channels: int, rate: int, bits: int | None, frames: int
52
+ ) -> Details:
53
+ if channels < 1 or rate < 1:
54
+ raise ValueError("The audio header has no channels or sample rate.")
55
+ return {
56
+ "format": kind,
57
+ "encoding": encoding,
58
+ "channels": channels,
59
+ "sample_rate": rate,
60
+ "bit_depth": bits,
61
+ "frames": frames,
62
+ "duration_seconds": round(frames / rate, 6),
63
+ "peak": None,
64
+ "peak_dbfs": None,
65
+ "silent": None,
66
+ }
67
+
68
+
69
+ def _header(stream: BinaryIO, length: int) -> bytes:
70
+ """Read the start of a chunk. A hostile length never becomes a large read."""
71
+ return stream.read(min(max(length, 0), HEADER_BYTES))
72
+
73
+
74
+ def _block_peak(
75
+ data: bytes, encoding: str, width: int, big: bool, signed: bool
76
+ ) -> float:
77
+ """Return the largest sample magnitude in a block, where 1.0 is full scale."""
78
+ if width == 1:
79
+ if signed:
80
+ small = array("b")
81
+ small.frombytes(data)
82
+ return max(max(small), -min(small)) / 128
83
+ # 8-bit WAV is unsigned with its midpoint at 128.
84
+ return max(max(data) - 128, 128 - min(data)) / 128
85
+ swap = big != (sys.byteorder == "big")
86
+ if encoding == "float":
87
+ floats = array("f" if width == 4 else "d")
88
+ floats.frombytes(data)
89
+ if swap:
90
+ floats.byteswap()
91
+ return max((abs(value) for value in floats if isfinite(value)), default=0.0)
92
+ if width == 3: # Widen to 32 bits. The sample fills the upper three bytes.
93
+ low, middle, high = (2, 1, 0) if big else (0, 1, 2)
94
+ widened = bytearray(len(data) // 3 * 4)
95
+ widened[1::4], widened[2::4], widened[3::4] = (
96
+ data[low::3],
97
+ data[middle::3],
98
+ data[high::3],
99
+ )
100
+ data, width, swap = bytes(widened), 4, sys.byteorder == "big"
101
+ samples = array("h" if width == 2 else "i")
102
+ samples.frombytes(data)
103
+ if swap:
104
+ samples.byteswap()
105
+ return max(max(samples), -min(samples)) / (1 << (8 * width - 1))
106
+
107
+
108
+ def _measure(
109
+ details: Details,
110
+ stream: BinaryIO,
111
+ frame_bytes: int,
112
+ *,
113
+ big: bool = False,
114
+ signed_bytes: bool = True,
115
+ ) -> Details:
116
+ """Add peak level for PCM or float samples that start at the stream position."""
117
+ channels, frames = details["channels"], details["frames"]
118
+ encoding = str(details["encoding"])
119
+ if not isinstance(channels, int) or not isinstance(frames, int):
120
+ return details
121
+ width = frame_bytes // channels
122
+ measurable = (encoding == "pcm" and width in {1, 2, 3, 4}) or (
123
+ encoding == "float" and width in {4, 8}
124
+ )
125
+ if (
126
+ not measurable
127
+ or width * channels != frame_bytes
128
+ or not 0 < frame_bytes <= MAX_FRAME_BYTES
129
+ or not 0 < frames * frame_bytes <= MAX_PEAK_BYTES
130
+ ):
131
+ return details
132
+ peak = 0.0
133
+ remaining = frames
134
+ while remaining > 0:
135
+ data = stream.read(
136
+ min(remaining, max(1, SCAN_BYTES // frame_bytes)) * frame_bytes
137
+ )
138
+ usable = len(data) - len(data) % frame_bytes
139
+ if usable == 0:
140
+ break
141
+ peak = max(peak, _block_peak(data[:usable], encoding, width, big, signed_bytes))
142
+ remaining -= usable // frame_bytes
143
+ if encoding == "pcm":
144
+ peak = min(peak, 1.0)
145
+ details["peak"] = round(peak, 6)
146
+ details["peak_dbfs"] = round(20 * log10(peak), 2) if peak > 0 else None
147
+ details["silent"] = peak == 0
148
+ return details
149
+
150
+
151
+ def _riff_chunks(stream: BinaryIO, wide: bool) -> Iterator[tuple[bytes, int]]:
152
+ """Yield chunk names and data lengths of a WAV file, or of a Wave64 file when wide."""
153
+ head, align = (24, 8) if wide else (8, 2)
154
+ for _ in range(MAX_CHUNKS):
155
+ header = stream.read(head)
156
+ if len(header) < head:
157
+ return
158
+ length = int.from_bytes(header[16:] if wide else header[4:], "little")
159
+ length -= head if wide else 0
160
+ if length < 0:
161
+ return
162
+ start = stream.tell()
163
+ yield header[:4], length
164
+ stream.seek(start + length + -length % align)
165
+
166
+
167
+ def _wav(stream: BinaryIO, size: int, wide: bool) -> Details:
168
+ layout: tuple[int, int, int, int, int] | None = None
169
+ wide_data: int | None = None
170
+ for name, length in _riff_chunks(stream, wide):
171
+ if name == b"ds64":
172
+ wide_data = int.from_bytes(_header(stream, length)[8:16], "little")
173
+ elif name == b"fmt ":
174
+ body = _header(stream, length)
175
+ if len(body) < 16:
176
+ break
177
+ tag, channels, rate, _, frame_bytes, bits = unpack("<HHIIHH", body[:16])
178
+ if tag == EXTENSIBLE and len(body) >= 26:
179
+ tag = int.from_bytes(body[24:26], "little")
180
+ layout = (tag, channels, rate, frame_bytes, bits)
181
+ elif name == b"data" and layout is not None:
182
+ tag, channels, rate, frame_bytes, bits = layout
183
+ if frame_bytes < 1:
184
+ break
185
+ if length == RF64_SIZE and wide_data is not None:
186
+ length = wide_data
187
+ frames = min(length, size - stream.tell()) // frame_bytes
188
+ encoding = {PCM: "pcm", IEEE_FLOAT: "float"}.get(tag, f"format {tag}")
189
+ details = _details(
190
+ "wave64" if wide else "wav", encoding, channels, rate, bits, frames
191
+ )
192
+ return _measure(details, stream, frame_bytes, signed_bytes=False)
193
+ raise ValueError("The WAV file has no usable format and data chunks.")
194
+
195
+
196
+ def _extended(data: bytes) -> float:
197
+ """Decode the 80-bit sample rate of an AIFF common chunk."""
198
+ exponent = int.from_bytes(data[:2], "big") & 0x7FFF
199
+ mantissa = int.from_bytes(data[2:10], "big")
200
+ return float(mantissa * 2.0 ** (exponent - 16383 - 63)) if mantissa else 0.0
201
+
202
+
203
+ def _aiff(stream: BinaryIO, compressed: bool) -> Details:
204
+ details: Details | None = None
205
+ frame_bytes = 0
206
+ big = True
207
+ for _ in range(MAX_CHUNKS):
208
+ header = stream.read(8)
209
+ if len(header) < 8:
210
+ break
211
+ name, length = header[:4], int.from_bytes(header[4:], "big")
212
+ start = stream.tell()
213
+ if name == b"COMM":
214
+ body = _header(stream, length)
215
+ if len(body) < 18:
216
+ break
217
+ channels, frames, bits = unpack(">hIh", body[:8])
218
+ encoding = "pcm"
219
+ if compressed and len(body) >= 22:
220
+ codec = body[18:22].decode("ascii", errors="replace").strip().lower()
221
+ big = codec != "sowt"
222
+ encoding = {"none": "pcm", "sowt": "pcm", "fl32": "float"}.get(
223
+ codec, codec
224
+ )
225
+ rate = round(_extended(body[8:18]))
226
+ details = _details("aiff", encoding, channels, rate, bits, frames)
227
+ frame_bytes = max(channels, 0) * ((bits + 7) // 8)
228
+ elif name == b"SSND" and details is not None:
229
+ offset = int.from_bytes(_header(stream, 8)[:4], "big")
230
+ stream.seek(offset, 1)
231
+ return _measure(details, stream, frame_bytes, big=big)
232
+ stream.seek(start + length + length % 2)
233
+ if details is None:
234
+ raise ValueError("The AIFF file has no usable common chunk.")
235
+ return details
236
+
237
+
238
+ def _flac(stream: BinaryIO) -> Details:
239
+ header = stream.read(4)
240
+ body = stream.read(34)
241
+ if len(header) < 4 or header[0] & 0x7F or len(body) < 34:
242
+ raise ValueError("The FLAC file has no stream information block.")
243
+ packed = int.from_bytes(body[10:18], "big")
244
+ return _details(
245
+ "flac",
246
+ "flac",
247
+ ((packed >> 41) & 7) + 1,
248
+ packed >> 44,
249
+ ((packed >> 36) & 31) + 1,
250
+ packed & ((1 << 36) - 1),
251
+ )
252
+
253
+
254
+ def _au(stream: BinaryIO, size: int) -> Details:
255
+ header = stream.read(20)
256
+ if len(header) < 20:
257
+ raise ValueError("The AU file has no complete header.")
258
+ offset, length, code, rate, channels = unpack(">5I", header)
259
+ encoding, width = AU_ENCODINGS.get(code, (f"encoding {code}", 0))
260
+ if width == 0 or channels < 1 or offset < 24:
261
+ raise ValueError("The AU file uses an unsupported encoding.")
262
+ available = max(0, size - offset)
263
+ frames = (available if length == RF64_SIZE else min(length, available)) // (
264
+ width * channels
265
+ )
266
+ details = _details("au", encoding, channels, rate, width * 8, frames)
267
+ stream.seek(offset)
268
+ return _measure(details, stream, width * channels, big=True)
269
+
270
+
271
+ def _caf(stream: BinaryIO, size: int) -> Details:
272
+ stream.seek(8)
273
+ described: tuple[float, bytes, int, int, int, int, int] | None = None
274
+ data_bytes = data_start = 0
275
+ packet_frames: int | None = None
276
+ for _ in range(MAX_CHUNKS):
277
+ header = stream.read(12)
278
+ if len(header) < 12:
279
+ break
280
+ name, length = header[:4], int.from_bytes(header[4:], "big", signed=True)
281
+ start = stream.tell()
282
+ if length < 0: # The data chunk may run to the end of the file.
283
+ length = size - start
284
+ if name == b"desc":
285
+ body = _header(stream, length)
286
+ if len(body) < 32:
287
+ break
288
+ described = unpack(">d4s5I", body[:32])
289
+ elif name == b"data":
290
+ data_bytes, data_start = max(0, length - 4), start + 4
291
+ elif name == b"pakt":
292
+ body = _header(stream, length)
293
+ if len(body) >= 16:
294
+ packet_frames = int.from_bytes(body[8:16], "big", signed=True)
295
+ stream.seek(start + length)
296
+ if described is None:
297
+ raise ValueError("The CAF file has no audio description chunk.")
298
+ rate, codec, flags, packet_bytes, frames_per_packet, channels, bits = described
299
+ encoding = codec.decode("ascii", errors="replace").strip().lower()
300
+ if encoding == "lpcm":
301
+ encoding = "float" if flags & 1 else "pcm"
302
+ frames = packet_frames if packet_frames is not None else 0
303
+ if packet_bytes and frames_per_packet:
304
+ frames = data_bytes // packet_bytes * frames_per_packet
305
+ details = _details("caf", encoding, channels, round(rate), bits or None, frames)
306
+ stream.seek(data_start)
307
+ return _measure(details, stream, packet_bytes, big=not flags & 2)
308
+
309
+
310
+ def _ogg(stream: BinaryIO, size: int) -> Details:
311
+ page = stream.read(HEADER_BYTES)
312
+ if len(page) < 28 or page[4] != 0:
313
+ raise ValueError("The Ogg file has no readable first page.")
314
+ serial = page[14:18]
315
+ packet = page[27 + page[26] :]
316
+ if packet.startswith(b"\x01vorbis") and len(packet) >= 16:
317
+ kind, channels, skip = "vorbis", packet[11], 0
318
+ rate = int.from_bytes(packet[12:16], "little")
319
+ elif packet.startswith(b"OpusHead") and len(packet) >= 12:
320
+ kind, channels, rate = "opus", packet[9], OPUS_RATE
321
+ skip = int.from_bytes(packet[10:12], "little")
322
+ else:
323
+ raise ValueError("The Ogg file holds neither Vorbis nor Opus audio.")
324
+ # The last page of the stream carries the position of its final sample.
325
+ stream.seek(max(0, size - 2 * OGG_PAGE_BYTES))
326
+ tail = stream.read()
327
+ position = 0
328
+ index = tail.rfind(b"OggS")
329
+ while index >= 0:
330
+ if tail[index + 14 : index + 18] == serial:
331
+ position = int.from_bytes(
332
+ tail[index + 6 : index + 14], "little", signed=True
333
+ )
334
+ break
335
+ index = tail.rfind(b"OggS", 0, index)
336
+ return _details("ogg", kind, channels, rate, None, max(0, position - skip))
337
+
338
+
339
+ def _mp3_frame(header: bytes) -> tuple[int, int, int, int, bool] | None:
340
+ """Decode a Layer III frame header: byte length, sample rate, channels, samples."""
341
+ if len(header) < 4 or header[0] != 0xFF or header[1] & 0xE0 != 0xE0:
342
+ return None
343
+ version, layer = (header[1] >> 3) & 3, (header[1] >> 1) & 3
344
+ kbps_index, rate_index = header[2] >> 4, (header[2] >> 2) & 3
345
+ if version == 1 or layer != 1 or kbps_index in {0, 15} or rate_index == 3:
346
+ return None
347
+ first = version == 3
348
+ rate = MP3_RATES[version][rate_index]
349
+ samples = 1152 if first else 576
350
+ length = samples // 8 * MP3_KBPS[first][kbps_index] * 1000 // rate
351
+ channels = 1 if header[3] >> 6 == 3 else 2
352
+ return length + ((header[2] >> 1) & 1), rate, channels, samples, first
353
+
354
+
355
+ def _mp3(stream: BinaryIO, size: int) -> Details:
356
+ start = 0
357
+ tag = stream.read(10)
358
+ if tag[:3] == b"ID3" and len(tag) == 10:
359
+ start = 10 + (tag[6] << 21 | tag[7] << 14 | tag[8] << 7 | tag[9])
360
+ start += 10 if tag[5] & 0x10 else 0
361
+ stream.seek(start)
362
+ window = stream.read(HEADER_BYTES)
363
+ offset = next(
364
+ (
365
+ index
366
+ for index in range(max(0, len(window) - 3))
367
+ if _mp3_frame(window[index : index + 4]) is not None
368
+ ),
369
+ None,
370
+ )
371
+ first = None if offset is None else _mp3_frame(window[offset : offset + 4])
372
+ if offset is None or first is None:
373
+ raise ValueError("The MP3 file has no Layer III audio frame.")
374
+ length, rate, channels, samples, mpeg1 = first
375
+ frame = window[offset : offset + length]
376
+ side = (32 if channels == 2 else 17) if mpeg1 else (17 if channels == 2 else 9)
377
+ # A cleared protection bit puts a two-byte checksum in front of the side information.
378
+ checksum = 0 if frame[1] & 1 else 2
379
+ info = frame[4 + checksum + side :]
380
+ if info[:4] in {b"Xing", b"Info"} and len(info) >= 12 and info[7] & 1:
381
+ total = int.from_bytes(info[8:12], "big") * samples
382
+ cursor = 12 + (4 if info[7] & 2 else 0) + (100 if info[7] & 4 else 0)
383
+ cursor += 4 if info[7] & 8 else 0
384
+ encoder = info[cursor : cursor + 24]
385
+ if encoder[:4] in {b"LAME", b"Lavc", b"Lavf"} and len(encoder) == 24:
386
+ # Encoder delay and end padding, twelve bits each, are not part of the audio.
387
+ total -= encoder[21] << 4 | encoder[22] >> 4
388
+ total -= (encoder[22] & 15) << 8 | encoder[23]
389
+ return _details("mp3", "mp3", channels, rate, None, max(0, total))
390
+ # No length header: count the frames. The file is read once, within a fixed budget.
391
+ if size - start - offset > MAX_MP3_SCAN_BYTES:
392
+ raise ValueError("The MP3 file has no length header and exceeds 256 MiB.")
393
+ stream.seek(start + offset)
394
+ data = stream.read()
395
+ total = position = 0
396
+ while (current := _mp3_frame(data[position : position + 4])) is not None:
397
+ if position + current[0] > len(data):
398
+ break
399
+ total += current[3]
400
+ position += current[0]
401
+ return _details("mp3", "mp3", channels, rate, None, total)
402
+
403
+
404
+ def _voc(stream: BinaryIO, size: int) -> Details:
405
+ stream.seek(len(VOC_MAGIC))
406
+ position = int.from_bytes(stream.read(2), "little")
407
+ rate = channels = 0
408
+ bits = 8
409
+ data_bytes = 0
410
+ extended: tuple[int, int] | None = None
411
+ for _ in range(MAX_CHUNKS):
412
+ stream.seek(position)
413
+ header = stream.read(4)
414
+ if len(header) < 4 or header[0] == 0:
415
+ break
416
+ kind, length = header[0], int.from_bytes(header[1:], "little")
417
+ body = _header(stream, min(length, 12))
418
+ if kind == 8 and len(body) >= 4:
419
+ extended = (int.from_bytes(body[:2], "little"), body[3] + 1)
420
+ elif kind == 1 and len(body) >= 2:
421
+ if extended is not None:
422
+ channels = extended[1]
423
+ rate = 256_000_000 // (65_536 - extended[0]) // channels
424
+ else:
425
+ rate, channels = 1_000_000 // (256 - body[0]), 1
426
+ bits = 16 if body[1] == 4 else 8
427
+ data_bytes += max(0, min(length, size - position - 4) - 2)
428
+ elif kind == 9 and len(body) >= 12:
429
+ rate, bits, channels = int.from_bytes(body[:4], "little"), body[4], body[5]
430
+ data_bytes += max(0, min(length, size - position - 4) - 12)
431
+ elif kind == 2:
432
+ data_bytes += max(0, min(length, size - position - 4))
433
+ position += 4 + length
434
+ if channels < 1 or bits not in {8, 16}:
435
+ raise ValueError("The VOC file has no supported sound data block.")
436
+ return _details(
437
+ "voc", "pcm", channels, rate, bits, data_bytes // (channels * bits // 8)
438
+ )
439
+
440
+
441
+ def audio_details(path: Path) -> Details:
442
+ """Describe an audio file in any format Hydrogen renders.
443
+
444
+ Peak level and silence are measured for PCM and float samples in WAV, Wave64,
445
+ AIFF, AU and CAF files of up to 512 MiB.
446
+ """
447
+ size = path.stat().st_size
448
+ with path.open("rb") as stream:
449
+ head = stream.read(len(VOC_MAGIC))
450
+ stream.seek(0)
451
+ magic = head[:4]
452
+ if magic == b"fLaC":
453
+ stream.seek(4)
454
+ details = _flac(stream)
455
+ elif magic in {b"RIFF", b"RF64"} and head[8:12] == b"WAVE":
456
+ stream.seek(12)
457
+ details = _wav(stream, size, wide=False)
458
+ elif magic == b"riff" and head[4:16] == bytes.fromhex(
459
+ "2e91cf11a5d628db04c10000"
460
+ ):
461
+ stream.seek(40)
462
+ details = _wav(stream, size, wide=True)
463
+ elif magic == b"FORM" and head[8:12] in {b"AIFF", b"AIFC"}:
464
+ stream.seek(12)
465
+ details = _aiff(stream, head[8:12] == b"AIFC")
466
+ elif magic == b".snd":
467
+ stream.seek(4)
468
+ details = _au(stream, size)
469
+ elif magic == b"caff":
470
+ details = _caf(stream, size)
471
+ elif magic == b"OggS":
472
+ details = _ogg(stream, size)
473
+ elif head == VOC_MAGIC:
474
+ details = _voc(stream, size)
475
+ elif magic[:3] == b"ID3" or _mp3_frame(magic) is not None:
476
+ details = _mp3(stream, size)
477
+ else:
478
+ raise ValueError(
479
+ "Audio details are available for WAV, Wave64, AIFF, AU, CAF, FLAC, "
480
+ "Ogg Vorbis, Opus, MP3 and VOC files."
481
+ )
482
+ return {**details, "bytes": size}