score-reader 0.1.5__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 (64) hide show
  1. score_reader-0.1.5.dist-info/METADATA +154 -0
  2. score_reader-0.1.5.dist-info/RECORD +64 -0
  3. score_reader-0.1.5.dist-info/WHEEL +5 -0
  4. score_reader-0.1.5.dist-info/entry_points.txt +2 -0
  5. score_reader-0.1.5.dist-info/licenses/LICENSE +202 -0
  6. score_reader-0.1.5.dist-info/licenses/NOTICE +13 -0
  7. score_reader-0.1.5.dist-info/top_level.txt +1 -0
  8. sheet_interpreter/__init__.py +9 -0
  9. sheet_interpreter/arpeggio_notation.py +111 -0
  10. sheet_interpreter/articulation_export.py +49 -0
  11. sheet_interpreter/audio.py +260 -0
  12. sheet_interpreter/beam_source.py +163 -0
  13. sheet_interpreter/boundary_ties.py +82 -0
  14. sheet_interpreter/bow_export.py +35 -0
  15. sheet_interpreter/clef_export.py +76 -0
  16. sheet_interpreter/cli.py +142 -0
  17. sheet_interpreter/clock_context.py +261 -0
  18. sheet_interpreter/continuous_slide_curve.py +89 -0
  19. sheet_interpreter/cue_caption.py +54 -0
  20. sheet_interpreter/data/LICENSE +202 -0
  21. sheet_interpreter/data/NOTICE +13 -0
  22. sheet_interpreter/data/music_sheets_v4_float16.tflite +0 -0
  23. sheet_interpreter/dynamic_export.py +76 -0
  24. sheet_interpreter/fall_off_notation.py +128 -0
  25. sheet_interpreter/grace_export.py +83 -0
  26. sheet_interpreter/guide_writer.py +287 -0
  27. sheet_interpreter/guitar_effect.py +32 -0
  28. sheet_interpreter/guitar_export.py +36 -0
  29. sheet_interpreter/hairpin_export.py +102 -0
  30. sheet_interpreter/interpreter.jar +0 -0
  31. sheet_interpreter/midi.py +340 -0
  32. sheet_interpreter/multi_rest_wire.py +62 -0
  33. sheet_interpreter/musicxml.py +937 -0
  34. sheet_interpreter/natural_harmonic_notation.py +125 -0
  35. sheet_interpreter/navigation.py +186 -0
  36. sheet_interpreter/neutral_rest_caption.py +58 -0
  37. sheet_interpreter/ocr.py +103 -0
  38. sheet_interpreter/octave_shift_export.py +94 -0
  39. sheet_interpreter/ornament_export.py +53 -0
  40. sheet_interpreter/page_processing_budget.py +17 -0
  41. sheet_interpreter/parenthesized_note_group.py +198 -0
  42. sheet_interpreter/pdf_annotations.py +52 -0
  43. sheet_interpreter/performance.py +478 -0
  44. sheet_interpreter/printed_tempo_spans.py +124 -0
  45. sheet_interpreter/reader.py +204 -0
  46. sheet_interpreter/rest_kinds.py +33 -0
  47. sheet_interpreter/runtime.py +17 -0
  48. sheet_interpreter/semantic_wire.py +321 -0
  49. sheet_interpreter/slide_numbering.py +43 -0
  50. sheet_interpreter/slide_performance.py +204 -0
  51. sheet_interpreter/slur_export.py +124 -0
  52. sheet_interpreter/slur_wire.py +159 -0
  53. sheet_interpreter/source_tempo_clock.py +93 -0
  54. sheet_interpreter/spelling_export.py +48 -0
  55. sheet_interpreter/straight_slide.py +76 -0
  56. sheet_interpreter/sudden_dynamic.py +47 -0
  57. sheet_interpreter/technique_export.py +62 -0
  58. sheet_interpreter/tie_owners.py +43 -0
  59. sheet_interpreter/tremolo_export.py +93 -0
  60. sheet_interpreter/tremolo_performance.py +45 -0
  61. sheet_interpreter/tremolo_wire.py +138 -0
  62. sheet_interpreter/typed_events.py +57 -0
  63. sheet_interpreter/typed_performance.py +44 -0
  64. sheet_interpreter/visual_size.py +18 -0
