# The &kmidi; Handbook

Bernd Johannes
Wuebben

    wuebben@kde.org

Greg
Lee

    lee@hawaii.edu

1999
2000
Greg Lee
2000-12-16
1.03.00

&kmidi; plays midi files using instrument patches. It does in software what a soundcard like the GUS (Gravis UltraSound) or Sound Blaster AWE does in hardware.

KMidi
Midi
Player
Timidity
Midi
to
Wav

## Introduction

&kmidi; plays midi files using instrument patches. It does in software what a soundcard like the GUSgus> (Gravis UltraSound) or Sound Blaster AWE does in hardware. So, the only hardware you need is a simple soundcard or chip. Even if you have a GUS or AWE, you might still like to try &kmidi;, since it sounds pretty good.

And it has the advantage that, if you'd like it to sound better, you can just roll up your sleeves and rewrite it, because of course you get the source code free.

It does, however, need some CPU time. I find that starting up new windows or sometimes just scrolling my screen causes dropouts in the music. Also, you'll want to get yourself some patchsets (see below). They're too bulky (10-12 megs) to include as part of the regular &kde; distribution, so I've include only 5 patches as examples. &kmidi; can handle 257 banks of 128 instruments each.

&kde; is based on Tuukka Toivonen's wonderful program TiMidity, which does most of the work. &kmidi; is a GUI front end for TiMidity, and TiMidity itself, with other alternative user interfaces, is included in the source distribution of &kmidi;. Thanks, Tuukka!

kmidi; supports at the moment (Version 1.3) the following platforms:

- &Linux;

- FreeBSD

- DEC OSF/1

- &HP-UX;

- SunOS

- Sun &Solaris;

Ports to other platforms should be easy. Please contact me if you ported &kmidi; to another platform.

For details about usage that may not be covered in this manual, see the `timidity` man page.

Remember midi files are typically around 50k or less and are therefore so easily downloaded that you will never run out of great midi's to play.

Have fun with &kmidi;!

Bernd Johannes Wuebben wuebben@kde.org

## Usage

### Getting Started

If you haven't used &kmidi; before, you'll see the name of one of the example midi files I included in the black window. Click the play button to play it. Move the mouse pointer around from button to button to get a brief tooltip description of what each button does when clicked on.

Click on the KMidi logo at the upper left to make the bottom panel visible. There you'll see a black window, the channel meter, which shows a bar graph of notes being played on the 16 midi channels. To its left is a patchset selector and a song selector. Click on the song selector to see a list of the other example midi files I included with the &kmidi; distribution. Click on another, if you like, to play it.

Click on the Info button to see information about the midi file you're playing and Karaoke lyrics (if the midi file has any).

Click the playlist button to look around your filesystem for midi files and compose your own list of files to play. Unless you click off the filter button, only midi files will be shown (regardless of whether they have a `.mid` or `.kar` suffix). Double click a filename on the left part of the screen to add the file to your playlist (shown on the right).

Don't be surprised or chagrined if some midi files produce little or no sound. &kmidi; as distributed has a pitifully small number of instrument patches. Sorry about that. Please see the section of this document on how to obtain patchsets on the net.

### Playlists

Click on the eject button to open the playlist manager. At the left you'll see the content of the directory you were in the last time you edited your playlist. At the right you see your current playlist. Select a midi file on the left to append to the playlist by double clicking on it. Or single click, then click on Add.

The only files shown on the left are midi files. Compressed midi files will not be recognized, unfortunately, so if you've used, say, `gzip` to compress the files, you'll want to click off the Filter button at the bottom. Then all files become visible. &kmidi; does not decide whether a file is a midi file or not by looking at the name; instead, it reads a bit of the file to see whether it appears to be a midi file. So there's no need to name your midi files with a `.mid` suffix.

Toward the bottom of the screen are your current playlists. When you first start, there will be only one, called default with the sample midis from the &kmidi; distribution. You change the contents of this by clicking once on the name default (if it is not already selected) then clicking File Save to replace the contents of the playlist file with your current playlist. Or click File Append to concatenate your current playlist onto the end of a playlist file. To create a new playlist, click File Save as ... instead and fill in the new name you've chosen into the little box that appears. Double click on the name of a playlist to replace your current playlist with the contents of the one you've saved. This can also be done from the front panel by single clicking on the name of a playlist in the Select Playlist box.

