aboutsummaryrefslogtreecommitdiff
path: root/portmidi/pm_common/portmidi.h
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-10-07 06:50:04 +0200
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-10-07 06:50:04 +0200
commit988f5d2b5343850e19ad1512cefe6c53953aa02e (patch)
tree1ff29934294e73b2575488c06df91866ce251dbe /portmidi/pm_common/portmidi.h
parent9b5839c58a2e1df8bddf6b98805998508ea417d5 (diff)
downloadttdaw-988f5d2b5343850e19ad1512cefe6c53953aa02e.tar.gz
Added bunch of examples
Diffstat (limited to 'portmidi/pm_common/portmidi.h')
-rwxr-xr-xportmidi/pm_common/portmidi.h974
1 files changed, 974 insertions, 0 deletions
diff --git a/portmidi/pm_common/portmidi.h b/portmidi/pm_common/portmidi.h
new file mode 100755
index 0000000..8696a73
--- /dev/null
+++ b/portmidi/pm_common/portmidi.h
@@ -0,0 +1,974 @@
1#ifndef PORTMIDI_PORTMIDI_H
2#define PORTMIDI_PORTMIDI_H
3
4#ifdef __cplusplus
5extern "C" {
6#endif /* __cplusplus */
7
8/*
9 * PortMidi Portable Real-Time MIDI Library
10 * PortMidi API Header File
11 * Latest version available at: http://sourceforge.net/projects/portmedia
12 *
13 * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
14 * Copyright (c) 2001-2006 Roger B. Dannenberg
15 *
16 * Permission is hereby granted, free of charge, to any person obtaining
17 * a copy of this software and associated documentation files
18 * (the "Software"), to deal in the Software without restriction,
19 * including without limitation the rights to use, copy, modify, merge,
20 * publish, distribute, sublicense, and/or sell copies of the Software,
21 * and to permit persons to whom the Software is furnished to do so,
22 * subject to the following conditions:
23 *
24 * The above copyright notice and this permission notice shall be
25 * included in all copies or substantial portions of the Software.
26 *
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
30 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
31 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
32 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 */
35
36/*
37 * The text above constitutes the entire PortMidi license; however,
38 * the PortMusic community also makes the following non-binding requests:
39 *
40 * Any person wishing to distribute modifications to the Software is
41 * requested to send the modifications to the original developer so that
42 * they can be incorporated into the canonical version. It is also
43 * requested that these non-binding requests be included along with the
44 * license above.
45 */
46
47/* CHANGELOG FOR PORTMIDI
48 * (see ../CHANGELOG.txt)
49 *
50 * NOTES ON HOST ERROR REPORTING:
51 *
52 * PortMidi errors (of type PmError) are generic,
53 * system-independent errors. When an error does not map to one of
54 * the more specific PmErrors, the catch-all code pmHostError is
55 * returned. This means that PortMidi has retained a more specific
56 * system-dependent error code. The caller can get more information
57 * by calling Pm_GetHostErrorText() to get a text string describing
58 * the error. Host errors can arise asynchronously from callbacks,
59 * * so there is no specific return code. Asynchronous errors are
60 * checked and reported by Pm_Poll. You can also check by calling
61 * Pm_HasHostError(). If this returns TRUE, Pm_GetHostErrorText()
62 * will return a text description of the error.
63 *
64 * NOTES ON COMPILE-TIME SWITCHES
65 *
66 * DEBUG assumes stdio and a console. Use this if you want
67 * automatic, simple error reporting, e.g. for prototyping. If
68 * you are using MFC or some other graphical interface with no
69 * console, DEBUG probably should be undefined.
70 * PM_CHECK_ERRORS more-or-less takes over error checking for
71 * return values, stopping your program and printing error
72 * messages when an error occurs. This also uses stdio for
73 * console text I/O. You can selectively disable this error
74 * checking by declaring extern int pm_check_errors; and
75 * setting pm_check_errors = FALSE; You can also reenable.
76 */
77/**
78 \defgroup grp_basics Basic Definitions
79 @{
80*/
81
82#include <stdint.h>
83
84#ifdef _WINDLL
85#define PMEXPORT __declspec(dllexport)
86#else
87#define PMEXPORT
88#endif
89
90#ifndef FALSE
91 #define FALSE 0
92#endif
93#ifndef TRUE
94 #define TRUE 1
95#endif
96
97/* default size of buffers for sysex transmission: */
98#define PM_DEFAULT_SYSEX_BUFFER_SIZE 1024
99
100
101typedef enum {
102 pmNoError = 0, /**< Normal return value indicating no error. */
103 pmNoData = 0, /**< @brief No error, also indicates no data available.
104 * Use this constant where a value greater than zero would
105 * indicate data is available.
106 */
107 pmGotData = 1, /**< A "no error" return also indicating data available. */
108 pmHostError = -10000,
109 pmInvalidDeviceId, /**< Out of range or
110 * output device when input is requested or
111 * input device when output is requested or
112 * device is already opened.
113 */
114 pmInsufficientMemory,
115 pmBufferTooSmall,
116 pmBufferOverflow,
117 pmBadPtr, /**< #PortMidiStream parameter is NULL or
118 * stream is not opened or
119 * stream is output when input is required or
120 * stream is input when output is required. */
121 pmBadData, /**< Illegal midi data, e.g., missing EOX. */
122 pmInternalError,
123 pmBufferMaxSize, /**< Buffer is already as large as it can be. */
124 pmNotImplemented, /**< The function is not implemented, nothing was done. */
125 pmInterfaceNotSupported, /**< The requested interface is not supported. */
126 pmNameConflict, /**< Cannot create virtual device because name is taken. */
127 pmDeviceRemoved /**< Output attempted after (USB) device was removed. */
128 /* NOTE: If you add a new error type, you must update Pm_GetErrorText(). */
129} PmError; /**< @brief @enum PmError PortMidi error code; a common return type.
130 * No error is indicated by zero; errors are indicated by < 0.
131 */
132
133/**
134 Pm_Initialize() is the library initialization function - call this before
135 using the library.
136
137 *NOTE:* PortMidi scans for available devices when #Pm_Initialize
138 is called. To observe subsequent changes in the available
139 devices, you must shut down PortMidi by calling #Pm_Terminate and
140 then restart by calling #Pm_Initialize again. *IMPORTANT*: On
141 MacOS, #Pm_Initialize *must* always be called on the same
142 thread. Otherwise, changes in the available MIDI devices will
143 *not* be seen by PortMidi. As an example, if you start PortMidi in
144 a thread for processing MIDI, do not try to rescan devices by
145 calling #Pm_Initialize in a GUI thread. Instead, start PortMidi
146 the first time and every time in the GUI thread. Alternatively,
147 let the GUI request a restart in the MIDI thread. (These
148 restrictions only apply to macOS.) Speaking of threads, on all
149 platforms, you are allowed to call #Pm_Initialize in one thread,
150 yet send MIDI or poll for incoming MIDI in another
151 thread. However, PortMidi is not "thread safe," which means you
152 cannot allow threads to call PortMidi functions concurrently.
153
154 @return pmNoError.
155
156 PortMidi is designed to support multiple interfaces (such as ALSA,
157 CoreMIDI and WinMM). It is possible to return pmNoError because there
158 are no supported interfaces. In that case, zero devices will be
159 available.
160*/
161PMEXPORT PmError Pm_Initialize(void);
162
163/**
164 Pm_Terminate() is the library termination function - call this after
165 using the library.
166*/
167PMEXPORT PmError Pm_Terminate(void);
168
169/** Represents an open MIDI device. */
170typedef void PortMidiStream;
171
172/** A shorter form of #PortMidiStream. */
173#define PmStream PortMidiStream
174
175/** Test whether stream has a pending host error. Normally, the client
176 finds out about errors through returned error codes, but some
177 errors can occur asynchronously where the client does not
178 explicitly call a function, and therefore cannot receive an error
179 code. The client can test for a pending error using
180 Pm_HasHostError(). If true, the error can be accessed by calling
181 Pm_GetHostErrorText(). Pm_Poll() is similar to Pm_HasHostError(),
182 but if there is no error, it will return TRUE (1) if there is a
183 pending input message.
184*/
185PMEXPORT int Pm_HasHostError(PortMidiStream * stream);
186
187
188/** Translate portmidi error number into human readable message.
189 These strings are constants (set at compile time) so client has
190 no need to allocate storage.
191*/
192PMEXPORT const char *Pm_GetErrorText(PmError errnum);
193
194/** Translate portmidi host error into human readable message.
195 These strings are computed at run time, so client has to allocate storage.
196 After this routine executes, the host error is cleared.
197*/
198PMEXPORT void Pm_GetHostErrorText(char * msg, unsigned int len);
199
200/** Any host error msg has at most this many characters, including EOS. */
201#define PM_HOST_ERROR_MSG_LEN 256u
202
203/** Devices are represented as small integers. Device ids range from 0
204 to Pm_CountDevices()-1. Pm_GetDeviceInfo() is used to get information
205 about the device, and Pm_OpenInput() and PmOpenOutput() are used to
206 open the device.
207*/
208typedef int PmDeviceID;
209
210/** This PmDeviceID (constant) value represents no device and may be
211 returned by Pm_GetDefaultInputDeviceID() or
212 Pm_GetDefaultOutputDeviceID() if no default exists.
213*/
214#define pmNoDevice -1
215
216/** MIDI device information is returned in this structure, which is
217 owned by PortMidi and read-only to applications. See Pm_GetDeviceInfo().
218*/
219#define PM_DEVICEINFO_VERS 200
220typedef struct {
221 int structVersion; /**< @brief this internal structure version */
222 const char *interf; /**< @brief underlying MIDI API, e.g.
223 "MMSystem" or "DirectX" */
224 char *name; /**< @brief device name, e.g. "USB MidiSport 1x1" */
225 int input; /**< @brief true iff input is available */
226 int output; /**< @brief true iff output is available */
227 int opened; /**< @brief used by generic PortMidi for error checking */
228 int is_virtual; /**< @brief true iff this is/was a virtual device */
229} PmDeviceInfo;
230
231/** MIDI system-dependent device or driver info is passed in this
232 structure, which is owned by the caller.
233*/
234#define PM_SYSDEPINFO_VERS 210
235
236enum PmSysDepPropertyKey {
237 pmKeyNone = 0, /**< a "noop" key value */
238 /** CoreMIDI Manufacturer name, value is string */
239 pmKeyCoreMidiManufacturer = 1,
240 /** Linux ALSA snd_seq_port_info_set_name, value is a string. Can be
241 passed in PmSysDepInfo to Pm_OpenInput or Pm_OpenOutput when opening
242 a device. The created port will be named accordingly and will be
243 visible for externally made connections (subscriptions). (Linux ALSA
244 ports are always enabled for this, but only get application-specific
245 names if you give it one.) This key/value is ignored when opening
246 virtual ports, which are named when they are created.) */
247 pmKeyAlsaPortName = 2,
248 /** Linux ALSA snd_seq_set_client_name, value is a string.
249 Can be passed in PmSysDepInfo to Pm_OpenInput or Pm_OpenOutput.
250 Pm_CreateVirtualInput or Pm_CreateVirtualOutput. Will override
251 any previously set client name and applies to all ports. */
252 pmKeyAlsaClientName = 3
253 /* if system-dependent code introduces more options, register
254 the key here to avoid conflicts. */
255};
256
257/** System-dependent information can be passed when creating and opening
258 ports using this data structure, which stores alternating keys and
259 values (addresses). See `pm_test/sendvirtual.c`, `pm_test/recvvirtual.c`,
260 and `pm_test/testio.c` for examples.
261 */
262typedef struct {
263 int structVersion; /**< @brief this structure version */
264 int length; /**< @brief number of properties in this structure */
265 struct {
266 enum PmSysDepPropertyKey key;
267 const void *value;
268 } properties[];
269} PmSysDepInfo;
270
271
272/** Get devices count, ids range from 0 to Pm_CountDevices()-1. */
273PMEXPORT int Pm_CountDevices(void);
274
275/**
276 Return the default device ID or pmNoDevice if there are no devices.
277 The result (but not pmNoDevice) can be passed to Pm_OpenMidi().
278
279 The use of these functions is not recommended. There is no natural
280 "default device" on any system, so defaults must be set by users.
281 (Currently, PortMidi just returns the first device it finds as
282 "default", so if there *is* a default, implementors should use
283 pm_add_device to add system default input and output devices
284 first.)
285
286 The recommended solution is pass the burden to applications. It is
287 easy to scan devices with PortMidi and build a device menu, and to
288 save menu selections in application preferences for next
289 time. This is my recommendation for any GUI program. For simple
290 command-line applications and utilities, see pm_test where all the
291 test programs now accept device numbers on the command line and/or
292 prompt for their entry.
293
294 On linux, you can create virtual ports and use an external program
295 to set up inter-application and device connections.
296
297 Some advice for preferences: MIDI devices used to be built-in or
298 plug-in cards, so the numbers rarely changed. Now MIDI devices are
299 often plug-in USB devices, so device numbers change, and you
300 probably need to design to reinitialize PortMidi to rescan
301 devices. MIDI is pretty stateless, so this isn't a big problem,
302 although it means you cannot find a new device while playing or
303 recording MIDI.
304
305 Since device numbering can change whenever a USB device is plugged
306 in, preferences should record *names* of devices rather than
307 device numbers. It is simple enough to use string matching to find
308 a prefered device, so PortMidi does not provide any built-in
309 lookup function.
310*/
311PMEXPORT PmDeviceID Pm_GetDefaultInputDeviceID(void);
312
313/** @brief see PmDeviceID Pm_GetDefaultInputDeviceID() */
314PMEXPORT PmDeviceID Pm_GetDefaultOutputDeviceID(void);
315
316/** Find a device that matches a pattern.
317
318 @param pattern a substring of the device name, or if the pattern
319 contains the two-character separator ", ", then the first part of
320 the pattern represents a device interface substring and the second
321 part after the separator represents a device name substring.
322
323 @param is_input restricts the search to an input when true, or an
324 output when false.
325
326 @return the number of the first device whose device interface
327 contains the interface pattern (if any), whose device name
328 contains the name pattern, and whose direction (input or output)
329 matches the #is_input parameter. If no match is found, #pmNoDevice
330 (-1) is returned.
331*/
332PMEXPORT PmDeviceID Pm_FindDevice(char *pattern, int is_input);
333
334
335/** Represents a millisecond clock with arbitrary start time.
336 This type is used for all MIDI timestamps and clocks.
337*/
338typedef int32_t PmTimestamp;
339typedef PmTimestamp (*PmTimeProcPtr)(void *time_info);
340
341/** TRUE if t1 before t2 */
342#define PmBefore(t1,t2) (((t1)-(t2)) < 0)
343/** @} */
344/**
345 \defgroup grp_device Input/Output Devices Handling
346 @{
347*/
348/** Get a PmDeviceInfo structure describing a MIDI device.
349
350 @param id the device to be queried.
351
352 If \p id is out of range or if the device designates a deleted
353 virtual device, the function returns NULL.
354
355 The returned structure is owned by the PortMidi implementation and
356 must not be manipulated or freed. The pointer is guaranteed to be
357 valid between calls to Pm_Initialize() and Pm_Terminate().
358*/
359PMEXPORT const PmDeviceInfo *Pm_GetDeviceInfo(PmDeviceID id);
360
361/** Open a MIDI device for input.
362
363 @param stream the address of a #PortMidiStream pointer which will
364 receive a pointer to the newly opened stream.
365
366 @param inputDevice the ID of the device to be opened (see #PmDeviceID).
367
368 @param inputSysDepInfo a pointer to an optional system-dependent
369 data structure (a #PmSysDepInfo struct) containing additional
370 information for device setup or handle processing. This parameter
371 is never required for correct operation. If not used, specify
372 NULL. Declared `void *` here for backward compatibility. Note that
373 with Linux ALSA, you can use this parameter to specify a client name
374 and port name.
375
376 @param bufferSize the number of input events to be buffered
377 waiting to be read using Pm_Read(). Messages will be lost if the
378 number of unread messages exceeds this value.
379
380 @param time_proc (address of) a procedure that returns time in
381 milliseconds. It may be NULL, in which case a default millisecond
382 timebase (PortTime) is used. If the application wants to use
383 PortTime, it should start the timer (call Pt_Start) before calling
384 Pm_OpenInput or Pm_OpenOutput. If the application tries to start
385 the timer *after* Pm_OpenInput or Pm_OpenOutput, it may get a
386 ptAlreadyStarted error from Pt_Start, and the application's
387 preferred time resolution and callback function will be ignored.
388 \p time_proc result values are appended to incoming MIDI data,
389 normally by mapping system-provided timestamps to the \p time_proc
390 timestamps to maintain the precision of system-provided
391 timestamps.
392
393 @param time_info is a pointer passed to time_proc.
394
395 @return #pmNoError and places a pointer to a valid
396 #PortMidiStream in the stream argument. If the open operation
397 fails, a nonzero error code is returned (see #PMError) and
398 the value of stream is invalid.
399
400 Any stream that is successfully opened should eventually be closed
401 by calling Pm_Close().
402*/
403PMEXPORT PmError Pm_OpenInput(PortMidiStream** stream,
404 PmDeviceID inputDevice,
405 void *inputSysDepInfo,
406 int32_t bufferSize,
407 PmTimeProcPtr time_proc,
408 void *time_info);
409
410/** Open a MIDI device for output.
411
412 @param stream the address of a #PortMidiStream pointer which will
413 receive a pointer to the newly opened stream.
414
415 @param outputDevice the ID of the device to be opened (see #PmDeviceID).
416
417 @param inputSysDepInfo a pointer to an optional system-specific
418 data structure (a #PmSysDepInfo struct) containing additional
419 information for device setup or handle processing. This parameter
420 is never required for correct operation. If not used, specify
421 NULL. Declared `void *` here for backward compatibility. Note that
422 with Linux ALSA, you can use this parameter to specify a client name
423 and port name.
424
425 @param bufferSize the number of output events to be buffered
426 waiting for output. In some cases -- see below -- PortMidi does
427 not buffer output at all and merely passes data to a lower-level
428 API, in which case \p bufferSize is ignored. Since MIDI speeds now
429 vary from 1 to 50 or more messages per ms (over USB), put some
430 thought into this number. E.g. if latency is 20ms and you want to
431 burst 100 messages in that time (5000 messages per second), you
432 should set \p bufferSize to at least 100. The default on Windows
433 assumes an average rate of 500 messages per second and in this
434 example, output would be slowed waiting for free buffers.
435
436 @param latency the delay in milliseconds applied to timestamps
437 to determine when the output should actually occur. (If latency is
438 < 0, 0 is assumed.) If latency is zero, timestamps are ignored
439 and all output is delivered immediately. If latency is greater
440 than zero, output is delayed until the message timestamp plus the
441 latency. (NOTE: the time is measured relative to the time source
442 indicated by time_proc. Timestamps are absolute, not relative
443 delays or offsets.) In some cases, PortMidi can obtain better
444 timing than your application by passing timestamps along to the
445 device driver or hardware, so the best strategy to minimize jitter
446 is: wait until the real time to send the message, compute the
447 message, attach the *ideal* output time (not the current real
448 time, because some time may have elapsed), and send the
449 message. The \p latency will be added to the timestamp, and
450 provided the elapsed computation time has not exceeded \p latency,
451 the message will be delivered according to the timestamp. If the
452 real time is already past the timestamp, the message will be
453 delivered as soon as possible. Latency may also help you to
454 synchronize MIDI data to audio data by matching \p latency to the
455 audio buffer latency.
456
457 @param time_proc (address of) a pointer to a procedure that
458 returns time in milliseconds. It may be NULL, in which case a
459 default millisecond timebase (PortTime) is used. If the
460 application wants to use PortTime, it should start the timer (call
461 Pt_Start) before calling #Pm_OpenInput or #Pm_OpenOutput. If the
462 application tries to start the timer *after* #Pm_OpenInput or
463 #Pm_OpenOutput, it may get a #ptAlreadyStarted error from #Pt_Start,
464 and the application's preferred time resolution and callback
465 function will be ignored. \p time_proc times are used to schedule
466 outgoing MIDI data (when latency is non-zero), usually by mapping
467 from time_proc timestamps to internal system timestamps to
468 maintain the precision of system-supported timing.
469
470 @param time_info a pointer passed to time_proc.
471
472 @return #pmNoError and places a pointer to a valid #PortMidiStream
473 in the stream argument. If the operation fails, a nonzero error
474 code is returned (see PMError) and the value of \p stream is
475 invalid.
476
477 Note: ALSA appears to have a fixed-size priority queue for timed
478 output messages. Testing indicates the queue can hold a little
479 over 400 3-byte MIDI messages. Thus, you can send 10,000
480 messages/second if the latency is 30ms (30ms * 10000 msgs/sec *
481 0.001 sec/ms = 300 msgs), but not if the latency is 50ms
482 (resulting in about 500 pending messages, which is greater than
483 the 400 message limit). Since timestamps in ALSA are relative,
484 they are of less value than absolute timestamps in macOS and
485 Windows. This is a limitation of ALSA and apparently a design
486 flaw.
487
488 Example 1: If I provide a timestamp of 5000, latency is 1, and
489 time_proc returns 4990, then the desired output time will be when
490 time_proc returns timestamp+latency = 5001. This will be 5001-4990
491 = 11ms from now.
492
493 Example 2: If I want to send at exactly 5010, and latency is 10, I
494 should wait until 5000, compute the messages and provide a
495 timestamp of 5000. As long as computation takes less than 10ms,
496 the message will be delivered at time 5010.
497
498 Example 3 (recommended): It is often convenient to ignore latency.
499 E.g. if a sequence says to output at time 5010, just wait until
500 5010, compute the message and use 5010 for the timestamp. Delivery
501 will then be at 5010+latency, but unless you are synchronizing to
502 something else, the absolute delay by latency will not matter.
503
504 Any stream that is successfully opened should eventually be closed
505 by calling Pm_Close().
506*/
507PMEXPORT PmError Pm_OpenOutput(PortMidiStream** stream,
508 PmDeviceID outputDevice,
509 void *outputSysDepInfo,
510 int32_t bufferSize,
511 PmTimeProcPtr time_proc,
512 void *time_info,
513 int32_t latency);
514
515/** Create a virtual input device.
516
517 @param name gives the virtual device name, which is visible to
518 other applications.
519
520 @param interf is the interface (System API) used to create the
521 device Default interfaces are "MMSystem", "CoreMIDI" and
522 "ALSA". Currently, these are the only ones implemented, but future
523 implementations could support DirectMusic, Jack, sndio, or others.
524
525 @param sysDepInfo contains interface-dependent additional
526 information (a #PmSysDepInfo struct), e.g., hints or options. This
527 parameter is never required for correct operation. If not used,
528 specify NULL. Declared `void *` here for backward compatibility.
529
530 @return a device ID or #pmNameConflict (\p name is invalid or
531 already exists) or #pmInterfaceNotSupported (\p interf is does not
532 match a supported interface).
533
534 The created virtual device appears to other applications as if it
535 is an output device. The device must be opened to obtain a stream
536 and read from it.
537
538 Virtual devices are not supported by Windows (Multimedia API). Calls
539 on Windows do nothing except return #pmNotImplemented.
540*/
541PMEXPORT PmError Pm_CreateVirtualInput(const char *name,
542 const char *interf,
543 void *sysDepInfo);
544
545/** Create a virtual output device.
546
547 @param name gives the virtual device name, which is visible to
548 other applications.
549
550 @param interf is the interface (System API) used to create the
551 device Default interfaces are "MMSystem", "CoreMIDI" and
552 "ALSA". Currently, these are the only ones implemented, but future
553 implementations could support DirectMusic, Jack, sndio, or others.
554
555 @param sysDepInfo contains interface-dependent additional
556 information (a #PmSysDepInfo struct), e.g., hints or options. This
557 parameter is never required for correct operation. If not used,
558 specify NULL. Declared `void *` here for backward compatibility.
559
560 @return a device ID or #pmInvalidDeviceId (\p name is invalid or
561 already exists) or #pmInterfaceNotSupported (\p interf is does not
562 match a supported interface).
563
564 The created virtual device appears to other applications as if it
565 is an input device. The device must be opened to obtain a stream
566 and write to it.
567
568 Virtual devices are not supported by Windows (Multimedia API). Calls
569 on Windows do nothing except return #pmNotImplemented.
570*/
571PMEXPORT PmError Pm_CreateVirtualOutput(const char *name,
572 const char *interf,
573 void *sysDepInfo);
574
575/** Remove a virtual device.
576
577 @param device a device ID (small integer) designating the device.
578
579 The device is removed; other applications can no longer see or open
580 this virtual device, which may be either for input or output. The
581 device must not be open. The device ID may be reused, but existing
582 devices are not renumbered. This means that the device ID could be
583 in the range from 0 to #Pm_CountDevices(), yet the device ID does
584 not designate a device. In that case, passing the ID to
585 #Pm_GetDeviceInfo() will return NULL.
586
587 @return #pmNoError if the device was deleted or #pmInvalidDeviceId
588 if the device is open, already deleted, or \p device is out of
589 range.
590*/
591PMEXPORT PmError Pm_DeleteVirtualDevice(PmDeviceID device);
592 /** @} */
593
594/**
595 @defgroup grp_events_filters Events and Filters Handling
596 @{
597*/
598
599/* Filter bit-mask definitions */
600/** filter active sensing messages (0xFE): */
601#define PM_FILT_ACTIVE (1 << 0x0E)
602/** filter system exclusive messages (0xF0): */
603#define PM_FILT_SYSEX (1 << 0x00)
604/** filter MIDI clock message (0xF8) */
605#define PM_FILT_CLOCK (1 << 0x08)
606/** filter play messages (start 0xFA, stop 0xFC, continue 0xFB) */
607#define PM_FILT_PLAY ((1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B))
608/** filter tick messages (0xF9) */
609#define PM_FILT_TICK (1 << 0x09)
610/** filter undefined FD messages */
611#define PM_FILT_FD (1 << 0x0D)
612/** filter undefined real-time messages */
613#define PM_FILT_UNDEFINED PM_FILT_FD
614/** filter reset messages (0xFF) */
615#define PM_FILT_RESET (1 << 0x0F)
616/** filter all real-time messages */
617#define PM_FILT_REALTIME (PM_FILT_ACTIVE | PM_FILT_SYSEX | PM_FILT_CLOCK | \
618 PM_FILT_PLAY | PM_FILT_UNDEFINED | PM_FILT_RESET | PM_FILT_TICK)
619/** filter note-on and note-off (0x90-0x9F and 0x80-0x8F */
620#define PM_FILT_NOTE ((1 << 0x19) | (1 << 0x18))
621/** filter channel aftertouch (most midi controllers use this) (0xD0-0xDF)*/
622#define PM_FILT_CHANNEL_AFTERTOUCH (1 << 0x1D)
623/** per-note aftertouch (0xA0-0xAF) */
624#define PM_FILT_POLY_AFTERTOUCH (1 << 0x1A)
625/** filter both channel and poly aftertouch */
626#define PM_FILT_AFTERTOUCH (PM_FILT_CHANNEL_AFTERTOUCH | \
627 PM_FILT_POLY_AFTERTOUCH)
628/** Program changes (0xC0-0xCF) */
629#define PM_FILT_PROGRAM (1 << 0x1C)
630/** Control Changes (CC's) (0xB0-0xBF)*/
631#define PM_FILT_CONTROL (1 << 0x1B)
632/** Pitch Bender (0xE0-0xEF*/
633#define PM_FILT_PITCHBEND (1 << 0x1E)
634/** MIDI Time Code (0xF1)*/
635#define PM_FILT_MTC (1 << 0x01)
636/** Song Position (0xF2) */
637#define PM_FILT_SONG_POSITION (1 << 0x02)
638/** Song Select (0xF3)*/
639#define PM_FILT_SONG_SELECT (1 << 0x03)
640/** Tuning request (0xF6) */
641#define PM_FILT_TUNE (1 << 0x06)
642/** All System Common messages (mtc, song position, song select, tune request) */
643#define PM_FILT_SYSTEMCOMMON (PM_FILT_MTC | PM_FILT_SONG_POSITION | \
644 PM_FILT_SONG_SELECT | PM_FILT_TUNE)
645
646
647/* Set filters on an open input stream to drop selected input types.
648
649 @param stream an open MIDI input stream.
650
651 @param filters indicate message types to filter (block).
652
653 @return #pmNoError or an error code.
654
655 By default, only active sensing messages are filtered.
656 To prohibit, say, active sensing and sysex messages, call
657 Pm_SetFilter(stream, PM_FILT_ACTIVE | PM_FILT_SYSEX);
658
659 Filtering is useful when midi routing or midi thru functionality
660 is being provided by the user application.
661 For example, you may want to exclude timing messages (clock, MTC,
662 start/stop/continue), while allowing note-related messages to pass.
663 Or you may be using a sequencer or drum-machine for MIDI clock
664 information but want to exclude any notes it may play.
665 */
666PMEXPORT PmError Pm_SetFilter(PortMidiStream* stream, int32_t filters);
667
668/** Create a mask that filters one channel. */
669#define Pm_Channel(channel) (1<<(channel))
670
671/** Filter incoming messages based on channel.
672
673 @param stream an open MIDI input stream.
674
675 @param mask indicates channels to be received.
676
677 @return #pmNoError or an error code.
678
679 The \p mask is a 16-bit bitfield corresponding to appropriate channels.
680 The #Pm_Channel macro can assist in calling this function.
681 I.e. to receive only input on channel 1, call with
682 Pm_SetChannelMask(Pm_Channel(1));
683 Multiple channels should be OR'd together, like
684 Pm_SetChannelMask(Pm_Channel(10) | Pm_Channel(11))
685
686 Note that channels are numbered 0 to 15 (not 1 to 16). Most
687 synthesizer and interfaces number channels starting at 1, but
688 PortMidi numbers channels starting at 0.
689
690 All channels are allowed by default
691*/
692PMEXPORT PmError Pm_SetChannelMask(PortMidiStream *stream, int mask);
693
694/** Terminate outgoing messages immediately.
695
696 @param stream an open MIDI output stream.
697
698 @result #pmNoError or an error code.
699
700 The caller should immediately close the output port; this call may
701 result in transmission of a partial MIDI message. There is no
702 abort for Midi input because the user can simply ignore messages
703 in the buffer and close an input device at any time. If the
704 specified behavior cannot be achieved through the system-level
705 interface (ALSA, CoreMIDI, etc.), the behavior may be that of
706 Pm_Close().
707 */
708PMEXPORT PmError Pm_Abort(PortMidiStream* stream);
709
710/** Close a midi stream, flush any pending buffers if possible.
711
712 @param stream an open MIDI input or output stream.
713
714 @result #pmNoError or an error code.
715
716 If the system-level interface (ALSA, CoreMIDI, etc.) does not
717 support flushing remaining messages, the behavior may be one of
718 the following (most preferred first): block until all pending
719 timestamped messages are delivered; deliver messages to a server
720 or kernel process for later delivery but return immediately; drop
721 messages (as in Pm_Abort()). Therefore, to be safe, applications
722 should wait until the output queue is empty before calling
723 Pm_Close(). E.g. calling Pt_Sleep(100 + latency); will give a
724 100ms "cushion" beyond latency (if any) before closing.
725*/
726PMEXPORT PmError Pm_Close(PortMidiStream* stream);
727
728/** (re)synchronize to the time_proc passed when the stream was opened.
729
730 @param stream an open MIDI input or output stream.
731
732 @result #pmNoError or an error code.
733
734 Typically, this is used when the stream must be opened before the
735 time_proc reference is actually advancing. In this case, message
736 timing may be erratic, but since timestamps of zero mean "send
737 immediately," initialization messages with zero timestamps can be
738 written without a functioning time reference and without
739 problems. Before the first MIDI message with a non-zero timestamp
740 is written to the stream, the time reference must begin to advance
741 (for example, if the time_proc computes time based on audio
742 samples, time might begin to advance when an audio stream becomes
743 active). After time_proc return values become valid, and BEFORE
744 writing the first non-zero timestamped MIDI message, call
745 Pm_Synchronize() so that PortMidi can observe the difference
746 between the current time_proc value and its MIDI stream time.
747
748 In the more normal case where time_proc values advance
749 continuously, there is no need to call #Pm_Synchronize. PortMidi
750 will always synchronize at the first output message and
751 periodically thereafter.
752*/
753PMEXPORT PmError Pm_Synchronize(PortMidiStream* stream);
754
755
756/** Encode a short Midi message into a 32-bit word. If data1
757 and/or data2 are not present, use zero.
758*/
759#define Pm_Message(status, data1, data2) \
760 ((((data2) << 16) & 0xFF0000) | \
761 (((data1) << 8) & 0xFF00) | \
762 ((status) & 0xFF))
763/** Extract the status field from a 32-bit midi message. */
764#define Pm_MessageStatus(msg) ((msg) & 0xFF)
765/** Extract the 1st data field (e.g., pitch) from a 32-bit midi message. */
766#define Pm_MessageData1(msg) (((msg) >> 8) & 0xFF)
767/** Extract the 2nd data field (e.g., velocity) from a 32-bit midi message. */
768#define Pm_MessageData2(msg) (((msg) >> 16) & 0xFF)
769
770typedef uint32_t PmMessage; /**< @brief see #PmEvent */
771/**
772 All MIDI data comes in the form of PmEvent structures. A sysex
773 message is encoded as a sequence of PmEvent structures, with each
774 structure carrying 4 bytes of the message, i.e. only the first
775 PmEvent carries the status byte.
776
777 All other MIDI messages take 1 to 3 bytes and are encoded in a whole
778 PmMessage with status in the low-order byte and remaining bytes
779 unused, i.e., a 3-byte note-on message will occupy 3 low-order bytes
780 of PmMessage, leaving the high-order byte unused.
781
782 Note that MIDI allows nested messages: the so-called "real-time" MIDI
783 messages can be inserted into the MIDI byte stream at any location,
784 including within a sysex message. MIDI real-time messages are one-byte
785 messages used mainly for timing (see the MIDI spec). PortMidi retains
786 the order of non-real-time MIDI messages on both input and output, but
787 it does not specify exactly how real-time messages are processed. This
788 is particulary problematic for MIDI input, because the input parser
789 must either prepare to buffer an unlimited number of sysex message
790 bytes or to buffer an unlimited number of real-time messages that
791 arrive embedded in a long sysex message. To simplify things, the input
792 parser is allowed to pass real-time MIDI messages embedded within a
793 sysex message, and it is up to the client to detect, process, and
794 remove these messages as they arrive.
795
796 When receiving sysex messages, the sysex message is terminated
797 by either an EOX status byte (anywhere in the 4 byte messages) or
798 by a non-real-time status byte in the low order byte of the message.
799 If you get a non-real-time status byte but there was no EOX byte, it
800 means the sysex message was somehow truncated. This is not
801 considered an error; e.g., a missing EOX can result from the user
802 disconnecting a MIDI cable during sysex transmission.
803
804 A real-time message can occur within a sysex message. A real-time
805 message will always occupy a full PmEvent with the status byte in
806 the low-order byte of the PmEvent message field. (This implies that
807 the byte-order of sysex bytes and real-time message bytes may not
808 be preserved -- for example, if a real-time message arrives after
809 3 bytes of a sysex message, the real-time message will be delivered
810 first. The first word of the sysex message will be delivered only
811 after the 4th byte arrives, filling the 4-byte PmEvent message field.
812
813 The timestamp field is observed when the output port is opened with
814 a non-zero latency. A timestamp of zero means "use the current time",
815 which in turn means to deliver the message with a delay of
816 latency (the latency parameter used when opening the output port.)
817 Do not expect PortMidi to sort data according to timestamps --
818 messages should be sent in the correct order, and timestamps MUST
819 be non-decreasing. See also "Example" for Pm_OpenOutput() above.
820
821 A sysex message will generally fill many #PmEvent structures. On
822 output to a #PortMidiStream with non-zero latency, the first timestamp
823 on sysex message data will determine the time to begin sending the
824 message. PortMidi implementations may ignore timestamps for the
825 remainder of the sysex message.
826
827 On input, the timestamp ideally denotes the arrival time of the
828 status byte of the message. The first timestamp on sysex message
829 data will be valid. Subsequent timestamps may denote
830 when message bytes were actually received, or they may be simply
831 copies of the first timestamp.
832
833 Timestamps for nested messages: If a real-time message arrives in
834 the middle of some other message, it is enqueued immediately with
835 the timestamp corresponding to its arrival time. The interrupted
836 non-real-time message or 4-byte packet of sysex data will be enqueued
837 later. The timestamp of interrupted data will be equal to that of
838 the interrupting real-time message to insure that timestamps are
839 non-decreasing.
840 */
841typedef struct {
842 PmMessage message;
843 PmTimestamp timestamp;
844} PmEvent;
845
846/** @} */
847
848/** \defgroup grp_io Reading and Writing Midi Messages
849 @{
850*/
851/** Retrieve midi data into a buffer.
852
853 @param stream the open input stream.
854
855 @return the number of events read, or, if the result is negative,
856 a #PmError value will be returned.
857
858 The Buffer Overflow Problem
859
860 The problem: if an input overflow occurs, data will be lost,
861 ultimately because there is no flow control all the way back to
862 the data source. When data is lost, the receiver should be
863 notified and some sort of graceful recovery should take place,
864 e.g. you shouldn't resume receiving in the middle of a long sysex
865 message.
866
867 With a lock-free fifo, which is pretty much what we're stuck with
868 to enable portability to the Mac, it's tricky for the producer and
869 consumer to synchronously reset the buffer and resume normal
870 operation.
871
872 Solution: the entire buffer managed by PortMidi will be flushed
873 when an overflow occurs. The consumer (Pm_Read()) gets an error
874 message (#pmBufferOverflow) and ordinary processing resumes as
875 soon as a new message arrives. The remainder of a partial sysex
876 message is not considered to be a "new message" and will be
877 flushed as well.
878*/
879PMEXPORT int Pm_Read(PortMidiStream *stream, PmEvent *buffer, int32_t length);
880
881/** Test whether input is available.
882
883 @param stream an open input stream.
884
885 @return TRUE, FALSE, or an error value.
886
887 If there was an asynchronous error, pmHostError is returned and you must
888 call again to determine if input is (also) available.
889
890 You should probably *not* use this function. Call Pm_Read()
891 instead. If it returns 0, then there is no data available. It is
892 possible for Pm_Poll() to return TRUE before the complete message
893 is available, so Pm_Read() could return 0 even after Pm_Poll()
894 returns TRUE. Only call Pm_Poll() if you want to know that data is
895 probably available even though you are not ready to receive data.
896*/
897PMEXPORT PmError Pm_Poll(PortMidiStream *stream);
898
899/** Write MIDI data from a buffer.
900
901 @param stream an open output stream.
902
903 @param buffer (address of) an array of MIDI event data.
904
905 @param length the length of the \p buffer.
906
907 @return TRUE, FALSE, or an error value.
908
909 \b buffer may contain:
910 - short messages
911 - sysex messages that are converted into a sequence of PmEvent
912 structures, e.g. sending data from a file or forwarding them
913 from midi input, with 4 SysEx bytes per PmEvent message,
914 low-order byte first, until the last message, which may
915 contain from 1 to 4 bytes ending in MIDI EOX (0xF7).
916 - PortMidi allows 1-byte real-time messages to be embedded
917 within SysEx messages, but only on 4-byte boundaries so
918 that SysEx data always uses a full 4 bytes (except possibly
919 at the end). Each real-time message always occupies a full
920 PmEvent (3 of the 4 bytes in the PmEvent's message are
921 ignored) even when embedded in a SysEx message.
922
923 Use Pm_WriteSysEx() to write a sysex message stored as a contiguous
924 array of bytes.
925
926 Sysex data may contain embedded real-time messages.
927
928 \p buffer is managed by the caller. The buffer may be destroyed
929 as soon as this call returns.
930*/
931PMEXPORT PmError Pm_Write(PortMidiStream *stream, PmEvent *buffer,
932 int32_t length);
933
934/** Write a timestamped non-system-exclusive midi message.
935
936 @param stream an open output stream.
937
938 @param when timestamp for the event.
939
940 @param msg the data for the event.
941
942 @result #pmNoError or an error code.
943
944 Messages are delivered in order, and timestamps must be
945 non-decreasing. (But timestamps are ignored if the stream was
946 opened with latency = 0, and otherwise, non-decreasing timestamps
947 are "corrected" to the lowest valid value.)
948*/
949PMEXPORT PmError Pm_WriteShort(PortMidiStream *stream, PmTimestamp when,
950 PmMessage msg);
951
952/** Write a timestamped system-exclusive midi message.
953
954 @param stream an open output stream.
955
956 @param when timestamp for the event.
957
958 @param msg the sysex message, terminated with an EOX status byte.
959
960 @result #pmNoError or an error code.
961
962 \p msg is managed by the caller and may be destroyed when this
963 call returns.
964*/
965PMEXPORT PmError Pm_WriteSysEx(PortMidiStream *stream, PmTimestamp when,
966 unsigned char *msg);
967
968/** @} */
969
970#ifdef __cplusplus
971}
972#endif /* __cplusplus */
973
974#endif /* PORTMIDI_PORTMIDI_H */