archaeopteryx 0.1.0

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 (44) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/MIDI_FLOW_DIAGRAM.md +61 -0
  4. data/README.md +133 -0
  5. data/bin/arcx +8 -0
  6. data/lib/archaeopteryx/app_pathname.rb +50 -0
  7. data/lib/archaeopteryx/application.rb +183 -0
  8. data/lib/archaeopteryx/application_runner.rb +23 -0
  9. data/lib/archaeopteryx/cli.rb +44 -0
  10. data/lib/archaeopteryx/client.rb +153 -0
  11. data/lib/archaeopteryx/clip.rb +119 -0
  12. data/lib/archaeopteryx/clip_application.rb +7 -0
  13. data/lib/archaeopteryx/commands/application_helper.rb +9 -0
  14. data/lib/archaeopteryx/commands/connections.rb +41 -0
  15. data/lib/archaeopteryx/commands/create_instrument.rb +15 -0
  16. data/lib/archaeopteryx/commands/generate.rb +44 -0
  17. data/lib/archaeopteryx/commands/new.rb +103 -0
  18. data/lib/archaeopteryx/commands/start.rb +13 -0
  19. data/lib/archaeopteryx/commands/status.rb +15 -0
  20. data/lib/archaeopteryx/commands/stop.rb +15 -0
  21. data/lib/archaeopteryx/commands/templates/Gemfile +3 -0
  22. data/lib/archaeopteryx/commands/templates/bin/arcx +6 -0
  23. data/lib/archaeopteryx/commands/templates/clips/clip.rb +3 -0
  24. data/lib/archaeopteryx/commands/templates/config/application.rb +8 -0
  25. data/lib/archaeopteryx/commands/templates/config/connections.yml +3 -0
  26. data/lib/archaeopteryx/commands/templates/instruments/instrument.rb +3 -0
  27. data/lib/archaeopteryx/commands/templates/live.rb +3 -0
  28. data/lib/archaeopteryx/commands.rb +12 -0
  29. data/lib/archaeopteryx/daemonize.rb +73 -0
  30. data/lib/archaeopteryx/duration_calculator.rb +35 -0
  31. data/lib/archaeopteryx/instrument.rb +60 -0
  32. data/lib/archaeopteryx/journey.rb +163 -0
  33. data/lib/archaeopteryx/live.rb +13 -0
  34. data/lib/archaeopteryx/mutator.rb +7 -0
  35. data/lib/archaeopteryx/note.rb +40 -0
  36. data/lib/archaeopteryx/notifier.rb +23 -0
  37. data/lib/archaeopteryx/probability_generator.rb +18 -0
  38. data/lib/archaeopteryx/registrable.rb +28 -0
  39. data/lib/archaeopteryx/rythm_sequence.rb +43 -0
  40. data/lib/archaeopteryx/track.rb +37 -0
  41. data/lib/archaeopteryx/track_notifier.rb +15 -0
  42. data/lib/archaeopteryx/version.rb +3 -0
  43. data/lib/archaeopteryx.rb +11 -0
  44. metadata +213 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: cd159f3160d99219dcc477e2fc64e64e3b49e166600e1e0792bd484821a0a408