Remove a playlist by clicking on its name, then clicking File Remove .

The vertical bar separating the directory list from the playlist can be dragged from left to right with the mouse. The horizontal bar separating these from the playlist names can be dragged up and down.

### Midi file names

The names of midi files you see on the front panel may differ slightly from the actual file names. For readability, &kmidi; replaces any _ in the midi file name by spaces and chops off the `.mid`/ `.MID` ending if present.

### Configuring

Clicking the configure button on the panel takes you to a configure screen where you can choose the background color of the panel's two windows and the led color. At the moment, the color used for percussion in the channel meter is not configurable - it's always yellow.

### Patchsets

On the bottom panel at the top left you'll find the patchset selector. For &kmidi; as distributed, you'll see three patchset options: piano + guitar, piano, and guitar. There isn't any real point to selecting the piano or guitar patchsets; the choices are there merely as an illustration. When you acquire a bunch of patchsets, you can set things up so as to switch between them from the panel. Here is how to do that:

For each patchset, create a `cfg` file describing the patches and their banks and instrument (midi program) numbers. Then in the file `timidity.cfg`, enter a line `source filename` and a preceding line if n, where filename is the name you gave to the file describing the patches, and n is the line where filename will appear in &kmidi;'s panel in the select patchset box. Clicking on this name will select the patchset. The numbering of the patchsets starts with number 0.

In `cfg` files, the banks/drumsets and names of patches must be given, since those that are not declared will not be loaded from files (GUS patch files or sound fonts) even though the patches are available. This way it's easy to exclude certain patches from a sound font so as to load better ones from a subseqently loaded font. Just don't declare them before you've asked to load the font.

When the same patch of the same bank or drumset is declared more than once, only the first declaration counts. So put your best fonts first.

There is a utility `sf2cfg` to construct a `cfg` file for a `sbk`/`sf2` sound font, which spits out all the patches that are present in the font. Also, I've included sample `cfg` files for `chaos8m.sf2` and `chaos12m.sf2`.

### Polyphony

Do you hear dropouts in the music? It's possible for &kmidi; to get behind in doing the many calculations required to adjust the pitch of instrument patches, filter the signal, combine notes, and so on. If this happens, you may be able to improve the situation by using the spinbox on the lower panel to the right. This adjusts the maximum number of polyphonic voices used at the same time. When you lower the maximum polyphony, you lighten &kmidi;'s burden at the cost of some chorus or reverb effect being lost, or some notes being cut short or actually being omitted altogether. (In some circumstances, &kmidi; generates extra notes to approximate the effect of midi chorus and reverberation.)

### Effects

Effects modify the sound in various ways, some of which I'm not too clear about. There are four ways effects may be requested and two ways you can control them.

A midi song may specify an effect for all the instruments playing on any particular one of the 16 midi channels. Or, it may specify several effects for several channels. When you click down the panel's eff button, the signal is filtered to approximate the midi effects: chorus, reverberation, celeste, and phaser. But there won't be any effects unless the song in the midi file asks for them. Two of the standard midi effects, harmonics and brightness, are not yet implemented by filters. (The filters were coded by Nicolas Witczak.)

When you don't click down the eff button, you still get some chorus and reverberation on channels where it's requested, but it's done in a different way. Now, instead of using filters, extra notes are generated. They are detuned slightly for chorus effect and delayed slightly for reverberation. There are also some adjustments made to note envelopes and vibrato. With eff turned off, you get no channel celeste or phaser effects.

A second way effects may be requested is by a patch. That is, an instrument patch may contain a suggested chorus and/or reverb level. AWE patches generally do specify effects, but Gravis-Forte patches don't. (That's why AWE patchsets tend to sound a bit fruity.) Effects requested this way are done by the ghost note method, and are unaffected by the eff button.

