ufor 0.1.0__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.
Files changed (57) hide show
  1. ufor/__init__.py +0 -0
  2. ufor/accidentals.py +85 -0
  3. ufor/arrangement.py +213 -0
  4. ufor/assets.py +46 -0
  5. ufor/automation.py +171 -0
  6. ufor/base.py +42 -0
  7. ufor/binding.py +217 -0
  8. ufor/broadcast.py +233 -0
  9. ufor/codec.py +91 -0
  10. ufor/composition.py +748 -0
  11. ufor/control.py +53 -0
  12. ufor/effects.py +761 -0
  13. ufor/encoding.py +33 -0
  14. ufor/envelope.py +164 -0
  15. ufor/events.py +159 -0
  16. ufor/expression.py +50 -0
  17. ufor/fixture.py +227 -0
  18. ufor/interface.py +214 -0
  19. ufor/lfo.py +95 -0
  20. ufor/library.py +293 -0
  21. ufor/library_files.py +231 -0
  22. ufor/light_animation.py +322 -0
  23. ufor/light_math.py +105 -0
  24. ufor/lights.py +131 -0
  25. ufor/modulation.py +198 -0
  26. ufor/musical.py +23 -0
  27. ufor/number.py +17 -0
  28. ufor/oscillator.py +48 -0
  29. ufor/playback.py +159 -0
  30. ufor/preset.py +15 -0
  31. ufor/py.typed +0 -0
  32. ufor/recording.py +291 -0
  33. ufor/references.py +11 -0
  34. ufor/samples/__init__.py +0 -0
  35. ufor/samples/controls.py +23 -0
  36. ufor/samples/crossfade.py +52 -0
  37. ufor/samples/enums.py +60 -0
  38. ufor/samples/instrument.py +353 -0
  39. ufor/samples/metadata.py +22 -0
  40. ufor/samples/playback.py +80 -0
  41. ufor/samples/processing.py +245 -0
  42. ufor/samples/selection.py +92 -0
  43. ufor/scala.py +51 -0
  44. ufor/scale.py +202 -0
  45. ufor/score.py +23 -0
  46. ufor/selector.py +111 -0
  47. ufor/sequence.py +54 -0
  48. ufor/sfz.py +1734 -0
  49. ufor/slideshow.py +248 -0
  50. ufor/streams.py +31 -0
  51. ufor/time.py +51 -0
  52. ufor/tuning.py +111 -0
  53. ufor/vl70.py +104 -0
  54. ufor-0.1.0.dist-info/METADATA +68 -0
  55. ufor-0.1.0.dist-info/RECORD +57 -0
  56. ufor-0.1.0.dist-info/WHEEL +4 -0
  57. ufor-0.1.0.dist-info/licenses/LICENSE +22 -0
