xref: /haiku/docs/user/midi2/midi2intro.dox (revision ed24eb5ff12640d052171c6a7feba37fab8a75d1)
1/*!
2\page midi2_intro Introduction to the MIDI2 Kit
3
4The Midi Kit is the API that implements support for generating, processing, and
5playing music in MIDI format. <A HREF="http://www.midi.org/">MIDI</A>, which
6stands for 'Musical Instrument Digital Interface', is a well-established
7standard for representing and communicating musical data. This document serves
8as an overview. If you would like to see all the components, please look at
9\link midi2 the list with classes \endlink .
10
11\section midi2twokits The two kits
12
13The BeOS comes with two different, but compatible Midi Kits. This documentation
14focuses on the "new" Midi Kit, or midi2 as we like to call it, that was
15introduced with BeOS R5. The old kit, which we'll refer to as midi1, is more
16complete than the new kit, but less powerful.
17
18Both kits let you create so-called MIDI endpoints, but the endpoints from midi1
19cannot be shared between different applications. The midi2 kit solves that
20problem, but unlike midi1 it does not include a General MIDI softsynth, nor
21does it have a facility for reading and playing Standard MIDI Files. Don't
22worry: both kits are compatible and you can mix-and-match them in your
23applications.
24
25The main differences between the two kits:
26
27- Instead of one BMidi object that both produces and consumes events, we have
28BMidiProducer and BMidiConsumer.
29- Applications are capable of sharing MIDI producers and consumers with other
30applications via the centralized Midi Roster.
31- Physical MIDI ports are now sharable without apps "stealing" events from each
32other.
33- Applications can now send/receive raw MIDI byte streams (useful if an
34application has its own MIDI parser/engine).
35- Channels are numbered 0..15, not 1..16
36- Timing is now specified in microseconds instead of milliseconds.
37
38\section midi2concepts Midi Kit concepts
39
40A brief overview of the elements that comprise the Midi Kit:
41
42- \b Endpoints. This is what the Midi Kit is all about: sending MIDI messages
43between endpoints. An endpoint is like a MIDI In or MIDI Out socket on your
44equipment; it either receives information or it sends information. Endpoints
45that send MIDI events are called \b producers; the endpoints that receive those
46events are called \b consumers. An endpoint that is created by your own
47application is called \b local; endpoints from other applications are \b
48remote. You can access remote endpoints using \b proxies.
49
50- \b Filters. A filter is an object that has a consumer and a producer
51endpoint. It reads incoming events from its consumer, performs some operation,
52and tells its producer to send out the results. In its current form, the Midi
53Kit doesn't provide any special facilities for writing filters.
54
55- \b Midi \b Roster. The roster is the list of all published producers and
56consumers. By publishing an endpoint, you allow other applications to talk to
57it. You are not required to publish your endpoints, in which case only your own
58application can use them.
59
60- \b Midi \b Server. The Midi Server does the behind-the-scenes work. It
61manages the roster, it connects endpoints, it makes sure that endpoints can
62communicate, and so on. The Midi Server is started automatically when BeOS
63boots, and you never have to deal with it directly. Just remember that it runs
64the show.
65
66- \b libmidi. The BMidi* classes live inside two shared libraries: libmidi.so
67and libmidi2.so. If you write an application that uses old Midi Kit, you must
68link it to libmidi.so. Applications that use the new Midi Kit must link to
69libmidi2.so. If you want to mix-and-match both kits, you should also link to
70both libraries.
71
72Here is a pretty picture:
73
74\image html midi2concepts.png
75
76\section midi2mediakit Midi Kit != Media Kit
77
78Be chose not to integrate the Midi Kit into the Media Kit as another media
79type, mainly because MIDI doesn't require any of the format negotiation that
80other media types need. Although the two kits look similar -- both have a
81"roster" for finding or registering "consumers" and "producers" -- there are
82some very important differences.
83
84The first and most important point to note is that BMidiConsumer and
85BMidiProducer in the Midi Kit are NOT directly analogous to BBufferConsumer and
86BBufferProducer in the Media Kit! In the Media Kit, consumers and producers are
87the data consuming and producing properties of a media node. A filter in the
88Media Kit, therefore, inherits from both BBufferConsumer and BBufferProducer,
89and implements their virtual member functions to do its work.
90
91In the Midi Kit, consumers and producers act as endpoints of MIDI data
92connections, much as media_source and media_destination do in the Media Kit.
93Thus, a MIDI filter does not derive from BMidiConsumer and BMidiProducer;
94instead, it contains BMidiConsumer and BMidiProducer objects for each of its
95distinct endpoints that connect to other MIDI objects. The Midi Kit does not
96allow the use of multiple virtual inheritance, so you can't create an object
97that's both a BMidiConsumer and a BMidiProducer.
98
99This also contrasts with the old Midi Kit's conception of a BMidi object, which
100stood for an object that both received and sent MIDI data. In the new Midi Kit,
101the endpoints of MIDI connections are all that matters. What lies between the
102endpoints, i.e., how a MIDI filter is actually structured, is entirely at your
103discretion.
104
105Also, rather than use token structs like media_node to make connections via the
106MediaRoster, the new kit makes the connections directly via the BMidiProducer
107object.
108
109\section midi2remotelocal Remote and local objects
110
111The Midi Kit makes a distinction between remote and local MIDI objects. You can
112only create local MIDI endpoints, which derive from either BMidiLocalConsumer
113or BMidiLocalProducer. Remote endpoints are endpoints that live in other
114applications, and you access them through BMidiRoster.
115
116BMidiRoster only gives you access to BMidiEndpoints, BMidiConsumers, and
117BMidiProducers. When you want to talk to remote MIDI objects, you do so through
118the proxy objects that BMidiRoster provides. Unlike BMidiLocalConsumer and
119BMidiLocalProducer, these classes do not provide a lot of functions. That is
120intentional. In order to hide the details of communication with MIDI endpoints
121in other applications, the Midi Kit must hide the details of how a particular
122endpoint is implemented.
123
124So, what can you do with remote objects? Only what BMidiConsumer,
125BMidiProducer, and BMidiEndpoint will let you do. You can connect objects, get
126the properties of these objects -- and that's about it.
127
128\section midi2lifespan Creating and destroying objects
129
130The constructors and destructors of most midi2 classes are private, which mean
131you cannot directly create them using the C++ <CODE>new</CODE> operator, on the
132stack, or as globals. Nor can you <CODE>delete</CODE> them. Instead, these
133objects are obtained through BMidiRoster. The only two exceptions to this rule
134are BMidiLocalConsumer and BMidiLocalProducer. These two objects may be
135directly created and subclassed by developers.
136
137\section midi2refcount Reference counting
138
139Each MIDI endpoint has a reference count associated with it, so that the Midi
140Roster can do proper bookkeeping. When you construct a BMidiLocalProducer or
141BMidiLocalConsumer endpoint, it starts with a reference count of 1. In
142addition, BMidiRoster increments the reference count of any object it hands to
143you as a result of \link BMidiRoster::NextEndpoint() NextEndpoint() \endlink or
144\link BMidiRoster::FindEndpoint() FindEndpoint() \endlink. Once the count hits
1450, the endpoint will be deleted.
146
147This means that, to delete an endpoint, you don't call the <CODE>delete</CODE>
148operator directly; instead, you call \link BMidiEndpoint::Release() Release()
149\endlink. To balance this call, there's also an \link BMidiEndpoint::Acquire()
150Acquire() \endlink, in case you have two disparate parts of your application
151working with the endpoint, and you don't want to have to keep track of who
152needs to Release() the endpoint.
153
154When you're done with any endpoint object, you must Release() it. This is true
155for both local and remote objects. Repeat after me: Release() when you're done.
156
157\section midi2events MIDI events
158
159To make some actual music, you need to \link BMidiProducer::Connect() Connect()
160\endlink your consumers to your producers. Then you tell the producer to
161"spray" MIDI events to all the connected consumers. The consumers are notified
162of these incoming events through a set of hook functions.
163
164The Midi Kit already provides a set of commonly used spray functions, such as
165\link BMidiLocalProducer::SprayNoteOn() SprayNoteOn() \endlink, \link
166BMidiLocalProducer::SprayControlChange() SprayControlChange() \endlink, and so
167on. These correspond one-to-one with the message types from the MIDI spec. You
168don't need to be a MIDI expert to use the kit, but of course some knowledge of
169the protocol helps. If you are really hardcore, you can also use the \link
170BMidiLocalProducer::SprayData() SprayData() \endlink to send raw MIDI events to
171the consumers.
172
173At the consumer side, a dedicated thread invokes a hook function for every
174incoming MIDI event. For every spray function, there is a corresponding hook
175function, e.g. \link BMidiLocalConsumer::NoteOn() NoteOn() \endlink and \link
176BMidiLocalConsumer::ControlChange() ControlChange() \endlink. The hardcore MIDI
177fanatics among you will be pleased to know that you can also tap into the \link
178BMidiLocalConsumer::Data() Data() \endlink hook and get your hands dirty with
179the raw MIDI data.
180
181\section midi2time Time
182
183The spray and hook functions accept a bigtime_t parameter named "time". This
184indicates when the MIDI event should be performed. The time is given in
185microseconds since the computer booted. To get the current tick measurement,
186you call the system_time() function from the Kernel Kit.
187
188If you override a hook function in one of your consumer objects, it should look
189at the time argument, wait until the designated time, and then perform its
190action. The preferred method is to use the Kernel Kit's
191<CODE>snooze_until()</CODE> function, which sends the consumer thread to sleep
192until the requested time has come. (Or, if the time has already passed, returns
193immediately.)
194
195Like this:
196
197\code
198void MyConsumer::NoteOn(
199    uchar channel, uchar note, uchar velocity, bigtime_t time)
200{
201    snooze_until(time, B_SYSTEM_TIMEBASE);
202    ...do your thing...
203}
204\endcode
205
206If you want your producers to run in real time, i.e. they produce MIDI data
207that needs to be performed immediately, you should pass time 0 to the spray
208functions (which also happens to be the default value). Since time 0 has
209already passed, <CODE>snooze_until()</CODE> returns immediately, and the
210consumer will process the events as soon as they are received.
211
212To schedule MIDI events for a performance time that lies somewhere in the
213future, the producer must take into account the consumer's latency. Producers
214should attempt to get notes to the consumer by or before
215<I>(scheduled_performance_time - latency)</I>. The time argument is still the
216scheduled performance time, so if your consumer has latency, it should snooze
217like this before it starts to perform the events:
218
219\code
220snooze_until(time - Latency(), B_SYSTEM_TIMEBASE);
221\endcode
222
223Note that a typical producer sends out its events as soon as it can; unlike a
224consumer, it does not have to snooze.
225
226\section midi2ports Other timing issues
227
228Each consumer object uses a Kernel Kit port to receive MIDI events from
229connected producers. The queue for this port is only 1 message deep. This means
230that if the consumer thread is asleep in a <CODE>snooze_until()</CODE>, it will
231not read its port. Consequently, any producer that tries to write a new event
232to this port will block until the consumer thread is ready to receive a new
233message. This is intentional, because it prevents producers from generating and
234queueing up thousands of events.
235
236This mechanism, while simple, puts on the producer the responsibility for
237sorting the events in time. Suppose your producer sends three Note On events,
238the first on t + 0, the second on t + 4, and the third on t + 2. This last
239event won't be received until after t + 4, so it will be two ticks too late. If
240this sort of thing can happen with your producer, you should somehow sort the
241events before you spray them. Of course, if you have two or more producers
242connected to the same consumer, it is nearly impossible to sort this all out
243(pardon the pun). So it is not wise to send the same kinds of events from more
244than one producer to one consumer at the same time.
245
246The article Introduction to MIDI, Part 2 in <A
247HREF="http://open-beos.sourceforge.net/nsl.php?mode=display&id=36">OpenBeOS
248Newsletter 36</A> describes this problem in more detail, and provides a
249solution. Go read it now!
250
251\section midi2filters Writing a filter
252
253A typical filter contains a consumer and a producer endpoint. It receives
254events from the consumer, processes them, and sends them out again using the
255producer. The consumer endpoint is a subclass of BMidiLocalConsumer, whereas
256the producer is simply a BMidiLocalProducer, not a subclass. This is a common
257configuration, because consumers work by overriding the event hooks to do work
258when MIDI data arrives. Producers work by sending an event when you call their
259member functions. You should hardly ever need to derive from BMidiLocalProducer
260(unless you need to know when the producer gets connected or disconnected,
261perhaps), but you'll always have to override one or more of
262BMidiLocalConsumer's member functions to do something useful with incoming
263data.
264
265Filters should ignore the time argument from the spray and hook functions, and
266simply pass it on unchanged. Objects that only filter data should process the
267event as quickly as possible and be done with it. Do not
268<CODE>snooze_until()</CODE> in the consumer endpoint of a filter!
269
270\section midi2apidiffs API differences
271
272As far as the end user is concerned, the Haiku Midi Kit is mostly the same
273as the BeOS R5 kits, although there are a few small differences in the API
274(mostly bug fixes):
275
276- BMidiEndpoint::IsPersistent() always returns false.
277- The B_MIDI_CHANGE_LATENCY notification is now properly sent. The Be kit
278  incorrectly set be:op to B_MIDI_CHANGED_NAME, even though the rest of the
279  message was properly structured.
280- If creating a local endpoint fails, you can still Release() the object
281  without crashing into the debugger.
282
283\section midi2seealso See also
284
285More about the Midi Kit:
286
287- \ref Midi2Defs.h
288- Be Newsletter Volume 3, Issue 47 - Motor Mix sample code
289- Be Newsletter Volume 4, Issue 3 - Overview of the new kit
290- <A HREF="http://haiku-os.org/documents/dev/introduction_to_midi_part_1">Newsletter
291  33</A>, Introduction to MIDI, Part 1
292- <A HREF="http://haiku-os.org/documents/dev/introduction_to_midi_part_2">Newsletter
293  36</A>, Introduction to MIDI, Part 2
294- Sample code and other goodies at the
295  <A HREF="http://haiku-os.org/about/teams/midi_kit">Haiku Midi Kit team page</A>
296
297Information about MIDI in general:
298
299- <A HREF="http://www.midi.org">MIDI Manufacturers Association</A>
300- <A HREF="http://www.borg.com/~jglatt/tutr/miditutr.htm">MIDI Tutorials</A>
301- <A HREF="http://www.borg.com/~jglatt/tech/midispec.htm">MIDI Specification</A>
302- <A HREF="http://www.borg.com/~jglatt/tech/midifile.htm">Standard MIDI File Format</A>
303- <A HREF="http://www.io.com/~jimm/midi_ref.html">Jim Menard's MIDI Reference</A>
304
305*/
306
307/*!
308\addtogroup midi2
309
310Please have a look at the \link midi2_intro introduction \endlink for a more
311comprehensive overview on how everything ties together.
312*/
313