ffaudio 4.2.0__py3-none-win_amd64.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.
ffaudio/__init__.py ADDED
@@ -0,0 +1,1697 @@
1
+ #
2
+ # Copyright (c) 2025 Odalith
3
+ #
4
+ # ffaudio is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
5
+ # License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any
6
+ # later version.
7
+ #
8
+ """
9
+ Python bindings for ffaudio 4, the music playback library (ctypes; no compiler needed).
10
+
11
+ import ffaudio
12
+ ffaudio.init("My Player")
13
+ ffaudio.play("/music/song.flac")
14
+ while True:
15
+ match ffaudio.wait_event(1.0):
16
+ case ffaudio.TrackEnded(error=err, message=msg) if err:
17
+ print("could not play:", msg)
18
+ case ffaudio.PrepareNext():
19
+ ffaudio.queue(next_song()) # gapless, or crossfaded
20
+
21
+ The names follow the C API without the au_ prefix (ffaudio.h is the reference for what each one does). Differences:
22
+
23
+ - Errors raise ffaudio.Error (with .code, an AU_RESULT) instead of returning a negative number.
24
+ - Structs that hold values are dataclasses (Fade, Crossfade, ReplayGain, Equalizer, ...); results are copied into
25
+ Python objects (MediaInfo, Status, CueSheet, ...), so there is nothing to release.
26
+ - Events are read by polling (wait_event() / poll_event(), on a thread of your choice); there is no on_event
27
+ callback, so no Python code runs on ffaudio's threads, except the callbacks you pass yourself
28
+ (GainScanSettings.on_cached, a custom fade curve, a loudness progress function).
29
+ - Strings are str in and out (UTF-8).
30
+ """
31
+
32
+ import ctypes
33
+ import enum
34
+ import math
35
+ import threading
36
+ from dataclasses import dataclass, field
37
+ from typing import Callable, Iterable, Optional, Sequence
38
+
39
+ from . import _native as _n
40
+ from ._native import lib as _lib
41
+
42
+ __all__ = [] # filled below with every public name
43
+
44
+ NAN = float("nan")
45
+
46
+
47
+ def _enc(s: Optional[str]) -> Optional[bytes]:
48
+ return None if s is None else s.encode("utf-8")
49
+
50
+
51
+ def _dec(b: Optional[bytes]) -> Optional[str]:
52
+ return None if b is None else b.decode("utf-8", "replace")
53
+
54
+
55
+ #+-----------------------------------------------------+
56
+ #| Results and errors |
57
+ #+-----------------------------------------------------+
58
+
59
+ class Result(enum.IntEnum):
60
+ OK = 0
61
+ ERR_NOT_INITIALIZED = -1
62
+ ERR_INVALID_ARGUMENT = -2
63
+ ERR_ALREADY_INITIALIZED = -3
64
+ ERR_NO_MEMORY = -4
65
+ ERR_SDL = -5
66
+ ERR_DEVICE = -6
67
+ ERR_WRONG_THREAD = -7
68
+ ERR_NOTHING_TO_DO = -8
69
+ ERR_FILE = -9
70
+ ERR_CANCELLED = -10
71
+ ERR_UNSUPPORTED = -11
72
+ ERR_NOT_SAVED = -12
73
+
74
+
75
+ def result_string(result: int) -> str:
76
+ return _dec(_lib.au_result_string(int(result)))
77
+
78
+
79
+ class Error(Exception):
80
+ """A call failed: .code is the AU_RESULT, str() says what it means (and, for filters, what was wrong)."""
81
+
82
+ def __init__(self, code: int, detail: str = ""):
83
+ self.code = code
84
+ try:
85
+ self.result = Result(code)
86
+ except ValueError:
87
+ self.result = None
88
+ text = result_string(code)
89
+ super().__init__(f"{text}: {detail}" if detail else text)
90
+
91
+
92
+ def _check(ret: int, detail: str = "") -> int:
93
+ if ret < 0:
94
+ raise Error(ret, detail)
95
+ return ret
96
+
97
+
98
+ def version() -> str:
99
+ return _dec(_lib.au_get_version())
100
+
101
+
102
+ #+-----------------------------------------------------+
103
+ #| Enums |
104
+ #+-----------------------------------------------------+
105
+
106
+ class LogLevel(enum.IntEnum):
107
+ INFO = 0
108
+ WARNING = 1
109
+ ERROR = 2
110
+ FATAL = 3
111
+
112
+
113
+ class EventType(enum.IntEnum):
114
+ LOG = 0
115
+ DEVICE = 1
116
+ DEVICES_CHANGED = 2
117
+ TRACK_OPENED = 3
118
+ TRACK_STARTED = 4
119
+ TRACK_ENDED = 5
120
+ RESTARTED = 6
121
+ DURATION = 7
122
+ PREPARE_NEXT = 8
123
+ BUFFERING = 9
124
+ STREAM_METADATA = 10
125
+ OVERFLOW = 11
126
+
127
+
128
+ class End(enum.IntEnum):
129
+ FINISHED = 0
130
+ SKIPPED = 1
131
+ ERROR = 2
132
+
133
+
134
+ class FadeCurve(enum.IntEnum):
135
+ EQUAL_POWER = 0
136
+ LINEAR = 1
137
+ S_CURVE = 2
138
+ LOGARITHMIC = 3
139
+ EXPONENTIAL = 4
140
+ CUSTOM = 5
141
+
142
+
143
+ class ReplayGainMode(enum.IntEnum):
144
+ OFF = 0
145
+ TRACK = 1
146
+ ALBUM = 2
147
+
148
+
149
+ class Downmix(enum.IntEnum):
150
+ FULL_LEVEL = 0
151
+ NORMALIZED = 1
152
+ CUSTOM = 2
153
+
154
+
155
+ class Upmix(enum.IntEnum):
156
+ NONE = 0
157
+ SURROUND = 1
158
+ CUSTOM = 2
159
+
160
+
161
+ class PictureType(enum.IntEnum):
162
+ ANY = -1
163
+ OTHER = 0
164
+ FRONT_COVER = 3
165
+ BACK_COVER = 4
166
+ LEAFLET = 5
167
+ MEDIA = 6
168
+ ARTIST = 8
169
+ BAND_LOGO = 19
170
+
171
+
172
+ class PeqType(enum.IntEnum):
173
+ PEAK = 0
174
+ LOW_SHELF = 1
175
+ HIGH_SHELF = 2
176
+ LOW_PASS = 3
177
+ HIGH_PASS = 4
178
+
179
+
180
+ class Bs2bProfile(enum.IntEnum):
181
+ DEFAULT = 0
182
+ CHU_MOY = 1
183
+ JAN_MEIER = 2
184
+
185
+
186
+ class ScanPriority(enum.IntEnum):
187
+ PREFETCH = 0
188
+ URGENT = 1
189
+
190
+
191
+ #+-----------------------------------------------------+
192
+ #| Events |
193
+ #+-----------------------------------------------------+
194
+
195
+ @dataclass(frozen=True)
196
+ class Event:
197
+ """Every event; the subclasses carry its data (match on them)."""
198
+ handle: int
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class Log(Event):
203
+ level: LogLevel
204
+ message: str
205
+ request: int
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class Device(Event):
210
+ ok: bool
211
+ fell_back: bool
212
+ name: Optional[str]
213
+ sample_rate: int
214
+ channels: int
215
+
216
+
217
+ @dataclass(frozen=True)
218
+ class DevicesChanged(Event):
219
+ pass
220
+
221
+
222
+ @dataclass(frozen=True)
223
+ class TrackOpened(Event):
224
+ duration: float
225
+ live: bool
226
+ seekable: bool
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class TrackStarted(Event):
231
+ pass
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class TrackEnded(Event):
236
+ reason: End
237
+ error: int # an AU_RESULT for End.ERROR, else 0
238
+ message: Optional[str] # what was logged for the error
239
+
240
+
241
+ @dataclass(frozen=True)
242
+ class Restarted(Event):
243
+ position: float
244
+ from_loop: bool
245
+ loops_remaining: int
246
+
247
+
248
+ @dataclass(frozen=True)
249
+ class DurationChanged(Event):
250
+ seconds: float
251
+
252
+
253
+ @dataclass(frozen=True)
254
+ class PrepareNext(Event):
255
+ pass
256
+
257
+
258
+ @dataclass(frozen=True)
259
+ class Buffering(Event):
260
+ active: bool
261
+ buffered_seconds: float
262
+
263
+
264
+ @dataclass(frozen=True)
265
+ class StreamMetadata(Event):
266
+ title: Optional[str]
267
+ artist: Optional[str]
268
+
269
+
270
+ @dataclass(frozen=True)
271
+ class Overflow(Event):
272
+ dropped: int
273
+
274
+
275
+ def _event(e: _n.AuEvent) -> Event:
276
+ t, h, d = e.type, e.handle, e.data
277
+ if t == EventType.LOG:
278
+ return Log(h, LogLevel(d.log.level), _dec(d.log.message) or "", d.log.request)
279
+ if t == EventType.DEVICE:
280
+ v = d.device
281
+ return Device(h, v.ok, v.fell_back, _dec(v.name), v.sample_rate, v.channels)
282
+ if t == EventType.DEVICES_CHANGED:
283
+ return DevicesChanged(h)
284
+ if t == EventType.TRACK_OPENED:
285
+ return TrackOpened(h, d.opened.duration, d.opened.live, d.opened.seekable)
286
+ if t == EventType.TRACK_STARTED:
287
+ return TrackStarted(h)
288
+ if t == EventType.TRACK_ENDED:
289
+ return TrackEnded(h, End(d.ended.reason), d.ended.error, _dec(d.ended.message))
290
+ if t == EventType.RESTARTED:
291
+ r = d.restarted
292
+ return Restarted(h, r.position, r.from_loop, r.loops_remaining)
293
+ if t == EventType.DURATION:
294
+ return DurationChanged(h, d.duration.seconds)
295
+ if t == EventType.PREPARE_NEXT:
296
+ return PrepareNext(h)
297
+ if t == EventType.BUFFERING:
298
+ return Buffering(h, d.buffering.active, d.buffering.buffered_seconds)
299
+ if t == EventType.STREAM_METADATA:
300
+ return StreamMetadata(h, _dec(d.metadata.title), _dec(d.metadata.artist))
301
+ return Overflow(h, d.overflow.dropped)
302
+
303
+
304
+ def poll_event() -> Optional[Event]:
305
+ """The oldest queued event, or None."""
306
+ e = _n.AuEvent()
307
+ return _event(e) if _lib.au_poll_event(ctypes.byref(e)) else None
308
+
309
+
310
+ def wait_event(timeout_seconds: float = -1.0) -> Optional[Event]:
311
+ """Waits up to timeout_seconds (< 0 = no limit); None on timeout and once shutdown() has been called."""
312
+ e = _n.AuEvent()
313
+ return _event(e) if _lib.au_wait_event(ctypes.byref(e), timeout_seconds) else None
314
+
315
+
316
+ #+-----------------------------------------------------+
317
+ #| Value types |
318
+ #+-----------------------------------------------------+
319
+
320
+ _keep_alive = [] # ctypes callbacks C may still call (custom fade curves, the gain scan's on_cached)
321
+
322
+
323
+ @dataclass
324
+ class Fade:
325
+ seconds: float = 0.0 # <= 0: no fade (a cut, or gapless at a natural end)
326
+ curve: FadeCurve = FadeCurve.EQUAL_POWER
327
+ custom: Optional[Callable[[float], float]] = None # for FadeCurve.CUSTOM: t (0..1) -> gain of the fade-in
328
+
329
+ def _native(self) -> _n.AuFade:
330
+ f = _n.AuFade(self.seconds, int(self.curve))
331
+ if self.custom is not None:
332
+ fn = self.custom
333
+ cb = _n.AuFadeCurveFn(lambda t, _user: float(fn(t)))
334
+ _keep_alive.append(cb) # sampled on ffaudio's control thread, later
335
+ f.custom = cb
336
+ return f
337
+
338
+
339
+ @dataclass
340
+ class Crossfade:
341
+ on_track_end: Fade = field(default_factory=Fade)
342
+ on_skip: Fade = field(default_factory=Fade)
343
+ on_play: Fade = field(default_factory=Fade)
344
+ on_stop: Fade = field(default_factory=Fade)
345
+ on_pause: Fade = field(default_factory=Fade)
346
+ min_track_seconds: float = 0.0
347
+
348
+ def _native(self) -> _n.AuCrossfade:
349
+ return _n.AuCrossfade(self.on_track_end._native(), self.on_skip._native(), self.on_play._native(),
350
+ self.on_stop._native(), self.on_pause._native(), self.min_track_seconds)
351
+
352
+
353
+ @dataclass
354
+ class ReplayGain:
355
+ """Gains in dB (re -18 LUFS) and linear peaks; NaN = missing."""
356
+ track_gain_db: float = NAN
357
+ track_peak: float = NAN
358
+ album_gain_db: float = NAN
359
+ album_peak: float = NAN
360
+ from_r128: bool = False
361
+
362
+ def _native(self) -> _n.AuReplayGain:
363
+ return _n.AuReplayGain(self.track_gain_db, self.track_peak, self.album_gain_db, self.album_peak,
364
+ self.from_r128)
365
+
366
+ @staticmethod
367
+ def _of(r: _n.AuReplayGain) -> "ReplayGain":
368
+ return ReplayGain(r.track_gain_db, r.track_peak, r.album_gain_db, r.album_peak, r.from_r128)
369
+
370
+ @property
371
+ def empty(self) -> bool:
372
+ return math.isnan(self.track_gain_db) and math.isnan(self.album_gain_db)
373
+
374
+
375
+ @dataclass
376
+ class ReplayGainSettings:
377
+ mode: ReplayGainMode = ReplayGainMode.OFF
378
+ preamp_db: float = 0.0 # -15..15; +4 plays at -14 LUFS (as most streaming services)
379
+ fallback_gain_db: float = 0.0 # for files without values, -30..15
380
+ prevent_clipping: bool = False
381
+ measure_missing: bool = False # measure untagged tracks in the background (writes the gain cache)
382
+ measure_wait_seconds: float = 0.0 # 0 = 0.5 s, < 0 = do not wait
383
+
384
+ def _native(self):
385
+ return _n.AuReplayGainSettings(int(self.mode), self.preamp_db, self.fallback_gain_db, self.prevent_clipping,
386
+ self.measure_missing, self.measure_wait_seconds)
387
+
388
+
389
+ @dataclass
390
+ class NetworkSettings:
391
+ user_agent: Optional[str] = None
392
+ timeout_seconds: float = 0.0
393
+ buffer_seconds: float = 0.0
394
+ max_buffer_seconds: float = 0.0
395
+ reconnect_attempts: int = 0
396
+
397
+
398
+ @dataclass
399
+ class PlayOptions:
400
+ """Options for one play()/queue(); None/0 = the default. Checked when the track is played."""
401
+ start_seconds: float = 0.0
402
+ length_seconds: float = 0.0
403
+ filters: Optional[str] = None
404
+ fade_in: Optional[Fade] = None
405
+ replaygain: Optional[ReplayGain] = None
406
+ http_headers: Optional[str] = None
407
+
408
+ def _native(self):
409
+ o = _lib.au_play_options_create()
410
+ if not o:
411
+ raise Error(Result.ERR_NO_MEMORY)
412
+ try:
413
+ _check(_lib.au_play_options_set_range(o, self.start_seconds, self.length_seconds), "range")
414
+ if self.filters:
415
+ _check(_lib.au_play_options_set_filters(o, _enc(self.filters)), f"filters {self.filters!r}")
416
+ if self.fade_in is not None:
417
+ f = self.fade_in._native()
418
+ _check(_lib.au_play_options_set_fade_in(o, ctypes.byref(f)), "fade_in")
419
+ if self.replaygain is not None:
420
+ rg = self.replaygain._native()
421
+ _check(_lib.au_play_options_set_replaygain(o, ctypes.byref(rg)))
422
+ if self.http_headers:
423
+ _check(_lib.au_play_options_set_http_headers(o, _enc(self.http_headers)))
424
+ except Error:
425
+ _lib.au_play_options_free(o)
426
+ raise
427
+ return o
428
+
429
+
430
+ @dataclass(frozen=True)
431
+ class Status:
432
+ handle: int
433
+ position: float
434
+ duration: float
435
+ buffering: bool
436
+ paused: bool
437
+ muted: bool
438
+ volume: float
439
+ speed: float
440
+ keep_pitch: bool
441
+ loop_count: int
442
+ sample_rate: int
443
+ channels: int
444
+
445
+
446
+ @dataclass(frozen=True)
447
+ class MediaInfo:
448
+ path: str
449
+ container: str
450
+ codec: str
451
+ channel_layout: str
452
+ duration: float # -1 = unknown
453
+ bit_rate: int
454
+ sample_rate: int
455
+ channels: int
456
+ bits_per_sample: int
457
+ live: bool
458
+ seekable: bool
459
+ track_number: int
460
+ track_total: int
461
+ disc_number: int
462
+ disc_total: int
463
+ replaygain: ReplayGain
464
+ tags: tuple # ((key, value), ...) in file order
465
+ picture_count: int
466
+
467
+ def tag(self, key: str, default: Optional[str] = None) -> Optional[str]:
468
+ """A tag by its normalized lower-case name ("title", "artist", "album", "album_artist", "date", ...)."""
469
+ k = key.lower()
470
+ for name, value in self.tags:
471
+ if name.lower() == k:
472
+ return value
473
+ return default
474
+
475
+ @property
476
+ def title(self) -> Optional[str]:
477
+ return self.tag("title")
478
+
479
+ @property
480
+ def artist(self) -> Optional[str]:
481
+ return self.tag("artist")
482
+
483
+ @property
484
+ def album(self) -> Optional[str]:
485
+ return self.tag("album")
486
+
487
+
488
+ def _media_info(p) -> MediaInfo:
489
+ m = p.contents
490
+ tags = tuple((_dec(m.tags[i].key), _dec(m.tags[i].value)) for i in range(m.tag_count))
491
+ return MediaInfo(_dec(m.path), _dec(m.container), _dec(m.codec), _dec(m.channel_layout), m.duration, m.bit_rate,
492
+ m.sample_rate, m.channels, m.bits_per_sample, m.live, m.seekable, m.track_number, m.track_total,
493
+ m.disc_number, m.disc_total, ReplayGain._of(m.replaygain), tags, m.picture_count)
494
+
495
+
496
+ @dataclass(frozen=True)
497
+ class Picture:
498
+ data: bytes
499
+ mime: str
500
+ type: int
501
+ width: int
502
+ height: int
503
+ description: str
504
+
505
+
506
+ #+-----------------------------------------------------+
507
+ #| Lifetime, device, playback |
508
+ #+-----------------------------------------------------+
509
+
510
+ def init(app_name: Optional[str] = None) -> None:
511
+ """Start the player. Events are queued for poll_event() / wait_event(). The device opens with the first
512
+ play() or queue(), or at open_device()."""
513
+ _check(_lib.au_init(_enc(app_name), _n.AuEventFn(), None)) # a NULL callback: events are queued
514
+
515
+
516
+ def open_device() -> None:
517
+ _check(_lib.au_open_device())
518
+
519
+
520
+ def shutdown() -> None:
521
+ _check(_lib.au_shutdown())
522
+
523
+
524
+ def set_device(name: Optional[str]) -> None:
525
+ """A name from list_devices(); None = the system default (followed when it changes)."""
526
+ _check(_lib.au_set_device(_enc(name)))
527
+
528
+
529
+ def set_output_format(channels: int = 0, sample_rate: int = 0) -> None:
530
+ _check(_lib.au_set_output_format(channels, sample_rate))
531
+
532
+
533
+ def list_devices() -> list:
534
+ n = ctypes.c_int(0)
535
+ p = _lib.au_list_devices(ctypes.byref(n))
536
+ try:
537
+ return [_dec(p[i]) for i in range(n.value)] if p else []
538
+ finally:
539
+ _lib.au_free_devices(p, n.value)
540
+
541
+
542
+ def device_name() -> str:
543
+ buf = ctypes.create_string_buffer(512)
544
+ _check(_lib.au_get_device_name(buf, len(buf)))
545
+ return _dec(buf.value)
546
+
547
+
548
+ def _track_call(fn, path: str, options: Optional[PlayOptions]) -> int:
549
+ o = options._native() if options is not None else None
550
+ try:
551
+ return _check(fn(_enc(path), o), path)
552
+ finally:
553
+ if o:
554
+ _lib.au_play_options_free(o)
555
+
556
+
557
+ def play(path: str, options: Optional[PlayOptions] = None) -> int:
558
+ """Play a file or URL now; returns its handle."""
559
+ return _track_call(_lib.au_play, path, options)
560
+
561
+
562
+ def queue(path: str, options: Optional[PlayOptions] = None) -> int:
563
+ """Play it after the current track (gapless or crossfaded), replacing a queued one; returns its handle."""
564
+ return _track_call(_lib.au_queue, path, options)
565
+
566
+
567
+ def skip() -> None:
568
+ _check(_lib.au_skip())
569
+
570
+
571
+ def clear_queue() -> None:
572
+ _check(_lib.au_clear_queue())
573
+
574
+
575
+ def stop() -> None:
576
+ _check(_lib.au_stop())
577
+
578
+
579
+ def pause(paused: bool = True) -> None:
580
+ _check(_lib.au_pause(paused))
581
+
582
+
583
+ def seek(seconds: float) -> None:
584
+ _check(_lib.au_seek(seconds))
585
+
586
+
587
+ def seek_fraction(fraction: float) -> None:
588
+ _check(_lib.au_seek_fraction(fraction))
589
+
590
+
591
+ def set_crossfade(crossfade: Optional[Crossfade]) -> None:
592
+ c = crossfade._native() if crossfade is not None else None
593
+ _check(_lib.au_set_crossfade(ctypes.byref(c) if c is not None else None))
594
+
595
+
596
+ def set_speed(speed: float, keep_pitch: bool = True) -> None:
597
+ _check(_lib.au_set_speed(speed, keep_pitch))
598
+
599
+
600
+ def set_volume(gain: float) -> None:
601
+ """0..2, 1 = 100 %."""
602
+ _check(_lib.au_set_volume(gain))
603
+
604
+
605
+ def set_muted(muted: bool) -> None:
606
+ _check(_lib.au_set_muted(muted))
607
+
608
+
609
+ def set_loop_count(count: int) -> None:
610
+ """-1 = forever, 0 = none."""
611
+ _check(_lib.au_set_loop_count(count))
612
+
613
+
614
+ def set_prepare_next(seconds: float) -> None:
615
+ _check(_lib.au_set_prepare_next(seconds))
616
+
617
+
618
+ def set_network(settings: Optional[NetworkSettings]) -> None:
619
+ if settings is None:
620
+ _check(_lib.au_set_network(None))
621
+ return
622
+ s = _n.AuNetworkSettings(_enc(settings.user_agent), settings.timeout_seconds, settings.buffer_seconds,
623
+ settings.max_buffer_seconds, settings.reconnect_attempts)
624
+ _check(_lib.au_set_network(ctypes.byref(s)))
625
+
626
+
627
+ def is_network_url(path: str) -> bool:
628
+ return bool(_lib.au_is_network_url(_enc(path)))
629
+
630
+
631
+ def status() -> Status:
632
+ s = _n.AuStatus()
633
+ _lib.au_get_status(ctypes.byref(s))
634
+ return Status(s.handle, s.position, s.duration, s.buffering, s.paused, s.muted, s.volume, s.speed, s.keep_pitch,
635
+ s.loop_count, s.sample_rate, s.channels)
636
+
637
+
638
+ #+-----------------------------------------------------+
639
+ #| Filters |
640
+ #+-----------------------------------------------------+
641
+
642
+ def set_filters(filters: Optional[str]) -> None:
643
+ _check(_lib.au_set_filters(_enc(filters or None)), filters or "")
644
+
645
+
646
+ def set_track_filters(handle: int, filters: Optional[str]) -> None:
647
+ _check(_lib.au_set_track_filters(handle, _enc(filters or None)), filters or "")
648
+
649
+
650
+ def set_source_filters(filters: Optional[str]) -> None:
651
+ _check(_lib.au_set_source_filters(_enc(filters or None)), filters or "")
652
+
653
+
654
+ def send_filter_command(target: str, command: str, arg: str, handle: int = 0) -> None:
655
+ """A runtime command to a named filter, e.g. ("equalizer@eq_3", "g", "-6"); handle 0 = every live track."""
656
+ _check(_lib.au_send_filter_command(handle, _enc(target), _enc(command), _enc(arg)))
657
+
658
+
659
+ def validate_filters(filters: str) -> bool:
660
+ return _lib.au_validate_filters(_enc(filters)) == 0
661
+
662
+
663
+ def set_downmix(mode: Downmix, custom_filters: Optional[str] = None) -> None:
664
+ _check(_lib.au_set_downmix(int(mode), _enc(custom_filters)))
665
+
666
+
667
+ def set_upmix(mode: Upmix, custom_filters: Optional[str] = None) -> None:
668
+ _check(_lib.au_set_upmix(int(mode), _enc(custom_filters)))
669
+
670
+
671
+ def filter_available(name: str) -> bool:
672
+ return bool(_lib.au_filter_available(_enc(name)))
673
+
674
+
675
+ def _from_native(cls, n):
676
+ return cls(**{name: (list(getattr(n, name)) if isinstance(getattr(n, name), ctypes.Array) else getattr(n, name))
677
+ for name, _ in n._fields_})
678
+
679
+
680
+ def _to_native(ncls, v):
681
+ n = ncls()
682
+ for name, ctype in ncls._fields_:
683
+ value = getattr(v, name)
684
+ if isinstance(getattr(n, name), ctypes.Array):
685
+ getattr(n, name)[:] = list(value)
686
+ else:
687
+ setattr(n, name, value)
688
+ return n
689
+
690
+
691
+ _EQ = _lib.au_equalizer_defaults()
692
+ _STEREO, _LIMITER, _COMP = _lib.au_stereo_defaults(), _lib.au_limiter_defaults(), _lib.au_compressor_defaults()
693
+ _DECLICK, _DECLIP, _XFEED = _lib.au_declick_defaults(), _lib.au_declip_defaults(), _lib.au_crossfeed_defaults()
694
+ EQ_BANDS = _n.EQ_BANDS
695
+
696
+
697
+ @dataclass
698
+ class Equalizer:
699
+ """10 bands at 31, 62, 125, 250, 500 Hz, 1, 2, 4, 8, 16 kHz; every default is the library's."""
700
+ gain_db: list = field(default_factory=lambda: list(_EQ.gain_db))
701
+ frequency_hz: list = field(default_factory=lambda: list(_EQ.frequency_hz))
702
+ width_hz: list = field(default_factory=lambda: list(_EQ.width_hz))
703
+ preamp_db: float = _EQ.preamp_db
704
+
705
+
706
+ def equalizer_defaults() -> Equalizer:
707
+ return _from_native(Equalizer, _lib.au_equalizer_defaults())
708
+
709
+
710
+ @dataclass
711
+ class PeqBand:
712
+ type: PeqType = PeqType.PEAK
713
+ frequency_hz: float = 1000.0
714
+ q: float = 0.7071
715
+ gain_db: float = 0.0
716
+
717
+
718
+ @dataclass
719
+ class ParametricEq:
720
+ preamp_db: float = 0.0
721
+ bands: list = field(default_factory=list) # up to 32 PeqBand
722
+
723
+ def _native(self):
724
+ n = _n.AuParametricEq()
725
+ n.preamp_db = self.preamp_db
726
+ n.band_count = len(self.bands)
727
+ for i, b in enumerate(self.bands[:_n.PEQ_MAX_BANDS]):
728
+ n.bands[i] = _n.AuPeqBand(int(b.type), b.frequency_hz, b.q, b.gain_db)
729
+ return n
730
+
731
+
732
+ def parametric_eq_parse(text: str) -> ParametricEq:
733
+ """EqualizerAPO / AutoEq "ParametricEQ.txt" text."""
734
+ out = _n.AuParametricEq()
735
+ err = ctypes.create_string_buffer(256)
736
+ _check(_lib.au_parametric_eq_parse(_enc(text), ctypes.byref(out), err, len(err)), _dec(err.value))
737
+ return ParametricEq(out.preamp_db, [PeqBand(PeqType(out.bands[i].type), out.bands[i].frequency_hz,
738
+ out.bands[i].q, out.bands[i].gain_db) for i in range(out.band_count)])
739
+
740
+
741
+ @dataclass
742
+ class Stereo:
743
+ balance: float = _STEREO.balance # -1 (left) .. 1 (right)
744
+ width: float = _STEREO.width # 0 = mono .. 4
745
+ swap: bool = _STEREO.swap
746
+
747
+
748
+ @dataclass
749
+ class Limiter:
750
+ ceiling_db: float = _LIMITER.ceiling_db
751
+ attack_ms: float = _LIMITER.attack_ms
752
+ release_ms: float = _LIMITER.release_ms
753
+
754
+
755
+ @dataclass
756
+ class Compressor:
757
+ threshold_db: float = _COMP.threshold_db
758
+ ratio: float = _COMP.ratio
759
+ attack_ms: float = _COMP.attack_ms
760
+ release_ms: float = _COMP.release_ms
761
+ knee_db: float = _COMP.knee_db
762
+ makeup_db: float = _COMP.makeup_db
763
+
764
+
765
+ def compressor_night() -> Compressor:
766
+ return _from_native(Compressor, _lib.au_compressor_night())
767
+
768
+
769
+ @dataclass
770
+ class Declick:
771
+ window_ms: float = _DECLICK.window_ms
772
+ overlap_percent: float = _DECLICK.overlap_percent
773
+ threshold: float = _DECLICK.threshold
774
+ burst: float = _DECLICK.burst
775
+
776
+
777
+ @dataclass
778
+ class Declip:
779
+ window_ms: float = _DECLIP.window_ms
780
+ overlap_percent: float = _DECLIP.overlap_percent
781
+ threshold: float = _DECLIP.threshold
782
+
783
+
784
+ @dataclass
785
+ class Crossfeed:
786
+ strength: float = _XFEED.strength
787
+ range: float = _XFEED.range
788
+ slope: float = _XFEED.slope
789
+ level_in: float = _XFEED.level_in
790
+ level_out: float = _XFEED.level_out
791
+
792
+
793
+ class FilterBuilder:
794
+ """Builds an FFmpeg filter string (ffaudio_filters.h). Every add_* returns the builder, so calls chain; an
795
+ invalid value raises Error saying what was wrong, and leaves the builder as it was. None settings = defaults.
796
+
797
+ filters = ffaudio.FilterBuilder().add_equalizer(eq, name="eq").add_limiter().string
798
+ """
799
+
800
+ def __init__(self):
801
+ self._fb = _lib.au_fb_create()
802
+ if not self._fb:
803
+ raise Error(Result.ERR_NO_MEMORY)
804
+
805
+ def __del__(self):
806
+ if getattr(self, "_fb", None):
807
+ _lib.au_fb_free(self._fb)
808
+ self._fb = None
809
+
810
+ def __enter__(self):
811
+ return self
812
+
813
+ def __exit__(self, *exc):
814
+ self.__del__()
815
+
816
+ @property
817
+ def string(self) -> str:
818
+ """The filter string so far ("" when empty)."""
819
+ return _dec(_lib.au_fb_peek(self._fb))
820
+
821
+ def __str__(self):
822
+ return self.string
823
+
824
+ def clear(self) -> "FilterBuilder":
825
+ _lib.au_fb_clear(self._fb)
826
+ return self
827
+
828
+ def _done(self, ret: int) -> "FilterBuilder":
829
+ _check(ret, _dec(_lib.au_fb_last_error(self._fb)))
830
+ return self
831
+
832
+ def add(self, filter_string: str) -> "FilterBuilder":
833
+ return self._done(_lib.au_fb_add(self._fb, _enc(filter_string)))
834
+
835
+ def add_volume_db(self, gain_db: float, name: Optional[str] = None) -> "FilterBuilder":
836
+ return self._done(_lib.au_fb_add_volume_db(self._fb, _enc(name), gain_db))
837
+
838
+ def add_equalizer(self, eq: Optional[Equalizer] = None, name: Optional[str] = None) -> "FilterBuilder":
839
+ n = _to_native(_n.AuEqualizer, eq) if eq is not None else None
840
+ return self._done(_lib.au_fb_add_equalizer(self._fb, _enc(name), ctypes.byref(n) if n else None))
841
+
842
+ def add_parametric_eq(self, eq: Optional[ParametricEq] = None, name: Optional[str] = None) -> "FilterBuilder":
843
+ n = eq._native() if eq is not None else None
844
+ return self._done(_lib.au_fb_add_parametric_eq(self._fb, _enc(name), ctypes.byref(n) if n else None))
845
+
846
+ def add_tone(self, bass_db: float, treble_db: float, name: Optional[str] = None) -> "FilterBuilder":
847
+ return self._done(_lib.au_fb_add_tone(self._fb, _enc(name), bass_db, treble_db))
848
+
849
+ def _add(self, fn, ncls, value, name):
850
+ n = _to_native(ncls, value) if value is not None else None
851
+ return self._done(fn(self._fb, _enc(name), ctypes.byref(n) if n is not None else None))
852
+
853
+ def add_stereo(self, stereo: Optional[Stereo] = None, name: Optional[str] = None) -> "FilterBuilder":
854
+ return self._add(_lib.au_fb_add_stereo, _n.AuStereo, stereo, name)
855
+
856
+ def add_limiter(self, limiter: Optional[Limiter] = None, name: Optional[str] = None) -> "FilterBuilder":
857
+ return self._add(_lib.au_fb_add_limiter, _n.AuLimiter, limiter, name)
858
+
859
+ def add_compressor(self, compressor: Optional[Compressor] = None, name: Optional[str] = None) -> "FilterBuilder":
860
+ return self._add(_lib.au_fb_add_compressor, _n.AuCompressor, compressor, name)
861
+
862
+ def add_declick(self, declick: Optional[Declick] = None, name: Optional[str] = None) -> "FilterBuilder":
863
+ return self._add(_lib.au_fb_add_declick, _n.AuDeclick, declick, name)
864
+
865
+ def add_declip(self, declip: Optional[Declip] = None, name: Optional[str] = None) -> "FilterBuilder":
866
+ return self._add(_lib.au_fb_add_declip, _n.AuDeclip, declip, name)
867
+
868
+ def add_crossfeed(self, crossfeed: Optional[Crossfeed] = None, name: Optional[str] = None) -> "FilterBuilder":
869
+ return self._add(_lib.au_fb_add_crossfeed, _n.AuCrossfeed, crossfeed, name)
870
+
871
+ def add_bs2b(self, profile: Bs2bProfile = Bs2bProfile.DEFAULT, name: Optional[str] = None) -> "FilterBuilder":
872
+ return self._done(_lib.au_fb_add_bs2b_profile(self._fb, _enc(name), int(profile)))
873
+
874
+
875
+ #+-----------------------------------------------------+
876
+ #| ReplayGain, metadata |
877
+ #+-----------------------------------------------------+
878
+
879
+ def set_replaygain(settings: Optional[ReplayGainSettings]) -> None:
880
+ n = settings._native() if settings is not None else None
881
+ _check(_lib.au_set_replaygain(ctypes.byref(n) if n is not None else None))
882
+
883
+
884
+ def track_gain_db(handle: int = 0) -> float:
885
+ v = ctypes.c_double()
886
+ _check(_lib.au_track_gain_db(handle, ctypes.byref(v)))
887
+ return v.value
888
+
889
+
890
+ def probe(path: str) -> MediaInfo:
891
+ err = ctypes.c_int(0)
892
+ p = _lib.au_probe(_enc(path), ctypes.byref(err))
893
+ if not p:
894
+ raise Error(err.value or Result.ERR_FILE, path)
895
+ try:
896
+ return _media_info(p)
897
+ finally:
898
+ _lib.au_media_info_release(p)
899
+
900
+
901
+ def track_info(handle: int = 0) -> Optional[MediaInfo]:
902
+ """The details of a playing or queued track once AU_EVENT_TRACK_OPENED has come; None before."""
903
+ p = _lib.au_track_info(handle)
904
+ if not p:
905
+ return None
906
+ try:
907
+ return _media_info(p)
908
+ finally:
909
+ _lib.au_media_info_release(p)
910
+
911
+
912
+ def media_picture(path: str, type: PictureType = PictureType.ANY) -> Optional[Picture]:
913
+ """An embedded picture (the front cover first for ANY), or None when there is none."""
914
+ err = ctypes.c_int(0)
915
+ p = _lib.au_media_picture(_enc(path), int(type), ctypes.byref(err))
916
+ if not p:
917
+ if err.value and err.value != Result.ERR_NOTHING_TO_DO:
918
+ raise Error(err.value, path)
919
+ return None
920
+ try:
921
+ v = p.contents
922
+ return Picture(ctypes.string_at(v.data, v.size), _dec(v.mime) or "", v.type, v.width, v.height,
923
+ _dec(v.description) or "")
924
+ finally:
925
+ _lib.au_picture_release(p)
926
+
927
+
928
+ #+-----------------------------------------------------+
929
+ #| ReplayGain cache and loudness |
930
+ #+-----------------------------------------------------+
931
+
932
+ def gain_cache_set_file(path: Optional[str]) -> None:
933
+ """None = the default location, "" = memory only."""
934
+ _check(_lib.au_gain_cache_set_file(_enc(path)))
935
+
936
+
937
+ def gain_cache_file() -> str:
938
+ buf = ctypes.create_string_buffer(4096)
939
+ _check(_lib.au_gain_cache_get_file(buf, len(buf)))
940
+ return _dec(buf.value)
941
+
942
+
943
+ def gain_cache_get(path: str) -> Optional[ReplayGain]:
944
+ r = _n.AuReplayGain()
945
+ return ReplayGain._of(r) if _lib.au_gain_cache_get(_enc(path), ctypes.byref(r)) else None
946
+
947
+
948
+ def gain_cache_set(path: str, rg: ReplayGain) -> bool:
949
+ """True when it is stored in the file too, False when only in memory (the file could not be written)."""
950
+ n = rg._native()
951
+ ret = _lib.au_gain_cache_set(_enc(path), ctypes.byref(n))
952
+ if ret == Result.ERR_NOT_SAVED:
953
+ return False
954
+ _check(ret, path)
955
+ return True
956
+
957
+
958
+ def gain_cache_remove(path: str) -> bool:
959
+ """True when there was an entry."""
960
+ ret = _lib.au_gain_cache_remove(_enc(path))
961
+ if ret == Result.ERR_NOTHING_TO_DO:
962
+ return False
963
+ if ret != Result.ERR_NOT_SAVED:
964
+ _check(ret, path)
965
+ return True
966
+
967
+
968
+ def gain_cache_clear() -> None:
969
+ ret = _lib.au_gain_cache_clear()
970
+ if ret != Result.ERR_NOT_SAVED:
971
+ _check(ret)
972
+
973
+
974
+ def gain_cache_count() -> int:
975
+ return _lib.au_gain_cache_count()
976
+
977
+
978
+ @dataclass(frozen=True)
979
+ class Loudness:
980
+ silent: bool
981
+ integrated_lufs: float
982
+ loudness_range_lu: float
983
+ true_peak: float
984
+ sample_peak: float
985
+ duration: float
986
+ replaygain_gain_db: float
987
+ r128_gain_db: float
988
+ r128_gain_q78: int
989
+
990
+
991
+ def _loudness_options(skip_true_peak: bool, progress):
992
+ o = _n.AuLoudnessOptions(skip_true_peak)
993
+ cb = None
994
+ if progress is not None:
995
+ cb = _n.AuLoudnessProgressFn(lambda fraction, _user: bool(progress(fraction)))
996
+ o.progress = cb
997
+ return o, cb
998
+
999
+
1000
+ def loudness_analyze(path: str, skip_true_peak: bool = False,
1001
+ progress: Optional[Callable[[float], bool]] = None) -> Loudness:
1002
+ """Measure one file (blocks; progress(fraction) returning False cancels)."""
1003
+ o, _cb = _loudness_options(skip_true_peak, progress)
1004
+ out = _n.AuLoudness()
1005
+ _check(_lib.au_loudness_analyze(_enc(path), ctypes.byref(o), ctypes.byref(out)), path)
1006
+ return _from_native(Loudness, out)
1007
+
1008
+
1009
+ def loudness_to_replaygain(track: Loudness, album: Optional[Loudness] = None) -> ReplayGain:
1010
+ t = _to_native(_n.AuLoudness, track)
1011
+ a = _to_native(_n.AuLoudness, album) if album is not None else None
1012
+ return ReplayGain._of(_lib.au_loudness_to_replaygain(ctypes.byref(t), ctypes.byref(a) if a else None))
1013
+
1014
+
1015
+ def gain_cache_scan(path: str, skip_true_peak: bool = False) -> ReplayGain:
1016
+ """The cached values, or measure the file (blocks) and store them."""
1017
+ o, _cb = _loudness_options(skip_true_peak, None)
1018
+ out = _n.AuReplayGain()
1019
+ ret = _lib.au_gain_cache_scan(_enc(path), ctypes.byref(o), ctypes.byref(out))
1020
+ if ret != Result.ERR_NOT_SAVED:
1021
+ _check(ret, path)
1022
+ return ReplayGain._of(out)
1023
+
1024
+
1025
+ @dataclass
1026
+ class GainScanSettings:
1027
+ threads: int = 0
1028
+ skip_true_peak: bool = False
1029
+ # (path, result, ReplayGain or None) on a scan worker thread: keep it short, hand the work to your own thread
1030
+ on_cached: Optional[Callable[[str, int, Optional[ReplayGain]], None]] = None
1031
+ measure_streams: bool = False
1032
+
1033
+
1034
+ def set_gain_scan(settings: Optional[GainScanSettings]) -> None:
1035
+ if settings is None:
1036
+ _check(_lib.au_set_gain_scan(None))
1037
+ return
1038
+ n = _n.AuGainScanSettings(settings.threads, settings.skip_true_peak)
1039
+ n.measure_streams = settings.measure_streams
1040
+ if settings.on_cached is not None:
1041
+ fn = settings.on_cached
1042
+
1043
+ def cached(path, result, rg, _user):
1044
+ try:
1045
+ fn(_dec(path), result, ReplayGain._of(rg.contents) if rg else None)
1046
+ except Exception: # never into C
1047
+ pass
1048
+
1049
+ cb = _n.AuGainCachedFn(cached)
1050
+ _keep_alive.append(cb)
1051
+ n.on_cached = cb
1052
+ _check(_lib.au_set_gain_scan(ctypes.byref(n)))
1053
+
1054
+
1055
+ def _paths(paths: Sequence[str]):
1056
+ arr = (ctypes.c_char_p * len(paths))(*[_enc(p) for p in paths])
1057
+ return arr, len(paths)
1058
+
1059
+
1060
+ def gain_scan_request(paths: Sequence[str], priority: ScanPriority = ScanPriority.PREFETCH) -> int:
1061
+ """Measure files in the background (results go to the cache and on_cached); returns how many were queued."""
1062
+ arr, n = _paths(paths)
1063
+ return _check(_lib.au_gain_scan_request(arr, n, int(priority)))
1064
+
1065
+
1066
+ def gain_scan_request_album(paths: Sequence[str], priority: ScanPriority = ScanPriority.PREFETCH) -> int:
1067
+ arr, n = _paths(paths)
1068
+ return _check(_lib.au_gain_scan_request_album(arr, n, int(priority)))
1069
+
1070
+
1071
+ def gain_scan_cancel() -> None:
1072
+ _lib.au_gain_scan_cancel()
1073
+
1074
+
1075
+ def gain_scan_pending() -> int:
1076
+ return _lib.au_gain_scan_pending()
1077
+
1078
+
1079
+ def gain_scan_stop() -> None:
1080
+ _check(_lib.au_gain_scan_stop())
1081
+
1082
+
1083
+ #+-----------------------------------------------------+
1084
+ #| Meters |
1085
+ #+-----------------------------------------------------+
1086
+
1087
+ @dataclass(frozen=True)
1088
+ class Levels:
1089
+ channels: int
1090
+ sample_rate: int
1091
+ window_seconds: float
1092
+ peak: tuple # per channel, linear (1.0 = full scale)
1093
+ rms: tuple
1094
+
1095
+
1096
+ def levels(window_seconds: float = 0.05) -> Levels:
1097
+ """Peak and RMS of the last window_seconds heard (0 < window <= 0.5)."""
1098
+ v = _n.AuLevels()
1099
+ _check(_lib.au_get_levels(window_seconds, ctypes.byref(v)))
1100
+ c = max(0, min(v.channels, 8))
1101
+ return Levels(v.channels, v.sample_rate, v.window_seconds, tuple(v.peak[:c]), tuple(v.rms[:c]))
1102
+
1103
+
1104
+ class Spectrum:
1105
+ """A spectrum analyzer over what is heard (an FFT of fft_size samples, 256..16384, a power of two)."""
1106
+
1107
+ def __init__(self, fft_size: int = 2048):
1108
+ self.fft_size = fft_size
1109
+ self._sp = _lib.au_spectrum_create(fft_size)
1110
+ if not self._sp:
1111
+ raise Error(Result.ERR_INVALID_ARGUMENT, f"fft_size {fft_size}")
1112
+ self._mags = (ctypes.c_float * (fft_size // 2 + 1))()
1113
+ self.sample_rate = 0
1114
+
1115
+ def __del__(self):
1116
+ if getattr(self, "_sp", None):
1117
+ _lib.au_spectrum_free(self._sp)
1118
+ self._sp = None
1119
+
1120
+ def read(self, channel: int = -1) -> list:
1121
+ """fft_size / 2 + 1 magnitudes (linear, a full-scale sine reads 1.0); channel -1 = all."""
1122
+ rate = ctypes.c_int(0)
1123
+ _check(_lib.au_spectrum_read(self._sp, channel, self._mags, len(self._mags), ctypes.byref(rate)))
1124
+ self.sample_rate = rate.value
1125
+ return list(self._mags)
1126
+
1127
+ def bands(self, n_bands: int = 32, f_min: float = 30.0, f_max: float = 16000.0, channel: int = -1) -> list:
1128
+ """read(), grouped into n_bands log-spaced bands from f_min to f_max Hz (linear magnitudes)."""
1129
+ self.read(channel)
1130
+ out = (ctypes.c_float * n_bands)()
1131
+ if self.sample_rate <= 0:
1132
+ return [0.0] * n_bands
1133
+ _check(_lib.au_spectrum_bands(self._mags, self.fft_size, self.sample_rate, f_min, f_max, out, n_bands))
1134
+ return list(out)
1135
+
1136
+
1137
+ #+-----------------------------------------------------+
1138
+ #| Playlists and cue sheets |
1139
+ #+-----------------------------------------------------+
1140
+
1141
+ @dataclass(frozen=True)
1142
+ class PlaylistEntry:
1143
+ path: str # ready for play() / queue()
1144
+ title: str # "" when the playlist has none
1145
+ duration: float # -1 when unknown
1146
+ # Since 4.2, for entries of a Playlist / PlayQueue:
1147
+ id: int = 0
1148
+ start_seconds: float = 0.0 # the range to play; 0, 0 = the whole file
1149
+ length_seconds: float = 0.0
1150
+ replaygain: Optional["ReplayGain"] = None # None when the entry has no values
1151
+ user_key: str = ""
1152
+
1153
+ def play_options(self) -> "PlayOptions":
1154
+ """The options that play this entry: its range and ReplayGain values."""
1155
+ return PlayOptions(start_seconds=self.start_seconds, length_seconds=self.length_seconds,
1156
+ replaygain=self.replaygain)
1157
+
1158
+
1159
+ def _playlist(p) -> list:
1160
+ try:
1161
+ v = p.contents
1162
+ return [PlaylistEntry(_dec(v.entries[i].contents.path), _dec(v.entries[i].contents.title) or "",
1163
+ v.entries[i].contents.duration) for i in range(v.count)]
1164
+ finally:
1165
+ _lib.au_playlist_file_release(p)
1166
+
1167
+
1168
+ def playlist_read(path_or_url: str) -> list:
1169
+ """The entries of an M3U/M3U8/PLS file or URL."""
1170
+ err = ctypes.c_int(0)
1171
+ p = _lib.au_playlist_read(_enc(path_or_url), ctypes.byref(err))
1172
+ if not p:
1173
+ raise Error(err.value or Result.ERR_FILE, path_or_url)
1174
+ return _playlist(p)
1175
+
1176
+
1177
+ def playlist_parse(text: str, base: Optional[str] = None) -> list:
1178
+ """Playlist text; base is where it came from (the playlist's own path or URL), for relative entries."""
1179
+ data = _enc(text)
1180
+ err = ctypes.c_int(0)
1181
+ p = _lib.au_playlist_parse(data, len(data), _enc(base), ctypes.byref(err))
1182
+ if not p:
1183
+ raise Error(err.value or Result.ERR_INVALID_ARGUMENT)
1184
+ return _playlist(p)
1185
+
1186
+
1187
+ @dataclass(frozen=True)
1188
+ class CueTrack:
1189
+ number: int
1190
+ path: str
1191
+ start_seconds: float
1192
+ length_seconds: float # 0 = to the end of the file
1193
+ title: str
1194
+ performer: str
1195
+ songwriter: str
1196
+ isrc: str
1197
+ replaygain: ReplayGain
1198
+
1199
+ def play_options(self) -> PlayOptions:
1200
+ """The options that play this track: its range, and the sheet's ReplayGain values if any."""
1201
+ return PlayOptions(start_seconds=self.start_seconds, length_seconds=self.length_seconds,
1202
+ replaygain=None if self.replaygain.empty else self.replaygain)
1203
+
1204
+
1205
+ @dataclass(frozen=True)
1206
+ class CueSheet:
1207
+ title: str
1208
+ performer: str
1209
+ genre: str
1210
+ date: str
1211
+ tracks: tuple
1212
+
1213
+
1214
+ def _cue(p) -> CueSheet:
1215
+ try:
1216
+ v = p.contents
1217
+ tracks = []
1218
+ for i in range(v.count):
1219
+ t = v.tracks[i].contents
1220
+ tracks.append(CueTrack(t.number, _dec(t.path), t.start_seconds, t.length_seconds, _dec(t.title) or "",
1221
+ _dec(t.performer) or "", _dec(t.songwriter) or "", _dec(t.isrc) or "",
1222
+ ReplayGain._of(t.replaygain)))
1223
+ return CueSheet(_dec(v.title) or "", _dec(v.performer) or "", _dec(v.genre) or "", _dec(v.date) or "",
1224
+ tuple(tracks))
1225
+ finally:
1226
+ _lib.au_cue_release(p)
1227
+
1228
+
1229
+ def cue_read(path_or_url: str) -> CueSheet:
1230
+ """The tracks of a .cue file, of an audio file with an embedded cue sheet, or of a file's chapters."""
1231
+ err = ctypes.c_int(0)
1232
+ p = _lib.au_cue_read(_enc(path_or_url), ctypes.byref(err))
1233
+ if not p:
1234
+ raise Error(err.value or Result.ERR_FILE, path_or_url)
1235
+ return _cue(p)
1236
+
1237
+
1238
+ #+-----------------------------------------------------+
1239
+ #| Playlists and the play queue |
1240
+ #+-----------------------------------------------------+
1241
+
1242
+ class Sort(enum.IntEnum):
1243
+ ADDED = 0
1244
+ TITLE = 1
1245
+ PATH = 2
1246
+ DURATION = 3
1247
+ USER_KEY = 4
1248
+
1249
+
1250
+ class Repeat(enum.IntEnum):
1251
+ OFF = 0
1252
+ ALL = 1
1253
+ ONE = 2
1254
+
1255
+
1256
+ def _entry(p) -> Optional[PlaylistEntry]:
1257
+ if not p:
1258
+ return None
1259
+ e = p.contents
1260
+ rg = ReplayGain._of(e.replaygain)
1261
+ return PlaylistEntry(_dec(e.path), _dec(e.title) or "", e.duration, e.id, e.start_seconds, e.length_seconds,
1262
+ None if rg.empty else rg, _dec(e.user_key) or "")
1263
+
1264
+
1265
+ def _ids(ids) -> tuple:
1266
+ ids = list(ids)
1267
+ return (ctypes.c_int64 * max(1, len(ids)))(*ids), len(ids)
1268
+
1269
+
1270
+ class Playlist:
1271
+ """A list of entries in order, each with an id (see ffaudio_playlist.h). Use it from one thread at a time."""
1272
+
1273
+ def __init__(self, _handle=None, _owner=None):
1274
+ self._owner = _owner # a PlayQueue whose own list this is: kept alive, never freed here
1275
+ self._pl = _handle if _handle is not None else _lib.au_playlist_create()
1276
+ if not self._pl:
1277
+ raise Error(Result.ERR_NO_MEMORY)
1278
+
1279
+ def __del__(self):
1280
+ if getattr(self, "_pl", None) and getattr(self, "_owner", None) is None:
1281
+ _lib.au_playlist_free(self._pl)
1282
+ self._pl = None
1283
+
1284
+ def copy(self) -> "Playlist":
1285
+ """A copy with the same ids."""
1286
+ p = _lib.au_playlist_copy(self._pl)
1287
+ if not p:
1288
+ raise Error(Result.ERR_NO_MEMORY)
1289
+ return Playlist(p)
1290
+
1291
+ def __len__(self) -> int:
1292
+ return _lib.au_playlist_count(self._pl)
1293
+
1294
+ def __getitem__(self, index: int) -> PlaylistEntry:
1295
+ if index < 0:
1296
+ index += len(self)
1297
+ e = _entry(_lib.au_playlist_at(self._pl, index))
1298
+ if e is None:
1299
+ raise IndexError(index)
1300
+ return e
1301
+
1302
+ def __iter__(self):
1303
+ for i in range(len(self)):
1304
+ yield self[i]
1305
+
1306
+ @property
1307
+ def ids(self) -> list:
1308
+ return [e.id for e in self]
1309
+
1310
+ def find(self, id: int) -> Optional[PlaylistEntry]:
1311
+ return _entry(_lib.au_playlist_find(self._pl, id))
1312
+
1313
+ def index_of(self, id: int) -> int:
1314
+ """The entry's index, or -1."""
1315
+ i = _lib.au_playlist_index_of(self._pl, id)
1316
+ return i if i >= 0 else -1
1317
+
1318
+ def add(self, path: str, index: int = -1, title: Optional[str] = None, duration: Optional[float] = None,
1319
+ start_seconds: float = 0.0, length_seconds: float = 0.0, replaygain: Optional[ReplayGain] = None,
1320
+ user_key: Optional[str] = None) -> int:
1321
+ """A new entry before `index` (-1 = at the end), with these values; its id."""
1322
+ id = _lib.au_playlist_add(self._pl, index, _enc(path))
1323
+ _check(id, path)
1324
+ if title:
1325
+ self.set_title(id, title)
1326
+ if duration is not None:
1327
+ self.set_duration(id, duration)
1328
+ if start_seconds or length_seconds:
1329
+ self.set_range(id, start_seconds, length_seconds)
1330
+ if replaygain is not None:
1331
+ self.set_replaygain(id, replaygain)
1332
+ if user_key:
1333
+ self.set_user_key(id, user_key)
1334
+ return id
1335
+
1336
+ def add_from(self, source: "Playlist", id: int, index: int = -1) -> int:
1337
+ """A copy of source's entry `id`: the id it got (the same, unless this list has it already)."""
1338
+ return _check(_lib.au_playlist_add_from(self._pl, index, source._pl, id))
1339
+
1340
+ def add_list(self, source: "Playlist", index: int = -1) -> int:
1341
+ return _check(_lib.au_playlist_add_list(self._pl, index, source._pl))
1342
+
1343
+ def add_file(self, path_or_url: str, index: int = -1) -> int:
1344
+ """The entries of an M3U/M3U8/PLS file or URL; how many."""
1345
+ err = ctypes.c_int(0)
1346
+ p = _lib.au_playlist_read(_enc(path_or_url), ctypes.byref(err))
1347
+ if not p:
1348
+ raise Error(err.value or Result.ERR_FILE, path_or_url)
1349
+ try:
1350
+ return _check(_lib.au_playlist_add_file(self._pl, index, p))
1351
+ finally:
1352
+ _lib.au_playlist_file_release(p)
1353
+
1354
+ def add_cue(self, path_or_url: str, index: int = -1) -> int:
1355
+ """The tracks of a cue sheet, embedded cue sheet or chapters (ranges and ReplayGain values); how many."""
1356
+ err = ctypes.c_int(0)
1357
+ p = _lib.au_cue_read(_enc(path_or_url), ctypes.byref(err))
1358
+ if not p:
1359
+ raise Error(err.value or Result.ERR_FILE, path_or_url)
1360
+ try:
1361
+ return _check(_lib.au_playlist_add_cue(self._pl, index, p))
1362
+ finally:
1363
+ _lib.au_cue_release(p)
1364
+
1365
+ def remove(self, id: int) -> None:
1366
+ _check(_lib.au_playlist_remove(self._pl, id), "no such entry")
1367
+
1368
+ def clear(self) -> None:
1369
+ _check(_lib.au_playlist_clear(self._pl))
1370
+
1371
+ def move(self, id: int, index: int) -> None:
1372
+ _check(_lib.au_playlist_move(self._pl, id, index), "move")
1373
+
1374
+ def set_order(self, ids) -> None:
1375
+ """Put the entries in this order (every id once)."""
1376
+ arr, n = _ids(ids)
1377
+ _check(_lib.au_playlist_set_order(self._pl, arr, n), "not every id once")
1378
+
1379
+ def set_title(self, id: int, title: Optional[str]) -> None:
1380
+ _check(_lib.au_playlist_set_title(self._pl, id, _enc(title)))
1381
+
1382
+ def set_duration(self, id: int, seconds: float) -> None:
1383
+ _check(_lib.au_playlist_set_duration(self._pl, id, seconds))
1384
+
1385
+ def set_range(self, id: int, start_seconds: float, length_seconds: float) -> None:
1386
+ _check(_lib.au_playlist_set_range(self._pl, id, start_seconds, length_seconds))
1387
+
1388
+ def set_replaygain(self, id: int, replaygain: Optional[ReplayGain]) -> None:
1389
+ rg = replaygain._native() if replaygain is not None else None
1390
+ _check(_lib.au_playlist_set_replaygain(self._pl, id, ctypes.byref(rg) if rg is not None else None))
1391
+
1392
+ def set_user_key(self, id: int, key: Optional[str]) -> None:
1393
+ _check(_lib.au_playlist_set_user_key(self._pl, id, _enc(key)))
1394
+
1395
+ def sort(self, key: Sort = Sort.TITLE, descending: bool = False) -> None:
1396
+ """Stable: sorts combine. Text ignores ASCII case and compares numbers by value."""
1397
+ _check(_lib.au_playlist_sort(self._pl, int(key), descending))
1398
+
1399
+ def sort_by(self, key: Callable[[PlaylistEntry], object], reverse: bool = False) -> None:
1400
+ """Sort with a Python key function (stable), e.g. by data of your own looked up by user_key."""
1401
+ entries = list(self)
1402
+ entries.sort(key=key, reverse=reverse)
1403
+ self.set_order(e.id for e in entries)
1404
+
1405
+
1406
+ class PlayQueue:
1407
+ """What plays: history <- current -> up next -> the queue's playlist (see ffaudio_playlist.h)."""
1408
+
1409
+ def __init__(self):
1410
+ self._q = _lib.au_play_queue_create()
1411
+ if not self._q:
1412
+ raise Error(Result.ERR_NO_MEMORY)
1413
+ self.playlist = Playlist(_lib.au_play_queue_playlist(self._q), _owner=self)
1414
+ self.up_next = Playlist(_lib.au_play_queue_up_next(self._q), _owner=self)
1415
+
1416
+ def __del__(self):
1417
+ if getattr(self, "_q", None):
1418
+ _lib.au_play_queue_free(self._q)
1419
+ self._q = None
1420
+
1421
+ def set_playlist(self, playlist: Playlist, start_id: int = 0) -> None:
1422
+ """Play from a copy of `playlist` (same ids); start_id becomes current (0: the current entry stays)."""
1423
+ _check(_lib.au_play_queue_set_playlist(self._q, playlist._pl, start_id), "set_playlist")
1424
+
1425
+ @property
1426
+ def shuffled(self) -> bool:
1427
+ return _lib.au_play_queue_shuffled(self._q)
1428
+
1429
+ def set_shuffle(self, on: bool) -> None:
1430
+ _check(_lib.au_play_queue_set_shuffle(self._q, on))
1431
+
1432
+ def set_repeat(self, mode: Repeat) -> None:
1433
+ _check(_lib.au_play_queue_set_repeat(self._q, int(mode)))
1434
+
1435
+ def set_history_size(self, entries: int) -> None:
1436
+ _check(_lib.au_play_queue_set_history_size(self._q, entries))
1437
+
1438
+ def set_clear_on_new_playlist(self, clear: bool) -> None:
1439
+ _check(_lib.au_play_queue_set_clear_on_new_playlist(self._q, clear))
1440
+
1441
+ def set_shuffle_seed(self, seed: int) -> None:
1442
+ _check(_lib.au_play_queue_set_shuffle_seed(self._q, seed))
1443
+
1444
+ @property
1445
+ def current(self) -> Optional[PlaylistEntry]:
1446
+ return _entry(_lib.au_play_queue_current(self._q))
1447
+
1448
+ def peek_next(self) -> Optional[PlaylistEntry]:
1449
+ return _entry(_lib.au_play_queue_peek_next(self._q))
1450
+
1451
+ def set_current(self, id: int) -> None:
1452
+ _check(_lib.au_play_queue_set_current(self._q, id), "not in the queue")
1453
+
1454
+ def next(self) -> Optional[PlaylistEntry]:
1455
+ return _entry(_lib.au_play_queue_next(self._q))
1456
+
1457
+ def previous(self) -> Optional[PlaylistEntry]:
1458
+ return _entry(_lib.au_play_queue_previous(self._q))
1459
+
1460
+ @property
1461
+ def order(self) -> list:
1462
+ """The playlist in play order (its own order, or the shuffled one)."""
1463
+ return [_entry(_lib.au_play_queue_order_at(self._q, i)) for i in range(_lib.au_play_queue_order_count(self._q))]
1464
+
1465
+ @property
1466
+ def order_position(self) -> int:
1467
+ return _lib.au_play_queue_order_position(self._q)
1468
+
1469
+ def move(self, id: int, position: int) -> None:
1470
+ _check(_lib.au_play_queue_move(self._q, id, position), "move")
1471
+
1472
+ def keep_order(self) -> None:
1473
+ _check(_lib.au_play_queue_keep_order(self._q))
1474
+
1475
+ def set_order(self, ids) -> None:
1476
+ arr, n = _ids(ids)
1477
+ _check(_lib.au_play_queue_set_order(self._q, arr, n), "not every id once")
1478
+
1479
+ @property
1480
+ def history(self) -> list:
1481
+ """What played, most recent first."""
1482
+ return [_entry(_lib.au_play_queue_history_at(self._q, i))
1483
+ for i in range(_lib.au_play_queue_history_count(self._q))]
1484
+
1485
+ def clear_history(self) -> None:
1486
+ _check(_lib.au_play_queue_clear_history(self._q))
1487
+
1488
+
1489
+ #+-----------------------------------------------------+
1490
+ #| Lyrics |
1491
+ #+-----------------------------------------------------+
1492
+
1493
+ class LyricsSource(enum.IntEnum):
1494
+ LRC_FILE = 0
1495
+ TAG = 1
1496
+ TEXT = 2
1497
+
1498
+
1499
+ @dataclass(frozen=True)
1500
+ class LyricsLine:
1501
+ time: float # seconds from the start of the file; -1 in lyrics without times
1502
+ text: str
1503
+
1504
+
1505
+ @dataclass(frozen=True)
1506
+ class Lyrics:
1507
+ synced: bool
1508
+ lines: tuple
1509
+ text: str
1510
+ language: str # ISO 639-2 from the tag, "" when unknown
1511
+ source: LyricsSource
1512
+
1513
+ def line_at(self, seconds: float) -> int:
1514
+ """Index of the line sung at `seconds` (the last one at or before it); -1 before the first or unsynced."""
1515
+ import bisect
1516
+ if not self.synced:
1517
+ return -1
1518
+ return bisect.bisect_right([ln.time for ln in self.lines], seconds) - 1
1519
+
1520
+
1521
+ def _lyrics(p) -> Lyrics:
1522
+ try:
1523
+ v = p.contents
1524
+ lines = tuple(LyricsLine(v.lines[i].contents.time, _dec(v.lines[i].contents.text) or "")
1525
+ for i in range(v.count))
1526
+ return Lyrics(v.synced, lines, _dec(v.text) or "", _dec(v.language) or "", LyricsSource(v.source))
1527
+ finally:
1528
+ _lib.au_lyrics_release(p)
1529
+
1530
+
1531
+ def lyrics_read(path_or_url: str) -> Optional[Lyrics]:
1532
+ """A file's lyrics: a .lrc file next to it, else its tags. None when it has none."""
1533
+ err = ctypes.c_int(0)
1534
+ p = _lib.au_lyrics_read(_enc(path_or_url), ctypes.byref(err))
1535
+ if not p:
1536
+ if err.value == Result.ERR_NOTHING_TO_DO:
1537
+ return None
1538
+ raise Error(err.value or Result.ERR_FILE, path_or_url)
1539
+ return _lyrics(p)
1540
+
1541
+
1542
+ def lyrics_parse(text: str) -> Lyrics:
1543
+ """LRC or plain lyrics text."""
1544
+ data = _enc(text)
1545
+ err = ctypes.c_int(0)
1546
+ p = _lib.au_lyrics_parse(data, len(data), ctypes.byref(err))
1547
+ if not p:
1548
+ raise Error(err.value or Result.ERR_INVALID_ARGUMENT)
1549
+ return _lyrics(p)
1550
+
1551
+
1552
+ #+-----------------------------------------------------+
1553
+ #| Decoder and waveform |
1554
+ #+-----------------------------------------------------+
1555
+
1556
+ @dataclass
1557
+ class DecodeOptions:
1558
+ """What to decode and how; 0 = the file's own channels / rate, length 0 = to the end."""
1559
+ channels: int = 0
1560
+ sample_rate: int = 0
1561
+ start_seconds: float = 0.0
1562
+ length_seconds: float = 0.0
1563
+ filters: Optional[str] = None
1564
+ http_headers: Optional[str] = None
1565
+
1566
+ def _native(self):
1567
+ o = _lib.au_decode_options_create()
1568
+ if not o:
1569
+ raise Error(Result.ERR_NO_MEMORY)
1570
+ try:
1571
+ _check(_lib.au_decode_options_set_format(o, self.channels, self.sample_rate), "format")
1572
+ _check(_lib.au_decode_options_set_range(o, self.start_seconds, self.length_seconds), "range")
1573
+ if self.filters:
1574
+ _check(_lib.au_decode_options_set_filters(o, _enc(self.filters)), f"filters {self.filters!r}")
1575
+ if self.http_headers:
1576
+ _check(_lib.au_decode_options_set_http_headers(o, _enc(self.http_headers)))
1577
+ except Error:
1578
+ _lib.au_decode_options_free(o)
1579
+ raise
1580
+ return o
1581
+
1582
+
1583
+ def _with_decode_options(options: Optional[DecodeOptions], fn):
1584
+ o = options._native() if options is not None else None
1585
+ try:
1586
+ return fn(o)
1587
+ finally:
1588
+ if o:
1589
+ _lib.au_decode_options_free(o)
1590
+
1591
+
1592
+ class Decoder:
1593
+ """A file or URL decoded to float samples, without the player. Use it from one thread (interrupt() from any)."""
1594
+
1595
+ def __init__(self, path: str, options: Optional[DecodeOptions] = None):
1596
+ err = ctypes.c_int(0)
1597
+ self._d = _with_decode_options(options, lambda o: _lib.au_decoder_open(_enc(path), o, ctypes.byref(err)))
1598
+ if not self._d:
1599
+ raise Error(err.value or Result.ERR_FILE, path)
1600
+ self.channels = _lib.au_decoder_channels(self._d)
1601
+ self.sample_rate = _lib.au_decoder_sample_rate(self._d)
1602
+ self._buf = None
1603
+
1604
+ def __del__(self):
1605
+ self.close()
1606
+
1607
+ def __enter__(self):
1608
+ return self
1609
+
1610
+ def __exit__(self, *exc):
1611
+ self.close()
1612
+
1613
+ def close(self) -> None:
1614
+ if getattr(self, "_d", None):
1615
+ _lib.au_decoder_close(self._d)
1616
+ self._d = None
1617
+
1618
+ def _handle(self):
1619
+ if not self._d:
1620
+ raise Error(Result.ERR_INVALID_ARGUMENT, "decoder is closed")
1621
+ return self._d
1622
+
1623
+ @property
1624
+ def duration(self) -> float:
1625
+ """Seconds in the file (or range); -1 when unknown."""
1626
+ return _lib.au_decoder_duration(self._handle())
1627
+
1628
+ @property
1629
+ def position(self) -> float:
1630
+ return _lib.au_decoder_position(self._handle())
1631
+
1632
+ def read(self, frames: int = 4096) -> "array.array":
1633
+ """Up to `frames` frames as interleaved floats (array('f'), frames x channels); empty at the end."""
1634
+ import array
1635
+ n_floats = frames * self.channels
1636
+ if self._buf is None or len(self._buf) < n_floats:
1637
+ self._buf = (ctypes.c_float * n_floats)()
1638
+ got = _lib.au_decoder_read(self._handle(), self._buf, frames)
1639
+ _check(got)
1640
+ out = array.array("f")
1641
+ out.frombytes(ctypes.string_at(self._buf, got * self.channels * 4))
1642
+ return out
1643
+
1644
+ def __iter__(self):
1645
+ while True:
1646
+ block = self.read()
1647
+ if not block:
1648
+ return
1649
+ yield block
1650
+
1651
+ def seek(self, seconds: float) -> None:
1652
+ _check(_lib.au_decoder_seek(self._handle(), seconds))
1653
+
1654
+ def info(self) -> MediaInfo:
1655
+ p = _lib.au_decoder_info(self._handle())
1656
+ if not p:
1657
+ raise Error(Result.ERR_NO_MEMORY)
1658
+ try:
1659
+ return _media_info(p)
1660
+ finally:
1661
+ _lib.au_media_info_release(p)
1662
+
1663
+ def interrupt(self) -> None:
1664
+ """From any thread: the read in progress and every later one raise ERR_CANCELLED."""
1665
+ if self._d:
1666
+ _lib.au_decoder_interrupt(self._d)
1667
+
1668
+
1669
+ @dataclass(frozen=True)
1670
+ class Waveform:
1671
+ duration: float
1672
+ seconds_per_point: float
1673
+ min: tuple # per point, the lowest sample (all channels)
1674
+ max: tuple
1675
+ rms: tuple
1676
+
1677
+
1678
+ def waveform(path: str, points: int = 800, options: Optional[DecodeOptions] = None,
1679
+ progress: Optional[Callable[[float], bool]] = None) -> Waveform:
1680
+ """Lowest, highest and RMS level of `points` equal slices of a file. progress(fraction) -> False cancels."""
1681
+ err = ctypes.c_int(0)
1682
+ cb = _n.AuWaveformProgressFn(lambda f, _u: bool(progress(f))) if progress else _n.AuWaveformProgressFn()
1683
+ p = _with_decode_options(options, lambda o: _lib.au_waveform_analyze(_enc(path), o, points, cb, None,
1684
+ ctypes.byref(err)))
1685
+ if not p:
1686
+ raise Error(err.value or Result.ERR_FILE, path)
1687
+ try:
1688
+ w = p.contents
1689
+ c = w.count
1690
+ return Waveform(w.duration, w.seconds_per_point, tuple(w.min[:c]), tuple(w.max[:c]), tuple(w.rms[:c]))
1691
+ finally:
1692
+ _lib.au_waveform_release(p)
1693
+
1694
+
1695
+ __all__ = [n for n in dir() if not n.startswith("_") and n not in ("ctypes", "enum", "math", "threading", "dataclass",
1696
+ "field", "Callable", "Iterable", "Optional",
1697
+ "Sequence")]