4
+ data.tar.gz: b8f6fa35a89c4d1bc7d3ba9f158d832200db1b1cf490557e68c793c421ba54fb
5
+ SHA512:
6
+ metadata.gz: 87797e6dcc6b7d344ddaca19802b2e82fd896201f1d36c8ca3d637e520050cdb8d5b544d2a680a710593dc4ba4a3b64e73a18e800e6af5b5908d1bafd7f049fc
7
+ data.tar.gz: bbf7fe302807a9d18c821b351400162a3056e789d02a0ee1fe78f7ef4e6f07780eaf7cead5d6d6535b24150af7a4d4927b4c26efe351e9de86b77a0d5bf0ab87
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2010-2026 StupidCodeFactory (Yann Marquet)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,61 @@
1
+ # MIDI Message Flow
2
+
3
+ How MIDI clock reaches Ruby, and how notes go back out. The C extension and the `RCoreMidi::Client` base class live in the [rcoremidi](https://github.com/StupidCodeFactory/rcoremidi) gem (`ext/rcoremidi/client.c`); the scheduling is `Archaeopteryx::Client` (`lib/archaeopteryx/client.rb`), a subclass that overrides the clock hooks.
4
+
5
+ ```
6
+ MIDI master (DAW, drum machine)
7
+ │ Start FA · Clock F8 · Stop FC · Continue FB · Song Position F2
8
+ ▼
9
+ CoreMIDI ──► receive block CoreMIDI real-time thread
10
+ │ reads Universal MIDI Packets (MIDI 1.0 protocol)
11
+ │ tracks the tick position (Start ⇒ next F8 is tick 0)
12
+ │ copies {kind, tick, packet host time} into a lock-free
13
+ │ ring buffer (1024 events, C11 atomics, no allocation)
14
+ │ signals a dispatch semaphore
15
+ ▼
16
+ Client#start (any Ruby thread, e.g. Thread.new { client.start })
17
+ │ waits on the semaphore with the GVL released,
18
+ │ so every other Ruby thread keeps running
19
+ │ re-acquires the GVL, drains the ring buffer and calls:
20
+ │ on_start(host_time)
21
+ │ on_tick(tick, host_time)
22
+ │ on_stop / on_continue (only if defined)
23
+ │ then runs pending interrupts (traps, Ctrl-C, Thread#kill)
24
+ ▼
25
+ Archaeopteryx::Client (subclass of RCoreMidi::Client)
26
+ │ measures the tick period from the clock host times
27
+ │ (forgotten on Stop, so a tempo change while stopped
28
+ │ is picked up from the first clocks after Continue)
29
+ │ counts an interval only when it and the previous one
30
+ │ are at least 2 ms, so the catch-up clocks a DAW sends
31
+ │ with Continue and the shortened gap after them are
32
+ │ ignored
33
+ │ on Start, generates bar 1; one beat (24 ticks) before
34
+ │ each later bar, generates it
35
+ │ converts each note's offset into a clock position
36
+ │ sends each note 3 ticks before its position, timed from
37
+ │ the latest clock and the measured tick period
38
+ │ Continue plays the rest of the current bar from the
39
+ │ resume point, skipping notes already in the past
40
+ │ a Song Position jump while playing restarts the same
41
+ │ way from the new position
42
+ ▼
43
+ send_packets(destination, notes, base_host_time)
44
+ │ one call per destination: an instrument's output:
45
+ │ port, or the app's midi_out
46
+ │ validates bytes and timestamps, converts MIDI 1.0 bytes
47
+ │ to Universal MIDI Packets, sorts by time
48
+ │ (note-off before note-on at the same instant)
49
+ ▼
50
+ MIDISendEventList: CoreMIDI schedules each event at its host time ──► synth
51
+ ```
52
+
53
+ The shared CoreMIDI client lives on a dedicated run-loop thread, so setup notifications reach it. `Device.all` rebuilds its list after any setup change.
54
+
55
+ ## Guarantees
56
+
57
+ - The CoreMIDI thread never takes a lock, allocates, prints or calls Ruby.
58
+ - Ruby code only ever runs on the thread that called `start`, with the GVL held and no CoreFoundation frames on the stack, so exceptions unwind normally.
59
+ - `start` returns when `stop` or `dispose` is called. Exceptions raised in a handler, Ctrl-C and `Thread#kill` propagate out of `start`. Signals with a trap handler and `Thread#wakeup` do not stop the clock.
60
+ - Clock messages received while the clock is not running are ignored. If Ruby falls more than 1024 events behind, new events are dropped and counted in `dropped_clock_events`.
61
+ - `on_stop` calls `silence`, which unschedules pending packets and sends All Sound Off and All Notes Off on all 16 channels of every destination the client has sent to (up to 16). `dispose` does the same.
data/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # Archaeopteryx
2
+
3
+ Live coding MIDI in Ruby. You write clips (rhythmic and melodic patterns) and
4
+ instruments (which clip plays on which bar, on which MIDI channel) as plain
5
+ Ruby files. Then you start a session that follows an external MIDI clock from
6
+ your DAW or drum machine. Edit a file while it plays and the change is heard
7
+ from the next bar Archaeopteryx prepares, one beat ahead of the bar.
8
+
9
+ Archaeopteryx is built on [rcoremidi](https://github.com/StupidCodeFactory/rcoremidi),
10
+ a C extension for macOS CoreMIDI. rcoremidi receives the clock and schedules
11
+ timestamped notes. Archaeopteryx decides which notes to play and when.
12
+
13
+ ## Requirements
14
+
15
+ - macOS. rcoremidi wraps CoreMIDI, so it does not build anywhere else.
16
+ - Ruby 3.2 or later.
17
+ - A MIDI clock source and a synth listening on a MIDI port. The IAC Driver
18
+ (Audio MIDI Setup > MIDI Studio > IAC Driver > "Device is online") gives
19
+ you a virtual bus between Archaeopteryx and your DAW.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ gem install archaeopteryx
25
+ ```
26
+
27
+ This also installs rcoremidi (the CoreMIDI driver) and
28
+ [musicalism](https://github.com/StupidCodeFactory/musicalism) (keys and chords).
29
+ `arcx new` writes a Gemfile for the generated set, so `bundle install` inside it
30
+ is enough.
31
+
32
+ To work on Archaeopteryx itself, check out `rcoremidi` and `musicalism` next to
33
+ this repository, or set `RCOREMIDI_PATH` and `MUSICALISM_PATH`. Then compile
34
+ the driver and run the specs:
35
+
36
+ ```bash
37
+ (cd ../rcoremidi && bundle install && bundle exec rake compile)
38
+ bundle install
39
+ bundle exec rake spec
40
+ ```
41
+
42
+ ## Quickstart
43
+
44
+ ```bash
45
+ arcx new my_set # app skeleton; MIDI in/out default to IAC Driver Bus 1
46
+ cd my_set && bundle install
47
+ arcx connections # list MIDI inputs and outputs with their unique IDs
48
+ arcx generate clip drum
49
+ arcx start # wait for the clock (add -d to run in the background)
50
+ arcx status # in another shell: is the session running?
51
+ arcx stop
52
+ ```
53
+
54
+ `arcx new` creates `clips/`, `instruments/`, `config/application.rb` and
55
+ `config/connections.yml`. `connections.yml` names the client and the unique IDs
56
+ of its MIDI input (the clock) and output (the notes). Edit it with IDs from
57
+ `arcx connections` to use other ports.
58
+
59
+ Archaeopteryx follows the clock and does not send one. Press play in the DAW
60
+ (sending MIDI clock to the input port), and the session plays bar 1 from the
61
+ DAW's Start. It also handles Stop and Continue. The tempo is measured from the
62
+ clock, and `config.bpm` (default 120) is the fallback before the first clocks
63
+ arrive.
64
+
65
+ ### A clip
66
+
67
+ ```ruby
68
+ # clips/progression.rb
69
+ Archaeopteryx::Clip.register :progression do
70
+ key 'A minor'
71
+
72
+ note 'E5', 16, [1, 0, 0, 0] * 4 # a pitch, 16 steps per bar
73
+ note 1, 16, [0.9, 0, 0.3, 0] * 4 # scale degree 1 of the key
74
+ chord :iv, 16, [1, 0, 0, 0, 0, 0, 0, 0] * 2, inversion: 1
75
+ end
76
+ ```
77
+
78
+ Each step is the probability that the note plays, from 0.0 to 1.0. Probability
79
+ only applies when the instrument enables it (see below). Otherwise any value
80
+ above 0 plays.
81
+
82
+ `modulate` plays one voice-led chord per bar, taking you to another key
83
+ through a pivot chord:
84
+
85
+ ```ruby
86
+ Archaeopteryx::Clip.register :pads do
87
+ key 'C major'
88
+ modulate to: 'G major', via: :vi, rhythm: [1, 0, 1, 0] * 4
89
+ end
90
+ ```
91
+
92
+ ### An instrument
93
+
94
+ ```ruby
95
+ # instruments/keys.rb
96
+ Archaeopteryx::Instrument.register :keys, 0 do # MIDI channel 1
97
+ play 1..8, :progression # bars 1 to 8
98
+ play 9..16, :pads, true # true enables the step probabilities
99
+ end
100
+ ```
101
+
102
+ Save either file while the session runs, and it is reloaded in place. The
103
+ next bar to be prepared uses the new version.
104
+
105
+ ## How it works
106
+
107
+ `Archaeopteryx::Client` subclasses `RCoreMidi::Client` and overrides its clock
108
+ hooks (`on_start`, `on_tick`, `on_stop`, `on_continue`). One beat before each
109
+ bar, it asks every instrument for that bar's notes. It turns them into clock
110
+ positions and sends each note a few ticks ahead with
111
+ `send_packets`, timed from the measured tick period. See
112
+ [MIDI_FLOW_DIAGRAM.md](MIDI_FLOW_DIAGRAM.md) for the full path, and
113
+ `script/clock_lab` for a tool that checks note timing against a clock.
114
+
115
+ ## History
116
+
117
+ This project started from [Giles Bowkett's archaeopteryx](https://github.com/gilesbowkett/archaeopteryx)
118
+ (2008), a probabilistic MIDI step sequencer and collection of music hacks in
119
+ Ruby. This repository began as a 2008 fork of it. Its probabilistic step
120
+ sequencing inspired the clips here.
121
+
122
+ The live coding layer was then written inside the rcoremidi gem (from 2010)
123
+ and moved here when rcoremidi became a driver-only gem. Both histories are
124
+ preserved in this repository. The original archaeopteryx code, with Giles
125
+ Bowkett's MIT license (`mit_license.txt`), is in the commits before the merge
126
+ of the rcoremidi history. You can browse it with
127
+ `git show 6fec6b9:mit_license.txt` or `git log -- README`.
128
+
129
+ ## License
130
+
131
+ MIT, see [LICENSE](LICENSE). The original archaeopteryx code in this
132
+ repository's history keeps its own MIT license (Copyright 2008 Giles Bowkett
133
+ and contributors).
data/bin/arcx ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler'
4
+ require 'bundler/setup'
5
+ require 'archaeopteryx/cli'
6
+
7
+ APP_PATH = File.join(File.expand_path(File.join(__dir__, '..')))
8
+ Archaeopteryx::CLI.start(ARGV)
@@ -0,0 +1,50 @@
1
+ require 'pathname'
2
+ require 'archaeopteryx/cli'
3
+ module Archaeopteryx
4
+ class AppPathname < Pathname
5
+ def valid?
6
+ true
7
+ end
8
+
9
+ def connections_file
10
+ config_dir.join(Archaeopteryx::Commands::New::CONNECTIONS)
11
+ end
12
+
13
+ def log_file
14
+ join(Archaeopteryx::CLI::LOG_DIR).join('arcx.log')
15
+ end
16
+
17
+ def instrument_files
18
+ Dir["#{instruments_dir}/**/*.rb"]
19
+ end
20
+
21
+ def clip_files
22
+ Dir["#{clips_dir}/**/*.rb"]
23
+ end
24
+
25
+ def pid_file
26
+ pid_dir
27
+ .join('arcx.pid')
28
+ end
29
+
30
+ def pid_dir
31
+ tmp_dir.join('pids')
32
+ end
33
+
34
+ def tmp_dir
35
+ join('tmp')
36
+ end
37
+
38
+ def config_dir
39
+ join('config')
40
+ end
41
+
42
+ def clips_dir
43
+ join(Archaeopteryx::CLI::CLIPS_DIR)
44
+ end
45
+
46
+ def instruments_dir
47
+ join(Archaeopteryx::CLI::INSTRUMENTS_DIR)
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,183 @@
1
+ require 'yaml'
2
+ require 'archaeopteryx/app_pathname'
3
+ require 'archaeopteryx/client'
4
+ require 'logger'
5
+ require 'listen'
6
+
7
+ module Archaeopteryx
8
+ class Configuration
9
+ attr_accessor :bpm, :logger
10
+
11
+ def initialize
12
+ self.bpm = 120
13
+ self.logger ||= Logger.new($stdout)
14
+ end
15
+ end
16
+
17
+ class Application
18
+ attr_reader :connections
19
+
20
+ def self.config
21
+ @@config ||= Configuration.new
22
+ end
23
+
24
+ def self.root
25
+ @root ||= AppPathname.new(Dir.pwd).expand_path
26
+ end
27
+
28
+ def self.load_clips!
29
+ root.clip_files.each { |clip| load clip }
30
+ end
31
+
32
+ def self.load_instruments!
33
+ root.instrument_files.each { |instrument| load instrument }
34
+ end
35
+
36
+ def self.connections
37
+ @connections ||= YAML.load_file(root.connections_file, symbolize_names: true)
38
+ end
39
+
40
+ def initialize
41
+ raise 'Could not find application root' unless self.class.root.valid?
42
+ end
43
+
44
+ def run(daemon_mode: false)
45
+ if daemon_mode
46
+ Process.daemon
47
+ Process.setproctitle('arcx:live %s' % root)
48
+ write_pid_file
49
+ redirect_output
50
+
51
+ client.midi_in = midi_in
52
+ client.midi_out = midi_out
53
+ client.create_live
54
+
55
+ config.logger = Logger.new(root.log_file)
56
+
57
+ else
58
+ client.midi_in = midi_in
59
+ client.midi_out = midi_out
60
+ client.create_live
61
+
62
+ config.logger = Logger.new(STDOUT)
63
+
64
+ end
65
+
66
+ trap 'SIGINT', proc {
67
+ client.dispose
68
+ puts 'quiting'
69
+ exit(0)
70
+ }
71
+
72
+ wait_for_start
73
+ end
74
+
75
+ def stop
76
+ if root.pid_file.exist?
77
+ Process.kill('QUIT', Integer(root.pid_file.read))
78
+ else
79
+ config.logger.info('No Arcx application seems to be running')
80
+ end
81
+ end
82
+
83
+ def log_status
84
+ config.logger.info("Process is #{pid_status}")
85
+ end
86
+
87
+ def config
88
+ self.class.config
89
+ end
90
+
91
+ private
92
+
93
+ attr_writer :root, :connections
94
+
95
+ def listeners
96
+ @listeners ||= Listen.to(root.clips_dir, root.instruments_dir) do |modified, added, _removed|
97
+ (modified + added).flat_map.each do |file|
98
+ load file
99
+ end
100
+ end
101
+ end
102
+
103
+ def wait_for_start
104
+ listeners.start
105
+ config.logger.info 'Arcx live successfully started'
106
+ client.start
107
+ end
108
+
109
+ def redirect_output
110
+ FileUtils.mkdir_p root.log_file.dirname
111
+ # FileUtils.touch root.log_file
112
+ root.log_file.chmod(0o644)
113
+ $stderr.reopen(root.log_file, 'a')
114
+ $stdout.reopen($stderr)
115
+ $stdout.sync = $stderr.sync = true
116
+ end
117
+
118
+ def write_pid_file
119
+ if root.pid_file.exist?
120
+ check_pid
121
+ else
122
+ root.pid_file.open(::File::CREAT | ::File::EXCL | ::File::WRONLY) do |f|
123
+ f.write(Process.pid)
124
+ end
125
+ at_exit do
126
+ root.pid_file.delete if root.pid_file.exist?
127
+ end
128
+ end
129
+ end
130
+
131
+ def check_pid
132
+ return unless root.pid_file.exist?
133
+
134
+ case pid_status
135
+ when :running, :not_owned
136
+ puts "An arcx lie appear to with running. Check #{root.pid_file}"
137
+ exit(1)
138
+ when :dead
139
+ root.pid_file.delete
140
+ end
141
+ end
142
+
143
+ def pid_status
144
+ return :exited unless root.pid_file.exist?
145
+
146
+ pid = root.pid_file.read.to_i
147
+ return :dead if pid.zero?
148
+
149
+ Process.kill(0, pid)
150
+ :running
151
+ rescue Errno::ESRCH
152
+ :dead
153
+ rescue Errno::EPERM
154
+ :not_owned
155
+ end
156
+
157
+ def client
158
+ @client ||= Archaeopteryx::Client.new(connection[:name]).tap do |_c|
159
+ puts "Client name: #{connection[:name]}"
160
+ end
161
+ end
162
+
163
+ def midi_in
164
+ @midi_in ||= RCoreMidi::MIDIObject.find_by_unique_id(connection[:midi_in]).tap do |_c|
165
+ puts "MIDI IN: #{connection[:midi_in]}"
166
+ end
167
+ end
168
+
169
+ def midi_out
170
+ @midi_out ||= RCoreMidi::MIDIObject.find_by_unique_id(connection[:midi_out]).tap do |_c|
171
+ puts "MIDI OUT: #{connection[:midi_out]}"
172
+ end
173
+ end
174
+
175
+ def connection
176
+ self.class.connections.first
177
+ end
178
+
179
+ def root
180
+ self.class.root
181
+ end
182
+ end
183
+ end
@@ -0,0 +1,23 @@
1
+ module Archaeopteryx
2
+
3
+ class ApplicationRunner
4
+
5
+ def run()
6
+ Process.daemon
7
+ redirect_output
8
+ write_pid_file(Process.pid)
9
+ client.midi_in = midi_in
10
+ client.midi_out = midi_out
11
+ client.create_live(config.bpm)
12
+
13
+ trap 'SIGINT', Proc.new {
14
+ client.dispose
15
+ puts "quiting"
16
+ exit(0)
17
+ }
18
+ sleep
19
+ end
20
+
21
+ end
22
+
23
+ end
@@ -0,0 +1,44 @@
1
+ require 'archaeopteryx'
2
+ require 'archaeopteryx/commands'
3
+ require 'yaml'
4
+
5
+ module Archaeopteryx
6
+ class CLI < Thor
7
+ include Thor::Actions
8
+
9
+ DIRS = [
10
+ CLIPS_DIR = 'clips'.freeze,
11
+ INSTRUMENTS_DIR = 'instruments'.freeze,
12
+ CONFIG_DIR = 'config'.freeze,
13
+ TMP_DIR = 'tmp'.freeze,
14
+ LOG_DIR = 'log'.freeze,
15
+ BIN_DIR = 'bin'.freeze
16
+ ]
17
+
18
+ APPLICATION = 'application.rb'.freeze
19
+
20
+ def self.source_root
21
+ File.expand_path(__dir__)
22
+ end
23
+
24
+ desc 'generate [GENERATOR_TYPE]', 'Generate code: clips and instruments'
25
+ register Commands::Generate, 'generate', 'generate[GENERATOR_TYPE]', 'Generate code: clips and instruments'
26
+
27
+ desc 'new [APP_PATH]', 'Generate code: clips and instruments'
28
+ register Commands::New, 'new', 'new[APP_PATH]', 'Generate code: clips and instruments'
29
+
30
+ desc 'connections', 'Generate a new midi connection'
31
+ register Commands::Connections, 'connections', 'connections', 'Prints available MIDI connections'
32
+
33
+ register Commands::Start, 'start', 'start', 'Start Arcx live session'
34
+
35
+ register Commands::Stop, 'stop', 'stop', 'Stop Arcx live session'
36
+ register Commands::Status, 'status', 'status', 'Check if Arcx live session is running'
37
+
38
+ private
39
+
40
+ def app_const
41
+ @app_name ||= File.basename(destination_root).split(/_|-/).map(&:capitalize).join
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,153 @@
1
+ module Archaeopteryx
2
+ # Schedules the bars generated by Live against the MIDI clock received by
3
+ # the rcoremidi driver.
4
+ #
5
+ # RCoreMidi::Client calls the hooks below from the thread running #start.
6
+ # One bar ahead of time this client asks Live for that bar's notes, turns
7
+ # their offsets into clock positions, and sends each note a few ticks before
8
+ # it is due, timed from the latest clock and the measured tick period.
9
+ class Client < RCoreMidi::Client
10
+ TICKS_PER_BAR = TICKS_PER_QUARTER * 4
11
+ BAR_PREPARATION_TICKS = TICKS_PER_QUARTER
12
+ NOTE_LOOKAHEAD_TICKS = 3
13
+ TICK_PERIOD_SMOOTHING = 4
14
+ TICK_POSITION_PRECISION = 3
15
+ MINIMUM_CLOCK_INTERVAL_NANOSECONDS = 2_000_000
16
+ NANOSECONDS_PER_MINUTE = 60_000_000_000.0
17
+
18
+ PendingNote = Struct.new(:on, :on_tick, :off, :off_tick, :destination)
19
+
20
+ def on_start(_host_time)
21
+ self.playing = true
22
+ self.pending_notes = []
23
+ prepare_bar(1)
24
+ end
25
+
26
+ def on_continue
27
+ self.playing = true
28
+ self.prepared_bar = nil
29
+ end
30
+
31
+ def on_tick(tick, host_time)
32
+ position_moved = position_moved?(tick)
33
+ measure_tick_period(tick, host_time)
34
+ return unless playing
35
+
36
+ resume_at(tick) if position_moved || prepared_bar.nil?
37
+ prepare_bar(prepared_bar + 1) while bar_at(tick + BAR_PREPARATION_TICKS) > prepared_bar
38
+ send_due_notes(tick, host_time)
39
+ end
40
+
41
+ def on_stop
42
+ self.playing = false
43
+ self.pending_notes = []
44
+ forget_clock_tempo
45
+ silence
46
+ end
47
+
48
+ def create_live
49
+ connect!
50
+ end
51
+
52
+ def live
53
+ @live ||= Live.new
54
+ end
55
+
56
+ private
57
+
58
+ attr_accessor :playing, :prepared_bar, :pending_notes, :last_tick, :last_tick_host_time, :last_interval,
59
+ :tick_period
60
+
61
+ def position_moved?(tick)
62
+ last_tick && !(last_tick + 1..last_tick + NOTE_LOOKAHEAD_TICKS + 1).cover?(tick)
63
+ end
64
+
65
+ def resume_at(tick)
66
+ self.pending_notes = []
67
+ prepare_bar(bar_at(tick))
68
+ pending_notes.reject! { |note| note.on_tick < tick }
69
+ end
70
+
71
+ def prepare_bar(bar)
72
+ first_tick = first_tick_of(bar)
73
+ notes = notes_for_bar(bar).map do |note|
74
+ PendingNote.new(note.on, first_tick + ticks_in(note.on_timestamp),
75
+ note.off, first_tick + ticks_in(note.off_timestamp), note.destination)
76
+ end
77
+ self.pending_notes = (pending_notes + notes).sort_by(&:on_tick)
78
+ self.prepared_bar = bar
79
+ end
80
+
81
+ def notes_for_bar(bar)
82
+ live.generate_beats(bar: bar).flatten.compact
83
+ end
84
+
85
+ def ticks_in(offset_nanoseconds)
86
+ (offset_nanoseconds / configured_tick_nanoseconds).round(TICK_POSITION_PRECISION)
87
+ end
88
+
89
+ def send_due_notes(tick, host_time)
90
+ take_due_notes(tick).group_by { |note| note.destination || midi_out }.each do |destination, notes|
91
+ send_packets(destination, notes.map { |note| timed_from(tick, note) }, host_time)
92
+ end
93
+ end
94
+
95
+ def take_due_notes(tick)
96
+ horizon = tick_period ? tick + NOTE_LOOKAHEAD_TICKS : tick
97
+ due_count = pending_notes.index { |note| note.on_tick > horizon } || pending_notes.size
98
+ pending_notes.shift(due_count)
99
+ end
100
+
101
+ def timed_from(tick, note)
102
+ on_timestamp = ([note.on_tick - tick, 0].max * tick_nanoseconds).round
103
+ off_timestamp = on_timestamp + ((note.off_tick - note.on_tick) * tick_nanoseconds).round
104
+ TimedNote.new(note.on, on_timestamp, note.off, off_timestamp)
105
+ end
106
+
107
+ def tick_nanoseconds
108
+ tick_period ? RCoreMidi::HostTime.to_nanoseconds(tick_period) : configured_tick_nanoseconds
109
+ end
110
+
111
+ def configured_tick_nanoseconds
112
+ NANOSECONDS_PER_MINUTE / (Application.config.bpm * TICKS_PER_QUARTER)
113
+ end
114
+
115
+ def measure_tick_period(tick, host_time)
116
+ interval = host_time - last_tick_host_time if last_tick && tick == last_tick + 1
117
+ record_tick_interval(interval) if full_clock_interval?(interval)
118
+ self.last_interval = interval
119
+ self.last_tick = tick
120
+ self.last_tick_host_time = host_time
121
+ end
122
+
123
+ def full_clock_interval?(interval)
124
+ plausible_clock_interval?(interval) && plausible_clock_interval?(last_interval)
125
+ end
126
+
127
+ def plausible_clock_interval?(interval)
128
+ interval&.positive? && RCoreMidi::HostTime.to_nanoseconds(interval) >= MINIMUM_CLOCK_INTERVAL_NANOSECONDS
129
+ end
130
+
131
+ def record_tick_interval(interval)
132
+ self.tick_period = tick_period ? smoothed(tick_period, interval) : interval
133
+ end
134
+
135
+ def forget_clock_tempo
136
+ self.last_tick = nil
137
+ self.last_interval = nil
138
+ self.tick_period = nil
139
+ end
140
+
141
+ def smoothed(average, sample)
142
+ ((average * (TICK_PERIOD_SMOOTHING - 1)) + sample) / TICK_PERIOD_SMOOTHING
143
+ end
144
+
145
+ def bar_at(tick)
146
+ (tick / TICKS_PER_BAR) + 1
147
+ end
148
+
149
+ def first_tick_of(bar)
150
+ (bar - 1) * TICKS_PER_BAR
151
+ end
152
+ end
153
+ end