Thirdly, you may request effects. Notice the four checkboxes at the right of the panel. Each has three states: normal (the default), extra, and off. The middle two checkboxes control chorus and reverb. If they are set to normal, effects are treated as described above. Set to extra, extra notes are generated for chorus or reverb for all instruments and all channels, and this is in addition to the effects filters if they are requested by clicking eff. When they are set to off, no extra chorus or reverb notes are generated.

Finally, effects may be requested by midi system exclusive message in a midi file -- sysexes. These are intended to control the hardware of specific synthesizers. &kmidi; does a certain amount of decoding of sysexes for Roland GS synths and Yamaha XG synths and does its best to modify the sound accordingly. Chorus, reverb, and variations on these are done by the ghost note method and can be switched off with the checkboxes just mentioned. However, when the celeste variation of chorusing is requested in an XG sysex, this invokes Witczak's celeste filter, provided the eff button is clicked on.

### Command Line Options

Except for giving the names of one or more midi files on the command line, the material in this section is probably not very useful to know about. If you have a need for these options, you'd probably prefer to use the command line version of this program: timidity.

    kmidi
    options filename

Use "-" as filename to read a MIDI file from `stdin`

#### Options:

`-o` `filename`

  Place output on filename, which may be a file, device, or HP-UX audio server, depending on the output mode selected with the `-O` option. The special filename ``-'' causes output to be placed on `stdout`.

`-O` `mode`

  Selects the output mode from the compiled-in alternatives. mode must begin with one of the supported output mode identifiers. Run TiMidity with the `-h` option to see a list.

`-s` `freq`

  Set sampling frequency to `freq` (Hz or kHz) Not all sound devices are capable of all frequencies -- an approximate frequency may be selected, depending on the implementation.

`-a`

  Enable the antialiasing filter. Samples are run through a lowpass filter before playing, which reduces aliasing noise at low resampling frequencies.

`-f`

  Enable fast decay mode. Toggles fast envelopes. Some MIDI files sound better when notes decay slower -- it gives the impression of reverb.

`-p` `n`

  Sets polyphony (maximum number of simultaneous voices).

`-A` `n`

  Amplify volume by `n` percent (may cause clipping)

`-C` `n`

  Sets the ratio of sampling and control frequencies. This determines how often envelopes are recalculated -- small ratios yield better quality but use more CPU time.

`-E`

  Turns on Witczak's effect filters for chorus, reverb, phaser, and celeste.

`-&num;` `n`

  Select patch set

`-L` `dir`

  Append dir to search path

`-c` `file`

  Read extra configuration file

`-I` `n`

  Use program `n` as the default

`-P` `file`

  Use patch `file` for all programs

`-D` `n`

  Play drums on channel `n`

`-Q` `n`

  Ignore channel `n`

`-F`

  Enable fast panning

`-U`

  Unload instruments from memory between MIDI files

`-i` `mode`

  Select user interface (see below for list)

`-B` `n`

  Set number of buffer fragments

`-h`

  Display the help message

#### Available output modes (`-0`)

`-O` `d`

  &Linux; `dsp` device

`-O` `w`

  RIFF WAVE file

`-O` `r`

  raw waveform data

#### Output format options (append to `-O`)

``8'`

  8-bit sample width

``1'`

  16-bit sample width

``U'`

  uLaw encoding

``l'`

  linear encoding

``M'`

  monophonic

``S'`

  stereo

``s'`

  signed output

``u'`

  unsigned output

``x'`

  byte-swapped output

#### Available interfaces (append to `-i`)

`q`

  &kmidi; &Qt; interface

`d`

  dumb interface

#### Interface options (append to `-i``?` option)

``v'`

  more verbose (cumulative)

``q'`

  quieter (cumulative)

``t'`

  trace playing

`-i`

  mode Select user interface (see below for list)

## Questions and Answers

Where do I get a full patch set?

Please refer to the corresponding section in the &kmidi; installation chapter.

## Design

### Processes

&kmidi; is the user front end which handles the screen display and button presses, etc. It executes as a separate process from &timidity;, which reads midi files and plays them.

### Synthesis Model

