summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/VRCSDK/SDK3/Runtime/Midi/PortMidi/MidiOutput.cs
blob: fe56081c6acf1ac061074a20568c09834fa22e85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Runtime.InteropServices;

namespace PortMidi
{
    public class MidiOutput : MidiStream
    {
        public MidiOutput(IntPtr stream, Int32 outputDevice, int latency)
            : base(stream, outputDevice)
        {
        }

        public void Write(MidiEvent midiEvent)
        {
            if (midiEvent.SysEx != null)
            {
                WriteSysEx(midiEvent.Timestamp, midiEvent.SysEx);
            }
            else
            {
                Write(midiEvent.Timestamp, midiEvent.Message);
            }
        }

        private void Write(Int32 when, MidiMessage msg)
        {
            var ret = PortMidiMarshal.Pm_WriteShort(stream, when, msg);
            if (ret != MidiErrorType.NoError)
            {
                throw new MidiException(ret,
                    $"Failed to write message {msg.Value} : {PortMidiMarshal.Pm_GetErrorText((MidiErrorType) ret)}");
            }
        }

        private void WriteSysEx(Int32 when, byte[] sysEx)
        {
            var ret = PortMidiMarshal.Pm_WriteSysEx(stream, when, sysEx);
            if (ret != MidiErrorType.NoError)
                throw new MidiException(ret,
                    $"Failed to write sysEx message : {PortMidiMarshal.Pm_GetErrorText((MidiErrorType) ret)}");
        }

        public void Write(MidiEvent[] buffer)
        {
            Write(buffer, 0, buffer.Length);
        }

        private void Write(MidiEvent[] buffer, int index, int length)
        {
            var gch = GCHandle.Alloc(buffer);
            try
            {
                var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, index);
                var ret = PortMidiMarshal.Pm_Write(stream, ptr, length);
                if (ret != MidiErrorType.NoError)
                {
                    throw new MidiException(ret,
                        $"Failed to write messages : {PortMidiMarshal.Pm_GetErrorText((MidiErrorType) ret)}");
                }
            }
            finally
            {
                gch.Free();
            }
        }
    }
}