PortMidi / portmidi

portmidi is a cross-platform MIDI input/output library
Other
118 stars 33 forks source link

handling hot plugged devices #63

Closed mrf-r closed 8 months ago

mrf-r commented 8 months ago

Hello! When disconnecting or connecting (USB) devices during operation (after Pm_Initialize()), the value returned by Pm_CountDevices() does not change. Pm_Read() also does not return any errors. Is this a limitation or a bug? Is it possible to implement this functionality in future versions? Could you please suggest a way to track changes in hardware configuration at runtime? Tested on Windows11(MinGW-w64) and Ubuntu

rbdannenberg commented 8 months ago

This is a limitation, not a bug. Scanning for devices is not a particularly real-time operation and on some systems I think it requires another thread (and be careful with that because PortMidi is not only single-threaded but if you poll PortMidi at a raised priority, there would be priority inversion problems interacting with a lower-priority thread, which is why PortMidi passes data through a lock-free queue.) My solution is a menu selection to explicitly rescan devices. This shuts down and reinitializes PortMidi. While shut down, application calls to poll for MIDI or send MIDI have to be intercepted since devices are closed. After reinitializing, device numbers may change, but I search for and reconnect devices based on names. All of this operates in a fairly small abstraction layer above the PortMidi API. This is all implemented in my language Serpent and ties into both a Preferences library and a Menu system, so it would not make sense to put it in PortMidi. I'm happy to share the code.

mrf-r commented 8 months ago

So there is no way for the program to know that used device has become unplugged?

rbdannenberg commented 8 months ago

Not from within PortMidi. For any given system (Win32, MacOS, Linux), you can write your own code to detect unplugged or newly plugged devices in a way that's consistent with your requirements. If you need access to hidden data in PortMidi, I would see that as a priority for PortMidi supports, and maybe we could make some additional code for monitoring device status available outside the core PortMidi library.

mrf-r commented 8 months ago

Ok, I see. Thanks for the answers, Roger! I looked at other libraries and it seems like this is common behavior. I'll try to find a more reliable USB cable)