summaryrefslogtreecommitdiff
path: root/VRCSDK3Worlds/Assets/VRCSDK/SDK3/Runtime/Midi/PortMidi/MidiDeviceManager.cs
blob: 4628afc1fe6dba2a53aeb51e14d9a39e0cc87652 (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
68
69
using System;
using System.Collections.Generic;
using PmDeviceID = System.Int32;
using PortMidiStream = System.IntPtr;
using PmError = PortMidi.MidiErrorType;

namespace PortMidi
{
    public static class MidiDeviceManager
    {
        private const int DefaultBufferSize = 1024;

        static MidiDeviceManager()
        {
            PortMidiMarshal.Pm_Initialize();
            AppDomain.CurrentDomain.DomainUnload += delegate { PortMidiMarshal.Pm_Terminate(); };
        }

        public static int DeviceCount => PortMidiMarshal.Pm_CountDevices();

        public static int DefaultInputDeviceId => PortMidiMarshal.Pm_GetDefaultInputDeviceID();

        public static int DefaultOutputDeviceId => PortMidiMarshal.Pm_GetDefaultOutputDeviceID();

        public static IEnumerable<MidiDeviceInfo> AllDevices
        {
            get
            {
                for (var i = 0; i < DeviceCount; i++)
                {
                    yield return GetDeviceInfo(i);
                }
            }
        }

        private static MidiDeviceInfo GetDeviceInfo(PmDeviceID id)
        {
            return new MidiDeviceInfo(id, PortMidiMarshal.Pm_GetDeviceInfo(id));
        }

        public static MidiInput OpenInput(PmDeviceID inputDevice)
        {
            return OpenInput(inputDevice, DefaultBufferSize);
        }

        private static MidiInput OpenInput(PmDeviceID inputDevice, int bufferSize)
        {
            PortMidiStream stream = default;
            var e = PortMidiMarshal.Pm_OpenInput(out stream, inputDevice, IntPtr.Zero, bufferSize, null, IntPtr.Zero);
            if (e != PmError.NoError)
            {
                throw new MidiException(e, $"Failed to open MIDI input device {e}");
            }
            
            return new MidiInput(stream, inputDevice);
        }

        public static MidiOutput OpenOutput(PmDeviceID outputDevice)
        {
            PortMidiStream stream;
            var e = PortMidiMarshal.Pm_OpenOutput(out stream, outputDevice, IntPtr.Zero, 0, null, IntPtr.Zero, 0);
            if (e != PmError.NoError)
            {
                throw new MidiException(e, $"Failed to open MIDI output device {e}");
            }
            return new MidiOutput(stream, outputDevice, 0);
        }
    }
}