@@ -0,0 +1,340 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Standard MIDI preview writer; no synthesizer, sound bank or external dependency."""
4
+ import math
5
+ import struct
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from .boundary_ties import resolve_boundary_ties
9
+ from .navigation import project_navigation
10
+ from .typed_events import event_kind, validate_unpitched
11
+ from .tie_owners import releasing_links, sound_lanes
12
+ from .typed_performance import unpitched_intervals
13
+ from .guitar_effect import validate as validate_guitar, pitch_offset as guitar_pitch_offset
14
+ from .continuous_slide_curve import curve as continuous_slide_curve, gated_end
15
+ from .slide_performance import prepare_slides, resolve_slides
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class UnpitchedMidiPreview:
20
+ """Explicit caller choice of percussion address, velocity and maximum gate in quarter beats.
21
+
22
+ Channel 10 is reserved for this preview. Its note number is a percussion
23
+ address, not the source note's pitch or a recovered instrument identity.
24
+ No default mapping is provided. Written notation and score time stay intact.
25
+ """
26
+ percussion_note: int
27
+ velocity: int
28
+ gate_beats: float
29
+
30
+ def __post_init__(self):
31
+ if type(self.percussion_note) is not int or not 0 <= self.percussion_note <= 127:
32
+ raise ValueError('Percussion preview address must be an integer 0..127')
33
+ if type(self.velocity) is not int or not 1 <= self.velocity <= 127:
34
+ raise ValueError('Percussion preview velocity must be an integer 1..127')
35
+ if (type(self.gate_beats) not in (int, float) or not math.isfinite(self.gate_beats)
36
+ or not 0 < self.gate_beats <= 128):
37
+ raise ValueError('Percussion preview gate must be finite and positive, at most 128 quarter beats')
38
+
39
+
40
+ def _check_unpitched_clock(document, policy):
41
+ unpitched = False
42
+ for page in document['pages']:
43
+ for note in page['events']:
44
+ event_kind(note)
45
+ validate_unpitched(note)
46
+ if event_kind(note) != 'UNPITCHED':
47
+ continue
48
+ unpitched = True
49
+ start, duration, extent = note['startBeat'], note['durationBeats'], page['totalBeats']
50
+ if (any(type(value) not in (int, float) or not math.isfinite(value)
51
+ for value in (start, duration, extent)) or start < 0 or duration <= 0
52
+ or start + duration > extent + 1e-6):
53
+ raise ValueError('An unpitched MIDI preview needs a finite span inside its page timeline')
54
+ if unpitched:
55
+ if not isinstance(policy, UnpitchedMidiPreview):
56
+ raise ValueError('Unpitched MIDI export needs an explicit UnpitchedMidiPreview policy')
57
+ for page in document['pages']:
58
+ beats, extent = page['measureBeats'], page['totalBeats']
59
+ if (any(type(value) not in (int, float) or not math.isfinite(value)
60
+ or not 0 < value <= 128 for value in beats)
61
+ or type(extent) not in (int, float) or not math.isfinite(extent)
62
+ or not math.isclose(sum(beats), extent, abs_tol=1e-6)):
63
+ raise ValueError('Unpitched MIDI page extent must agree with finite written measures')
64
+ return unpitched
65
+
66
+
67
+ def variable_length(value):
68
+ if not 0 <= value <= 0x0FFFFFFF:
69
+ raise ValueError("MIDI delta time exceeds four bytes")
70
+ out = [value & 127]
71
+ value >>= 7
72
+ while value:
73
+ out.insert(0, (value & 127) | 128)
74
+ value >>= 7
75
+ return bytes(out)
76
+
77
+
78
+ def performed_document(document, bpm=120):
79
+ """Resolve the existing source/Java clocks without assigning a backend identity."""
80
+ document = prepare_slides(document)
81
+ unpitched_intervals(document)
82
+ document = resolve_boundary_ties(document)
83
+ if not math.isfinite(bpm) or not 15 <= bpm <= 400:
84
+ raise ValueError("Initial BPM must be 15..400 quarter notes per minute")
85
+ from .performance import perform_expressions
86
+ expressive_document = perform_expressions(document, bpm)
87
+ if expressive_document is None:
88
+ document = project_navigation(document, bpm)
89
+ else:
90
+ document, bpm = expressive_document, 120
91
+ document = resolve_slides(document)
92
+ return document, bpm, expressive_document is not None
93
+
94
+
95
+ def performance_events(document, bpm=120, *, unpitched_preview=None):
96
+ """Shared MIDI-performance clock/messages for notation and audio previews."""
97
+ _check_unpitched_clock(document, unpitched_preview)
98
+ document, bpm, expressive_document = performed_document(document, bpm)
99
+ return _performance_events_prepared(document, bpm, expressive_document, unpitched_preview)
100
+
101
+
102
+ def _performance_events_prepared(document, bpm, expressive_document, unpitched_preview=None):
103
+ ppq = 480
104
+ tempo = round(60_000_000 / bpm)
105
+ events = [(0, 0, b"\xff\x51\x03" + tempo.to_bytes(3, "big"))]
106
+ offset = 0.0
107
+ tones = []
108
+ percussion = []
109
+ for interval in unpitched_intervals(document):
110
+ note = interval['note']
111
+ start = max(0, round(interval['startBeat']*ppq))
112
+ written_end = max(start+1, round(interval['endBeat']*ppq))
113
+ dead = (note.get('guitarEffect') or {}).get('type') == 'dead'
114
+ gate = min(unpitched_preview.gate_beats, (interval['endBeat']-interval['startBeat'])*(.12 if dead else 1))
115
+ end = min(written_end, start+max(1, round(gate*ppq)))
116
+ attack = note.get('performanceAttack')
117
+ reference = max(attack['gain'], attack['settledGain']) if attack else 1.
118
+ gain = reference*(.25 if dead else 1)
119
+ velocity = 0 if gain == 0 else max(1, min(127, round(unpitched_preview.velocity*gain)))
120
+ if velocity:
121
+ percussion.append((start, end, unpitched_preview.percussion_note, velocity, attack, reference))
122
+ source_rows = []
123
+ for page in document["pages"]:
124
+ starts = [0.0]
125
+ for beats in page["measureBeats"]:
126
+ starts.append(starts[-1] + beats)
127
+ for change in page["score"]["tempoChanges"]:
128
+ bar = change["measureIndex"]
129
+ beat = offset + starts[bar] + page["measureBeats"][bar] * change["positionInMeasure"]
130
+ micros = round(60_000_000 / change["bpm"])
131
+ events.append((round(beat * ppq), 0, b"\xff\x51\x03" + micros.to_bytes(3, "big")))
132
+ for note in sorted(page["events"], key=lambda n: n["startBeat"]):
133
+ if event_kind(note) == 'UNPITCHED':
134
+ continue
135
+ pitch = note["midi"]
136
+ if not 0 <= pitch <= 127:
137
+ continue
138
+ start = max(0, round((offset + note["startBeat"]) * ppq))
139
+ end = max(start + 1, round((offset + note["startBeat"] + note["durationBeats"]) * ppq))
140
+ lane = (note["staffCount"], note["staffIndex"], pitch)
141
+ subdivision = note.get("tremoloBeats", 0)
142
+ if subdivision not in (0, .5, .25, .125, .0625):
143
+ raise ValueError("Unsupported tremolo subdivision")
144
+ step = round(subdivision * ppq)
145
+ gliss = note.get("glissando")
146
+ if gliss is not None:
147
+ if (not isinstance(gliss, dict) or gliss.get("style") != "white_keys"
148
+ or type(gliss.get("targetMidi")) is not int or not 0 <= gliss["targetMidi"] <= 127):
149
+ raise ValueError("Unsupported glissando performance")
150
+ if step or note.get("guitarEffect"):
151
+ raise ValueError("Conflicting glissando performance")
152
+ continuous = note.get('_continuousSlide')
153
+ if continuous is not None:
154
+ if (not isinstance(continuous, dict) or set(continuous) not in ({'sourceMidi'}, {'sourceMidi', 'gate'})
155
+ or type(continuous['sourceMidi']) is not int or not 0 <= continuous['sourceMidi'] <= 127
156
+ or type(continuous.get('gate', 1)) not in (int, float)
157
+ or continuous.get('gate', 1) not in (.28, .5, .75, 1.)
158
+ or gliss is not None or step or note.get('guitarEffect')
159
+ or note.get('tiedFromPrevious')):
160
+ raise ValueError('Unsupported conflicting continuous slide performance')
161
+ source_rows.append(dict(start=start, end=end, lane=lane, tied=note['tiedFromPrevious'],
162
+ eligible=not note.get('grace', False), step=step,
163
+ effect=note.get('guitarEffect', {}), gliss=gliss, continuous=continuous, note=note))
164
+ offset += page["totalBeats"]
165
+ links = releasing_links(source_rows, lambda row: sound_lanes(row, ppq // 8, round(ppq * .04)),
166
+ lambda old, row: row['gliss'] is None and old['gliss'] is None
167
+ # A new marked slide is an attack; an unmarked tail may extend an existing slide.
168
+ and row['continuous'] is None and row['effect'] == old['effect'])
169
+ owners = {}
170
+ for index in sorted(range(len(source_rows)), key=lambda i: (source_rows[i]['start'], i)):
171
+ row = source_rows[index]
172
+ prior = owners.get(links.get(index))
173
+ # An unmarked tied middle note inherits the original sound's tremolo subdivision.
174
+ if prior is not None and row['step'] != 0 and prior[3] != row['step']:
175
+ prior = None
176
+ if prior is not None:
177
+ prior[1] = max(prior[1], row['end'])
178
+ owners[index] = prior
179
+ else:
180
+ tone = [row['start'], row['end'], row['lane'][2], row['step'], row['effect'], row['gliss'],
181
+ row['note'].get('performanceAttack'), row['note']['staffCount'], row['continuous']]
182
+ tones.append(tone)
183
+ owners[index] = tone
184
+ active = {}
185
+ channel_parts = {}
186
+ pedal_controls = []
187
+ pedal_offset = 0.
188
+ for page in document['pages']:
189
+ pedal_controls.extend(dict(c, tick=round((pedal_offset+c['beat'])*ppq))
190
+ for c in page.get('pedalControls', []))
191
+ pedal_offset += page['totalBeats']
192
+ has_pedal = bool(pedal_controls)
193
+ pedal_spans = []
194
+ held_parts = {}
195
+ for control in sorted(pedal_controls, key=lambda c: (c['tick'], c['value'])):
196
+ part = control['staffCount']
197
+ if control['value']:
198
+ held_parts[part] = control['tick']
199
+ elif part in held_parts:
200
+ pedal_spans.append((part, held_parts.pop(part), control['tick']))
201
+ performed = []
202
+ final_tempos = tuple(events)
203
+ for start, end, pitch, step, effect, gliss, attack, part, continuous in tones:
204
+ if continuous is not None:
205
+ end = gated_end(start, end, continuous.get('gate', 1), final_tempos, ppq)
206
+ if gliss is not None:
207
+ performed.extend((a, b, midi, effect, attack if a == start else None, part, None) for a, b, midi in
208
+ white_key_gliss(start, end, pitch, gliss["targetMidi"]))
209
+ elif step:
210
+ performed.extend((tick, min(end, tick + step), pitch, effect, attack if tick == start else None, part, None) for tick in range(start, end, step))
211
+ else:
212
+ performed.append((start, end, pitch, effect, attack, part, continuous))
213
+ spread = []
214
+ for start, end, pitch, effect, attack, part, continuous in performed:
215
+ _, _, rank = validate_guitar(effect)
216
+ start += round(rank * min(ppq * .024, (end-start)/14))
217
+ spread.append((start, end, pitch, effect, attack, part, continuous))
218
+ for start, end, pitch, effect, attack, part, continuous in sorted(spread, key=lambda n: (n[0], n[2])):
219
+ kind = effect.get("type", "none")
220
+ delta = effect.get("semitones", 0)
221
+ expressive = kind in ("slide", "bend", "bend_release", "whammy", "whammy_release", "pre_bend") or effect.get("vibrato", False) or attack is not None or continuous is not None
222
+ # Pitch bend is channel-wide. Isolate it from every overlapping note, including other pitches.
223
+ channel = next((c for c in range(16) if c != 9 and (not has_pedal or channel_parts.get(c, part) == part) and all(
224
+ stop <= start or (not expressive and not bent and other != pitch)
225
+ for stop, other, bent in active.get(c, []))), None)
226
+ if channel is None:
227
+ raise ValueError("MIDI channel capacity exceeded by overlapping voices/effects")
228
+ if has_pedal:
229
+ channel_parts[channel] = part
230
+ active[channel] = [(stop, other, bent) for stop, other, bent in active.get(channel, []) if stop > start]
231
+ release = max([end]+[up for count, down, up in pedal_spans if count == part and down < end < up])
232
+ active[channel].append((release, pitch, expressive))
233
+ velocity = 20 if kind == "dead" else 62 if kind in ("hammer_on", "pull_off", "tap") else 80
234
+ if attack is not None:
235
+ velocity = max(1, min(127, round(velocity*attack['gain'])))
236
+ ramp = max(1, round(attack['seconds']*ppq*bpm/60))
237
+ for index in range(7):
238
+ tick = start+round(ramp*index/6)
239
+ if tick >= end:
240
+ break
241
+ gain = attack['gain']+(attack['settledGain']-attack['gain'])*index/6
242
+ expression = max(0, min(127, round(127*gain/attack['gain'])))
243
+ events.append((tick, 2, bytes([0xB0 | channel, 11, expression])))
244
+ elif expressive_document:
245
+ # Exclusive attack channels may be reused after their release.
246
+ events.append((start, 2, bytes([0xB0 | channel, 11, 127])))
247
+ sounding_end = start + max(1, round((end-start) * (.12 if kind == "dead" else .45 if effect.get("palmMute") else 1)))
248
+ if expressive:
249
+ # RPN 0: +/-24 semitones, confined to this note's exclusive channel.
250
+ bend_range, continuous_bends = (continuous_slide_curve(start, end, continuous['sourceMidi'], pitch, final_tempos, ppq)
251
+ if continuous is not None else (24, None))
252
+ for controller, value in ((101, 0), (100, 0), (6, bend_range), (38, 0), (101, 127), (100, 127)):
253
+ events.append((start, 1, bytes([0xB0 | channel, controller, value])))
254
+ if continuous_bends is not None:
255
+ for tick, bend in continuous_bends:
256
+ if tick < sounding_end:
257
+ events.append((tick, 2, bytes([0xE0 | channel, bend & 127, bend >> 7])))
258
+ count = 0 if continuous_bends is not None else max(2, min(256, (end-start)//15))
259
+ for i in range(count+1) if count else ():
260
+ t = i/count
261
+ smooth = lambda x: x*x*(3-2*x)
262
+ pitch_offset = guitar_pitch_offset(kind, delta, t)
263
+ if effect.get("vibrato"):
264
+ age = t*(end-start)/ppq*60/bpm
265
+ pitch_offset += .18*math.sin(age*math.pi*10)*min(1,t*8)
266
+ bend = max(0,min(16383,round(8192+pitch_offset/24*8192)))
267
+ tick = start+round((end-start)*t)
268
+ if tick < sounding_end:
269
+ events.append((tick, 2, bytes([0xE0 | channel, bend & 127, bend >> 7])))
270
+ events.append((release, 1, bytes([0xE0 | channel, 0, 64])))
271
+ events.extend([(start, 3, bytes([0x90 | channel, pitch, velocity])),
272
+ (sounding_end, 0, bytes([0x80 | channel, pitch, 0]))])
273
+ # Pedal is channel-wide too. Keep unrelated parts isolated and release before redepress.
274
+ for part in sorted({c['staffCount'] for c in pedal_controls}):
275
+ if part not in channel_parts.values():
276
+ channel = next((c for c in range(16) if c != 9 and c not in channel_parts), None)
277
+ if channel is None:
278
+ raise ValueError('MIDI channel capacity exceeded by pedal parts')
279
+ channel_parts[channel] = part
280
+ for control in sorted(pedal_controls, key=lambda c: (c['tick'], c['value'])):
281
+ for channel, part in channel_parts.items():
282
+ if part == control['staffCount']:
283
+ events.append((control['tick'], 1 if control['value'] == 0 else 2,
284
+ bytes([0xb0 | channel, 64, control['value']])))
285
+ # The selected percussion address is fixed. Overlap cannot retain independent
286
+ # attacks reliably on one MIDI channel/address, so require a routing decision.
287
+ previous_end = -1
288
+ percussion_expression = 127
289
+ for start, end, address, velocity, attack, reference in sorted(percussion, key=lambda value: value[:4]):
290
+ if start < previous_end:
291
+ raise ValueError('Overlapping unpitched attacks require an explicit multi-address percussion routing policy')
292
+ previous_end = end
293
+ if attack is None:
294
+ if percussion_expression != 127:
295
+ events.append((start, 2, bytes([0xb9, 11, 127])))
296
+ percussion_expression = 127
297
+ else:
298
+ ramp = max(1, round(attack['seconds']*ppq*bpm/60))
299
+ for index in range(7):
300
+ tick = start+round(ramp*index/6)
301
+ if tick >= end:
302
+ break
303
+ gain = attack['gain']+(attack['settledGain']-attack['gain'])*index/6
304
+ percussion_expression = max(0,min(127,round(127*gain/reference)))
305
+ events.append((tick, 2, bytes([0xb9, 11, percussion_expression])))
306
+ events.extend([(start, 3, bytes([0x99, address, velocity])),
307
+ (end, 0, bytes([0x89, address, 0]))])
308
+ ordered = sorted(events, key=lambda x: (x[0], x[1]))
309
+ return ppq, ordered, max(ordered[-1][0], round(offset * ppq))
310
+
311
+
312
+ def white_key_gliss(start, end, source, target):
313
+ """Hold two thirds, then play intervening white keys; target stays a written note."""
314
+ direction = 1 if target > source else -1
315
+ pitches = [midi for midi in range(source + direction, target, direction)
316
+ if midi % 12 in (0, 2, 4, 5, 7, 9, 11)]
317
+ if not pitches:
318
+ return [(start, end, source)]
319
+ hold = start + round((end-start)*2/3)
320
+ result = [(start, hold, source)] if hold > start else []
321
+ for index, midi in enumerate(pitches):
322
+ a = hold + round((end-hold)*index/len(pitches))
323
+ b = hold + round((end-hold)*(index+1)/len(pitches))
324
+ if b > a:
325
+ result.append((a, b, midi))
326
+ return result
327
+
328
+
329
+ def write_midi(document, path, bpm=120, *, unpitched_preview=None):
330
+ ppq, events, end_tick = performance_events(document, bpm, unpitched_preview=unpitched_preview)
331
+ track = bytearray()
332
+ last = 0
333
+ for tick, _, message in events:
334
+ track.extend(variable_length(tick - last))
335
+ track.extend(message)
336
+ last = tick
337
+ # Rests and skipped voices still occupy performed score time.
338
+ track.extend(variable_length(end_tick - last))
339
+ track.extend(b"\xff\x2f\x00")
340
+ Path(path).write_bytes(b"MThd" + struct.pack(">IHHH", 6, 0, 1, ppq) + b"MTrk" + struct.pack(">I", len(track)) + track)
@@ -0,0 +1,62 @@
1
+ # Copyright 2026 Luckolite
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """MRG1 printed multi-rest identity. Never infer groups from empty/repeated bars."""
4
+ import struct
5
+ FIELDS=("firstMeasureIndex","measureCount","staffIndex","staffCount")
6
+ MAGIC=0x4D524731
7
+ MAX_GROUPS=2048
8
+
9
+ def checked(groups, measures):
10
+ if groups is None: groups=[]
11
+ if type(measures) is not int or not 0 <= measures <= 100000 or not isinstance(groups,list) or len(groups)>MAX_GROUPS:
12
+ raise ValueError("Invalid printed rest group dimensions")
13
+ used=set(); result=[]
14
+ for g in groups:
15
+ if not isinstance(g,dict) or set(g)!=set(FIELDS) or any(type(g[k]) is not int for k in FIELDS):
16
+ raise ValueError("Invalid printed rest group record")
17
+ first,count,staff,staffs=(g[k] for k in FIELDS)
18
+ if not (0<=first<=measures-count and 2<=count<=32 and 0<=staff<staffs<=32):
19
+ raise ValueError("Printed rest group outside score")
20
+ for m in range(first,first+count):
21
+ key=(m,staff,staffs)
22
+ if key in used: raise ValueError("Overlapping printed rest groups")
23
+ used.add(key)
24
+ result.append(dict(g))
25
+ return result
26
+
27
+ def checked_score(score):
28
+ supplied=score.get("multiRestGroups")
29
+ if supplied is None: return []
30
+ if not isinstance(supplied,list): raise ValueError("Invalid printed rest group collection")
31
+ if not supplied: return []
32
+ groups=checked(supplied,len(score["measures"]))
33
+ if len(score["notes"])>100000 or len(score["rests"])>100000:
34
+ raise ValueError("Printed rest ownership input too large")
35
+ note_measures={n["measureIndex"] for n in score["notes"]}
36
+ note_lanes={(n["measureIndex"],n["staffIndex"],n["staffCount"]) for n in score["notes"]}
37
+ full={};other=set();foreign=set()
38
+ for rest in score["rests"]:
39
+ key=(rest["measureIndex"],rest["staffIndex"],rest["staffCount"])
40
+ kind=rest.get("kind")
41
+ if ((type(kind) is str and kind=="FULL_MEASURE") or (type(kind) is int and kind==1)) and rest["durationBeats"]==4:
42
+ full[key]=full.get(key,0)+1
43
+ else: other.add(key)
44
+ if rest["staffIndex"]!=0 or rest["staffCount"]!=1:foreign.add(rest["measureIndex"])
45
+ for g in groups:
46
+ first,count,staff,staffs=(g[k] for k in FIELDS)
47
+ for m in range(first,first+count):
48
+ key=(m,staff,staffs)
49
+ if key in note_lanes or staffs==1 and m in note_measures or key in other or full.get(key)!=1 or staffs==1 and m in foreign:
50
+ raise ValueError("Printed rest group conflicts with score")
51
+ return groups
52
+
53
+ def encode_groups(groups, measures):
54
+ groups=checked(groups,measures)
55
+ return struct.pack(">iii",MAGIC,4+16*len(groups),len(groups))+b"".join(struct.pack(">iiii",*(g[k] for k in FIELDS)) for g in groups)
56
+
57
+ def decode_groups(data, measures):
58
+ if len(data)<12: raise ValueError("Truncated printed rest frame")
59
+ magic,length,count=struct.unpack_from(">iii",data)
60
+ if magic!=MAGIC or not 0<=count<=MAX_GROUPS or length!=4+16*count or len(data)!=8+length:
61
+ raise ValueError("Invalid printed rest frame")
62
+ return checked([dict(zip(FIELDS,struct.unpack_from(">iiii",data,12+16*i)))for i in range(count)],measures)