hum 1.0.2__tar.gz → 1.0.4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.2
3
+ Version: 1.0.4
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -346,51 +346,78 @@ def auto_play(obj):
346
346
 
347
347
  class ReplayEvents:
348
348
  """
349
- An iterator that replays a sequence of timestamped knob updates in real-time.
349
+ Replays timestamped knob updates, optionally emitting None or sleeping to simulate
350
+ timing.
350
351
 
351
- This class takes a list of (timestamp, KnobsDict) events and yields
352
- each update at the correct real-time intervals, automatically sleeping
353
- between updates to recreate the original timing.
352
+ Parameters
353
+ ----------
354
+ events : List[Tuple[float, KnobsDict]]
355
+ A list of (timestamp, knob updates) pairs.
356
+ emit_none : bool
357
+ If True, yields None to simulate time passage; if False, uses time.sleep.
358
+ time_scale : float
359
+ Time compression/stretch factor: 2.0 = 2x faster, 0.5 = half speed.
360
+ ensure_sorted : bool
361
+ Whether to sort the events by timestamp.
354
362
 
355
- Usage:
356
- ------
357
- Simply wrap your recorded control events and feed them into play_events:
363
+ Example
364
+ -------
358
365
 
359
- synth.play_events(ReplayEvents(control_events))
366
+ Consider these events:
360
367
 
361
- Why use ReplayEvents?
362
- ----------------------
363
- - Centralizes real-time replay logic.
364
- - Makes it easy to later add speed controls, jitter, filtering, etc.
365
- - Keeps `play_events` clean and flexible.
366
- - Supports a future where playback streams can be manipulated easily.
368
+ >>> events = [
369
+ ... (0.0, {'freq': 220}),
370
+ ... (0.05, {'freq': 330}),
371
+ ... (0.10, {'freq': 440}),
372
+ ... ]
373
+
374
+ >>> list(ReplayEvents(events, time_scale=50.0))
375
+ [{'freq': 220}, {'freq': 330}, {'freq': 440}]
376
+
377
+ That is, we should really get back the same events, without the timestamps.
378
+
379
+ >>> list(ReplayEvents(events, time_scale=10.0))
380
+ [{'freq': 220}, {'freq': 330}, {'freq': 440}]
381
+
382
+ >>> list(ReplayEvents(events, time_scale=10.0)) == list(dict(events).values())
383
+ True
384
+
385
+ The timestamps are used to pace when new events are emitted.
386
+ Note: Usually we'll use time_scale=1.0 (the default), but we use time_scale=50 here
387
+ just to accelerate the tests.
388
+
389
+ The default is to sleep until the next event should be emitted, but you can also
390
+ emulate a real-time sensor reads by setting emit_none=True.
391
+ In this case, the instance will emit `None` if there's no event to emit at that time.
392
+
393
+ >>> list(ReplayEvents(events, emit_none=True, time_scale=2.0)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
394
+ [{'freq': 220}, None, ...]
367
395
 
368
- Parameters
369
- ----------
370
- control_events : List[Tuple[float, KnobsDict]]
371
- A list of (timestamp, knob updates) pairs.
372
- speed : float
373
- A multiplier for playback speed. 1.0 = normal speed,
374
- 2.0 = twice as fast, 0.5 = half speed, etc. Default is 1.0.
375
396
  """
376
397
 
377
- def __init__(
378
- self, control_events: List[Tuple[float, KnobsDict]], speed: float = 1.0
379
- ):
380
- self.control_events = control_events
381
- self.speed = speed
398
+ def __init__(self, events, *, emit_none=True, time_scale=1.0, ensure_sorted=False):
399
+ if ensure_sorted:
400
+ if not events:
401
+ raise ValueError("Events list must not be empty.")
402
+ self.events = sorted(events, key=lambda x: x[0])
403
+ else:
404
+ self.events = events
405
+ self.emit_none = emit_none
406
+ self.time_scale = time_scale
382
407
 