ufor/__init__.py ADDED
File without changes
ufor/accidentals.py ADDED
@@ -0,0 +1,85 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import StrEnum, auto
4
+
5
+ FLAT, SHARP = '♭', '♯'
6
+ HALF_FLAT, HALF_SHARP = 'v', '^'
7
+ CANONICAL = {'b': FLAT, '#': SHARP}
8
+ ACCIDENTALS = FLAT + SHARP + HALF_FLAT + HALF_SHARP
9
+ ACCIDENTAL_CANONICAL = {
10
+ '#': SHARP,
11
+ 'b': FLAT,
12
+ FLAT: FLAT,
13
+ SHARP: SHARP,
14
+ HALF_FLAT: HALF_FLAT,
15
+ HALF_SHARP: HALF_SHARP,
16
+ }
17
+
18
+
19
+ class Accidentals(StrEnum):
20
+ # No accidentals are allowed
21
+ none = auto()
22
+
23
+ # Standard accidentals are allowed, with just # and -
24
+ whole = auto()
25
+
26
+ # Extended accidentals are allowed:
27
+ # + means up one step
28
+ # # means up two steps
29
+ # - means down one step
30
+ # b means down two steps
31
+ half = auto()
32
+
33
+
34
+ class AccidentalNames:
35
+ def __init__(self, accidentals: Accidentals) -> None:
36
+ self.accidentals = accidentals
37
+
38
+ @property
39
+ def symbols(self) -> str:
40
+ return {
41
+ Accidentals.none: '',
42
+ Accidentals.whole: FLAT + SHARP,
43
+ Accidentals.half: ACCIDENTALS,
44
+ }[self.accidentals]
45
+
46
+ def canonical(self, s: str) -> str:
47
+ for k, v in CANONICAL.items():
48
+ s = s.replace(k, v)
49
+ return s
50
+
51
+ def name(self, note: str, offset: int, use_sharp: bool) -> str:
52
+ match self.accidentals:
53
+ case Accidentals.none:
54
+ return note
55
+ case Accidentals.whole:
56
+ accidental = SHARP if use_sharp else FLAT
57
+ return note + accidental * offset
58
+ case Accidentals.half:
59
+ large = SHARP if use_sharp else FLAT
60
+ small = HALF_SHARP if use_sharp else HALF_FLAT
61
+ return note + large * (offset // 2) + small * (offset % 2)
62
+ raise AssertionError(f'Unknown accidentals {self.accidentals}')
63
+
64
+ def flat_sharp_names(
65
+ self, note: str, next_note: str, interval: int, offset: int
66
+ ) -> tuple[str, str]:
67
+ flat = self.name(next_note, interval - offset, False)
68
+ sharp = self.name(note, offset, True)
69
+ if self.accidentals == Accidentals.half and offset > interval // 2:
70
+ return sharp, flat
71
+ return flat, sharp
72
+
73
+ def split_note(self, s: str, names: str) -> tuple[str, str]:
74
+ if s and s[0] in names:
75
+ note = s[0]
76
+ s = s[1:]
77
+ while (
78
+ s
79
+ and (accidental := ACCIDENTAL_CANONICAL.get(s[0]))
80
+ and accidental in self.symbols
81
+ ):
82
+ note += accidental
83
+ s = s[1:]
84
+ return note, s
85
+ raise ValueError(f'Bad number {s=}')
ufor/arrangement.py ADDED
@@ -0,0 +1,213 @@
1
+ from graphlib import CycleError, TopologicalSorter
2
+ from typing import Literal, Self
3
+
4
+ from pydantic import Field, model_validator
5
+
6
+ from .base import Identifier, Model, unique
7
+ from .interface import (
8
+ Connection,
9
+ Input,
10
+ InputSelection,
11
+ InterfaceScore,
12
+ MixBinding,
13
+ OutputSelection,
14
+ Part,
15
+ )
16
+ from .streams import AudioType, FileDestination
17
+ from .time import Timebase
18
+
19
+
20
+ class TrackSpec(Model):
21
+ name: Identifier
22
+ stream: AudioType
23
+
24
+
25
+ class BusSpec(Model):
26
+ name: Identifier
27
+ stream: AudioType
28
+ gain: float = 1.0
29
+
30
+
31
+ class ClipSpec(Model):
32
+ name: Identifier
33
+ source: OutputSelection
34
+ track: Identifier
35
+ source_start: int = Field(ge=0, strict=True)
36
+ source_end: int = Field(gt=0, strict=True)
37
+ timeline_start: int = Field(ge=0, strict=True)
38
+ gain: float = 1.0
39
+
40
+ @model_validator(mode='after')
41
+ def validate_interval(self) -> Self:
42
+ if self.source_end <= self.source_start:
43
+ raise ValueError('source_end must be greater than source_start')
44
+ return self
45
+
46
+
47
+ class RouteSpec(Model):
48
+ source: Identifier
49
+ destination: Identifier
50
+ gain: float = 1.0
51
+
52
+
53
+ class ControlClip(Model):
54
+ """Place a reusable automation score on this arrangement's timeline."""
55
+
56
+ name: Identifier
57
+ source: OutputSelection
58
+ source_start: int = Field(strict=True)
59
+ source_end: int = Field(strict=True)
60
+ timeline_start: int = Field(ge=0, strict=True)
61
+
62
+ @model_validator(mode='after')
63
+ def validate_interval(self) -> Self:
64
+ if self.source_end <= self.source_start:
65
+ raise ValueError('source_end must be greater than source_start')
66
+ return self
67
+
68
+
69
+ class Arrangement(Model):
70
+ timebase: Identifier
71
+ media_types: list[str] = Field(default_factory=lambda: ['audio'])
72
+ parts: list[Part] = Field(default_factory=list)
73
+ connections: list[Connection] = Field(default_factory=list)
74
+ tracks: list[TrackSpec] = Field(default_factory=list)
75
+ buses: list[BusSpec] = Field(default_factory=list)
76
+ clips: list[ClipSpec] = Field(default_factory=list)
77
+ routes: list[RouteSpec] = Field(default_factory=list)
78
+ control_clips: list[ControlClip] = Field(default_factory=list)
79
+
80
+ @model_validator(mode='after')
81
+ def graph_references(self) -> Self:
82
+ for kind, items in (
83
+ ('name', self.parts),
84
+ ('track', self.tracks),
85
+ ('bus', self.buses),
86
+ ('clip', self.clips),
87
+ ('control clip', self.control_clips),
88
+ ):
89
+ unique((i.name for i in items), f'{kind} ID')
90
+ unique(((r.source, r.destination) for r in self.routes), 'route')
91
+ tracks = {t.name: t.stream for t in self.tracks}
92
+ buses = {b.name: b.stream for b in self.buses}
93
+ if overlap := tracks.keys() & buses.keys():
94
+ raise ValueError(f'Track and bus IDs collide: {sorted(overlap)}')
95
+ streams = tracks | buses
96
+ sources = {n.name for n in self.parts}
97
+ for clip in self.clips:
98
+ if clip.source.name not in sources:
99
+ raise ValueError(f'Clip {clip.name}: unknown source {clip.source}')
100
+ if clip.track not in tracks:
101
+ raise ValueError(f'Clip {clip.name}: unknown track {clip.track}')
102
+ for route in self.routes:
103
+ if route.source not in streams:
104
+ raise ValueError(f'Route has unknown source {route.source}')
105
+ if route.destination not in buses:
106
+ raise ValueError(
107
+ f'Route has unknown destination bus {route.destination}'
108
+ )
109
+ if streams[route.source] != buses[route.destination]:
110
+ raise ValueError('Route channel layouts and timebases must match')
111
+ _ = self.bus_order
112
+ for clip in self.control_clips:
113
+ if clip.source.name not in sources:
114
+ raise ValueError(
115
+ f'Control clip {clip.name}: unknown source {clip.source}'
116
+ )
117
+ unique((c.destination for c in self.connections), 'input connection')
118
+ for connection in self.connections:
119
+ if (
120
+ connection.source.name not in sources
121
+ or connection.destination.name not in sources
122
+ ):
123
+ raise ValueError('connection references an unknown part')
124
+ try:
125
+ list(
126
+ TopologicalSorter(
127
+ {
128
+ n.name: [
129
+ c.source.name
130
+ for c in self.connections
131
+ if c.destination.name == n.name
132
+ ]
133
+ for n in self.parts
134
+ }
135
+ ).static_order()
136
+ )
137
+ except CycleError as error:
138
+ raise ValueError('Connection cycle') from error
139
+ return self
140
+
141
+ @property
142
+ def bus_order(self) -> list[str]:
143
+ buses = {b.name for b in self.buses}
144
+ dependencies = {
145
+ b.name: [
146
+ r.source
147
+ for r in self.routes
148
+ if r.destination == b.name and r.source in buses
149
+ ]
150
+ for b in self.buses
151
+ }
152
+ try:
153
+ return list(TopologicalSorter(dependencies).static_order())
154
+ except CycleError as error:
155
+ raise ValueError(f'Routing cycle: {error.args[1]}') from error
156
+
157
+
158
+ class ArrangementScore(InterfaceScore):
159
+ kind: Literal['arrangement'] = 'arrangement'
160
+ timebases: list[Timebase] = Field(min_length=1, max_length=1)
161
+ body: Arrangement
162
+ destinations: list[FileDestination] = Field(default_factory=list)
163
+
164
+ @model_validator(mode='after')
165
+ def audio_clock(self) -> Self:
166
+ outputs = {p.name for p in self.outputs}
167
+ if any(d.output not in outputs for d in self.destinations):
168
+ raise ValueError('Destination references an unknown output')
169
+ parts = {n.name for n in self.body.parts}
170
+ tracks = {t.name: t.stream for t in self.body.tracks}
171
+ buses = {b.name: b.stream for b in self.body.buses}
172
+ forwarded = []
173
+ for point in [*self.inputs, *self.outputs]:
174
+ binding = point.binding
175
+ if isinstance(binding, MixBinding):
176
+ stream = (
177
+ tracks.get(binding.track)
178
+ if binding.track is not None
179
+ else buses.get(binding.bus)
180
+ )
181
+ if stream != point.stream:
182
+ raise ValueError(
183
+ 'mix export requires a matching output contract '
184
+ 'and existing track/bus'
185
+ )
186
+ elif isinstance(binding, (InputSelection, OutputSelection)):
187
+ if binding.name not in parts:
188
+ raise ValueError('binding references an unknown part')
189
+ if isinstance(point, Input):
190
+ forwarded.append(binding)
191
+ else:
192
+ raise ValueError(
193
+ 'arrangement input/output requires a mix or part binding'
194
+ )
195
+ unique(
196
+ [*forwarded, *(c.destination for c in self.body.connections)],
197
+ 'input binding',
198
+ )
199
+ if any(p.binding.name not in parts for p in self.parameters):
200
+ raise ValueError('parameter binding references an unknown part')
201
+ clock = self.timebases[0]
202
+ if any(
203
+ n.stream.timebase != clock.name
204
+ for n in [*self.body.tracks, *self.body.buses]
205
+ ):
206
+ raise ValueError('audio port references an unknown timebase')
207
+ if self.body.timebase != clock.name:
208
+ raise ValueError('arrangement references an unknown timebase')
209
+ if clock.rate.denominator != 1:
210
+ raise ValueError(
211
+ 'audio arrangement rate must be integer samples per second'
212
+ )
213
+ return self
ufor/assets.py ADDED
@@ -0,0 +1,46 @@
1
+ """Asset identity and portable paths, without loading payloads."""
2
+
3
+ from pathlib import PurePosixPath, PureWindowsPath
4
+ from typing import Self
5
+ from urllib.parse import urlsplit
6
+
7
+ from pydantic import Field, field_validator, model_validator
8
+
9
+ from .base import Identifier, Model
10
+
11
+
12
+ class Asset(Model):
13
+ name: Identifier
14
+ path: str = Field(min_length=1)
15
+ encoding: str = Field(min_length=1)
16
+ byte_length: int = Field(ge=0, strict=True)
17
+ sha256: str = Field(pattern=r'^[0-9a-f]{64}$')
18
+
19
+ @field_validator('path')
20
+ @classmethod
21
+ def portable_path(cls, value: str) -> str:
22
+ path = PurePosixPath(value)
23
+ if (
24
+ path.is_absolute()
25
+ or PureWindowsPath(value).drive
26
+ or urlsplit(value).scheme
27
+ or '\\' in value
28
+ or '..' in path.parts
29
+ or str(path) == '.'
30
+ ):
31
+ raise ValueError('asset path must remain inside the document directory')
32
+ return value
33
+
34
+
35
+ class AudioDescription(Model):
36
+ timebase: Identifier
37
+ channels: list[str] = Field(min_length=1)
38
+ frames: int = Field(ge=0, strict=True)
39
+
40
+ @model_validator(mode='after')
41
+ def named_channels(self) -> Self:
42
+ if any(not c for c in self.channels):
43
+ raise ValueError('channels must have names')
44
+ if len(self.channels) != len(set(self.channels)):
45
+ raise ValueError('channel names must be unique')
46
+ return self
ufor/automation.py ADDED
@@ -0,0 +1,171 @@
1
+ """Portable scalar timeline automation, evaluated in one resolved scope."""
2
+
3
+ from enum import StrEnum, auto
4
+ from fractions import Fraction
5
+ from itertools import pairwise
6
+ from math import fsum, prod
7
+ from typing import Literal, Self
8
+
9
+ from pydantic import Field, StrictBool, model_validator
10
+
11
+ from .base import Identifier, Model, Number, unique
12
+ from .control import Scope
13
+ from .interface import ControlBinding, ControlType, InterfaceScore, Output
14
+ from .modulation import Operation, Target, Unit
15
+ from .time import Timebase
16
+
17
+
18
+ class Quantity(StrEnum):
19
+ gain = auto()
20
+ frequency = auto()
21
+ gate = auto()
22
+
23
+
24
+ class Interpolation(StrEnum):
25
+ hold = auto()
26
+ linear = auto()
27
+
28
+
29
+ class Knot(Model):
30
+ tick: int = Field(strict=True)
31
+ value: Number | StrictBool
32
+
33
+
34
+ class TimelineCurve(Model):
35
+ name: Identifier
36
+ unit: Unit
37
+ interpolation: Interpolation = Interpolation.linear
38
+ knots: list[Knot] = Field(min_length=1)
39
+ operation: Operation | None = None
40
+
41
+ @model_validator(mode='after')
42
+ def ordered(self) -> Self:
43
+ if any(a.tick >= b.tick for a, b in pairwise(self.knots)):
44
+ raise ValueError('curve ticks must be strictly increasing')
45
+ return self
46
+
47
+
48
+ class Automation(Model):
49
+ """One parameter's base value and explicitly combined timeline writers."""
50
+
51
+ target: Target
52
+ scope: Scope
53
+ quantity: Quantity
54
+ unit: Unit
55
+ default: Number | StrictBool
56
+ curves: list[TimelineCurve] = Field(default_factory=list)
57
+
58
+ @model_validator(mode='after')
59
+ def contracts(self) -> Self:
60
+ required = {
61
+ Quantity.gain: Unit.ratio,
62
+ Quantity.frequency: Unit.hz,
63
+ Quantity.gate: Unit.logical,
64
+ }[self.quantity]
65
+ if self.unit != required:
66
+ raise ValueError(f'{self.quantity} requires unit {required}')
67
+ check_value(self.quantity, self.default)
68
+ unique([c.name for c in self.curves], 'curve names')
69
+ if sum(c.operation is None for c in self.curves) > 1:
70
+ raise ValueError('competing direct writers require explicit operations')
71
+ for curve in self.curves:
72
+ expected = (
73
+ Unit.ratio if curve.operation == Operation.multiply else self.unit
74
+ )
75
+ if curve.unit != expected:
76
+ raise ValueError(f'curve {curve.name} requires unit {expected}')
77
+ if self.quantity == Quantity.gate:
78
+ if curve.operation is not None:
79
+ raise ValueError('gates do not support arithmetic combination')
80
+ if curve.interpolation != Interpolation.hold:
81
+ raise ValueError('gates require hold interpolation')
82
+ for knot in curve.knots:
83
+ if curve.operation is None:
84
+ check_value(self.quantity, knot.value)
85
+ elif isinstance(knot.value, bool):
86
+ raise ValueError('arithmetic contributions must be numeric')
87
+ return self
88
+
89
+
90
+ class AutomationScore(InterfaceScore):
91
+ kind: Literal['automation'] = 'automation'
92
+ timebases: list[Timebase] = Field(min_length=1, max_length=1)
93
+ outputs: list[Output] = Field(min_length=1, max_length=1)
94
+ body: Automation
95
+
96
+ @model_validator(mode='after')
97
+ def control_export(self) -> Self:
98
+ if self.inputs:
99
+ raise ValueError('automation scores have no inputs')
100
+ if self.parameters:
101
+ raise ValueError('automation scores have no configurable parameters')
102
+ output = self.outputs[0]
103
+ if not isinstance(output.binding, ControlBinding) or not isinstance(
104
+ output.stream, ControlType
105
+ ):
106
+ raise ValueError('automation scores export one control stream')
107
+ timebase = self.timebases[0]
108
+ if (
109
+ output.stream.timebase != timebase.name
110
+ or output.stream.quantity != self.body.quantity
111
+ or output.stream.unit != self.body.unit
112
+ or output.stream.scope != self.body.scope
113
+ ):
114
+ raise ValueError('automation output must match its curve contract')
115
+ return self
116
+
117
+
118
+ def evaluate(
119
+ score: AutomationScore, tick: int, override: float | bool | None = None
120
+ ) -> float | bool:
121
+ """Before a curve starts, use the base or the operation's neutral value."""
122
+ if isinstance(tick, bool) or not isinstance(tick, int):
123
+ raise ValueError('query tick must be an integer')
124
+ body = score.body
125
+ base = body.default if override is None else override
126
+ check_value(body.quantity, base)
127
+ additions: list[float] = []
128
+ multipliers: list[float] = []
129
+ for curve in sorted(body.curves, key=lambda c: c.name):
130
+ if tick < curve.knots[0].tick:
131
+ continue
132
+ value = curve_value(curve, tick)
133
+ if curve.operation is None:
134
+ base = value
135
+ elif curve.operation == Operation.add:
136
+ additions.append(float(value))
137
+ else:
138
+ multipliers.append(float(value))
139
+ if body.quantity == Quantity.gate:
140
+ return base
141
+ result = (float(base) + fsum(additions)) * prod(multipliers)
142
+ check_value(body.quantity, result)
143
+ return result
144
+
145
+
146
+ def curve_value(curve: TimelineCurve, tick: int) -> float | bool:
147
+ """Read an active curve; callers handle its pre-start base value."""
148
+ if tick < curve.knots[0].tick:
149
+ raise ValueError('curve has not started')
150
+ for first, second in pairwise(curve.knots):
151
+ if tick < second.tick:
152
+ if curve.interpolation == Interpolation.hold:
153
+ return first.value
154
+ progress = Fraction(tick - first.tick, second.tick - first.tick)
155
+ return (1 - float(progress)) * first.value + float(progress) * second.value
156
+ return curve.knots[-1].value
157
+
158
+
159
+ def check_value(quantity: Quantity, value: float | bool) -> None:
160
+ if quantity == Quantity.gate:
161
+ if not isinstance(value, bool):
162
+ raise ValueError('gate values must be booleans')
163
+ return
164
+ if isinstance(value, bool) or not isinstance(value, (float, int)):
165
+ raise ValueError('gain and frequency values must be numbers')
166
+ if not float('-inf') < value < float('inf'):
167
+ raise ValueError('control values must be finite')
168
+ if quantity == Quantity.gain and value < 0:
169
+ raise ValueError('gain must be nonnegative')
170
+ if quantity == Quantity.frequency and value <= 0:
171
+ raise ValueError('frequency must be positive')
ufor/base.py ADDED
@@ -0,0 +1,42 @@
1
+ """Pure document values, independent of devices and rendering."""
2
+
3
+ from collections.abc import Hashable, Iterable
4
+ from typing import Annotated
5
+
6
+ from pydantic import AfterValidator, BaseModel, ConfigDict, Field
7
+
8
+
9
+ class Model(BaseModel, frozen=True):
10
+ model_config = ConfigDict(
11
+ extra='forbid', allow_inf_nan=False, validate_default=True
12
+ )
13
+
14
+
15
+ def identifier(value: str) -> str:
16
+ if not value or not value[0].islower():
17
+ raise ValueError('must start with a lowercase letter')
18
+ if any(not (c.islower() or c.isdigit() or c in '-_') for c in value):
19
+ raise ValueError('must contain only lowercase letters, numbers, - or _')
20
+ return value
21
+
22
+
23
+ def unique(values: Iterable[Hashable], label: str) -> None:
24
+ seen: set[Hashable] = set()
25
+ for value in values:
26
+ if value in seen:
27
+ raise ValueError(f'duplicate {label}: {value}')
28
+ seen.add(value)
29
+
30
+
31
+ Identifier = Annotated[str, AfterValidator(identifier)]
32
+
33
+ Text = Annotated[str, Field(min_length=1)]
34
+ Key = Annotated[int, Field(strict=True)]
35
+ Bipolar = Annotated[float, Field(strict=True, ge=-1, le=1)]
36
+ Frame = Annotated[int, Field(strict=True, ge=0)]
37
+ Number = Annotated[float, Field(strict=True)]
38
+ Seconds = Annotated[float, Field(strict=True, ge=0)]
39
+ Frequency = Annotated[float, Field(strict=True, gt=0)]
40
+ PositiveSeconds = Annotated[float, Field(strict=True, gt=0)]
41
+ Positive = Annotated[float, Field(strict=True, gt=0)]
42
+ UnitInterval = Annotated[float, Field(strict=True, ge=0, le=1)]