portmidi.odin 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package portmidi
  2. import "core:c"
  3. import "core:strings"
  4. PORTMIDI_SHARED :: #config(PORTMIDI_SHARED, false)
  5. when ODIN_OS == .Windows {
  6. when PORTMIDI_SHARED {
  7. #panic("Shared linking not supported for portmidi on windows yet")
  8. } else {
  9. foreign import lib {
  10. "portmidi_s.lib",
  11. "system:Winmm.lib",
  12. "system:Advapi32.lib",
  13. }
  14. }
  15. } else {
  16. foreign import lib "system:portmidi"
  17. }
  18. #assert(size_of(b32) == size_of(c.int))
  19. DEFAULT_SYSEX_BUFFER_SIZE :: 1024
  20. Error :: enum c.int {
  21. NoError = 0,
  22. NoData = 0, /**< A "no error" return that also indicates no data avail. */
  23. GotData = 1, /**< A "no error" return that also indicates data available */
  24. HostError = -10000,
  25. InvalidDeviceId, /** out of range or
  26. * output device when input is requested or
  27. * input device when output is requested or
  28. * device is already opened
  29. */
  30. InsufficientMemory,
  31. BufferTooSmall,
  32. BufferOverflow,
  33. BadPtr, /* Stream parameter is nil or
  34. * stream is not opened or
  35. * stream is output when input is required or
  36. * stream is input when output is required */
  37. BadData, /** illegal midi data, e.g. missing EOX */
  38. InternalError,
  39. BufferMaxSize, /** buffer is already as large as it can be */
  40. }
  41. /** A single Stream is a descriptor for an open MIDI device.
  42. */
  43. Stream :: distinct rawptr
  44. @(default_calling_convention="c", link_prefix="Pm_")
  45. foreign lib {
  46. /**
  47. Initialize() is the library initialisation function - call this before
  48. using the library.
  49. */
  50. Initialize :: proc() -> Error ---
  51. /**
  52. Terminate() is the library termination function - call this after
  53. using the library.
  54. */
  55. Terminate :: proc() -> Error ---
  56. /**
  57. Test whether stream has a pending host error. Normally, the client finds
  58. out about errors through returned error codes, but some errors can occur
  59. asynchronously where the client does not
  60. explicitly call a function, and therefore cannot receive an error code.
  61. The client can test for a pending error using HasHostError(). If true,
  62. the error can be accessed and cleared by calling GetErrorText().
  63. Errors are also cleared by calling other functions that can return
  64. errors, e.g. OpenInput(), OpenOutput(), Read(), Write(). The
  65. client does not need to call HasHostError(). Any pending error will be
  66. reported the next time the client performs an explicit function call on
  67. the stream, e.g. an input or output operation. Until the error is cleared,
  68. no new error codes will be obtained, even for a different stream.
  69. */
  70. HasHostError :: proc(stream: Stream) -> b32 ---
  71. }
  72. /** Translate portmidi error number into human readable message.
  73. These strings are constants (set at compile time) so client has
  74. no need to allocate storage
  75. */
  76. GetErrorText :: proc (errnum: Error) -> string {
  77. @(default_calling_convention="c")
  78. foreign lib {
  79. Pm_GetErrorText :: proc(errnum: Error) -> cstring ---
  80. }
  81. return string(Pm_GetErrorText(errnum))
  82. }
  83. /** Translate portmidi host error into human readable message.
  84. These strings are computed at run time, so client has to allocate storage.
  85. After this routine executes, the host error is cleared.
  86. */
  87. GetHostErrorText :: proc (buf: []byte) -> string {
  88. @(default_calling_convention="c")
  89. foreign lib {
  90. Pm_GetHostErrorText :: proc(msg: [^]u8, len: c.uint) ---
  91. }
  92. Pm_GetHostErrorText(raw_data(buf), u32(len(buf)))
  93. str := string(buf[:])
  94. return strings.truncate_to_byte(str, 0)
  95. }
  96. HDRLENGTH :: 50
  97. HOST_ERROR_MSG_LEN :: 256 /* any host error msg will occupy less
  98. than this number of characters */
  99. DeviceID :: distinct c.int
  100. NoDevice :: DeviceID(-1)
  101. DeviceInfo :: struct {
  102. structVersion: c.int, /**< this internal structure version */
  103. interf: cstring, /**< underlying MIDI API, e.g. MMSystem or DirectX */
  104. name: cstring, /**< device name, e.g. USB MidiSport 1x1 */
  105. input: b32, /**< true iff input is available */
  106. output: b32, /**< true iff output is available */
  107. opened: b32, /**< used by generic PortMidi code to do error checking on arguments */
  108. }
  109. @(default_calling_convention="c", link_prefix="Pm_")
  110. foreign lib {
  111. /** Get devices count, ids range from 0 to CountDevices()-1. */
  112. CountDevices :: proc() -> c.int ---
  113. GetDefaultInputDeviceID :: proc() -> DeviceID ---
  114. GetDefaultOutputDeviceID :: proc() -> DeviceID ---
  115. }
  116. /**
  117. Timestamp is used to represent a millisecond clock with arbitrary
  118. start time. The type is used for all MIDI timestampes and clocks.
  119. */
  120. Timestamp :: distinct i32
  121. TimeProc :: proc "c" (time_info: rawptr) -> Timestamp
  122. Before :: #force_inline proc "c" (t1, t2: Timestamp) -> b32 {
  123. return b32((t1-t2) < 0)
  124. }
  125. @(default_calling_convention="c", link_prefix="Pm_")
  126. foreign lib {
  127. /**
  128. GetDeviceInfo() returns a pointer to a DeviceInfo structure
  129. referring to the device specified by id.
  130. If id is out of range the function returns nil.
  131. The returned structure is owned by the PortMidi implementation and must
  132. not be manipulated or freed. The pointer is guaranteed to be valid
  133. between calls to Initialize() and Terminate().
  134. */
  135. GetDeviceInfo :: proc(id: DeviceID) -> ^DeviceInfo ---
  136. /**
  137. OpenInput() and OpenOutput() open devices.
  138. stream is the address of a Stream pointer which will receive
  139. a pointer to the newly opened stream.
  140. inputDevice is the id of the device used for input (see DeviceID above).
  141. inputDriverInfo is a pointer to an optional driver specific data structure
  142. containing additional information for device setup or handle processing.
  143. inputDriverInfo is never required for correct operation. If not used
  144. inputDriverInfo should be nil.
  145. outputDevice is the id of the device used for output (see DeviceID above.)
  146. outputDriverInfo is a pointer to an optional driver specific data structure
  147. containing additional information for device setup or handle processing.
  148. outputDriverInfo is never required for correct operation. If not used
  149. outputDriverInfo should be nil.
  150. For input, the buffersize specifies the number of input events to be
  151. buffered waiting to be read using Read(). For output, buffersize
  152. specifies the number of output events to be buffered waiting for output.
  153. (In some cases -- see below -- PortMidi does not buffer output at all
  154. and merely passes data to a lower-level API, in which case buffersize
  155. is ignored.)
  156. latency is the delay in milliseconds applied to timestamps to determine
  157. when the output should actually occur. (If latency is < 0, 0 is assumed.)
  158. If latency is zero, timestamps are ignored and all output is delivered
  159. immediately. If latency is greater than zero, output is delayed until the
  160. message timestamp plus the latency. (NOTE: the time is measured relative
  161. to the time source indicated by time_proc. Timestamps are absolute,
  162. not relative delays or offsets.) In some cases, PortMidi can obtain
  163. better timing than your application by passing timestamps along to the
  164. device driver or hardware. Latency may also help you to synchronize midi
  165. data to audio data by matching midi latency to the audio buffer latency.
  166. time_proc is a pointer to a procedure that returns time in milliseconds. It
  167. may be nil, in which case a default millisecond timebase (PortTime) is
  168. used. If the application wants to use PortTime, it should start the timer
  169. (call Pt_Start) before calling OpenInput or OpenOutput. If the
  170. application tries to start the timer *after* OpenInput or OpenOutput,
  171. it may get a ptAlreadyStarted error from Pt_Start, and the application's
  172. preferred time resolution and callback function will be ignored.
  173. time_proc result values are appended to incoming MIDI data, and time_proc
  174. times are used to schedule outgoing MIDI data (when latency is non-zero).
  175. time_info is a pointer passed to time_proc.
  176. Example: If I provide a timestamp of 5000, latency is 1, and time_proc
  177. returns 4990, then the desired output time will be when time_proc returns
  178. timestamp+latency = 5001. This will be 5001-4990 = 11ms from now.
  179. return value:
  180. Upon success Open() returns NoError and places a pointer to a
  181. valid Stream in the stream argument.
  182. If a call to Open() fails a nonzero error code is returned (see
  183. PMError above) and the value of port is invalid.
  184. Any stream that is successfully opened should eventually be closed
  185. by calling Close().
  186. */
  187. OpenInput :: proc(stream: ^Stream,
  188. inputDevice: DeviceID,
  189. inputDriverInfo: rawptr,
  190. bufferSize: i32,
  191. time_proc: TimeProc,
  192. time_info: rawptr) -> Error ---
  193. OpenOutput :: proc(stream: ^Stream,
  194. outputDevice: DeviceID,
  195. outputDriverInfo: rawptr,
  196. bufferSize: i32,
  197. time_proc: TimeProc,
  198. time_info: rawptr,
  199. latency: i32) -> Error ---
  200. }
  201. @(default_calling_convention="c", link_prefix="Pm_")
  202. foreign lib {
  203. /**
  204. SetFilter() sets filters on an open input stream to drop selected
  205. input types. By default, only active sensing messages are filtered.
  206. To prohibit, say, active sensing and sysex messages, call
  207. SetFilter(stream, FILT_ACTIVE | FILT_SYSEX);
  208. Filtering is useful when midi routing or midi thru functionality is being
  209. provided by the user application.
  210. For example, you may want to exclude timing messages (clock, MTC, start/stop/continue),
  211. while allowing note-related messages to pass.
  212. Or you may be using a sequencer or drum-machine for MIDI clock information but want to
  213. exclude any notes it may play.
  214. */
  215. SetFilter :: proc(stream: Stream, filters: i32) -> Error ---
  216. }
  217. /* Filter bit-mask definitions */
  218. /** filter active sensing messages (0xFE): */
  219. FILT_ACTIVE :: 1 << 0x0E
  220. /** filter system exclusive messages (0xF0): */
  221. FILT_SYSEX :: 1 << 0x00
  222. /** filter MIDI clock message (0xF8) */
  223. FILT_CLOCK :: 1 << 0x08
  224. /** filter play messages (start 0xFA, stop 0xFC, continue 0xFB) */
  225. FILT_PLAY :: (1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B)
  226. /** filter tick messages (0xF9) */
  227. FILT_TICK :: 1 << 0x09
  228. /** filter undefined FD messages */
  229. FILT_FD :: 1 << 0x0D
  230. /** filter undefined real-time messages */
  231. FILT_UNDEFINED :: FILT_FD
  232. /** filter reset messages (0xFF) */
  233. FILT_RESET :: 1 << 0x0F
  234. /** filter all real-time messages */
  235. FILT_REALTIME :: FILT_ACTIVE | FILT_SYSEX | FILT_CLOCK | FILT_PLAY | FILT_UNDEFINED | FILT_RESET | FILT_TICK
  236. /** filter note-on and note-off (0x90-0x9F and 0x80-0x8F */
  237. FILT_NOTE :: (1 << 0x19) | (1 << 0x18)
  238. /** filter channel aftertouch (most midi controllers use this) (0xD0-0xDF)*/
  239. FILT_CHANNEL_AFTERTOUCH :: 1 << 0x1D
  240. /** per-note aftertouch (0xA0-0xAF) */
  241. FILT_POLY_AFTERTOUCH :: 1 << 0x1A
  242. /** filter both channel and poly aftertouch */
  243. FILT_AFTERTOUCH :: FILT_CHANNEL_AFTERTOUCH | FILT_POLY_AFTERTOUCH
  244. /** Program changes (0xC0-0xCF) */
  245. FILT_PROGRAM :: 1 << 0x1C
  246. /** Control Changes (CC's) (0xB0-0xBF)*/
  247. FILT_CONTROL :: 1 << 0x1B
  248. /** Pitch Bender (0xE0-0xEF*/
  249. FILT_PITCHBEND :: 1 << 0x1E
  250. /** MIDI Time Code (0xF1)*/
  251. FILT_MTC :: 1 << 0x01
  252. /** Song Position (0xF2) */
  253. FILT_SONG_POSITION :: 1 << 0x02
  254. /** Song Select (0xF3)*/
  255. FILT_SONG_SELECT :: 1 << 0x03
  256. /** Tuning request (0xF6)*/
  257. FILT_TUNE :: 1 << 0x06
  258. /** All System Common messages (mtc, song position, song select, tune request) */
  259. FILT_SYSTEMCOMMON :: FILT_MTC | FILT_SONG_POSITION | FILT_SONG_SELECT | FILT_TUNE
  260. Channel :: #force_inline proc "c" (channel: c.int) -> c.int {
  261. return 1<<c.uint(channel)
  262. }
  263. @(default_calling_convention="c", link_prefix="Pm_")
  264. foreign lib {
  265. /**
  266. SetChannelMask() filters incoming messages based on channel.
  267. The mask is a 16-bit bitfield corresponding to appropriate channels.
  268. The _Channel macro can assist in calling this function.
  269. i.e. to set receive only input on channel 1, call with
  270. SetChannelMask(Channel(1));
  271. Multiple channels should be OR'd together, like
  272. SetChannelMask(Channel(10) | Channel(11))
  273. Note that channels are numbered 0 to 15 (not 1 to 16). Most
  274. synthesizer and interfaces number channels starting at 1, but
  275. PortMidi numbers channels starting at 0.
  276. All channels are allowed by default
  277. */
  278. SetChannelMask :: proc(stream: Stream, mask: c.int) -> Error ---
  279. /**
  280. Abort() terminates outgoing messages immediately
  281. The caller should immediately close the output port;
  282. this call may result in transmission of a partial midi message.
  283. There is no abort for Midi input because the user can simply
  284. ignore messages in the buffer and close an input device at
  285. any time.
  286. */
  287. Abort :: proc(stream: Stream) -> Error ---
  288. /**
  289. Close() closes a midi stream, flushing any pending buffers.
  290. (PortMidi attempts to close open streams when the application
  291. exits -- this is particularly difficult under Windows.)
  292. */
  293. Close :: proc(stream: Stream) -> Error ---
  294. /**
  295. Synchronize() instructs PortMidi to (re)synchronize to the
  296. time_proc passed when the stream was opened. Typically, this
  297. is used when the stream must be opened before the time_proc
  298. reference is actually advancing. In this case, message timing
  299. may be erratic, but since timestamps of zero mean
  300. "send immediately," initialization messages with zero timestamps
  301. can be written without a functioning time reference and without
  302. problems. Before the first MIDI message with a non-zero
  303. timestamp is written to the stream, the time reference must
  304. begin to advance (for example, if the time_proc computes time
  305. based on audio samples, time might begin to advance when an
  306. audio stream becomes active). After time_proc return values
  307. become valid, and BEFORE writing the first non-zero timestamped
  308. MIDI message, call Synchronize() so that PortMidi can observe
  309. the difference between the current time_proc value and its
  310. MIDI stream time.
  311. In the more normal case where time_proc
  312. values advance continuously, there is no need to call
  313. Synchronize. PortMidi will always synchronize at the
  314. first output message and periodically thereafter.
  315. */
  316. Synchronize :: proc(stream: Stream) -> Error ---
  317. }
  318. /**
  319. MessageMake() encodes a short Midi message into a 32-bit word. If data1
  320. and/or data2 are not present, use zero.
  321. MessageStatus(), MessageData1(), and
  322. MessageData2() extract fields from a 32-bit midi message.
  323. */
  324. MessageMake :: #force_inline proc "c" (status: c.int, data1, data2: c.int) -> Message {
  325. return Message(((data2 << 16) & 0xFF0000) | ((data1 << 8) & 0xFF00) | (status & 0xFF))
  326. }
  327. MessageStatus :: #force_inline proc "c" (msg: Message) -> c.int {
  328. return c.int(msg & 0xFF)
  329. }
  330. MessageData1 :: #force_inline proc "c" (msg: Message) -> c.int {
  331. return c.int((msg >> 8) & 0xFF)
  332. }
  333. MessageData2 :: #force_inline proc "c" (msg: Message) -> c.int {
  334. return c.int((msg >> 16) & 0xFF)
  335. }
  336. MessageCompose :: MessageMake
  337. MessageDecompose :: #force_inline proc "c" (msg: Message) -> (status, data1, data2: c.int) {
  338. status = c.int(msg & 0xFF)
  339. data1 = c.int((msg >> 8) & 0xFF)
  340. data2 = c.int((msg >> 16) & 0xFF)
  341. return
  342. }
  343. Message :: distinct i32
  344. /**
  345. All midi data comes in the form of Event structures. A sysex
  346. message is encoded as a sequence of Event structures, with each
  347. structure carrying 4 bytes of the message, i.e. only the first
  348. Event carries the status byte.
  349. Note that MIDI allows nested messages: the so-called "real-time" MIDI
  350. messages can be inserted into the MIDI byte stream at any location,
  351. including within a sysex message. MIDI real-time messages are one-byte
  352. messages used mainly for timing (see the MIDI spec). PortMidi retains
  353. the order of non-real-time MIDI messages on both input and output, but
  354. it does not specify exactly how real-time messages are processed. This
  355. is particulary problematic for MIDI input, because the input parser
  356. must either prepare to buffer an unlimited number of sysex message
  357. bytes or to buffer an unlimited number of real-time messages that
  358. arrive embedded in a long sysex message. To simplify things, the input
  359. parser is allowed to pass real-time MIDI messages embedded within a
  360. sysex message, and it is up to the client to detect, process, and
  361. remove these messages as they arrive.
  362. When receiving sysex messages, the sysex message is terminated
  363. by either an EOX status byte (anywhere in the 4 byte messages) or
  364. by a non-real-time status byte in the low order byte of the message.
  365. If you get a non-real-time status byte but there was no EOX byte, it
  366. means the sysex message was somehow truncated. This is not
  367. considered an error; e.g., a missing EOX can result from the user
  368. disconnecting a MIDI cable during sysex transmission.
  369. A real-time message can occur within a sysex message. A real-time
  370. message will always occupy a full Event with the status byte in
  371. the low-order byte of the Event message field. (This implies that
  372. the byte-order of sysex bytes and real-time message bytes may not
  373. be preserved -- for example, if a real-time message arrives after
  374. 3 bytes of a sysex message, the real-time message will be delivered
  375. first. The first word of the sysex message will be delivered only
  376. after the 4th byte arrives, filling the 4-byte Event message field.
  377. The timestamp field is observed when the output port is opened with
  378. a non-zero latency. A timestamp of zero means "use the current time",
  379. which in turn means to deliver the message with a delay of
  380. latency (the latency parameter used when opening the output port.)
  381. Do not expect PortMidi to sort data according to timestamps --
  382. messages should be sent in the correct order, and timestamps MUST
  383. be non-decreasing. See also "Example" for OpenOutput() above.
  384. A sysex message will generally fill many Event structures. On
  385. output to a Stream with non-zero latency, the first timestamp
  386. on sysex message data will determine the time to begin sending the
  387. message. PortMidi implementations may ignore timestamps for the
  388. remainder of the sysex message.
  389. On input, the timestamp ideally denotes the arrival time of the
  390. status byte of the message. The first timestamp on sysex message
  391. data will be valid. Subsequent timestamps may denote
  392. when message bytes were actually received, or they may be simply
  393. copies of the first timestamp.
  394. Timestamps for nested messages: If a real-time message arrives in
  395. the middle of some other message, it is enqueued immediately with
  396. the timestamp corresponding to its arrival time. The interrupted
  397. non-real-time message or 4-byte packet of sysex data will be enqueued
  398. later. The timestamp of interrupted data will be equal to that of
  399. the interrupting real-time message to insure that timestamps are
  400. non-decreasing.
  401. */
  402. Event :: struct {
  403. message: Message,
  404. timestamp: Timestamp,
  405. }
  406. @(default_calling_convention="c", link_prefix="Pm_")
  407. foreign lib {
  408. /**
  409. Read() retrieves midi data into a buffer, and returns the number
  410. of events read. Result is a non-negative number unless an error occurs,
  411. in which case a Error value will be returned.
  412. Buffer Overflow
  413. The problem: if an input overflow occurs, data will be lost, ultimately
  414. because there is no flow control all the way back to the data source.
  415. When data is lost, the receiver should be notified and some sort of
  416. graceful recovery should take place, e.g. you shouldn't resume receiving
  417. in the middle of a long sysex message.
  418. With a lock-free fifo, which is pretty much what we're stuck with to
  419. enable portability to the Mac, it's tricky for the producer and consumer
  420. to synchronously reset the buffer and resume normal operation.
  421. Solution: the buffer managed by PortMidi will be flushed when an overflow
  422. occurs. The consumer (Read()) gets an error message (.BufferOverflow)
  423. and ordinary processing resumes as soon as a new message arrives. The
  424. remainder of a partial sysex message is not considered to be a "new
  425. message" and will be flushed as well.
  426. */
  427. Read :: proc(stream: Stream, buffer: [^]Event, length: i32) -> c.int ---
  428. /**
  429. Poll() tests whether input is available.
  430. */
  431. Poll :: proc(stream: Stream) -> Error ---
  432. /**
  433. Write() writes midi data from a buffer. This may contain:
  434. - short messages
  435. or
  436. - sysex messages that are converted into a sequence of Event
  437. structures, e.g. sending data from a file or forwarding them
  438. from midi input.
  439. Use WriteSysEx() to write a sysex message stored as a contiguous
  440. array of bytes.
  441. Sysex data may contain embedded real-time messages.
  442. */
  443. Write :: proc(stream: Stream, buffer: [^]Event, length: i32) -> Error ---
  444. /**
  445. WriteShort() writes a timestamped non-system-exclusive midi message.
  446. Messages are delivered in order as received, and timestamps must be
  447. non-decreasing. (But timestamps are ignored if the stream was opened
  448. with latency = 0.)
  449. */
  450. WriteShort :: proc(stream: Stream, whence: Timestamp, msg: Message) -> Error ---
  451. /**
  452. WriteSysEx() writes a timestamped system-exclusive midi message.
  453. */
  454. WriteSysEx :: proc(stream: Stream, whence: Timestamp, msg: cstring) -> Error ---
  455. }