383
- def __iter__(self) -> Iterator[Union[KnobsDict, None]]:
384
- if not self.control_events:
385
- return
386
- base_time, first_update = self.control_events[0]
387
- yield first_update
388
- for (curr_time, updates), (next_time, _) in zip(
389
- self.control_events, self.control_events[1:]
390
- ):
391
- sleep_duration = (next_time - curr_time) / self.speed
392
- time.sleep(max(sleep_duration, 0))
393
- yield updates
408
+ def __iter__(self):
409
+ prev_time = self.events[0][0]
410
+ for timestamp, knobs in self.events:
411
+ delay = (timestamp - prev_time) / self.time_scale
412
+ if self.emit_none:
413
+ steps = int(delay / 0.01)
414
+ for _ in range(steps):
415
+ yield None
416
+ else:
417
+ if delay > 0:
418
+ time.sleep(delay)
419
+ yield knobs
420
+ prev_time = timestamp
394
421
 
395
422
 
396
423
  def list_if_string(x):
@@ -717,43 +744,7 @@ class Synth(MutableMapping):
717
744
  if self._record_on_start:
718
745
  self.stop_recording()
719
746
 
720
- def play_events(
721
- self,
722
- events: Iterator[Union[KnobsDict, None]],
723
- *,
724
- idle_sleep_time=0.01,
725
- inter_event_delay=0,
726
- tail_time=1.0,
727
- ):
728
- """
729
- Play an event stream, applying updates from an iterator of KnobsDicts or None.
730
-
731
- Parameters
732
- ----------
733
- events : Iterator[Union[KnobsDict, None]]
734
- An iterator yielding KnobsDict updates (or None for idle).
735
- tail_time : float
736
- Time to wait after finishing event playback to allow sound to finish.
737
- idle_sleep_time : float
738
- Time to sleep if the iterator yields None (idle).
739
- inter_event_delay : float
740
- Time to sleep systematically after each non-None event.
741
- """
742
- with self:
743
- for event in events:
744
- if event is None:
745
- time.sleep(idle_sleep_time)
746
- continue
747
-
748
- self.update(event)
749
-
750
- if inter_event_delay > 0:
751
- time.sleep(inter_event_delay)
752
-
753
- time.sleep(tail_time)
754
-
755
- def replay_events(self, control_events, *, tail_time=1.0):
756
- self.play_events(ReplayEvents(control_events), tail_time=tail_time)
747
+ # Rendering events (playing recordings etc.) --------------------------------------
757
748
 
758
749
  def render_events(
759
750
  self,
@@ -764,7 +755,7 @@ class Synth(MutableMapping):
764
755
  file_format="wav",
765
756
  suffix_buffer_seconds=0.0,
766
757
  ):
767
- """Render the recording to a file or return it processed by the egress function."""
758
+ """Render the control events to an audio file or return it via an egress function."""
768
759
  if not control_events:
769
760
  control_events = self.get_recording()
770
761
  if not control_events:
@@ -784,25 +775,12 @@ class Synth(MutableMapping):
784
775
  synth_output = self._synth_func(**raw_params).out()
785
776
  table_recorder = TableRec(synth_output, table=table).play()
786
777
 
787
- try:
788
- for i, (event_time, updates) in enumerate(normalized):
789
- next_time = (
790
- normalized[i + 1][TIME_IDX]
791
- if i + 1 < len(normalized)
792
- else total_duration
793
- )
794
- dur = next_time - event_time
795
-
796
- for key, val in updates.items():
797
- if isinstance(val, dict):
798
- for attr in ["value", "time", "mul", "add"]:
799
- if attr in val:
800
- setattr(raw_params[key], attr, val[attr])
801
- else:
802
- raw_params[key].value = val
778
+ def delay_func(dur):
779
+ server.recordOptions(dur=dur)
780
+ server.start()
803
781
 
804
- server.recordOptions(dur=dur)
805
- server.start()
782
+ try:
783
+ self._apply_event_sequence(normalized, delay_func, raw_params=raw_params)
806
784
  finally:
807
785
  table_recorder.stop()
808
786
 
@@ -824,6 +802,85 @@ class Synth(MutableMapping):
824
802
  else:
825
803
  raise ValueError("Invalid egress")
826
804
 
