summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/VRCSDK/SDK3/Runtime/Midi/PortMidi/MidiInput.cs
blob: dbb356238e8323a357fa00553dd01783f0b27d91 (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
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace PortMidi
{
    public class MidiInput : MidiStream
    {
        public MidiInput(IntPtr stream, Int32 inputDevice)
            : base(stream, inputDevice)
        {
        }

        public bool HasData => PortMidiMarshal.Pm_Poll(stream) == MidiErrorType.GotData;

        public int Read(byte[] buffer, int index, int length)
        {
            var gch = GCHandle.Alloc(buffer);
            try
            {
                var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, index);
                int size = PortMidiMarshal.Pm_Read(stream, ptr, length);
                if (size < 0)
                {
                    throw new MidiException((MidiErrorType) size,
                        PortMidiMarshal.Pm_GetErrorText((MidiErrorType) size));
                }
                return size * 4;
            }
            finally
            {
                gch.Free();
            }
        }

        public Event ReadEvent(byte[] buffer, int index, int length)
        {
            var gch = GCHandle.Alloc(buffer);
            try
            {
                var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, index);
                int size = PortMidiMarshal.Pm_Read(stream, ptr, length);
                if (size < 0)
                {
                    throw new MidiException((MidiErrorType) size,
                        PortMidiMarshal.Pm_GetErrorText((MidiErrorType) size));
                }

                return new Event(Marshal.PtrToStructure<PmEvent>(ptr));
            }
            finally
            {
                gch.Free();
            }
        }
    }
}