Module: Cyclotone::Backends::MIDIMessageSupport

Included in:
MIDIBackend, MIDIFileBackend
Defined in:
lib/cyclotone/backends/midi_message_support.rb

Constant Summary collapse

SUPPORTED_NOTE_CONTROLS =
%i[
  note channel velocity gain velocity_scale release_velocity release_velocity_scale sustain sustain_cycles fractional_notes
].freeze
SUPPORTED_CC_CONTROLS =
%i[
  cc channel cc_scale controller_scale
].freeze
UNSUPPORTED_CONTROL_POLICIES =
%i[ignore error].freeze
FRACTIONAL_NOTE_POLICIES =
%i[floor round error].freeze

Instance Method Summary collapse

Instance Method Details

#messages_for(event, cps: nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/cyclotone/backends/midi_message_support.rb', line 15

def messages_for(event, cps: nil)
  values = event.value.is_a?(Hash) ? event.value : { note: event.value }
  if values.key?(:cc)
    validate_unsupported_controls!(values, SUPPORTED_CC_CONTROLS)
    return control_change_messages(values)
  end

  notes = Array(values[:note])
  return [] if notes.empty? || notes.all?(&:nil?)

  validate_unsupported_controls!(values, SUPPORTED_NOTE_CONTROLS)

  active_channel = normalize_channel(values[:channel] || channel)
  sustain = [extract_sustain(values, event, cps), 0.0].max
  velocity_scale = values[:velocity_scale]
  attack_velocity = normalize_velocity(values[:velocity] || values[:gain] || 1.0, scale: velocity_scale)
  release_velocity = normalize_velocity(
    values.fetch(:release_velocity, 0),
    scale: values.fetch(:release_velocity_scale, velocity_scale)
  )

  notes.compact.flat_map do |note|
    normalized_note = normalize_note(note, policy: values.fetch(:fractional_notes, fractional_note_policy))

    [
      {
        type: :note_on,
        channel: active_channel,
        note: normalized_note,
        velocity: attack_velocity
      },
      {
        type: :note_off,
        channel: active_channel,
        note: normalized_note,
        velocity: release_velocity,
        delay: sustain
      }
    ]
  end
end