&timidity; has a tone generator, two envelope generators, three low frequency sine-wave oscillators, a low pass filter, and an effects unit. (The low pass filter is used only when &kmidi;'s fourth interpolation option is chosen and the on filt button is depressed -- at present it doesn't work well.)

The tone generator resamples instrument patches at the basic frequencies appropriate for specific notes being played. (The interpolation algorithm used is selectable using the four checkboxes on the upper panel.)

The envelope generators modulate each note with successively: an attack phase, a hold phase, a decay, and a release. One of the generators affects amplitude, and the other affects pitch and/or the cutoff frequency of the low pass filter.

The low frequency oscillators modulate amplitude (for tremolo), frequency (for vibrato), and the low pass filter cutoff frequency (XG rezo sweep).

The effects unit supplies echo, detuning, reverberation, chorusing, celeste, and phaser effects. Echo (done by generating extra echo notes) and reverberation (done with a filter) implement midi reverberation. Detuning (done by generating extra pitch bent notes) and chorusing (done with a filter) implement midi chorusing. (The effects filters are active only when &kmidi;'s eff button is pressed on. Echo and detuning can be controlled with the middle two checkboxes on the right of the lower panel and from the Chorus and Reverb menus.)

Instruments may have either one or two tone elements, and for each of these, a patch set may provide separate patches for different note-velocity ranges (commonly for pianos) and for different note-pitch ranges. GUS patch sets, however, provide only one tone element and one velocity range per instrument. (If you click the rightmost checkbox at the right of the lower panel, &kmidi; will display in its info window the names of patches as it loads them, a `(2)` if they have two tone elements, and the velocity range.)

### Midi Implementation

Almost all midi messages and controllers that I'm aware of are implemented somehow (meaning that they cause something to happen, if not necessarily the right thing). NRPN controllers for setting attack and decay time are not implemented, because I haven't found any midi files that use them. The flanging controller is not implemented (though flanging requested in an XG sysex dump is implemented). Only a few of the hardware oriented controls in Roland and Yamaha system exclusive dumps are implemented.

&timidity; can handle midi files meant to play on up to four synthesizers, keeping separate the four sets of 16 channels for each synth. However, in the midi file, the synths have to be selected using port commands (in either Roland-GS or Yamaha-XG sysex dumps). Some midi files intended for multiple synths don't have port commands. (The info window shows port commands when present.)

The &kmidi; vertical-bar display of channel activity is limited to two sets of 16 channels. The channel chart of patches with horizontal bars for controller values is limited to just one set of 16 channels.

### Volume

I've reduced the volumes levels &timidity; generates quite a lot, as compared with the original implementation. This minimizes clipping and gives an increased dynamic range. (There may be some artifacts now at low volumes, unfortunately.) If you need more volume, I suggest you turn up the volume somewhere else, either use &kmix; to turn up the line volume, the mixer volume for `/dev/dsp`, or turn up earphones, amplified speakers, or whatever.

### Computation Issues

&timidity; can fall behind in computing data to send out to the sound driver, and then there are dropouts in the music. &timidity; tries to anticipate the possibility of a dropout by monitoring the state of its output buffer and those of the sound driver, and when there is not much in the buffers, it tries to catch up by minimising the calculations it has to do: it uses a cruder interpolation routine in resampling, stops doing extra echo and detuned notes for reverb and chorus effects, and starts terminating notes early, or even skipping notes altogether. So, depending on midi song, patchset, how fast your system is, even if you don't hear dropouts, you will notice a loss in quality as &timidity; gets busier. &kmidi;'s front panel lights give some picture of how desperate &timidity; is becoming in its effort to keep the music playing. (Signs of desperation: the buffer led goes from healthy greenish to busy orangeish, the interpolation led turns off (meaning linear interpolation is being used for resampling), the echo led goes off, or the detuning led goes off (meaning no extra echo or detuned notes are being played).

Monitoring the output buffer involves calling the sound driver to find out how much data it has buffered up. I know how to do this for Hannu Savolainen's OSS driver (&Linux; and some other systems), perhaps for older Suns (it used to work), but not for other drivers.

You can lighten &timidity;'s computational burden by various maneuvers:

1. Reduce the permitted polyphony (spin box on the lower panel).

2. Turn off the eff button.

3. Choose cheaper resampling interpolation (one of the check boxes on the upper panel, furthest to the left.)

4. Turn off echo, detuning, or stereo, using the left three checkboxes on the lower panel.

5. Choose the Dry setting on the Reverb menu.

Of course, there is generally some attendant loss in quality. Having the filt button on doesn't cost anything unless you've also chosen the cspline + filter interpolation option.

### Memory Issues

It's possible for &timidity; to use an excessive amount of memory for patches. Symptoms are your window system becoming very sluggish, or crashing. This is probably only a problem when using big sf2 soundfonts of 30+ megabytes. For instance, the piano patches in Personal Choice's PC400 soundfont can occupy 25 megs each. After playing a list of midi files which use three of these pianos, well, that's 75 megs of ram right there. In its configuration dialog, &kmidi; lets you set a maximum number of megs to be used to keep patches used in playing previous midi files; when this maximum is exceeded, &timidity; will unload least recently used patches, returning ram to the system. The default maximum is 60 megs, which works ok on my system (I have 48 megs ram and 196 megs cache). Setting this to a lower value means that more patches have to be reloaded from patch files as you play through a list of midi songs, which slows things up. If you're ram rich, you can set it to no limit.

If you allowed enough room, entire soundfont files are read at once, instead of patch by patch. Setting the maximum too low can be counterproductive, because soundfont files occupy much less memory in toto when the entire file is read than when the patches are read individually (I don't know why).

For little-endian systems like x86, rather than being read in, sf2 soundfonts are mmapped. This is much faster on startup. I haven't figured out a way to do this for big-endian systems.

After playing each midi file, &kmidi; will report in the info window on how much memory is currently occupied by patches.

If you don't have much ram or cache memory, setting a low maximum for patch memory might not prevent &kmidi; from crashing your system. So be careful using big soundfonts.

## Licenses and Credits

&kmidi; uses Tuukka Toivonen's &timidity; 0.2i engine Copyright (C) 1995 Tuukka Toivonen toivonen@clinet.fi. In fact, an enhanced version of Tuukka's original program with five other alternative user interfaces is included with the &kmidi; distribution. (See below for information on compiling &timidity;.)

&kmidi; and &timidity; use AWE SoundFont extensions done by Takashi Iwai iwai@dragon.mm.t.u-tokyo.ac.jp and AMD InterWave extensions done by Greg Lee lee@hawaii.edu which enable you to use SoundFonts (`.sbk`/`.sf2` files) and IW patchsets (`.fff`/`.dat` files) in addition to Gravis/Forte `.pat` files.

## Copyright

&kmidi; Copyright 1997 Bernd Johannes Wuebben wuebben@kde.org

&kmidi; uses Tuukka Toivonen's &timidity; 0.2i engine, Copyright © 1995 Tukka Toivonen toivonen@clinet.fi.

&underFDL; &underGPL;

## Installation

### How to obtain &kmidi;

&kmidi; is part of the &kde; project http://www.kde.org. &kmidi; can be found on ftp://ftp.kde.org/pub/kde/, the main &FTP; site of the &kde; project.

### Requirements

In order to successfully compile &kmidi;, you need appropriate versions of the program libraries in `kdelibs`. All required libraries as well as &kmidi; itself can be found on ftp://ftp.kde.org/pub/kde.

To compile the dumb commandline interface of &timidity;, any standard &UNIX; type system should do. The other interfaces have special requirements (see the various `README` files in the distribution). The &Motif; interface works reasonably well with Lesstif, but better with &Motif;.

### Compilation and installation

If you previously installed &kmidi;, it would be wise to move your configuration directory (probably `&dollar;`KDEDIR`/share/apps/kmidi/config/`) before installing this version, since the files that go here have changed, and you'll want to use or at least look at the new versions. Similarly, before installing the non-&kde; version of &timidity;, back up `/usr/local/lib/timidity/`. On the other hand, for a completely fresh install you should remove any files in these two directories, since the old files might not be replaced by new versions.

If you have the entire kdemultimedia distribution, cd to the kdemultimedia directory and

    &percnt;./configure

Alternatively, to include all of the other user interfaces:

    &percnt;./configure
    --enable-interface=ncurses,xaw,gtk,tcltk,slang,motif

Then to make all the multimedia programs, stay in that directory, or to make just &kmidi;, `cd` to the `kmidi` directory, and

    &percnt; make
    &percnt; make install

The non &kde; version of &timidity;, `timidity`, is compiled and installed at the same time as &kmidi;. The `man` page `timidity.1` is not, however, automatically installed in `/usr/man/man1/`.

### Where to get a full set of patches?

There are two sorts of patches that &kmidi;/&timidity; can use: GUS patches and AWE32 SoundFonts (`sf2` files). A set of samples and parameters for a single instrument, a patch, is in a separate file for GUS patches, but AWE SoundFonts put everything in a single `.sf2` file (or `.sbk`).

I recommend `.sf2` SoundFonts, and of those, the Chaos fonts mentioned below, in preference.

Open up &kmidi;'s configuration window for pointers to some web pages with patch sets. Here are some other places to get patches:

Dan Hollis goemon@anime.net has put together a patch set. Please visit his page at http://www.anime.net/~goemon/timidity and help him make this the best set available.

New: I have uploaded the above patchset to ftp.kde.org. It is currently in ftp://fiwi02.wiwi.uni-tuebingen.de/pub/kde/stable/Beta2/apps/multimedia/sound/, but I expect we will move it around a bit until we found a good location for it. So just poke around a bit on ftp.kde.org, if the set can no longer be found at the above mentioned location by the time you read this.

Patches can also be found packaged as dep or rpm modules on the Sunsite archive:

- Debian: timidity-patches_0.1.tar.gz

- RPM: timidity-patches-1-1.i386.rpm

- RPM: timidity-patches-1-1.src.rpm-try2

I have not tried the above (yet), and personally use the Midia patch set together with a few additional patches and a couple of additional drum sets. The Midia patch set can be found at: ftp://archive.cs.umbc.edu/pub/midia/.

For additional patches and drum sets: (get the gsdrum and wow patches) ftp://ftp/cdrom.com/pub/gus/sound/patches/files/.

Vincent Pagel has put together a collection of patches. This link can only be reached during night hours (Paris). ftp://sig.enst.fr/pub/midi/instruments/. The config file that goes with his patch set can be found here.

Also check the Timdity Page

and Takashi's page. Takashi's page recommends the 8 meg AWE32 SoundFont `chaos8m.sf2` and the 12 meg AWE32 SoundFont `chaos12m.sf2` available at , which are very nice. (They are packaged as self-decompressing `.exe` files.)

#### Patch set installation

Some of the above patch sets come with a `.cfg` configuration file similar to the .cfg files which come with KMidi and reside in `KDEDIR/share/apps/kmidi/config`. &kmidi; has configuration files ready made for you for a number of common patch sets, such as the media patch set. For `.sf2` SoundFonts, a utility program is supplied, `sf2cfg`, which constructs a `.cfg` file from a `.sf2` font. This is compiled along with &timidity;.

It is not necessary to give `.cfg` files names with a `.cfg` extension. They are ordinary text files whose structure is described in another section of this manual.

In order to complete the installation of a complete patchset edit the file `timidity.cfg` and source the appropriate config files for the patch set/sets you downloaded. Look at `timidity.cfg` for an example. That's it. Now you can go ahead and play the other midis that are in the &kmidi; distribution ( and any others of course).

#### Miscellaneous

Occasionally you will see that &kmidi; can't find a patch for a particular instrument. ( Open the Info Window in order to see this information ) In that case, all you have to do is go out and get yourself the missing patch and install it by moving the patch into the patch/ directory and editing your patch set `.cfg` file to tell &kmidi; that the new patch is available now.

Sometimes a particular instrument doesn't sound all that well. In that case, simply go out and get yourself a different patch from any of the Ultrasound archives and replace the not so optimal patch by a better one. As you can see, it is totally up to you how good every instrument will sound. You can even make your own patches with the `pat2wav` utility which is included in the &kmidi; distribution.