omnipython-apps 0.1.4.dev8__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.
- apps/__init__.py +5 -0
- apps/about/__init__.py +257 -0
- apps/about/app.json +1 -0
- apps/about/credits.py +12 -0
- apps/about/facts.py +398 -0
- apps/about/fonts/OFL.txt +93 -0
- apps/about/fonts/latin1_14.bin +0 -0
- apps/about/fonts/latin1_16.bin +0 -0
- apps/about/fonts/latin1_24.bin +0 -0
- apps/about/fonts/latin1_32.bin +0 -0
- apps/about/fonts/latin1_40.bin +0 -0
- apps/backline/__init__.py +58 -0
- apps/backline/app.json +1 -0
- apps/backline/app.py +475 -0
- apps/backline/art.py +717 -0
- apps/backline/ask.py +781 -0
- apps/backline/box.py +502 -0
- apps/backline/cast.py +137 -0
- apps/backline/desk/__init__.py +329 -0
- apps/backline/desk/editor.py +331 -0
- apps/backline/desk/grid.py +154 -0
- apps/backline/desk/look.py +169 -0
- apps/backline/desk/pedals.py +102 -0
- apps/backline/desk/perform.py +157 -0
- apps/backline/desk/prompt.py +210 -0
- apps/backline/desk/strip.py +159 -0
- apps/backline/desk_main.py +226 -0
- apps/backline/engine.py +622 -0
- apps/backline/floor.py +509 -0
- apps/backline/footswitch.py +119 -0
- apps/backline/glyphs.py +82 -0
- apps/backline/kits.py +428 -0
- apps/backline/midipedal.py +362 -0
- apps/backline/page_data.py +413 -0
- apps/backline/parts.py +145 -0
- apps/backline/pedal.py +107 -0
- apps/backline/remote.py +134 -0
- apps/backline/songs/ballad_68.json +1 -0
- apps/backline/songs/bossa.json +1 -0
- apps/backline/songs/country_train.json +1 -0
- apps/backline/songs/funk.json +1 -0
- apps/backline/songs/metal.json +1 -0
- apps/backline/songs/pop.json +1 -0
- apps/backline/songs/rock.json +1 -0
- apps/backline/songs/shuffle.json +1 -0
- apps/battery/__init__.py +101 -0
- apps/battery/app.json +1 -0
- apps/bit_world/act_deck.py +683 -0
- apps/bit_world/act_game.py +762 -0
- apps/bit_world/act_pet.py +1032 -0
- apps/bit_world/app.json +1 -0
- apps/bit_world/bit_output.py +45 -0
- apps/bit_world/bit_palette.py +503 -0
- apps/bit_world/bit_sound.py +431 -0
- apps/bit_world/bit_sprites.py +632 -0
- apps/bit_world/bit_world.py +534 -0
- apps/btreceiver/__init__.py +690 -0
- apps/btreceiver/app.json +1 -0
- apps/btreceiver/chime.py +155 -0
- apps/btreceiver/demo.py +529 -0
- apps/btreceiver/screen.py +633 -0
- apps/camera/__init__.py +316 -0
- apps/camera/app.json +1 -0
- apps/card/__init__.py +113 -0
- apps/card/app.json +1 -0
- apps/cast/__init__.py +631 -0
- apps/cast/app.json +1 -0
- apps/cast/receivers.py +193 -0
- apps/chess/__init__.py +18 -0
- apps/chess/app.json +1 -0
- apps/chess/app.py +922 -0
- apps/chess/art.py +323 -0
- apps/chess/ble.py +411 -0
- apps/chess/engine.py +925 -0
- apps/chess/game.py +327 -0
- apps/chess/net.py +261 -0
- apps/clock/__init__.py +38 -0
- apps/clock/app.json +1 -0
- apps/detect/__init__.py +214 -0
- apps/detect/app.json +1 -0
- apps/fmsynth/__init__.py +41 -0
- apps/fmsynth/algorithms.py +61 -0
- apps/fmsynth/app.json +1 -0
- apps/fmsynth/app.py +355 -0
- apps/fmsynth/editor.py +206 -0
- apps/fmsynth/engine.py +257 -0
- apps/fmsynth/meters.py +262 -0
- apps/fmsynth/midi.py +375 -0
- apps/fmsynth/panel_view.py +1071 -0
- apps/fmsynth/patches/fmsynth-01.syx +0 -0
- apps/fmsynth/settings.py +138 -0
- apps/fmsynth/voice.py +398 -0
- apps/gamepad/__init__.py +685 -0
- apps/gamepad/app.json +1 -0
- apps/gamepad/pad.py +94 -0
- apps/gamepad/watch.py +352 -0
- apps/hidden/__init__.py +72 -0
- apps/hidden/app.json +1 -0
- apps/home/__init__.py +483 -0
- apps/home/app.json +1 -0
- apps/home/main.py +36 -0
- apps/homeassistant/__init__.py +213 -0
- apps/homeassistant/api.py +104 -0
- apps/homeassistant/app.json +1 -0
- apps/huey/__init__.py +287 -0
- apps/huey/acting.py +184 -0
- apps/huey/actor.py +194 -0
- apps/huey/app.json +1 -0
- apps/huey/client.py +125 -0
- apps/huey/servers.py +121 -0
- apps/huey/settings.example.json +8 -0
- apps/huey/settings.py +97 -0
- apps/huey/turn.py +504 -0
- apps/huey/voice.py +217 -0
- apps/info/__init__.py +810 -0
- apps/info/app.json +1 -0
- apps/lora/__init__.py +62 -0
- apps/lora/app.json +1 -0
- apps/manifest.py +71 -0
- apps/medialink_baby_monitor/__init__.py +222 -0
- apps/medialink_baby_monitor/app.json +1 -0
- apps/medialink_doorbell/__init__.py +251 -0
- apps/medialink_doorbell/app.json +1 -0
- apps/medialink_hands_free/__init__.py +217 -0
- apps/medialink_hands_free/app.json +1 -0
- apps/medialink_surveillance_camera/__init__.py +258 -0
- apps/medialink_surveillance_camera/app.json +1 -0
- apps/medialink_video_doorbell/__init__.py +289 -0
- apps/medialink_video_doorbell/app.json +1 -0
- apps/medialink_videophone/__init__.py +273 -0
- apps/medialink_videophone/app.json +1 -0
- apps/medialink_walkie_talkie/__init__.py +228 -0
- apps/medialink_walkie_talkie/app.json +1 -0
- apps/midicontroller/__init__.py +774 -0
- apps/midicontroller/app.json +1 -0
- apps/midicontroller/links.py +421 -0
- apps/midicontroller/surface.py +343 -0
- apps/midiengine/__init__.py +977 -0
- apps/midiengine/app.json +1 -0
- apps/midiengine/banks.py +85 -0
- apps/midiengine/midiin.py +165 -0
- apps/midiengine/player.py +392 -0
- apps/midiengine/umidiparser.py +1413 -0
- apps/mp3/__init__.py +240 -0
- apps/mp3/app.json +1 -0
- apps/perch/__init__.py +119 -0
- apps/perch/app.json +1 -0
- apps/perch/huey.py +481 -0
- apps/perch/huey_props.py +386 -0
- apps/perch/huey_shift.py +42 -0
- apps/perch/huey_views.py +296 -0
- apps/perch/scene_bench.py +680 -0
- apps/perch/scene_coast.py +479 -0
- apps/perch/scene_desk.py +492 -0
- apps/perch/stage.py +1274 -0
- apps/perch/vec.py +366 -0
- apps/repl/__init__.py +325 -0
- apps/repl/app.json +1 -0
- apps/roku/__init__.py +156 -0
- apps/roku/app.json +1 -0
- apps/rokucam/__init__.py +362 -0
- apps/rokucam/app.json +1 -0
- apps/security/__init__.py +261 -0
- apps/security/app.json +1 -0
- apps/settings/__init__.py +221 -0
- apps/settings/app.json +1 -0
- apps/shell/__init__.py +33 -0
- apps/shell/app.json +1 -0
- apps/spotify/__init__.py +669 -0
- apps/spotify/app.json +1 -0
- apps/spotify/screen.py +82 -0
- apps/steps/__init__.py +58 -0
- apps/steps/app.json +1 -0
- apps/stompbox/__init__.py +31 -0
- apps/stompbox/app.json +1 -0
- apps/stompbox/app.py +668 -0
- apps/stompbox/boards.json +20 -0
- apps/stompbox/effects.py +241 -0
- apps/stompbox/engine.py +340 -0
- apps/stompbox/footswitch.py +331 -0
- apps/stompbox/inputs.py +449 -0
- apps/stompbox/meter.py +72 -0
- apps/stompbox/outputs.py +135 -0
- apps/stompbox/pedals.txt +45 -0
- apps/stompbox/presets.py +106 -0
- apps/stompbox/styles.py +135 -0
- apps/stompbox/ui.py +817 -0
- apps/stompbox/wavfile.py +73 -0
- apps/synthstation/__init__.py +20 -0
- apps/synthstation/app.json +1 -0
- apps/synthstation/audio.py +397 -0
- apps/synthstation/catalog.py +50 -0
- apps/synthstation/meters.py +136 -0
- apps/synthstation/midi.py +380 -0
- apps/synthstation/pads.py +177 -0
- apps/synthstation/parts.py +128 -0
- apps/synthstation/station.py +1069 -0
- apps/system/__init__.py +11 -0
- apps/system/app.json +1 -0
- apps/touchcal/__init__.py +324 -0
- apps/touchcal/app.json +1 -0
- apps/touchcal/fit.py +262 -0
- apps/wake/__init__.py +268 -0
- apps/wake/app.json +1 -0
- apps/wake/feed.py +155 -0
- apps/watch/__init__.py +355 -0
- apps/watch/app.json +1 -0
- apps/watch/faces.py +35 -0
- apps/watch/wheel.py +157 -0
- apps/weather/__init__.py +278 -0
- apps/weather/app.json +1 -0
- apps/weather/icons.py +172 -0
- apps/weather/sizing.py +71 -0
- apps/weather/zippad.py +172 -0
- omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
- omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
- omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
- omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1413 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022 Hermann Paul von Borries (bixb922)
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
#
|
|
5
|
+
# umidiparser 1.2 (https://github.com/bixb922/umidiparser, PyPI
|
|
6
|
+
# ``umidiparser``). It parses Standard MIDI files on MicroPython,
|
|
7
|
+
# CircuitPython and CPython alike, streaming a track from the file rather
|
|
8
|
+
# than loading it; the midiEngine app's file player (``player.py``) reads
|
|
9
|
+
# .mid files through it. Unchanged but for this header and the three chunk
|
|
10
|
+
# id reads, which use its own ``decode_ascii`` instead of
|
|
11
|
+
# ``decode("latin-1")``, an encoding MicroPython hasn't got. Its licence,
|
|
12
|
+
# from the release's LICENSE file:
|
|
13
|
+
#
|
|
14
|
+
# MIT License
|
|
15
|
+
#
|
|
16
|
+
# Copyright (c) 2022 bixb922
|
|
17
|
+
#
|
|
18
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
19
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
20
|
+
# in the Software without restriction, including without limitation the rights
|
|
21
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
22
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
23
|
+
# furnished to do so, subject to the following conditions:
|
|
24
|
+
#
|
|
25
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
26
|
+
# copies or substantial portions of the Software.
|
|
27
|
+
#
|
|
28
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
29
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
30
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
31
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
32
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
33
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
34
|
+
# SOFTWARE.
|
|
35
|
+
|
|
36
|
+
"""
|
|
37
|
+
NAME
|
|
38
|
+
umidiparser
|
|
39
|
+
ff
|
|
40
|
+
AUTHOR
|
|
41
|
+
Hermann Paul von Borries
|
|
42
|
+
|
|
43
|
+
LICENSE
|
|
44
|
+
MIT, Copyright (c) Hermann Paul von Borries
|
|
45
|
+
|
|
46
|
+
INSTALLATION
|
|
47
|
+
Copy umidiparser.py to your device.
|
|
48
|
+
|
|
49
|
+
DESCRIPTION
|
|
50
|
+
This module allows to parse midi files.
|
|
51
|
+
This module does not contain a sound synthesizer, only the capabilities to
|
|
52
|
+
read and interpret a midi file.
|
|
53
|
+
Example:
|
|
54
|
+
|
|
55
|
+
import umidiparser
|
|
56
|
+
Import utime
|
|
57
|
+
for event in umidiplay.MidiFile("example.mid"):
|
|
58
|
+
utime.sleep_us( event.delta_us )
|
|
59
|
+
if event.status == umidiplay.NOTE_ON:
|
|
60
|
+
... start the note event.note on event.channel with event.velocity
|
|
61
|
+
elif event.status == umidiplay.NOTE_OFF :
|
|
62
|
+
... stop the note event.note stop to sound ...
|
|
63
|
+
elif event.status == umidiplay.PROGRAM_CHANGE:
|
|
64
|
+
... change midi program to event.program on event.channel ....
|
|
65
|
+
else:
|
|
66
|
+
print("other event", event )
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
import time
|
|
71
|
+
import sys
|
|
72
|
+
|
|
73
|
+
# Change log: v1.2
|
|
74
|
+
# Added CircuitPython compatibility
|
|
75
|
+
# Removed use of os.path.abspath, does not exist in micropython/circuitpython
|
|
76
|
+
# Renamed time functions "ticks_now_us", "ticks_diff_us" to "time_now_us", "time_diff_us"
|
|
77
|
+
# Changed decode from meta event data for compatibility with all Python versions, now only
|
|
78
|
+
# ascii is decoded.
|
|
79
|
+
# New method MidiTrack.play, removed track_number parameter.
|
|
80
|
+
# Corrected possible error if playing open file again
|
|
81
|
+
# Added event.is_channel() to test for channel events
|
|
82
|
+
# Allow MidiFile.play() used in async for (with asyncio.sleep instead of sleep). Requires asyncio
|
|
83
|
+
# Play funcion computes event.timestamp_us for each event
|
|
84
|
+
|
|
85
|
+
# Compatibility wrapper for python/micropython/circuitpython functions
|
|
86
|
+
_implementation = sys.implementation.name
|
|
87
|
+
if _implementation == "micropython":
|
|
88
|
+
from micropython import const
|
|
89
|
+
import uasyncio as asyncio
|
|
90
|
+
time_sleep_us = lambda usec: time.sleep_us( usec )
|
|
91
|
+
time_now_us = lambda: time.ticks_us()
|
|
92
|
+
time_diff_us = lambda x, y: time.ticks_diff( x, y )
|
|
93
|
+
asyncio_sleep_ms = lambda x: asyncio.sleep_ms( x )
|
|
94
|
+
elif _implementation == "circuitpython":
|
|
95
|
+
from micropython import const
|
|
96
|
+
try:
|
|
97
|
+
import uasyncio as asyncio
|
|
98
|
+
except:
|
|
99
|
+
pass
|
|
100
|
+
time_sleep_us = lambda usec: time.sleep( usec/1_000_000 )
|
|
101
|
+
time_now_us = lambda: time.monotonic_ns()/1_000
|
|
102
|
+
time_diff_us = lambda x, y: x - y
|
|
103
|
+
asyncio_sleep_ms = lambda x: asyncio.sleep_ms( x )
|
|
104
|
+
else:
|
|
105
|
+
# Must be CPython
|
|
106
|
+
import asyncio
|
|
107
|
+
const = lambda x: x
|
|
108
|
+
time_sleep_us = lambda usec: time.sleep( usec/1_000_000 )
|
|
109
|
+
time_now_us = lambda : int(time.time()*1_000_000)
|
|
110
|
+
time_diff_us = lambda x, y: x - y
|
|
111
|
+
asyncio_sleep_ms = lambda x: asyncio.sleep( x/1000 )
|
|
112
|
+
|
|
113
|
+
# Make the @micropython.native decorator do nothing
|
|
114
|
+
def micropython( function ):
|
|
115
|
+
return function
|
|
116
|
+
micropython.native = lambda function : function
|
|
117
|
+
|
|
118
|
+
# Only utf-8 encoding available in Micropython 1.19.1 or CircuitPython 7.3.3
|
|
119
|
+
# Should probably be .decode("iso8859-1", errors="backslashreplace")
|
|
120
|
+
decode_ascii = lambda x : "".join( chr(z) for z in x )
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# Constants for the MIDI channel events, first nibble
|
|
124
|
+
NOTE_OFF = const(0x80)
|
|
125
|
+
NOTE_ON = const(0x90)
|
|
126
|
+
POLYTOUCH = const(0xa0)
|
|
127
|
+
CONTROL_CHANGE = const(0xb0)
|
|
128
|
+
PROGRAM_CHANGE = const(0xc0)
|
|
129
|
+
AFTERTOUCH = const(0xd0)
|
|
130
|
+
PITCHWHEEL = const(0xe0)
|
|
131
|
+
_FIRST_CHANNEL_EVENT = const(0x80)
|
|
132
|
+
_LAST_CHANNEL_EVENT = const(0xef)
|
|
133
|
+
# Most midi channel events have 2 bytes of data, except this range that has 1 byte events
|
|
134
|
+
# which consists of two event types:
|
|
135
|
+
_FIRST_1BYTE_EVENT = const(0xc0)
|
|
136
|
+
_LAST_1BYTE_EVENT = const(0xdf)
|
|
137
|
+
|
|
138
|
+
# Meta messages
|
|
139
|
+
_META_PREFIX = const(0xff)
|
|
140
|
+
# Meta messages, second byte
|
|
141
|
+
SEQUENCE_NUMBER = const(0x00)
|
|
142
|
+
TEXT = const(0x01)
|
|
143
|
+
COPYRIGHT = const(0x02)
|
|
144
|
+
TRACK_NAME = const(0x03)
|
|
145
|
+
INSTRUMENT_NAME = const(0x04)
|
|
146
|
+
LYRICS = const(0x05)
|
|
147
|
+
MARKER = const(0x06)
|
|
148
|
+
CUE_MARKER = const(0x07)
|
|
149
|
+
PROGRAM_NAME = const(0x08)
|
|
150
|
+
DEVICE_NAME = const(0x09)
|
|
151
|
+
CHANNEL_PREFIX = const(0x20)
|
|
152
|
+
MIDI_PORT = const(0x21)
|
|
153
|
+
END_OF_TRACK = const(0x2f)
|
|
154
|
+
SET_TEMPO = const(0x51)
|
|
155
|
+
SMPTE_OFFSET = const(0x54)
|
|
156
|
+
TIME_SIGNATURE = const(0x58)
|
|
157
|
+
KEY_SIGNATURE = const(0x59)
|
|
158
|
+
SEQUENCER_SPECIFIC = const(0x7f)
|
|
159
|
+
_FIRST_META_EVENT = const(0x00)
|
|
160
|
+
_LAST_META_EVENT = const(0x7f)
|
|
161
|
+
|
|
162
|
+
# Sysex/escape events
|
|
163
|
+
SYSEX = const(0xf0)
|
|
164
|
+
ESCAPE = const(0xf7)
|
|
165
|
+
|
|
166
|
+
# MidiParser reuses a buffer for meta and sysex events
|
|
167
|
+
# This is the starting size for this buffer.
|
|
168
|
+
# If there are larger messages in a file, this buffer will increase automatically
|
|
169
|
+
# to accomodate the larger data
|
|
170
|
+
_INITIAL_EVENT_BUFFER_SIZE = const(20)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# Parse midi variable length number format,
|
|
174
|
+
# used for time deltas and meta message lengths
|
|
175
|
+
@micropython.native
|
|
176
|
+
def _midi_number_to_int( midi_data ):
|
|
177
|
+
# Converts a midi variable length number to integer. In midi files,
|
|
178
|
+
# variable length numbers are used for delta times (time difference between
|
|
179
|
+
#one midi event and the next) and for variable length fields in meta messages.
|
|
180
|
+
data_byte = next( midi_data )
|
|
181
|
+
if data_byte <= 0x7f:
|
|
182
|
+
# This "if" is really only for an improvement in speed, because
|
|
183
|
+
# most variable length numbers tend to be 1 byte long, so this
|
|
184
|
+
# is the most probable execution path.
|
|
185
|
+
return data_byte
|
|
186
|
+
|
|
187
|
+
# The value spans more than one byte, parse until
|
|
188
|
+
# a byte with most significant bit "on" is found, and gather
|
|
189
|
+
# 7 bits of data for each byte found, according to Midi standard.
|
|
190
|
+
value = data_byte & 0x7f
|
|
191
|
+
while data_byte >= 0x80:
|
|
192
|
+
data_byte = next( midi_data )
|
|
193
|
+
value = (value<<7) | (data_byte & 0x7f )
|
|
194
|
+
return value
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _process_events( event_iterator,
|
|
199
|
+
miditicks_per_quarter,
|
|
200
|
+
reuse_event_object ):
|
|
201
|
+
# This function iterates through the provided event iterator,
|
|
202
|
+
# getting one MidiEvent at a time, and processes MIDI meta set tempo
|
|
203
|
+
# events to convert the time delta in MIDI ticks to time delta in microseconds,
|
|
204
|
+
# rounded to the next microsecond.
|
|
205
|
+
# The function also ensures that there will be a MIDI meta end of track event
|
|
206
|
+
# at the end (as should be according to MIDI standard).
|
|
207
|
+
# If the reuse_event_object parameter is set to False, a independent deep copy
|
|
208
|
+
# of each event is returned. If the reuse_event_object is True, the same
|
|
209
|
+
# object is returned over and over, to reduce CPU usage and RAM heap allocation.
|
|
210
|
+
|
|
211
|
+
# Start with default "microseconds per quarter" according to midi standard
|
|
212
|
+
tempo = 500_000
|
|
213
|
+
|
|
214
|
+
for event in event_iterator:
|
|
215
|
+
|
|
216
|
+
if not reuse_event_object:
|
|
217
|
+
event = event.copy()
|
|
218
|
+
|
|
219
|
+
# According to MIDI spec
|
|
220
|
+
# time (in ms) = number_of_ticks * tempo / divisor * 1000
|
|
221
|
+
# where tempo is expressed in microseconds per quarter note and
|
|
222
|
+
# the divisor is expressed in MIDI ticks per quarter note
|
|
223
|
+
# Do the math in microseconds.
|
|
224
|
+
# Do not use floating point, in some microcontrollers
|
|
225
|
+
# floating point is slow or lacks precision.
|
|
226
|
+
event.delta_us = ( event.delta_miditicks * tempo \
|
|
227
|
+
+ (miditicks_per_quarter//2) \
|
|
228
|
+
) // miditicks_per_quarter
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# Process tempo meta event, get tempo to be used for
|
|
232
|
+
# event.delta_us calculation for next events.
|
|
233
|
+
status = event.status
|
|
234
|
+
if status == SET_TEMPO:
|
|
235
|
+
tempo = event.tempo
|
|
236
|
+
|
|
237
|
+
# If end_of_track is seen, stop processing events
|
|
238
|
+
elif status == END_OF_TRACK:
|
|
239
|
+
yield event
|
|
240
|
+
# Ignore events after end of track
|
|
241
|
+
break
|
|
242
|
+
|
|
243
|
+
yield event
|
|
244
|
+
|
|
245
|
+
else:
|
|
246
|
+
# Loop ended without end_of_track meta event, yield one
|
|
247
|
+
# last event of type "end of track" to make caller happy.
|
|
248
|
+
yield MidiEvent()._set_end_of_track()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class MidiParser:
|
|
255
|
+
# This class instantiates a MidiParser, the class constructor
|
|
256
|
+
# accepts a iterable with MIDI events in MIDI file format, i.e.
|
|
257
|
+
# it accepts a iterable for the content of a MIDI file track.
|
|
258
|
+
def __init__( self, midi_data ):
|
|
259
|
+
# Initialize a parser on the midi_data iterable. The parsing
|
|
260
|
+
# is then done with the parse_events method.
|
|
261
|
+
|
|
262
|
+
# Allocate data buffers for the sake of CPU and RAM efficiency,
|
|
263
|
+
# to avoid allocating new objects for each event parsed.
|
|
264
|
+
|
|
265
|
+
# Save midi data iterator
|
|
266
|
+
self._midi_data = midi_data
|
|
267
|
+
|
|
268
|
+
# The first event cannot be a "running status event"
|
|
269
|
+
self._running_status = None
|
|
270
|
+
|
|
271
|
+
# This buffer is for meta and sysex events.
|
|
272
|
+
# This buffer can potentially grow
|
|
273
|
+
# because it will eventually contain the largest midi meta, sysex,
|
|
274
|
+
# or escape event in the file.
|
|
275
|
+
self._buffer = bytearray(_INITIAL_EVENT_BUFFER_SIZE )
|
|
276
|
+
|
|
277
|
+
# The most frequently used buffers are 1 and 2 bytes long
|
|
278
|
+
# For CPU/RAM efficiency, preallocate these buffers.
|
|
279
|
+
# These two buffers are used only for midi channel events
|
|
280
|
+
self._buffer1 = memoryview(bytearray(1))
|
|
281
|
+
self._buffer2 = memoryview(bytearray(2))
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def parse_events( self ):
|
|
285
|
+
# This generator will parse the midi_data iterable
|
|
286
|
+
# and yield MidiEvent objects until end of data (i.e. this
|
|
287
|
+
# function is in itself a generator for events)
|
|
288
|
+
|
|
289
|
+
# For CPU and RAM efficiency, the midi event is returned
|
|
290
|
+
# in the same object, that is, the MidiEvent returned is allocated
|
|
291
|
+
# once, and set before yielding to the new values. It is responsibility
|
|
292
|
+
# of the caller to copy the event if needed. The data buffer in the
|
|
293
|
+
# event is also reused from one call to the next (see __init__).
|
|
294
|
+
|
|
295
|
+
# Exceptions:
|
|
296
|
+
# ValueError if the midi event subtype is in the range 0x7f to 0xff.
|
|
297
|
+
# RuntimeError if there is a running status event without a previous
|
|
298
|
+
# midi channel event.
|
|
299
|
+
# RuntimeError if a system common or real time event is detected (event
|
|
300
|
+
# status byte 0xf1-0xf6 and 0xf7-0xfe. These type of events are not allowed
|
|
301
|
+
# in MIDI files.
|
|
302
|
+
|
|
303
|
+
event = MidiEvent()
|
|
304
|
+
midi_data = self._midi_data
|
|
305
|
+
try:
|
|
306
|
+
while True:
|
|
307
|
+
# Parse a delta time
|
|
308
|
+
delta = _midi_number_to_int( midi_data )
|
|
309
|
+
|
|
310
|
+
# Parse a message
|
|
311
|
+
event_status, data = self._parse_message( )
|
|
312
|
+
|
|
313
|
+
# Set the event with new data
|
|
314
|
+
event._set( event_status, data, delta )
|
|
315
|
+
|
|
316
|
+
yield event
|
|
317
|
+
|
|
318
|
+
except StopIteration:
|
|
319
|
+
# No more input data, "next" in called function got end of data,
|
|
320
|
+
# stop this generator
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@micropython.native
|
|
325
|
+
def _parse_non_channel_events( self, event_status ):
|
|
326
|
+
# Parses meta, sysex and escape events
|
|
327
|
+
|
|
328
|
+
# Precondition: the event status byte has already been read.
|
|
329
|
+
# Postcondition: the event data has been parsed and the next
|
|
330
|
+
# byte in midi_data is a new MIDI event.
|
|
331
|
+
|
|
332
|
+
midi_data = self._midi_data
|
|
333
|
+
|
|
334
|
+
if event_status == _META_PREFIX:
|
|
335
|
+
# Midi messages event status has format
|
|
336
|
+
# 0xff nn (nn from 0x00-0x7f)
|
|
337
|
+
# discard 0xff, keep nn as event status
|
|
338
|
+
event_status = next( midi_data )
|
|
339
|
+
|
|
340
|
+
# The second event status byte might not be in range
|
|
341
|
+
# defined by standard
|
|
342
|
+
if not _FIRST_META_EVENT \
|
|
343
|
+
<= event_status \
|
|
344
|
+
<= _LAST_META_EVENT:
|
|
345
|
+
raise ValueError(\
|
|
346
|
+
f"Meta midi second event status byte (0x{event_status:x}) "
|
|
347
|
+
"not in range 0x00-0x7f")
|
|
348
|
+
|
|
349
|
+
# All non-channel events have a variable length field
|
|
350
|
+
data_length = _midi_number_to_int( midi_data )
|
|
351
|
+
|
|
352
|
+
# Data might be longer than available buffer
|
|
353
|
+
if data_length >= len(self._buffer):
|
|
354
|
+
# Increase buffer size to fit the data.
|
|
355
|
+
self._buffer = bytearray( data_length )
|
|
356
|
+
|
|
357
|
+
# Use a memoryview for efficiency, this avoids copying the buffer
|
|
358
|
+
# and allows to return a slice of the current size efficiently.
|
|
359
|
+
data = memoryview(self._buffer)[0:data_length]
|
|
360
|
+
|
|
361
|
+
# Now copy the data from the input midi_data to the buffer
|
|
362
|
+
for idx in range(data_length):
|
|
363
|
+
data[idx] = next( midi_data )
|
|
364
|
+
|
|
365
|
+
return event_status, data
|
|
366
|
+
|
|
367
|
+
@micropython.native
|
|
368
|
+
def _parse_channel_event( self, event_status, data_byte ):
|
|
369
|
+
# Parse midi channel events, i.e. events with event status
|
|
370
|
+
# byte 0x80 to 0xef. Procesess both regular channel events and
|
|
371
|
+
# running status events.
|
|
372
|
+
# Precondition: the event status byte has already been read.
|
|
373
|
+
# Postcondition: the event data has been parsed and the next
|
|
374
|
+
# byte in midi_data is a new MIDI event.
|
|
375
|
+
|
|
376
|
+
# Check if this event is 1 or 2 bytes long
|
|
377
|
+
if _FIRST_1BYTE_EVENT <= event_status \
|
|
378
|
+
<= _LAST_1BYTE_EVENT:
|
|
379
|
+
# This is a one-byte midi channel event,
|
|
380
|
+
# such as program change, use 1 byte preallocated buffer
|
|
381
|
+
data = self._buffer1
|
|
382
|
+
data[0] = data_byte
|
|
383
|
+
|
|
384
|
+
else:
|
|
385
|
+
# This is a two-byte midi channel event, such as note on,
|
|
386
|
+
# note off, use preallocated buffer
|
|
387
|
+
data = self._buffer2
|
|
388
|
+
data[0] = data_byte
|
|
389
|
+
data[1]= next( self._midi_data )
|
|
390
|
+
|
|
391
|
+
return event_status, data
|
|
392
|
+
|
|
393
|
+
@micropython.native
|
|
394
|
+
def _parse_message( self ):
|
|
395
|
+
# Parse a MIDI message in a MIDI file. Uses _parse_channel_event
|
|
396
|
+
# or _parse_non_channel_events depending on the event status byte.
|
|
397
|
+
# Precondition: the next byte in the midi_data is the
|
|
398
|
+
# event status byte.
|
|
399
|
+
midi_data = self._midi_data
|
|
400
|
+
|
|
401
|
+
# Preconditions: the next byte in midi_data should now be
|
|
402
|
+
# the starting byte of a midi event, i.e a
|
|
403
|
+
# midi event status byte. Delta time has already been parsed
|
|
404
|
+
|
|
405
|
+
# Get event_status byte
|
|
406
|
+
event_status = next( midi_data )
|
|
407
|
+
if event_status < 0x80:
|
|
408
|
+
# This is a running event. It has no event status byte,
|
|
409
|
+
# only data, the event status byte is the one from the last midi channel
|
|
410
|
+
# event seen in the midi_data.
|
|
411
|
+
|
|
412
|
+
# A running event at the beginning of a track is an error
|
|
413
|
+
if self._running_status is None:
|
|
414
|
+
raise RuntimeError("Midi running status without previous channel event")
|
|
415
|
+
|
|
416
|
+
# Reuse the event_status as first data byte and parse the event
|
|
417
|
+
return self._parse_channel_event(
|
|
418
|
+
self._running_status,
|
|
419
|
+
event_status )
|
|
420
|
+
|
|
421
|
+
if _FIRST_CHANNEL_EVENT \
|
|
422
|
+
<= event_status \
|
|
423
|
+
<= _LAST_CHANNEL_EVENT:
|
|
424
|
+
# Not a running event, this is a midi channel event
|
|
425
|
+
# (status 0x80-0xef) followed by 1 or 2 bytes of data
|
|
426
|
+
|
|
427
|
+
# Remember event status in case next event is a
|
|
428
|
+
# running status event
|
|
429
|
+
self._running_status = event_status
|
|
430
|
+
|
|
431
|
+
return self._parse_channel_event(
|
|
432
|
+
event_status,
|
|
433
|
+
next( midi_data ) )
|
|
434
|
+
|
|
435
|
+
if event_status in (_META_PREFIX, SYSEX, ESCAPE ):
|
|
436
|
+
return self._parse_non_channel_events( event_status )
|
|
437
|
+
|
|
438
|
+
# Neither midi channel event, nor meta, nor sysex/escape.
|
|
439
|
+
# Real time and system common events are not expected in MIDI files.
|
|
440
|
+
raise RuntimeError("Real time/system common event"
|
|
441
|
+
f" status 0x{event_status:x}"
|
|
442
|
+
" not supported in midi files")
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
class MidiEvent:
|
|
446
|
+
"""
|
|
447
|
+
Represents a parsed midi event.
|
|
448
|
+
|
|
449
|
+
"""
|
|
450
|
+
@micropython.native
|
|
451
|
+
def __init__( self ):
|
|
452
|
+
"""
|
|
453
|
+
Initializes MidiEvent, all instances are assigned None as value,
|
|
454
|
+
this is. This method is used internally by MidiParser.
|
|
455
|
+
|
|
456
|
+
Usually you will not need to create an instance of MidiEvent,
|
|
457
|
+
MidiEvent objects are returned by iterating over the MidiFile
|
|
458
|
+
object.
|
|
459
|
+
|
|
460
|
+
"""
|
|
461
|
+
# MidiEvent private instance variables:
|
|
462
|
+
# self._event_status_byte
|
|
463
|
+
# The original event status byte, as detected in the midi file.
|
|
464
|
+
# The difference with self.status is that the _event_status_byte
|
|
465
|
+
# still has the channel number in the lower half in the case of
|
|
466
|
+
# a midi channel event.
|
|
467
|
+
#
|
|
468
|
+
# self._status
|
|
469
|
+
# Same as self._event_status_byte but with the lower nibble
|
|
470
|
+
# cleared for midi channel events. self.status is a read only
|
|
471
|
+
# property for self._status.
|
|
472
|
+
#
|
|
473
|
+
# self._data
|
|
474
|
+
# The raw data of the event. self.data is the read only
|
|
475
|
+
# property for self._data.
|
|
476
|
+
|
|
477
|
+
self._event_status_byte = None
|
|
478
|
+
self._data = None
|
|
479
|
+
|
|
480
|
+
self._status = None
|
|
481
|
+
self.delta_miditicks = None
|
|
482
|
+
self.delta_us = None
|
|
483
|
+
self.timestamp_us = None
|
|
484
|
+
|
|
485
|
+
@micropython.native
|
|
486
|
+
def _set( self, event_status, data, delta_miditicks ):
|
|
487
|
+
# Set event information to the event status byte, data and
|
|
488
|
+
# delta time (in miditicks) specified in the parameters, replacing all
|
|
489
|
+
# previous information in the event (if there was any).
|
|
490
|
+
|
|
491
|
+
# event_status: contains the event status byte as found in the file.
|
|
492
|
+
# In case of midi channel events, lower nibble has the channel number.
|
|
493
|
+
# For meta messages, the first byte of the meta status is 0xff,
|
|
494
|
+
# so the event_status contains the second byte or "meta event type"
|
|
495
|
+
# with values from 0 to 0x7f (_FIRST_META_EVENT to _LAST_META_EVENT).
|
|
496
|
+
|
|
497
|
+
# data: a buffer with the raw data of the event.
|
|
498
|
+
|
|
499
|
+
# delta_miditicks: the delta time (time difference with previous event)
|
|
500
|
+
# in midi ticks (or pulses).
|
|
501
|
+
|
|
502
|
+
# Store event status byte and compute event.status
|
|
503
|
+
self._event_status_byte = event_status
|
|
504
|
+
if _FIRST_CHANNEL_EVENT <= event_status <= _LAST_CHANNEL_EVENT:
|
|
505
|
+
self._status = event_status & 0xf0
|
|
506
|
+
else:
|
|
507
|
+
self._status = event_status
|
|
508
|
+
|
|
509
|
+
self._data = data
|
|
510
|
+
self.delta_miditicks = delta_miditicks
|
|
511
|
+
self.delta_us = None
|
|
512
|
+
|
|
513
|
+
return self
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _set_end_of_track( self ):
|
|
517
|
+
self._set( END_OF_TRACK, b'', 0 )
|
|
518
|
+
self.delta_us = 0
|
|
519
|
+
return self
|
|
520
|
+
|
|
521
|
+
@micropython.native
|
|
522
|
+
def _check_property_available( self, *argv ):
|
|
523
|
+
# This method is used to check availabilty of a property.
|
|
524
|
+
# Check if self._status is in list of possible status values
|
|
525
|
+
# and raises AttributeError if not.
|
|
526
|
+
if self._status not in argv:
|
|
527
|
+
raise AttributeError(
|
|
528
|
+
f"Midi event 0x{self._status:02x}"
|
|
529
|
+
" does not support attribute")
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _get_event_name( self ):
|
|
533
|
+
# This metod is used by __str___.
|
|
534
|
+
# Computes the event name as a string. To keep memory
|
|
535
|
+
# requirements at a minimum, instead of having a dictionary of
|
|
536
|
+
# names, this method uses the global variables of thid
|
|
537
|
+
# module as dictionary.
|
|
538
|
+
|
|
539
|
+
# Make a dictionary out of the global names of this module
|
|
540
|
+
# Exclude private names starting with _ and
|
|
541
|
+
# exclude names that don't translate to an integer
|
|
542
|
+
event_names_dict = { globals()[varname] : varname.lower() \
|
|
543
|
+
for varname in globals() \
|
|
544
|
+
if isinstance(globals()[varname], int) \
|
|
545
|
+
and varname[0:1] != "_" }
|
|
546
|
+
|
|
547
|
+
try:
|
|
548
|
+
name = event_names_dict[self._status]
|
|
549
|
+
except KeyError:
|
|
550
|
+
# Show meaningful information for custom event numbers
|
|
551
|
+
if _FIRST_META_EVENT <= self._status <= _LAST_META_EVENT:
|
|
552
|
+
name = f"meta_0x{self._status:02x}"
|
|
553
|
+
else:
|
|
554
|
+
name = f"midi_0x{self._status:02x}"
|
|
555
|
+
return name
|
|
556
|
+
|
|
557
|
+
def _get_property_dict( self ):
|
|
558
|
+
# This is used by __str__
|
|
559
|
+
# Get values for allvalid @properties for
|
|
560
|
+
# this event, except the "data" property
|
|
561
|
+
|
|
562
|
+
property_dict = {}
|
|
563
|
+
for prop in dir(MidiEvent):
|
|
564
|
+
if prop[0:1] != "_":
|
|
565
|
+
try:
|
|
566
|
+
value = getattr( self, prop )
|
|
567
|
+
# Filter methods from the list
|
|
568
|
+
if isinstance(value,(int,str)):
|
|
569
|
+
property_dict[prop] = getattr(self, prop )
|
|
570
|
+
except AttributeError:
|
|
571
|
+
pass
|
|
572
|
+
return property_dict
|
|
573
|
+
|
|
574
|
+
def __str__( self ):
|
|
575
|
+
"""
|
|
576
|
+
Standard method to translate the event information to a string,
|
|
577
|
+
"""
|
|
578
|
+
description = self._get_event_name()
|
|
579
|
+
# Add event time attributes
|
|
580
|
+
description += " delta[miditicks]=" + str( self.delta_miditicks )
|
|
581
|
+
# Add data, show only a couple of bytes of data
|
|
582
|
+
description += " data=" + str( bytes( self._data[0:5] ) )
|
|
583
|
+
if len(self._data) > 5:
|
|
584
|
+
# Show only first 5 bytes in the data field.
|
|
585
|
+
description = description[0:-1] + "...'"
|
|
586
|
+
|
|
587
|
+
# Show time in microseconds only if already computed
|
|
588
|
+
if self.delta_us is not None:
|
|
589
|
+
description += " delta[usec]=" + str(self.delta_us)
|
|
590
|
+
|
|
591
|
+
# Get all @property names and their values
|
|
592
|
+
for prop, value in self._get_property_dict().items():
|
|
593
|
+
description += " " + prop + "=" + str(value)
|
|
594
|
+
return description
|
|
595
|
+
|
|
596
|
+
@property
|
|
597
|
+
@micropython.native
|
|
598
|
+
def status( self ):
|
|
599
|
+
"""
|
|
600
|
+
Returns the event status. For midi channel events, such as note on, note off,
|
|
601
|
+
program change, the lower nibble (lower 4 bits) are cleared (set to zero).
|
|
602
|
+
For a meta event, this is the meta type, for example 0x2f for "end of track".
|
|
603
|
+
This is the event type: note on, note off, meta text, etc.
|
|
604
|
+
"""
|
|
605
|
+
return self._status
|
|
606
|
+
|
|
607
|
+
@property
|
|
608
|
+
@micropython.native
|
|
609
|
+
def channel( self ):
|
|
610
|
+
"""
|
|
611
|
+
Returns the channel number for the event, 0-15.
|
|
612
|
+
|
|
613
|
+
channel property available for: NOTE_OFF NOTE_ON
|
|
614
|
+
POLYTOUCH CONTROL_CHANGE PROGRAM_CHANGE AFTERTOUCH
|
|
615
|
+
CHANNEL_PREFIX
|
|
616
|
+
"""
|
|
617
|
+
if _FIRST_CHANNEL_EVENT<= self._status <= \
|
|
618
|
+
_LAST_CHANNEL_EVENT:
|
|
619
|
+
# For midi event status byte 0x80 to 0xef,
|
|
620
|
+
# the channel is part of the event status byte
|
|
621
|
+
return self._event_status_byte & 0x0f
|
|
622
|
+
if self._status == CHANNEL_PREFIX:
|
|
623
|
+
return self._data[0]
|
|
624
|
+
raise AttributeError
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
@property
|
|
628
|
+
@micropython.native
|
|
629
|
+
def note( self ):
|
|
630
|
+
"""
|
|
631
|
+
Returns the note number for the event, usually 0-127.
|
|
632
|
+
|
|
633
|
+
note property available for: NOTE_OFF NOTE_ON POLYTOUCH
|
|
634
|
+
"""
|
|
635
|
+
self._check_property_available( NOTE_ON,
|
|
636
|
+
NOTE_OFF,
|
|
637
|
+
POLYTOUCH )
|
|
638
|
+
return self._data[0]
|
|
639
|
+
|
|
640
|
+
@property
|
|
641
|
+
@micropython.native
|
|
642
|
+
def velocity( self ):
|
|
643
|
+
"""
|
|
644
|
+
Returns the velocity fot the event, usually 0-127.
|
|
645
|
+
|
|
646
|
+
velocity property available for: NOTE_OFF NOTE_ON
|
|
647
|
+
"""
|
|
648
|
+
|
|
649
|
+
self._check_property_available( NOTE_ON, NOTE_OFF )
|
|
650
|
+
return self._data[1]
|
|
651
|
+
|
|
652
|
+
@property
|
|
653
|
+
def value( self ):
|
|
654
|
+
"""
|
|
655
|
+
Returns the the value in the event.
|
|
656
|
+
|
|
657
|
+
value property available for: AFTERTOUCH, CONTROL_CHANGE, POLYTOUCH
|
|
658
|
+
"""
|
|
659
|
+
if self._status == AFTERTOUCH:
|
|
660
|
+
return self._data[0]
|
|
661
|
+
if self._status in ( CONTROL_CHANGE, POLYTOUCH):
|
|
662
|
+
return self._data[1]
|
|
663
|
+
raise AttributeError
|
|
664
|
+
|
|
665
|
+
@property
|
|
666
|
+
def pitch( self ):
|
|
667
|
+
"""
|
|
668
|
+
Returns the pitch for a PITCHWHEEL midi channel event.
|
|
669
|
+
|
|
670
|
+
-8192 is the lowest value possible, 0 (zero) means "no pitch bend"
|
|
671
|
+
and 8191 is the highest possible value.
|
|
672
|
+
"""
|
|
673
|
+
self._check_property_available( PITCHWHEEL )
|
|
674
|
+
# lsb (0 - 127) and msb (0 - 127) together form a 14-bit number,
|
|
675
|
+
# allowing fine adjustment to pitch.
|
|
676
|
+
# Using hex, 00 40 is the central (no bend) setting.
|
|
677
|
+
# 00 00 gives the maximum downwards bend, and 7F 7F the
|
|
678
|
+
# maximum upwards bend.
|
|
679
|
+
# Return 0 for no bend/central bend, -8192 to -1 for downward
|
|
680
|
+
# bend and -1 to 8191 for upward bend
|
|
681
|
+
return (((self._data[1]&0x7f)-0x40)<<7)| (self._data[0]&0x7f)
|
|
682
|
+
|
|
683
|
+
@property
|
|
684
|
+
def program( self ):
|
|
685
|
+
"""
|
|
686
|
+
Returns the program number 0-127 for a PROGRAM_CHANGE event.
|
|
687
|
+
"""
|
|
688
|
+
self._check_property_available( PROGRAM_CHANGE )
|
|
689
|
+
return self._data[0]
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def control( self ):
|
|
693
|
+
"""
|
|
694
|
+
Returns the value for the controller 0-127 for a CONTROL_CHANGE event.
|
|
695
|
+
"""
|
|
696
|
+
self._check_property_available( CONTROL_CHANGE )
|
|
697
|
+
return self._data[0]
|
|
698
|
+
|
|
699
|
+
@property
|
|
700
|
+
def number( self ):
|
|
701
|
+
"""
|
|
702
|
+
Returns number of a SEQUENCE_NUMBER meta event.
|
|
703
|
+
Values range from 0 to 2**24.
|
|
704
|
+
"""
|
|
705
|
+
self._check_property_available( SEQUENCE_NUMBER )
|
|
706
|
+
# Meta event sequence number has a 2 byte big endian number
|
|
707
|
+
return int.from_bytes(self._data[0:2], "big" )
|
|
708
|
+
|
|
709
|
+
@property
|
|
710
|
+
def text( self ):
|
|
711
|
+
"""
|
|
712
|
+
Returns the text for a meta events.
|
|
713
|
+
|
|
714
|
+
text property is available for: TEXT COPYRIGHT LYRICS MARKER CUE_MARKER
|
|
715
|
+
|
|
716
|
+
Both event.text and event.name decode the data. Non ASCII
|
|
717
|
+
characters are shown for example as \xa5
|
|
718
|
+
|
|
719
|
+
"""
|
|
720
|
+
self._check_property_available( TEXT,
|
|
721
|
+
COPYRIGHT,
|
|
722
|
+
LYRICS,
|
|
723
|
+
MARKER,
|
|
724
|
+
CUE_MARKER )
|
|
725
|
+
|
|
726
|
+
return decode_ascii( self.data )
|
|
727
|
+
|
|
728
|
+
@property
|
|
729
|
+
def name( self ):
|
|
730
|
+
"""
|
|
731
|
+
Returns the text for a meta events.
|
|
732
|
+
|
|
733
|
+
name property available for: TRACK_NAME INSTRUMENT_NAME PROGRAM_NAME DEVICE_NAME
|
|
734
|
+
|
|
735
|
+
See text property for description of text conversion.
|
|
736
|
+
|
|
737
|
+
The raw data can be retrieved using the data property.
|
|
738
|
+
"""
|
|
739
|
+
self._check_property_available( TRACK_NAME,
|
|
740
|
+
INSTRUMENT_NAME,
|
|
741
|
+
PROGRAM_NAME,
|
|
742
|
+
DEVICE_NAME )
|
|
743
|
+
return decode_ascii( self.data )
|
|
744
|
+
|
|
745
|
+
@property
|
|
746
|
+
def port( self ):
|
|
747
|
+
"""
|
|
748
|
+
Returns the port number 0-256 for a meta MIDI_PORT message
|
|
749
|
+
"""
|
|
750
|
+
self._check_property_available( MIDI_PORT )
|
|
751
|
+
# Meta port event
|
|
752
|
+
return self._data[0]
|
|
753
|
+
|
|
754
|
+
@property
|
|
755
|
+
def tempo( self ):
|
|
756
|
+
"""
|
|
757
|
+
Returns the tempo (0 to 2**32 microseconds per quarter beat)
|
|
758
|
+
for a SET_TEMPO meta event.
|
|
759
|
+
This module interprets the tempo event before returning it, so
|
|
760
|
+
the following events returned will have their delta_us property
|
|
761
|
+
calculated with the new tempo value.
|
|
762
|
+
|
|
763
|
+
"""
|
|
764
|
+
self._check_property_available( SET_TEMPO )
|
|
765
|
+
# Meta tempo event, 4 bytes big endian with tempo
|
|
766
|
+
# in microseconds per quarter note or beat
|
|
767
|
+
return int.from_bytes( self._data[0:3], "big")
|
|
768
|
+
|
|
769
|
+
@property
|
|
770
|
+
def key( self ):
|
|
771
|
+
"""
|
|
772
|
+
Returns the key, as str, for a KEY_SIGNATURE meta event.
|
|
773
|
+
|
|
774
|
+
For mayor keys:
|
|
775
|
+
C, D, E, F, G, A, B, C#, F#, Cb, Db, Eb, Gb, Ab
|
|
776
|
+
|
|
777
|
+
For minor keys:
|
|
778
|
+
Cm, Dm, Em, Fm, Gm, Am, Bm, C#m, F#m, Cbm, Dbm, Ebm, Gbm, Abm
|
|
779
|
+
|
|
780
|
+
If the midi message contains a value out of range, a ValueError
|
|
781
|
+
is raised. The raw data can be read with the data property.
|
|
782
|
+
"""
|
|
783
|
+
self._check_property_available( KEY_SIGNATURE )
|
|
784
|
+
# Translate data of key meta messages to scale name
|
|
785
|
+
# 2 data bytes: sharps/flats and mayor/minor
|
|
786
|
+
# sharps/flats: 0=no flats/sharps, 1 to 7 number of sharps, -1 to -7 number of flats
|
|
787
|
+
# mayor/minor: 0=mayor, 1=minor
|
|
788
|
+
sharps_flats = self._data[0]
|
|
789
|
+
minor_mayor = self._data[1]
|
|
790
|
+
|
|
791
|
+
if sharps_flats > 128:
|
|
792
|
+
sharps_flats -= 256
|
|
793
|
+
if sharps_flats not in range(-7,8) \
|
|
794
|
+
or minor_mayor not in [0,1]:
|
|
795
|
+
raise ValueError(
|
|
796
|
+
"Midi file format error, key signature meta unrecogized data" )
|
|
797
|
+
if minor_mayor == 0:
|
|
798
|
+
scale_names = ("Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F",
|
|
799
|
+
"C",
|
|
800
|
+
"G", "D", "A", "E", "B", "F#", "C#" )
|
|
801
|
+
else:
|
|
802
|
+
scale_names = ( "Abm", "Ebm", "Bbm", "Fm", "Cm", "Gm", "Dm",
|
|
803
|
+
"Am",
|
|
804
|
+
"Em", "Bm", "F#m", "C#m", "G#m", "D#m", "A#m" )
|
|
805
|
+
return scale_names[sharps_flats+7]
|
|
806
|
+
|
|
807
|
+
# Time signature meta message
|
|
808
|
+
@property
|
|
809
|
+
def numerator( self ):
|
|
810
|
+
"""
|
|
811
|
+
Returns the numerator for the TIME_SIGNATURE meta messages, 0-255.
|
|
812
|
+
"""
|
|
813
|
+
self._check_property_available( TIME_SIGNATURE )
|
|
814
|
+
return self._data[0]
|
|
815
|
+
|
|
816
|
+
@property
|
|
817
|
+
def denominator( self ):
|
|
818
|
+
"""
|
|
819
|
+
Returns the denominator for the TIME_SIGNATURE meta messages, 0-255.
|
|
820
|
+
"""
|
|
821
|
+
self._check_property_available( TIME_SIGNATURE )
|
|
822
|
+
return 2**self._data[1]
|
|
823
|
+
|
|
824
|
+
@property
|
|
825
|
+
def clocks_per_click( self ):
|
|
826
|
+
"""
|
|
827
|
+
Returns the clocks_per_click for the TIME_SIGNATURE meta messages, 0-255.
|
|
828
|
+
"""
|
|
829
|
+
self._check_property_available( TIME_SIGNATURE )
|
|
830
|
+
return self._data[2]
|
|
831
|
+
|
|
832
|
+
@property
|
|
833
|
+
def notated_32nd_notes_per_beat( self ):
|
|
834
|
+
"""
|
|
835
|
+
Returns the notated_32nd_notes_per_beat for the TIME_SIGNATURE meta messages,
|
|
836
|
+
0-255.
|
|
837
|
+
"""
|
|
838
|
+
self._check_property_available( TIME_SIGNATURE )
|
|
839
|
+
return self._data[3]
|
|
840
|
+
|
|
841
|
+
@property
|
|
842
|
+
def frame_rate( self ):
|
|
843
|
+
"""
|
|
844
|
+
Returns the frame for the SMPTE_OFFSET meta messages,
|
|
845
|
+
which can be 24, 25, 29.97 or 30.
|
|
846
|
+
|
|
847
|
+
An invalid value in the MIDI file will raise a IndexError
|
|
848
|
+
"""
|
|
849
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
850
|
+
return [24,25,29.97,30][(self._data[0] >> 5)]
|
|
851
|
+
|
|
852
|
+
@property
|
|
853
|
+
def hours( self ):
|
|
854
|
+
"""
|
|
855
|
+
Returns the hour for the SMPTE_OFFSET meta message,
|
|
856
|
+
usually from 0 to 23.
|
|
857
|
+
"""
|
|
858
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
859
|
+
return self._data[0] & 0x1f
|
|
860
|
+
|
|
861
|
+
@property
|
|
862
|
+
def minutes( self ):
|
|
863
|
+
"""
|
|
864
|
+
Returns the minutes for the SMPTE_OFFSET meta message,
|
|
865
|
+
usually from 0 to 59.
|
|
866
|
+
"""
|
|
867
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
868
|
+
return self._data[1]
|
|
869
|
+
|
|
870
|
+
@property
|
|
871
|
+
def seconds( self ):
|
|
872
|
+
"""
|
|
873
|
+
Returns the seconds for the SMPTE_OFFSET meta message,
|
|
874
|
+
usually from 0 to 59.
|
|
875
|
+
"""
|
|
876
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
877
|
+
return self._data[2]
|
|
878
|
+
|
|
879
|
+
@property
|
|
880
|
+
def frames( self ):
|
|
881
|
+
"""
|
|
882
|
+
Returns the frames for the SMPTE_OFFSET meta message,
|
|
883
|
+
usually from 0 to 255.
|
|
884
|
+
"""
|
|
885
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
886
|
+
return self._data[3]
|
|
887
|
+
|
|
888
|
+
@property
|
|
889
|
+
def sub_frames( self ):
|
|
890
|
+
"""
|
|
891
|
+
Returns the sub frames for the SMPTE_OFFSET meta message,
|
|
892
|
+
usually from 0 to 59.
|
|
893
|
+
"""
|
|
894
|
+
self._check_property_available( SMPTE_OFFSET )
|
|
895
|
+
return self._data[4]
|
|
896
|
+
|
|
897
|
+
@property
|
|
898
|
+
def data( self ):
|
|
899
|
+
"""
|
|
900
|
+
Returns the raw data for the underlying message, with no transofrmations,
|
|
901
|
+
as a memoryview, without the event status byte or meta prefix.
|
|
902
|
+
"""
|
|
903
|
+
|
|
904
|
+
return self._data
|
|
905
|
+
|
|
906
|
+
@micropython.native
|
|
907
|
+
def copy( self ):
|
|
908
|
+
"""
|
|
909
|
+
Returns a deep copy (a complete independent copy) of the event.
|
|
910
|
+
"""
|
|
911
|
+
|
|
912
|
+
my_copy = MidiEvent()
|
|
913
|
+
my_copy._event_status_byte = self._event_status_byte
|
|
914
|
+
my_copy._status = self._status
|
|
915
|
+
my_copy._data = bytearray( self._data )
|
|
916
|
+
my_copy.delta_miditicks = self.delta_miditicks
|
|
917
|
+
my_copy.delta_us = self.delta_us
|
|
918
|
+
my_copy.timestamp_us = self.timestamp_us
|
|
919
|
+
return my_copy
|
|
920
|
+
|
|
921
|
+
def is_meta( self ):
|
|
922
|
+
"""
|
|
923
|
+
Returns True if this is a Meta event, such as
|
|
924
|
+
lyrics, set tempo or key signature.
|
|
925
|
+
Returns False if this is a MIDI channel event,
|
|
926
|
+
or a Sysex or Escape event.
|
|
927
|
+
"""
|
|
928
|
+
return _FIRST_META_EVENT <= self._status <= _LAST_META_EVENT
|
|
929
|
+
|
|
930
|
+
def is_channel( self ):
|
|
931
|
+
"""
|
|
932
|
+
Returns True if this event is a channel event
|
|
933
|
+
"""
|
|
934
|
+
return _FIRST_CHANNEL_EVENT <= self._status <= _LAST_CHANNEL_EVENT
|
|
935
|
+
|
|
936
|
+
def to_midi( self ):
|
|
937
|
+
"""
|
|
938
|
+
Returns the event as bytes, in a format that allows sending the
|
|
939
|
+
data to a MIDI controller.
|
|
940
|
+
|
|
941
|
+
to_midi will raise AttributeError if the event is for MIDI meta messages, these
|
|
942
|
+
occur in MIDI files and are not normally sent to MIDI controllers.
|
|
943
|
+
|
|
944
|
+
This function has not been tested with a real MIDI device.
|
|
945
|
+
"""
|
|
946
|
+
if self.is_meta():
|
|
947
|
+
raise AttributeError
|
|
948
|
+
return self._event_status_byte.to_bytes( 1, "big") + self._data
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
class MidiTrack:
|
|
953
|
+
"""
|
|
954
|
+
This object contains the track of a midi file. It is
|
|
955
|
+
created internally by the MidiFile function for each track
|
|
956
|
+
chunk found in the midi file.
|
|
957
|
+
|
|
958
|
+
MidiTrack objects are accessible via the MidiFile.tracks list
|
|
959
|
+
|
|
960
|
+
"""
|
|
961
|
+
def __init__( self,
|
|
962
|
+
file_object,
|
|
963
|
+
filename,
|
|
964
|
+
reuse_event_object,
|
|
965
|
+
buffer_size,
|
|
966
|
+
miditicks_per_quarter ):
|
|
967
|
+
"""
|
|
968
|
+
The MidiTrack cosntructor is called internally by MidiFile,
|
|
969
|
+
you don't need to create a MidiTrack.
|
|
970
|
+
"""
|
|
971
|
+
|
|
972
|
+
# Parameters are:
|
|
973
|
+
# file_object: This is the currently opened midi file, positioned at the start
|
|
974
|
+
# of this track's data,
|
|
975
|
+
# just before the 4 bytes with the track or chunk length.
|
|
976
|
+
# filename: the file name of file_object.
|
|
977
|
+
# file_object.name not available on CircuitPython
|
|
978
|
+
self._reuse_event_object = reuse_event_object
|
|
979
|
+
self._miditicks_per_quarter = miditicks_per_quarter
|
|
980
|
+
self._buffer_size = buffer_size
|
|
981
|
+
|
|
982
|
+
# MTrk header in file has just been processed, get chunk length
|
|
983
|
+
self._track_length = int.from_bytes( file_object.read(4), "big" )
|
|
984
|
+
|
|
985
|
+
if buffer_size <= 0:
|
|
986
|
+
# Read the entire track data to RAM
|
|
987
|
+
self._track_data = file_object.read( self._track_length )
|
|
988
|
+
else:
|
|
989
|
+
# Store filename and start position to open file when interation over track data starts
|
|
990
|
+
self._filename = filename
|
|
991
|
+
self._start_position = file_object.tell()
|
|
992
|
+
|
|
993
|
+
# Skip rest of track chunk, fast forward to beginning of next track
|
|
994
|
+
file_object.seek( self._track_length, 1 )
|
|
995
|
+
|
|
996
|
+
self._track_parser = None
|
|
997
|
+
self.event = None
|
|
998
|
+
self.current_miditicks = None
|
|
999
|
+
|
|
1000
|
+
def _buffered_data_generator( self ):
|
|
1001
|
+
# Generator to return byte by byte from a buffered track
|
|
1002
|
+
# (a track entirely in memory, buffer_size=0)
|
|
1003
|
+
# This way seems to be rather fast:
|
|
1004
|
+
return ( data_byte for data_byte in self._track_data )
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def _file_data_generator( self ):
|
|
1008
|
+
# Generator to return byte by byte of a track with
|
|
1009
|
+
# buffer_size>0. Reads portions of n bytes and then returns
|
|
1010
|
+
# byte by byte.
|
|
1011
|
+
|
|
1012
|
+
# Allocate buffer to be reused for each read
|
|
1013
|
+
buffer = bytearray( self._buffer_size )
|
|
1014
|
+
|
|
1015
|
+
# Open file again to read the track
|
|
1016
|
+
with open( self._filename, "rb") as file:
|
|
1017
|
+
file.seek( self._start_position )
|
|
1018
|
+
unread_bytes = self._track_length
|
|
1019
|
+
while True:
|
|
1020
|
+
# Read a buffer of data and yield byte by byte to caller
|
|
1021
|
+
bytes_read = file.readinto( buffer )
|
|
1022
|
+
yield from memoryview(buffer)[0:bytes_read]
|
|
1023
|
+
# Check if end of track reached
|
|
1024
|
+
unread_bytes -= bytes_read
|
|
1025
|
+
if unread_bytes <= 0 or bytes_read == 0:
|
|
1026
|
+
return
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def _get_midi_data( self ):
|
|
1030
|
+
# Choose method to return data
|
|
1031
|
+
if self._buffer_size <= 0:
|
|
1032
|
+
return self._buffered_data_generator
|
|
1033
|
+
return self._file_data_generator
|
|
1034
|
+
|
|
1035
|
+
def __iter__( self ):
|
|
1036
|
+
"""
|
|
1037
|
+
Iterating through a track will yield all events of that track
|
|
1038
|
+
of MIDI file. For example, to parse the first track in a midi file:
|
|
1039
|
+
|
|
1040
|
+
for event in MidiFile("example.mid").track[0]:
|
|
1041
|
+
.... process event ...
|
|
1042
|
+
|
|
1043
|
+
event.delta_miditicks will have the time difference with the previous
|
|
1044
|
+
event, in MIDI ticks (pulses).
|
|
1045
|
+
|
|
1046
|
+
event.delta_us is calculated as the time difference with the previous event
|
|
1047
|
+
in microseconds. For this calculation, the set tempo events and
|
|
1048
|
+
the MIDI ticks per quarter note (also called "pulses per beat")
|
|
1049
|
+
of the MIDI file header are taken into consideration.
|
|
1050
|
+
|
|
1051
|
+
The last event will always be a END_OF_TRACK event, if missing in the file.
|
|
1052
|
+
|
|
1053
|
+
"""
|
|
1054
|
+
# Get the parser to return event by event, process set tempo meta events,
|
|
1055
|
+
# calculate delta_us and ensure END_OF_TRACK present at the end.
|
|
1056
|
+
# This is used to parse a single track, for multitrack processing _track_parse_start
|
|
1057
|
+
# method is used
|
|
1058
|
+
return _process_events(
|
|
1059
|
+
MidiParser( iter(self._get_midi_data()()) ).parse_events(),
|
|
1060
|
+
self._miditicks_per_quarter,
|
|
1061
|
+
self._reuse_event_object )
|
|
1062
|
+
|
|
1063
|
+
# _track_parse_start and _track_parse_next are an iterator used
|
|
1064
|
+
# to merge tracks. Instead of just iterationg, they also keep track of the
|
|
1065
|
+
# sum of midi ticks in thr track. They allow comparing tracks to know which
|
|
1066
|
+
# has the next event.
|
|
1067
|
+
def _track_parse_start( self ):
|
|
1068
|
+
# This is an internal method called by MidiFile for multitrack processing.
|
|
1069
|
+
self._track_parser = MidiParser( iter(self._get_midi_data()()) ).parse_events()
|
|
1070
|
+
|
|
1071
|
+
# Get first event to get things going...
|
|
1072
|
+
self.event = next( self._track_parser )
|
|
1073
|
+
self.current_miditicks = self.event.delta_miditicks
|
|
1074
|
+
|
|
1075
|
+
return self
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
@micropython.native
|
|
1079
|
+
def _track_parse_next( self ):
|
|
1080
|
+
# Used internally by MidiFile object.
|
|
1081
|
+
# After doing a _track_parse_start, this will return the next event in track.
|
|
1082
|
+
self.event = next( self._track_parser )
|
|
1083
|
+
self.current_miditicks += self.event.delta_miditicks
|
|
1084
|
+
return self.event
|
|
1085
|
+
|
|
1086
|
+
|
|
1087
|
+
@micropython.native
|
|
1088
|
+
def __lt__( self, compare_to ):
|
|
1089
|
+
"""
|
|
1090
|
+
Used internally by the min function to compare the current time in miditicks
|
|
1091
|
+
of the different tracks, the goal is to find the next midi event
|
|
1092
|
+
of all tracks (the one with the smallest time since the beginning of the track)
|
|
1093
|
+
"""
|
|
1094
|
+
# Valid after _track_parse_start, in conjunction with _track_parse_next.
|
|
1095
|
+
return self.current_miditicks < compare_to.current_miditicks
|
|
1096
|
+
|
|
1097
|
+
def _get_current_miditicks(self):
|
|
1098
|
+
return self.current_miditicks
|
|
1099
|
+
|
|
1100
|
+
def play( self ):
|
|
1101
|
+
"""
|
|
1102
|
+
Plays the track. Intended for use with format 2 MIDI files.
|
|
1103
|
+
Sleeps between events, yielding the events on time.
|
|
1104
|
+
See also MidiFile.play.
|
|
1105
|
+
|
|
1106
|
+
"""
|
|
1107
|
+
return MidiPlay( self )
|
|
1108
|
+
|
|
1109
|
+
class MidiFile:
|
|
1110
|
+
"""
|
|
1111
|
+
Parses a MIDI file.
|
|
1112
|
+
"""
|
|
1113
|
+
def __init__( self,
|
|
1114
|
+
filename,
|
|
1115
|
+
buffer_size=100,
|
|
1116
|
+
reuse_event_object=False ):
|
|
1117
|
+
"""
|
|
1118
|
+
filename
|
|
1119
|
+
The name of a MIDI file, usually a .mid or .rtx MIDI file.
|
|
1120
|
+
|
|
1121
|
+
buffer_size=100
|
|
1122
|
+
The buffer size that will be allocated for each track, 0=read
|
|
1123
|
+
complete track to memory.
|
|
1124
|
+
|
|
1125
|
+
reuse_event_object=False
|
|
1126
|
+
True will reuse the event object during parsing, using less RAM.
|
|
1127
|
+
|
|
1128
|
+
Returns an iterator over the events in the MIDI file.
|
|
1129
|
+
"""
|
|
1130
|
+
|
|
1131
|
+
# Store parameters
|
|
1132
|
+
self._reuse_event_object = reuse_event_object
|
|
1133
|
+
self._buffer_size = buffer_size
|
|
1134
|
+
|
|
1135
|
+
# Process file
|
|
1136
|
+
with open( filename, "rb" ) as file:
|
|
1137
|
+
|
|
1138
|
+
# First chunk must be MThd midi header, process header and validate
|
|
1139
|
+
self._format_type, \
|
|
1140
|
+
number_of_chunks, \
|
|
1141
|
+
self._miditicks_per_quarter = self._get_header( file )
|
|
1142
|
+
|
|
1143
|
+
self._filename = filename
|
|
1144
|
+
|
|
1145
|
+
# Get all track objects of the file.
|
|
1146
|
+
# Disregard the number of chunks, read the real number of tracks present.
|
|
1147
|
+
self.tracks = []
|
|
1148
|
+
for _ in range(number_of_chunks):
|
|
1149
|
+
track_id = decode_ascii( file.read(4) )
|
|
1150
|
+
# Only process MTrk chunks
|
|
1151
|
+
if track_id == "MTrk":
|
|
1152
|
+
self.tracks.append( MidiTrack( file,
|
|
1153
|
+
filename,
|
|
1154
|
+
reuse_event_object,
|
|
1155
|
+
buffer_size,
|
|
1156
|
+
self._miditicks_per_quarter) )
|
|
1157
|
+
else:
|
|
1158
|
+
# Skip non-track chunk,
|
|
1159
|
+
# use MidiTrack but ignore result
|
|
1160
|
+
MidiTrack( file,
|
|
1161
|
+
filename,
|
|
1162
|
+
reuse_event_object,
|
|
1163
|
+
10,
|
|
1164
|
+
self._miditicks_per_quarter )
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def _get_header( self, file ):
|
|
1168
|
+
# Decodes the MIDI file header, returns the
|
|
1169
|
+
# values of the header:
|
|
1170
|
+
# format type (0-2), number of data chunks, MIDI ticks per quarter note
|
|
1171
|
+
|
|
1172
|
+
track_id = decode_ascii( file.read(4) )
|
|
1173
|
+
if track_id != "MThd":
|
|
1174
|
+
# It is said that Mac midi files may have 128 extra
|
|
1175
|
+
# bytes prepended (i.e. a Mac BInary Header)
|
|
1176
|
+
# Just in case, skip bytes until 128 bytes have been ignored,
|
|
1177
|
+
# then read track_id again
|
|
1178
|
+
# I have not been able to verify this.
|
|
1179
|
+
file.read(128-4)
|
|
1180
|
+
track_id = decode_ascii( file.read(4) )
|
|
1181
|
+
if track_id != "MThd":
|
|
1182
|
+
raise ValueError("Midi file does not start with MThd header")
|
|
1183
|
+
header_len = int.from_bytes( file.read(4), "big" )
|
|
1184
|
+
|
|
1185
|
+
if header_len < 6:
|
|
1186
|
+
raise ValueError(
|
|
1187
|
+
f"Midi file header MThd length ({header_len}) is smaller than 6 bytes"
|
|
1188
|
+
)
|
|
1189
|
+
# IF header is larger than 6 bytes, the extra bytes are ignored.
|
|
1190
|
+
|
|
1191
|
+
header_data = file.read( header_len )
|
|
1192
|
+
|
|
1193
|
+
# Format type 0: single MTrk chunk
|
|
1194
|
+
# Format type 1: two or more MTrk chunks to be merged
|
|
1195
|
+
# Format type 2: multiple MTrk chunks, each to be used separately
|
|
1196
|
+
format_type = int.from_bytes( header_data[0:2], "big" )
|
|
1197
|
+
|
|
1198
|
+
# Get number of data chunks (track chunks) in the file
|
|
1199
|
+
number_of_chunks = int.from_bytes( header_data[2:4], "big" )
|
|
1200
|
+
|
|
1201
|
+
# Get pulses per beat
|
|
1202
|
+
miditicks_per_quarter = int.from_bytes( header_data[4:6], "big" )
|
|
1203
|
+
|
|
1204
|
+
if miditicks_per_quarter > 32767:
|
|
1205
|
+
raise ValueError("Midi SMPTE time codes not supported")
|
|
1206
|
+
|
|
1207
|
+
return format_type, number_of_chunks, miditicks_per_quarter
|
|
1208
|
+
|
|
1209
|
+
@property
|
|
1210
|
+
def format_type( self ):
|
|
1211
|
+
"""
|
|
1212
|
+
Returns the MIDI format type as stored in the header of the MIDI file:
|
|
1213
|
+
"""
|
|
1214
|
+
return self._format_type
|
|
1215
|
+
|
|
1216
|
+
@property
|
|
1217
|
+
def miditicks_per_quarter( self ):
|
|
1218
|
+
"""
|
|
1219
|
+
Return the midi ticks per quarter note (also called pulses per beat)
|
|
1220
|
+
parameter in the MIDI header of the file.
|
|
1221
|
+
"""
|
|
1222
|
+
return self._miditicks_per_quarter
|
|
1223
|
+
|
|
1224
|
+
@property
|
|
1225
|
+
def filename( self ):
|
|
1226
|
+
"""
|
|
1227
|
+
Return the file name of the MIDI file, with absolute path.
|
|
1228
|
+
"""
|
|
1229
|
+
return self._filename
|
|
1230
|
+
|
|
1231
|
+
@property
|
|
1232
|
+
def buffer_size( self ):
|
|
1233
|
+
"""
|
|
1234
|
+
Return the buffer_size value. 0=tracks are buffered entirely in RAM.
|
|
1235
|
+
A number, for example buffer_size=100 means a buffer of 100 bytes is
|
|
1236
|
+
allocated per track to read the track data.
|
|
1237
|
+
|
|
1238
|
+
This allows to read large MIDI files efficiently on microcontrollers with small RAM.
|
|
1239
|
+
"""
|
|
1240
|
+
return self._buffer_size
|
|
1241
|
+
|
|
1242
|
+
@property
|
|
1243
|
+
def reuse_event_object( self ):
|
|
1244
|
+
"""
|
|
1245
|
+
Return the value of reuse_event_object.
|
|
1246
|
+
True: when iterating through a track or midi file, the same event object
|
|
1247
|
+
is returned over and over (this is an optimization recommended for Micropython)
|
|
1248
|
+
|
|
1249
|
+
False: when iterating through a track or midi file, a different event
|
|
1250
|
+
object is returned each time (this is the typical Python behavior).
|
|
1251
|
+
"""
|
|
1252
|
+
return self._reuse_event_object
|
|
1253
|
+
|
|
1254
|
+
def _track_merger( self ):
|
|
1255
|
+
# Merges all tracks of a multitrack format 1 file
|
|
1256
|
+
|
|
1257
|
+
# Iterate through each track, set up one iterator for each track
|
|
1258
|
+
# For this code to work, the track interator will always yield
|
|
1259
|
+
# a END_OF_TRACK event at the end of the track.
|
|
1260
|
+
play_tracks = [ track._track_parse_start() for track in self.tracks ]
|
|
1261
|
+
|
|
1262
|
+
# Current miditicks keeps the time, in MIDI ticks, since start of track
|
|
1263
|
+
# of the last event returned
|
|
1264
|
+
current_miditicks = 0
|
|
1265
|
+
|
|
1266
|
+
while True:
|
|
1267
|
+
# From all tracks, select the track with the next event, this is
|
|
1268
|
+
# the one with the lowest "current MIDI ticks time".
|
|
1269
|
+
next_track = min( play_tracks ) # Uses the __lt__ function of track
|
|
1270
|
+
|
|
1271
|
+
# Get the current event of the selected track
|
|
1272
|
+
event = next_track.event
|
|
1273
|
+
|
|
1274
|
+
# Adjust event miditicks to time difference with last event overall,
|
|
1275
|
+
# replacing delta time with last event in the event's track
|
|
1276
|
+
track_miditicks = next_track._get_current_miditicks()
|
|
1277
|
+
event.delta_miditicks = track_miditicks - current_miditicks
|
|
1278
|
+
|
|
1279
|
+
# If end_of_track is seen, don't continue to process this track
|
|
1280
|
+
if event.status == END_OF_TRACK:
|
|
1281
|
+
# Delete the track from the list of tracks being processed
|
|
1282
|
+
track_index = play_tracks.index(next_track)
|
|
1283
|
+
del play_tracks[track_index]
|
|
1284
|
+
|
|
1285
|
+
# If all tracks have ended, stop processing file
|
|
1286
|
+
if len(play_tracks) == 0:
|
|
1287
|
+
# Yield only the last end_of_track found
|
|
1288
|
+
yield event
|
|
1289
|
+
# And stop iteration
|
|
1290
|
+
return
|
|
1291
|
+
|
|
1292
|
+
# Don't yield end of track events (except for the last track)
|
|
1293
|
+
continue
|
|
1294
|
+
|
|
1295
|
+
yield event
|
|
1296
|
+
|
|
1297
|
+
# Update current time, this is now the time of the event
|
|
1298
|
+
# just returned
|
|
1299
|
+
current_miditicks = track_miditicks
|
|
1300
|
+
|
|
1301
|
+
# Get the next event of the selected track.
|
|
1302
|
+
# This has to be done after the yield, because this might
|
|
1303
|
+
# overwrite the yielded message if reuse_event_object=True.
|
|
1304
|
+
next_track._track_parse_next()
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def __iter__( self ):
|
|
1308
|
+
"""
|
|
1309
|
+
To get all the events of a format type 0 or format type 1 MIDI file,
|
|
1310
|
+
iterate through the MidiFile object, for example:
|
|
1311
|
+
for event in MidiFile("example.mid"):
|
|
1312
|
+
print(event)
|
|
1313
|
+
|
|
1314
|
+
"""
|
|
1315
|
+
# Check if there are tracks, there should be....
|
|
1316
|
+
if len(self.tracks) == 0:
|
|
1317
|
+
# No tracks in file, simulate an empty track
|
|
1318
|
+
# This will yield a single END_OF_TRACK event.
|
|
1319
|
+
return _process_events( iter([]),
|
|
1320
|
+
self._miditicks_per_quarter,
|
|
1321
|
+
self._reuse_event_object )
|
|
1322
|
+
|
|
1323
|
+
# Iterate over track instead of file for format 2 files
|
|
1324
|
+
if self._format_type == 2 and len(self.tracks) > 1:
|
|
1325
|
+
raise RuntimeError(
|
|
1326
|
+
"It's not possible to merge tracks of a MIDI format type 2 file")
|
|
1327
|
+
|
|
1328
|
+
# If there is only one track present,
|
|
1329
|
+
# iterate through the track only, no track merge is needed.
|
|
1330
|
+
# This reduces CPU usage, in some cases by up to 15%.
|
|
1331
|
+
if len(self.tracks) == 1:
|
|
1332
|
+
return iter(self.tracks[0])
|
|
1333
|
+
|
|
1334
|
+
# For multitrack file type 1 files, tracks must be merged.
|
|
1335
|
+
# Type 0 files with many tracks (not standard) are merged too.
|
|
1336
|
+
return _process_events( self._track_merger(),
|
|
1337
|
+
self._miditicks_per_quarter,
|
|
1338
|
+
self._reuse_event_object )
|
|
1339
|
+
|
|
1340
|
+
def length_us( self ):
|
|
1341
|
+
"""
|
|
1342
|
+
Returns the length of the MidiFile in microseconds.
|
|
1343
|
+
"""
|
|
1344
|
+
# Returns the duration of playback time of the midi file microseconds
|
|
1345
|
+
|
|
1346
|
+
# Start playing time at 0, in case there are no events
|
|
1347
|
+
playback_time_us = 0
|
|
1348
|
+
|
|
1349
|
+
# Iterate through all events
|
|
1350
|
+
# The complete file must be processed to compute length
|
|
1351
|
+
# Open another instance of the file, so that the current process is not disturbed
|
|
1352
|
+
for event in MidiFile( self.filename ):
|
|
1353
|
+
playback_time_us += event.delta_us
|
|
1354
|
+
|
|
1355
|
+
# Return the last time seen, or 0 if there were no events
|
|
1356
|
+
return playback_time_us
|
|
1357
|
+
|
|
1358
|
+
def play( self ):
|
|
1359
|
+
"""
|
|
1360
|
+
Iterate through the events of a MIDI file or a track,
|
|
1361
|
+
sleep until the event has to take place, and
|
|
1362
|
+
yield the event. Playing time is measured always from the start
|
|
1363
|
+
of file, correcting a possible accumulation of timing errors.
|
|
1364
|
+
"""
|
|
1365
|
+
return MidiPlay( self )
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
class MidiPlay:
|
|
1369
|
+
"""
|
|
1370
|
+
Internal class used to play a MIDI file waiting after each event for the next one.
|
|
1371
|
+
Use: MidiPlay( instance_of_MidiFile ) or MidiPlay( instance_of_MidiTrack )
|
|
1372
|
+
Uses the __iter__/__next__ functions of MidiFile and MidiTrack to iterathe over the events.
|
|
1373
|
+
"""
|
|
1374
|
+
def __init__( self, midi_event_source ):
|
|
1375
|
+
self.midi_event_source = midi_event_source
|
|
1376
|
+
|
|
1377
|
+
|
|
1378
|
+
def get_event_generator( self ):
|
|
1379
|
+
# Generator to iterate over the events and calculate the wait time
|
|
1380
|
+
# for each event. Wait time is corrected by adjusting with real time compared
|
|
1381
|
+
# to time since start of file.
|
|
1382
|
+
playing_started_at = time_now_us()
|
|
1383
|
+
midi_time = 0
|
|
1384
|
+
for event in self.midi_event_source:
|
|
1385
|
+
midi_time += event.delta_us
|
|
1386
|
+
now = time_now_us()
|
|
1387
|
+
playing_time = time_diff_us( now, playing_started_at )
|
|
1388
|
+
event.timestamp_us = midi_time
|
|
1389
|
+
yield (event, midi_time - playing_time)
|
|
1390
|
+
|
|
1391
|
+
def __iter__( self ):
|
|
1392
|
+
self.iterator = iter( self.get_event_generator() )
|
|
1393
|
+
return self
|
|
1394
|
+
|
|
1395
|
+
def __next__( self ):
|
|
1396
|
+
event, wait_time = next( self.iterator )
|
|
1397
|
+
if wait_time > 0:
|
|
1398
|
+
time_sleep_us( wait_time )
|
|
1399
|
+
return event
|
|
1400
|
+
|
|
1401
|
+
def __aiter__( self ):
|
|
1402
|
+
return self.__iter__()
|
|
1403
|
+
|
|
1404
|
+
async def __anext__( self ):
|
|
1405
|
+
# asyncio version of __next__
|
|
1406
|
+
try:
|
|
1407
|
+
event, wait_time = next( self. iterator )
|
|
1408
|
+
except StopIteration:
|
|
1409
|
+
raise StopAsyncIteration
|
|
1410
|
+
# If wait time <= 0, execute asyncio.sleep anyhow to yield control to other tasks
|
|
1411
|
+
await asyncio_sleep_ms( max(wait_time//1_000,0) )
|
|
1412
|
+
return event
|
|
1413
|
+
|