805
+ def play_events(
806
+ self,
807
+ events: Union[Iterator[Union[KnobsDict, None]], List[Tuple[float, KnobsDict]]],
808
+ *,
809
+ idle_sleep_time=0.01,
810
+ inter_event_delay=0,
811
+ tail_time=1.0,
812
+ ):
813
+ """
814
+ Play an event stream, applying updates from either:
815
+ - an iterator yielding KnobsDicts or None (real-time stream), or
816
+ - a list of (timestamp, KnobsDict) pairs (automatically wrapped).
817
+ """
818
+ # Auto-wrap if we detect a list of (timestamp, KnobsDict) format
819
+ if isinstance(events, list) and events and isinstance(events[0], tuple):
820
+ ts, ev = events[0]
821
+ if isinstance(ts, (int, float)) and isinstance(ev, dict):
822
+ events = ReplayEvents(events)
823
+
824
+ filtered_events = []
825
+ curr_time = 0.0
826
+ for e in events:
827
+ if e is not None:
828
+ filtered_events.append((curr_time, e))
829
+ curr_time += inter_event_delay
830
+ else:
831
+ time.sleep(idle_sleep_time)
832
+
833
+ def delay_func(dur):
834
+ time.sleep(dur)
835
+
836
+ with self:
837
+ self._apply_event_sequence(filtered_events, delay_func)
838
+ time.sleep(tail_time)
839
+
840
+ def replay_events(self, control_events, *, tail_time=1.0):
841
+ self.play_events(ReplayEvents(control_events), tail_time=tail_time)
842
+
843
+ def _apply_event_sequence(self, events, delay_func, raw_params=None):
844
+ """
845
+ Apply a sequence of events using a delay function.
846
+
847
+ Parameters
848
+ ----------
849
+ events : Iterable[Tuple[float, KnobsDict]]
850
+ Timestamped knob updates.
851
+ delay_func : Callable[[float], None]
852
+ Function to call to delay between events (e.g., time.sleep or offline record trigger).
853
+ raw_params : Optional[Dict[str, SigTo]]
854
+ If provided, updates will be applied to this dict instead of self.knobs.
855
+ """
856
+ if not events:
857
+ return
858
+
859
+ TIME_IDX = 0
860
+ base_time = events[0][TIME_IDX]
861
+ normalized = [(t - base_time, knobs) for t, knobs in events]
862
+
863
+ for i, (event_time, updates) in enumerate(normalized):
864
+ next_time = normalized[i + 1][TIME_IDX] if i + 1 < len(normalized) else None
865
+ dur = next_time - event_time if next_time is not None else None
866
+
867
+ for key, val in updates.items():
868
+ target = raw_params[key] if raw_params else self.knobs[key]
869
+ if isinstance(target, SigTo):
870
+ if isinstance(val, dict):
871
+ for attr in ["value", "time", "mul", "add"]:
872
+ if attr in val:
873
+ setattr(target, attr, val[attr])
874
+ else:
875
+ target.value = val
876
+ elif raw_params is None:
877
+ self.knobs[key] = val
878
+
879
+ if dur is not None:
880
+ delay_func(dur)
881
+
882
+ # Context manager support ---------------------------------------------------------
883
+
827
884
  def __del__(self):
828
885
  if self._server is not None:
829
886
  self._server.stop()
@@ -835,6 +892,20 @@ class Synth(MutableMapping):
835
892
  def __exit__(self, exc_type, exc_value, traceback):
836
893
  self.stop()
837
894
 
895
+ # Handling the decorator mechanisms -----------------------------------------------
896
+
897
+ def __new__(cls, synth_func=None, **kwargs):
898
+ # Case 1: Used directly as @Synth
899
+ if synth_func is not None and callable(synth_func):
900
+ instance = super().__new__(cls)
901
+ instance.__init__(synth_func, **kwargs)
902
+ return instance
903
+ # Case 2: Used with config as @Synth(knob_params=...)
904
+ else:
905
+ return partial(cls, **kwargs)
906
+
907
+ # MutableMapping interface --------------------------------------------------------
908
+
838
909
  @property
839
910
  def __signature__(self):
840
911
  return Signature(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hum
3
- Version: 1.0.2
3
+ Version: 1.0.4
4
4
  Summary: A python synthesizer for creating and manipulating audio signals.
5
5
  Home-page: https://github.com/thorwhalen/hum
6
6
  License: mit
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = hum
3
- version = 1.0.2
3
+ version = 1.0.4
4
4
  url = https://github.com/thorwhalen/hum
5
5
  platforms = any
6
6
  description_file = README.md
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes