# AWEDRV PROGRAMMING NOTES

ver.1.07

Takashi Iwai ( iwai@dragon.mm.t.u-tokyo.ac.jp)

Original version: http://bahamut.mm.t.u-tokyo.ac.jp/~iwai/awedrv/awedrv-prog.html

# 0. Preface

This document describes the basic methods to access and control the AWE32 sound driver (ver.0.4.1) by Takashi Iwai. The AWE32 sound driver provides full capability of Emu8000 chip in the AWE32/SB32 sound card. Please refer to AWE32 Developer's Information Package (ADIP) distributed by CreativeLabs for details about AWE32.

# 1. Preparation of a message buffer

Most of macros employ a certain write buffer to access to the sound driver. At beginning, this buffer must be defined. The method to define, or declare this buffer is prepared in `soundcard.h`.

1. Define a buffer for enough sizes (for example 2048 bytes)

       SEQ_DEFINEBUF(2048);

2. Define the file descriptor for `/dev/sequencer`.

       int seqfd;

3. Define `seqbuf_dump` function.

       void seqbuf_dump()
       {
       	if (_seqbufptr)
       		if (write(seqfd, _seqbuf, _seqbufptr) == -1) {
       			perror("write /dev/sequencer");
       			exit(-1);
       		}
       	_seqbufptr = 0;
       }

Most of `SEQ_*` macros write the data packet on this buffer. The buffer is occaionally flushed when it's almost filled. To force to send data to the driver, call `seqbuf_dump` (or identically `SEQ_DUMPBUF`) explicitly.

# 2. Opening a sound device

Then, open the sound driver device `/dev/sequencer`, and find out the AWE32 device number from synthesizer devices in it. Both the file descriptor and the device number must be specified for accessing to AWE32 driver later. Also, you should know other information of AWE32 driver, for example, allowed voices, etc from `synth_info` structure.

    struct synth_info card_info;
    int device;

    void seq_init()
    {
    	int nrsynths;

    	if ((seqfd = open("/dev/sequencer", O_WRONLY, 0)) < 0) {
    		perror("open /dev/sequencer");
    		exit(-1);
    	}

    	if (ioctl(seqfd, SNDCTL_SEQ_NRSYNTHS, &nrsynths) == -1) {
    		perror("there is no soundcard");
    		exit(-1);
    	}
    	device = -1;
    	for (i = 0; i < nrsynths; i++) {
    		card_info.device = i;
    		if (ioctl(seqfd, SNDCTL_SYNTH_INFO, &card_info) == -1) {
    			perror("cannot get info on soundcard");
    			exit(-1);
    		}
    		if (card_info.synth_type == SYNTH_TYPE_SAMPLE
    		    && card_info.synth_subtype == SAMPLE_TYPE_AWE32) {
    			device = i;
    			break;
    		}
    	}

    	if (device < 0) {
    		perror("No AWE synth device is found");
    		exit(-1);
    	}
    }

# 3. Loading a sample

The awedrv has different two ways of sample loading. One uses its own format, and another is the GUS compatible format. In any cases, the patch data is loaded by `SEQ_WRPATCH` macro.

    SEQ_WRPATCH(patch ptr, patchlen);

where `patch` is the pointer to the patch data, and `patchlen` is the total length of the patch data.

## 3.1. AWE32 specific patches

Many of SoundFont files are designed to share the sample data with different envelopes, or other effect parameters. Then, awedrv accepts two separate data: the sample data, and the voice information data. The former contains the sample offsets and sizes, loop position, type of sample data, a check sum value for validating, and the sample data itself. The latter contains the basic information to play a sample, for example, root key note, acceptable MIDI key and velocity ranges, envelopes, LFO's and cutoff parameters, and so on. All the AWE patch structures are defined in `awe_voice.h`.

All the patch data has the same 16 bytes header structure at the first block, defined as `awe_patch_info`:

    typedef struct awe_patch_info {
    	short key;			/* use AWE_PATCH here */
    	short device_no;		/* synthesizer number */
    	unsigned short sf_id;		/* file id */
    	short optarg;			/* optional argument */
    	long len;			/* data length (without this header) */
    	short type;			/* patch operation type */
    	short reserved;			/* word alignment data */
    } awe_patch_info;

where `key` must be `AWE_PATCH` value, and `device_no` is the above device number of AWE driver. `sf_id` is ignored in the current version. `sf_version` is the optional argument and depends on its operation type. `len` has the length of the following data (not including this patch header itself). `type` specifies the operation type of this patch data. The patch data follows after this header depending its operation type.

To load the soundfont data on the driver, the following sequences are applied:

1. Open AWE Patch
2. Load sample data
3. Load voice informations
4. Close AWE Patch

The sections below describe each operation.

### 3.1.1. Open AWE Patch

This operation is necessary before loading any patch data (sample or voice info). If loading operations are called without opening the patch, awedrv creates a patch information automatically as if it was opened via this operation. So, in this meaning, the "open" operation is not necessarilly required, but it's recommended to call this explicitly.

To open a patch, write a patch data including a header with the operation id `AWE_OPEN_PATCH` and `awe_open_parm` structure data following after the header,

    typedef struct _awe_open_parm {
    	unsigned short type;		/* sample type */
    	short reserved;
    	char name[AWE_PATCH_NAME_LEN];
    } awe_open_parm;

where `type` specifies the sample type, and `name` stores its name. The sample type holds an enumurated value from 0 to 6 indicating the type of patch data, and a bit flag 0x100 indicating that the sample is "locked". The locked samples will not be cleared even after AWE_REMOVE_LAST_SAMPLES operation. This means that the locked samples always remain unless all samples are cleared by SEQ_RESET_SAMPLES via ioctl. The sample name is a zero terminated string, and not referred from anywhere so far in the current version.

The data length of `awe_patch_info` is equal to `AWE_OPEN_PARM_SIZE`. Then, write the patch data containing both `awe_patch_info` and `awe_open_parm` as,

    SEQ_WRPATCH(patch, sizeof(*patch) + patch->len);

### 3.1.2. Close AWE Patch

This operation closes the patch currently opened by AWE_OPEN_PATCH operation. This is useful to exchange to another soundfont file for loading at next.

To close the patch, write a patch data containing only the patch header with the operation id `AWE_CLOSE_PATCH`. No optional argument nor the data structure is required. The data length of `awe_patch_info` is then equal to zero.

### 3.1.3. AWE Sample Information

The sample information is a variable length data which consists of a header containing the sample offset informations and sample wave data. The sample header is 32 bytes header which follows after the patch header.

    typedef struct awe_sample_info {
    	unsigned short sf_id;		/* file id */
    	unsigned short sample;		/* sample id */
    	long start, end;		/* start & end offset */
    	long loopstart, loopend;	/* loop start & end offset */
    	long size;			/* size (0 = ROM) */
    	short checksum_flag;		/* ignored */
    	unsigned short mode_flags;	/* mode flags */
    	unsigned long checksum;		/* ignored */
    } awe_sample_info;

where `sf_id` is the file id used internally and normally zero, `sample` is the sample id of this sample which is referred by voice information records. It's usually identical with the sampleId in soundfont files. `start` and `end` denote the sample start and end offset positions, `loopstart` and `loopend` denote the loop start and end positions, and `size` is the data length. The offsets and size are word length if the data is 16bit. Otherwise for 8bit data, they are defined as byte size. The zero `size` parameter means a ROM sample starting from `start` offset. When `size` has larger than zero, the sample is loaded on DRAM, and the offsets will be shifted. `checksum_flag` and `checksum` was obsolete parameters, and no more supported in ver.0.4.1.

`mode_flags` is 16bit flags of the sample data.

    #define AWE_SAMPLE_8BITS	1	/* wave data is 8bits */
    #define AWE_SAMPLE_UNSIGNED	2	/* wave data is unsigned */
    #define AWE_SAMPLE_NO_BLANK	4	/* no blank loop is attached */
    #define AWE_SAMPLE_SINGLESHOT	8	/* single-shot w/o loop */
    #define AWE_SAMPLE_BIDIR_LOOP	16	/* bidirectional looping */
    #define AWE_SAMPLE_STEREO_LEFT	32	/* stereo left sound */
    #define AWE_SAMPLE_STEREO_RIGHT	64	/* stereo right sound */
    #define AWE_SAMPLE_REVERSE_LOOP 128	/* reverse loop */

The 8bit or unsigned data is converted inside the awedrv to 16bit signed data. When `AWE_SAMPLE_NO_BLANK` is on, 48 words of blank loop is appended after the sample automatically. When `AWE_SAMPLE_SINGLESHOT` is on, the loop points are set on this blank loop. `AWE_SAMPLE_BIDIR_LOOP` indicates that the loop is bidirectional (pingpong), and the samples in this loop is extended as mirror image inside. `AWE_SAMPLE_REVERSE_LOOP` means the reverse loop. The loop sample is duplicated on mirror image inside the driver. Other `STEREO` flags show that the voice is a stereo sound. If the sample data doesn't contain any blank loop, `AWE_SAMPLE_NO_BLANK` flag should be set. Also, if the sample data is a single-shot, `AWE_SAMPLE_SINGLESHOT` flag should be set. Otherwise, you must add a blank loop after the sample, and direct the loop pointers on it by yourself.

The driver doesn't care about these stereo flags, but checks only the key note and velocity range. If two or more voices are suitable on the given note and velocity pair, all they should be played simultaneously. The multiple instruments are featured only in channel playing mode, but in normal mode, only the first matching voice is played.

To send a wave sample data, write a patch structure containing a patch header with the operation id `AWE_LOAD_DATA`, the sample header `awe_sample_info`, and the sample wave data if necessary. Thus, the `len` parameter of the first patch header becomes
(`AWE_SAMPLE_INFO_SIZE`) + data byte size).

### 3.1.4. AWE Voice Information

The voice information is also an variable length data record to specify the raw parameters of Emu8000 chip controls for each instrument. Multiple instruments can be defined as one voice information record if all of them are the same instrument with the same bank/preset pair.

The voice information has 4 bytes after the patch header,

    typedef struct _awe_voice_rec_hdr {
    	unsigned char bank;		/* midi bank number */
    	unsigned char instr;		/* midi preset number */
    	char nvoices;			/* number of voices */
    	char write_mode;		/* write mode */
    } awe_voice_rec_hdr;

where `bank` and `instr` specify the bank and program number of this instrument, and `nvoices` denotes the number of voices (samples) used in this instrument. If any voices with the same bank and program number exist already, the new voices are prepended before the list of older voices. `nvoices` must be larger than zero. Thus, `len` in patch header has the value
(`AWE_VOICE_REC_SIZE` + `nvoices` * `AWE_VOICE_INFO_SIZE`).
`write_mode` specifies how the voice infos are stored on the driver.

    #define AWE_WR_APPEND		0	/* append anyway */
    #define AWE_WR_EXCLUSIVE	1	/* skip if already exists */
    #define AWE_WR_REPLACE		2	/* replace if already exists */

Normally, `AWE_WR_APPEND` is used to append each data. In usual situation, it doesn't matter which mode is selected. If a data with the same preset/bank pair already exists on the driver as a same patch, the operation may differ depending on its write mode. When `AWE_WR_EXCLUSIVE` is specified, the new data is skipped. When `AWE_WR_REPLACE` is specified, the old data is thrown and the new data replaces with the old one. Otherwise, the data is always appended, and the new one is used together with the old data, that is, both of them are reproduced as one sound.

After this 4bytes record, `nvoices` of 92bytes of voice information for each sample are appended.

    typedef struct _awe_voice_info {
    	unsigned short sf_id;		/* file id */
    	unsigned short sample;		/* sample id */
    	long start, end;		/* sample offset correction */
    	long loopstart, loopend;	/* loop offset correction */
    	short rate_offset;		/* sample rate pitch offset */
    	unsigned short mode;		/* sample mode */
    	short root;			/* midi root key */
    	short tune;			/* pitch tuning (in cents) */
    	char low, high;			/* key note range */
    	char vellow, velhigh;		/* velocity range */
    	char fixkey, fixvel;		/* fixed key and velocity */
    	char pan, fixpan;		/* panning, fixed panning */
    	short exclusiveClass;		/* exclusive class (0 = none) */
    	unsigned char amplitude;	/* sample volume (127 max) */
    	unsigned char attenuation;	/* attenuation (0.375dB) */
    	short scaleTuning;		/* pitch scale tuning(%), normally 100 */
    	awe_voice_parm parm;		/* voice envelope parameters */
    	short index;			/* internal index (set by driver) */
    } awe_voice_info;

where `sf_id` is an internal file id and normally zero, `sample` is the referring sample id of this voice. `start`, `end`, `loopstart`, and `loopend` are the offset correction of this voices. For example, a value of `start` 30 means that this voice starts 30 points after the original start points.

`rate_offset` holds the pitch offset of this voice according to its sample rate. This value is an AWE specific logarithmic rate, that each 4096 is one octave shift. For example, a value of -2048 indicates the sample is played 6 semitones flat. The value can be calculated by the following equation.

    rate_offset = log(Hz / 44100) / log(2) * 4096

`mode` is 16bit flags indicating the kind of this voice.

    #define AWE_MODE_ROMSOUND		0x8000
    #define AWE_MODE_STEREO			1
    #define AWE_MODE_LOOPING		2
    #define AWE_MODE_NORELEASE		4	/* obsolete */
    #define AWE_MODE_INIT_PARM		8

`AWE_MODE_STEREO` and `AWE_MODE_NORELEASE` are ignored in the current version. `AWE_MODE_INIT_PARM` means that `parm` members are initialized at loading automatically.

`root` and `tune` contain the root key note and fine tune of this voice. The key is supplied by MIDI key value, from 0 to 127, and fine tune is a cents order. A positive fine tune value indicates the sound is played at a higher pitch, and a negative value means a lower pitch.

`low` and `high` define the key note range of this voice. If the key is out of this range, the driver skips this voice, and searches the next voice from voice list. To accepts all keys, `low` be 0, and `high` 127.

Similarly, `vellow` and `velhigh` define the velocity range of this voice. As well as in key note range, the voice is accepted only when the velocity is within this range.

`fixkey`, and `fixvel` indicate the fixed key and velocity of this voice. If the value is not -1, the key or velocity is fixed on this value.

`pan` has a panning position of the "dry" sound, from 0(left) to 127(right), or -1 for not specified. `fixpan` also contains the fixed panning position. If valid `fixpan` is given, the panning position is fixed to that value.

`exclusiveClass` is the exclusive class of this voice. If the value is zero, no exclusive system activates. Otherwise, the voices with the sample exclusive class are turned off before playing a new voice with this class. This feature is used for some drum instruments like hi-hat.

`amplitude` and `attenuation` define the volume of this voice. `amplitude` is a linear volume from 0 to 127, and `amplitude` means the attenuation from full level in 0.375dB order. For example, a voice with `attenuation` 40 is reproduced 15dB lower from full scale.

`scaleTuning` is a pitch scale tuning ratio, and normally is 100.

`index` is an internal sample index, and ignored at loading.

`parm` contains the modulation/volume envelopes, LFO's and other raw parameters of emu8000 chip.

    typedef struct _awe_voice_parm {
    	unsigned short moddelay;	/* modulation delay (ENVVAL) */
    	unsigned short modatkhld;	/* modulation attack & hold time (ATKHLD) */
    	unsigned short moddcysus;	/* modulation decay & sustain (DCYSUS) */
    	unsigned short modrelease;	/* modulation release time (DCYSUS) */
    	short modkeyhold, modkeydecay;	/* envelope change per key (not used) */
    	unsigned short voldelay;	/* volume delay (ENVVOL) */
    	unsigned short volatkhld;	/* volume attack & hold time (ATKHLDV) */
    	unsigned short voldcysus;	/* volume decay & sustain (DCYSUSV) */
    	unsigned short volrelease;	/* volume release time (DCYSUSV) */
    	short volkeyhold, volkeydecay;	/* envelope change per key (not used) */
    	unsigned short lfo1delay;	/* LFO1 delay (LFO1VAL) */
    	unsigned short lfo2delay;	/* LFO2 delay (LFO2VAL) */
    	unsigned short pefe;		/* modulation pitch & cutoff (PEFE) */
    	unsigned short fmmod;		/* LFO1 pitch & cutoff (FMMOD) */
    	unsigned short tremfrq;		/* LFO1 volume & freq (TREMFRQ) */
    	unsigned short fm2frq2;		/* LFO2 pitch & freq (FM2FRQ2) */
    	unsigned char cutoff;		/* initial cutoff (upper of IFATN) */
    	unsigned char filterQ;		/* initial filter Q [0-15] (upper of CCCA) */
    	unsigned char chorus;		/* chorus send */
    	unsigned char reverb;		/* reverb send */
    	unsigned short reserved[4];	/* not used */
    } awe_voice_parm;

The values correspond to the register values of emu8000 described in AWE32 Developer's Information Package (ADIP) by CreativeLabs. This record can be initialized internally in the driver by setting `AWE_MODE_INIT_PARM` flag in voice_info record.

It would be useful to use a fixed size record if only one voice is defined in one record.

    typedef struct _awe_voice_rec_patch {
    	awe_patch_info		patch;
    	awe_voice_rec_hdr	hdr;
    	awe_voice_info		info;
    } awe_voice_rec_patch;

### 3.1.5. Load a preset map

The preset map provides a virtual voice information for a preset. It redirects the voice information to another preset when the prescribed preset is searched. In the AWE MIDI player, this function is used to play XG midi files. The XG midi format defines its specific presets, and some of them are incompatible with GS/GM presets. This can be solved by making virtual presets mapping to the corresponding GS presets with different preset/bank numbers.

To load a preset map, use the operation AWE_MAP_PRESET, and the following another patch record as its body.

    typedef struct awe_voice_map {
    	int map_bank, map_instr, map_key;	/* key = -1 means all keys */
    	int src_bank, src_instr, src_key;
    } awe_voice_map;

The map_bank, map_instr and map_key define the destination bank, preset and key numbers, respectively. The latter, src_bank, src_instr and src_key define the source preset as well. If key number holds a value -1, it's regarded as searching all keys in the given preset.

### 3.1.6. Replace a sample data

This is a new function added in the ver.0.4 driver. It simply replaces the sample wave data with the new one. This function is useful to switch the wave sample data during playing another samples.

The patch record is as same as in the sample data record (3.1.2) except the operation id `AWE_REPLACE_DATA` and the optional argument (`optarg`). The optional argument defines the number of channels to be used for transfer the data. More channels can transfer more faster the sample data, though, of course, the available voices are restricted during transfer.

Note that the sample wave size must be equal with the replaced older data. Otherwise, the patch will be rejected.

## 3.2. Unload samples

The patch data can be unloaded by writing a patch with the operation id `AWE_UNLOAD_PATCH`. If this operation is accepted, the driver removes the voice informations and samples which were sent at last. Note that no "open" operation is required for unloading.

To unload the "unlocked" samples, use `AWE_REMOVE_LAST_SAMPLES` macro.

    AWE_REMOVE_LAST_SAMPLES(seqfd, device);

This macro uses ioctl, the file descriptor of the sequencer device is required as an argument. Since the ioctl is employed, the operation is done immediately without buffered.

## 3.3. Send user-defined modes

AWE driver ver.0.4.1 has a function to accept the new chorus and reverb parameters as user-defined modes.

### 3.3.1. Load user-defined chorus mode

### 3.3.2. Load user-defined reverb mode

## 3.4. GUS compatible patches

From ver.0.2.0, awedrv can receive GUS style patch records. The GUS patch structure is defined in `soundcard.h`. Unlikely to AWE patch, one sample is associated with one voice information in GUS patch.

    struct patch_info {
    	unsigned short key;		/* Use GUS_PATCH here */
    	short device_no;	/* Synthesizer number */
    	short instr_no;		/* Midi pgm# */
    	unsigned int mode;
    	int len;	/* Size of the wave data in bytes */
    	int loop_start, loop_end; /* Byte offsets from the beginning */
    	unsigned int base_freq;
    	unsigned int base_note;
    	unsigned int high_note;
    	unsigned int low_note;
    	int panning;	/* 0 to 15? */
    	int detuning;
    	unsigned char	env_rate[ 6 ];	 /* GUS HW ramping rate */
    	unsigned char	env_offset[ 6 ]; /* 255 == 100% */
    	unsigned char	tremolo_sweep;
    	unsigned char	tremolo_rate;
    	unsigned char	tremolo_depth;
    	unsigned char	vibrato_sweep;
    	unsigned char	vibrato_rate;
    	unsigned char	vibrato_depth;
    	int		scale_frequency;
    	unsigned int	scale_factor;		/* from 0 to 2048 or 0 to 2 */
            int		volume;
    	int		fractions;
            int		spare[3];
    	char data[1];	/* The waveform data starts here */
    };

`key` must be `GUS_PATCH` value, and `device_no` is the device number of AWE driver.

`instr_no` defines the program number of this sample. The bank number can be defined using the extended control `AWE_SET_GUS_BANK` function before loading the samples. As default, the bank is set to zero.

`mode` indicates the flags of this sample. Backward looping, scaling and fractions are not implemented yet. `len` has the length of the sample data in bytes order. Note that AWE patch holds in words order for 16bit samples, but GUS patch is always in bytes order. Similarly, loop position by `loop_start` and `loop_end` is in byte offset.

`base_freq`, base_note, `high_note`, and `low_note` are converted in the driver to corresponding key note and fine tunes.

`panning` parameter is passed as the initial position of dry sounds.

The 6 points volume envelope, tremolo, and vibrato parameters are converted to the AWE32 specific values in the driver.

Other parameters, `detuning`, `scale_frequency`, `scale_factor`, `volume`, and `fractions` are ignored.

The sample data follows after this is converted according to the flags specified automatically.

After setting these parameters and copying the sample data from data pointer, load this patch data on the driver.

    SEQ_WRPATCH(device, patch, sizeof(patch) + data byte size - 1);

# 4. Playing a voice

## 4.1. Playing modes

The AWE driver has several playing modes depending on its usage. One is the normal mode, and another is the channel mode. The former mode is as same as in the other sound driver like GUS and FM. Each preset is assigned to one voice number. On the contrast, the latter mode is used to make easy to handle MIDI operations. Each voice number is regarded as a MIDI channel, and the voice allocation is done automatically inside the driver.

More specifically, the driver has four playing modes: indirect, direct, multi, and multi2 modes. The first two modes behave as the normal playing mode, and the latter two modes as the channel playing mode. The indirect mode is a new type which was added from ver.0.4.1e. It assigns the actual voice for each voice number at each time it's played, while the direct mode fixes each voice per the corresponding voice number. The multi2 mode is an internal mode for /dev/sequencer2 control. Normally, this mode is not used explicitly.

The merit of indirect mode is capability of multi layered preset, and reduction of click noises. Many SoundFont files define presets including multiple instruments, instruments including multiple samples, and stereo sounds. In such a case, two or more samples must be played at the same time. Then, in the indirect mode, the driver assigns one or more voices when a voice number is called, and release the assigned voices when the note-off is called to the corresponding voice number. A released voice is left for a while until assgined as a new voice, so that this also reduces a click noise occuring when the voice is terminated. The multi and multi2 modes employ this same mechanism, too.

To change the current playing mode, call `AWE_CHANNEL_MODE` macro.

    AWE_SET_CHANNEL_MODE(device, mode);

where `mode` is one of the following predefined modes,

    #define AWE_PLAY_INDIRECT	0	/* indirect voice mode (default) */
    #define AWE_PLAY_MULTI		1	/* multi note voice mode */
    #define AWE_PLAY_DIRECT		2	/* direct single voice mode */
    #define AWE_PLAY_MULTI2		3	/* sequencer2 mode; used internally */

Note that the playing mode is reset at each time the device is closed to the indirect mode.

## 4.1. Selecting a program

The voice program is selected by `SEQ_SET_PROGRAM` macro.

    SEQ_SET_PROGRAM(device, voice, program);

where `voice` is the voice or channel number depending on the current playing mode. In the normal playing mode, the voice number usually has a value from 0 to 29. `program` is the program number to be played. AWE32 has 32 individual channels, but when playing samples on DRAM, the last two channels cannot be used due to DRAM refresh. Thus, in awedrv, only 30 channels are available.

In channel playing mode, `voice` becomes a MIDI channel number (usually from 0 to 15). The voices are allocated internally by the driver. Likewise, in all other sequencer controls, `voice` becomes the corresponding MIDI channel number.

The drum voices are assigned to individual programs with (key number + 128) by traditional reason. The awedrv itself has a capability to deal with the drumset as one program. In such a case, users must specify the preset number as the drumset number and the fixed bank number 128. You can also set the drum channels by extension control `AWE_DRUM_CHANNELS` with a bit-blt parameter, calculated by (1 << drum number), where drum number starts from 0. In these channels, the voices are assumed as a drum set.

    AWE_DRUM_CHANNELS(device, channels);

As default, only channel 10 is assumed as a drum channel, then the `channels` value is 0x200. Some MIDI files use also the channel 16 as a drum. In such a case, `channels` becomes 0x8200.

The awedrv has a bank selection mechanism. The bank selection can be done through MIDI control message #0, so is realized by `SEQ_CONTROL` macro like

    SEQ_CONTROL(device, voice, CTL_BANK_SELECT, bank);

where `bank` is the bank number of the sample. For drum voices (set by `AWE_DRUM_CHANNELS`), this number is ignored.

## 4.2. Setting various effects

### 4.2.1. Pitch control

To control the sample pitch or frequency, the pitch wheel control is used ordinally. The pitch change is calculated from two parameters, pitch bender range and pitch bending degree. The former, the pitch wheel, is controlled by `SEQ_BENDER` macro, or obsolete `SEQ_PITCHBEND` macro.

    SEQ_BENDER(device, voice, value);

Be careful that the parameter values are different between them. `SEQ_BENDER` has a value from 0 to 16384, and the center (no pitch shift) is 8192, just as same as in MIDI sequences. On the other hand, `SEQ_PITCHBEND` has a value from -8192 to 8192, and the center is 0. In both cases, the smaller than the center means lower pitch shift, and the larger means upper pitch shift, respectively. For example, when the bender range (see below) is 200, a value of -4096 indicates one octave flat from the normal pitch.

The latter control, the bender range, is done by `SEQ_BENDER_RANGE` macro. This function defines the bender range in (octave * 100). For example, a value of 400 indicates that the maximum wheel change to be four octave shift from the normal pitch. The default value is 200.

    SEQ_BENDER_RANGE(device, voice, value);

Both of these controls can be changed at real time during playing the sample.

### 4.2.2. Volume control

The volume of each voice can be controlled by three parameters: main volume, expression volume, and velocity. The total volume is calculated from the product of these three values as (main_volume * expression * velocity). While the last velocity parameters is specified at starting the sample, the other two parameters are given usually before playing it though they can be changed at real time during playing the sample.

The main volume is set via `SEQ_CONTROL` with the proper control code (`CTL_MAIN_VOLUE` and `CTRL_MAIN_VOLUME`), or obsolete `SEQ_MAIN_VOLUME` macro.

    SEQ_CONTROL(device, voice, CTL_MAIN_VOLUME, value);

The value for `SEQ_MAIN_VOLUME` is identical with MIDI value, from 0 to 127. When the playing mode is the normal mode, the control `CTL_MAIN_VOLUME` has a value from 0 to 20806 (= 16383 * 127 / 100). In the channel mode, it has the same value as MIDI, from 0 to 127. The `CTRL_MAIN_VOLUME` always has the same value as MIDI.

The expression volume is set via `SEQ_CONTROL` with the proper control code (`CTL_EXPRESSION` and `CTRL_EXPRESSION`), or obsolete `SEQ_EXPRESSION` macro.

    SEQ_CONTROL(device, voice, CTL_EXPRESSION, value);

The value for `SEQ_EXPRESSION` is identical with MIDI value, from 0 to 127. Similarly, when the playing mode is the normal mode, the control code`CTL_EXPRESSION` has a value from 0 to 16256 (= 127 * 128). In the channel mode, it has the same value as MIDI, from 0 to 127. The `CTRL_EXPRESSION` has the same value as MIDI, from 0 to 127.

Additionally, the awedrv has a total volume attenuation parameter. Users can change this initial attenuation using `AWE_INITIAL_ATTEN` control (identical with `AWE_INITIAL_VOLUME`).

    AWE_INITIAL_ATTEN(device, atten);

This value `atten` is the attenuation volume from full scale in 0.375 dB order. For example, a value of 10 means that 3.75 dB lower from full scale. The initial value is 32, 12dB below from full scale.

In the driver ver.0.4, the initial attenuation can be calculated as an additional attenuation from predefined "zero attenuation". The zero attenuation can be given via `AWE_MISC_MODE` control as

    AWE_MISC_MODE(device, AWE_MD_ZERO_ATTEN, atten);

Then, the attenuation is changed via `AWE_SET_ATTEN` control.

    AWE_SET_ATTEN(device, atten);

The definition of attenuation level is as same as the above. Note that `AWE_INITIAL_ATTEN` sets the absolute attenuation, while `AWE_SET_ATTEN` sets the relative attenation from zero level.

Also, the awedrv has an mixer control of Emu8000 chip. To change the bass and treble volume, use `AWE_EQUALIZER` macro.

    AWE_EQUALIZER(device, bass, treble);

where both `bass` and `treble` are the integer value from 0 (-12dB) to 11 (+12dB).

### 4.2.3. Panning position

The panning position is also set via control command, `SEQ_CONTROL` with the proper control code (`CTL_PAN`), or obsolete `SEQ_PANNING` macro.

    SEQ_CONTROL(device, voice, CTL_PAN, value);

The value for `SEQ_PANNING` is from -128(left) to 128(right), and different from MIDI value unlike volume controls above. But the value of `CTL_PAN` is identical with MIDI value, from 0(left) to 127(right).

The panning position can be changed during playing, but may cause a small clicking noise due to restriction of emu8000 chip. This is suppressed by `AWE_REALTIME_PAN` control.

    AWE_REALTIME_PAN(device, 0);

If the argument is zero, the panning position of the voices never changes during played.

### 4.2.4. Chorus and reverb effects

The AWE32 has chorus and reverb effects for each voice. In awedrv, these effects are controlled via `SEQ_CONTROL` with two control commands, `CTL_CHORUS_DEPTH` and `CTL_EXT_EFF_DEPTH`, for chorus and reverb, respectively.

    SEQ_CONTROL(device, voice, CTL_CHORUS_DEPTH, value);
    SEQ_CONTROL(device, voice, CTL_EXT_EFF_DEPTH, value);

In both cases, the value range is from 0 to 127, where 127 means 100% of output is send to the corresponding effect processor. These values cannot be changed during playing the sample.

Also, AWE32 has eight modes for both chorus and reverb effects. They can be changed by extended control by `AWE_CHORUS_MODE` and `AWE_REVERB_MODE`, respectively.

    AWE_CHORUS_MODE(device, mode);
    AWE_REVERB_MODE(device, mode);

In both cases, the range of the parameter value is from 0 to 7. The corresponding mode to each value is defined in `awe_voice.h`, that is, Chorus 1 - 4, Feedback, Flanger, Short Delay, and Short Delay 2 for chorus modes, and Room 1 - 3, Hall 1/2, Plate, Delay, Panning Delay for reverb modes. See AWE32 FAQ by CreativeLabs for meaning of each mode.

### 4.2.5. Other effects

The awedrv has several extended controls to write raw register values for emu8000 parameters. Through this function, users can control any function of AWE32 sound effects, although the parameter value itself is not generic.

The extended controls are passed through `AWE_SEND_EFFECT` macro with specified commands and values.

    AWE_SEND_EFFECT(device, voice, command, value);

The commands are defined in `awe_voice.h`, that is,

    /* 0*/	AWE_FX_ENV1_DELAY,	/* WORD: ENVVAL */
    /* 1*/	AWE_FX_ENV1_ATTACK,	/* BYTE: up ATKHLD */
    /* 2*/	AWE_FX_ENV1_HOLD,	/* BYTE: lw ATKHLD */
    /* 3*/	AWE_FX_ENV1_DECAY,	/* BYTE: lw DCYSUS */
    /* 4*/	AWE_FX_ENV1_RELEASE,	/* BYTE: lw DCYSUS */
    /* 5*/	AWE_FX_ENV1_SUSTAIN,	/* BYTE: up DCYSUS */
    /* 6*/	AWE_FX_ENV1_PITCH,	/* BYTE: up PEFE */
    /* 7*/	AWE_FX_ENV1_CUTOFF,	/* BYTE: lw PEFE */

    /* 8*/	AWE_FX_ENV2_DELAY,	/* WORD: ENVVOL */
    /* 9*/	AWE_FX_ENV2_ATTACK,	/* BYTE: up ATKHLDV */
    /*10*/	AWE_FX_ENV2_HOLD,	/* BYTE: lw ATKHLDV */
    /*11*/	AWE_FX_ENV2_DECAY,	/* BYTE: lw DCYSUSV */
    /*12*/	AWE_FX_ENV2_RELEASE,	/* BYTE: lw DCYSUSV */
    /*13*/	AWE_FX_ENV2_SUSTAIN,	/* BYTE: up DCYSUSV */

    /*14*/	AWE_FX_LFO1_DELAY,	/* WORD: LFO1VAL */
    /*15*/	AWE_FX_LFO1_FREQ,	/* BYTE: lo TREMFRQ */
    /*16*/	AWE_FX_LFO1_VOLUME,	/* BYTE: up TREMFRQ */
    /*17*/	AWE_FX_LFO1_PITCH,	/* BYTE: up FMMOD */
    /*18*/	AWE_FX_LFO1_CUTOFF,	/* BYTE: lo FMMOD */

    /*19*/	AWE_FX_LFO2_DELAY,	/* WORD: LFO2VAL */
    /*20*/	AWE_FX_LFO2_FREQ,	/* BYTE: lo FM2FRQ2 */
    /*21*/	AWE_FX_LFO2_PITCH,	/* BYTE: up FM2FRQ2 */

    /*22*/	AWE_FX_INIT_PITCH,	/* SHORT: pitch offset */
    /*23*/	AWE_FX_CHORUS,		/* BYTE: chorus effects send (0-255) */
    /*24*/	AWE_FX_REVERB,		/* BYTE: reverb effects send (0-255) */
    /*25*/	AWE_FX_CUTOFF,		/* BYTE: up IFATN */
    /*26*/	AWE_FX_FILTERQ,		/* BYTE: up CCCA */

    /*27*/	AWE_FX_SAMPLE_START,	/* SHORT: offset */
    /*28*/	AWE_FX_LOOP_START,	/* SHORT: offset */
    /*29*/	AWE_FX_LOOP_END,	/* SHORT: offset */
    /*30*/	AWE_FX_COARSE_SAMPLE_START,	/* SHORT: upper word offset */
    /*31*/	AWE_FX_COARSE_LOOP_START,	/* SHORT: upper word offset */
    /*32*/	AWE_FX_COARSE_LOOP_END,		/* SHORT: upper word offset */
    /*33*/	AWE_FX_ATTEN,		/* BYTE: lo IFATN */

The commands 0 - 7 define parameters of the modulation envelope, 8 - 13 of the volume envelope, 14 - 18 of LFO1, 19 - 21 of LFO2, 22 - 26 of other effect parameters for total voice, and the later provides sample start position, and loop offset. See ADIP for the parameter values of envelopes and LFO's.

`AWE_ADD_EFFECT` is used to adjust the effect from predefined value in the voice patch data. The relative value is given as an argument, while the absolute value is given in `AWE_SEND_EFFECT` control.

    AWE_ADD_EFFECT(device, voice, command, value);

On the channel mode, these effects are kept unless `AWE_UNSET_EFFECT` macro is used.

    AWE_UNSET_EFFECT(device, voice, layer, command);

On the normal mode, the effects are always cleared after the voice is off. To suppress this, set `AWE_MD_KEEP_EFFECT` by `AWE_MISC_MODE` control.

    AWE_MISC_MODE(device, AWE_MD_KEEP_EFFECT, 1);

Also, on the channel mode, each instrument "layer" can be controlled via `AWE_SEND_LAYER_EFFECT` and `AWE_ADD_LAYER_EFFECT` macros. It affects the effects only on one layer (= one voice) specified in the argument.

    AWE_SEND_EFFECT_LAYER(device, voice, layer, command, value);

GUS compatible extended controls are partly implemented. `GUS_VOICE_POS` is interpreted inside as an extension control 27(`AWE_FX_SAMPLE_START`) and 30(`AWE_FX_COARSE_SAMPLE_START`).

## 4.3. Starting a note

There are two ways to start a voice. The standard method is to call `SEQ_START_NOTE` macro.

    SEQ_START_NOTE(device, voice, note, velocity);

where `note` and `velocity` are the MIDI key and velocity to be played, respectively. A sample including the specified note in its key range is searched from all samples with given bank and program numbers. Then, the volume and pitch parameters are computed here from specified note and velocity. If this sample is an exclusive voice like drum hi-hat sounds, turn off other voices with the same exclusive key, that is the other hi-hat sounds which is being played. After that, start this voice.

In the normal playing mode, the note 255 has a special meaning. When this function is called with the note 255, only volume is changed according its velocity, and never affects the envelope change, and so on. This can be used for dynamic volume control without using other `SEQ_CONTROL` functions. Note that this feature is ignored in the channel playing mode.

If the velocity is specified as zero, then one channel is allocated, but the sound is not started. It starts when volume change control is received later.

The another way for start is to call a GUS specific control

    GUS_VOICEON(device, voice, mode);

where `mode` is a voice mode, but ignored in awedrv. This simply starts a sound on the channel, so voice parameters like program, pitch and volume must be set before calling this function.

# 5. Modulating a voice

## 5.1. Changing volume

Many methods are provided to change the volume of the sample. One is to use `SEQ_KEY_PRESSURE` macro, or `AWE_KEY_PRESSURE` macro, depending on its playing mode. In the channel playing mode, the former macro `SEQ_KEY_PRESSURE` is ignored due to compatibility problems. Thus, in the channel mode, use the latter `AWE_KEY_PRESSURE` macro instead. The parameter value is as same as MIDI pressure value, from 0 to 127.

    AWE_KEY_PRESSURE(device, voice, note, velocity);

The second way is updating main or expression volume on each channel by `SEQ_CONTROL` or other macros (see 4.2.2). Also, using `SEQ_START_NOTE` with a special note 255 is available for changing volume as explained above.

## 5.2. Changing pitch

You can change pitch of the sound by using the pitch wheel, or by `AWE_SEND_EFFECT` with `AWE_FX_INIT_PITCH` command (see 4.2.1).

## 5.3. Changing panning position

The panning position is able to be changed at real time, but it may cause a noise as explained above (see 4.2.3).

## 5.4. Changing chorus and reverb

The chorus and reverb effects can NOT be changed at real time. However, the chorus and reverb modes are possible to be changed.

## 5.5. Changing other effects

The LFO1 depth can be changed via `AWE_CHN_PRESSURE` and `CTL_MODWHEEL` MIDI control. The former affets all the voices on the channel, while the latter affects only one voice (in the channel mode).

    AWE_CHN_PRESSURE(device, channel, value);
    SEQ_CONTROL(device, voice, CTL_MODWHEEL, value);

The value is MIDI value from 0 to 127.

The LFO parameters (frequency, volume, pitch shift, and cutoff shift), and LFO2 parameters (frequency, and pitch shift) can be changed at real time via `AWE_SEND_EFFECT` control. Also, total cutoff frequency can be changed. The values are passed through the extended controls (see 4.2.5).

# 6. Timer control

The awedrv itself doesn't provide any timer control functions. Use the standard timer macros, `SEQ_START_TIMER`, `SEQ_WAIT_TIME` or `SEQ_DELTA_TIME`, and `SEQ_STOP_TIMER`.

# 7. Ending a voice

To end a sound, call `SEQ_STOP_NOTE` macro. This releases the sound from the sustain level to silence according to the volume envelope. The note and velocity parameters are ignored.

    SEQ_STOP_NOTE(device, voice, note, velocity);

Or, you can terminate the voice completely by extended control, `AWE_TERMINATE_CHANNEL`. This stops the sound without any releasing echo.

    AWE_TERMINATE_CHANNEL(device, voice);

To terminate all voices, the extended control `AWE_TERMINATE_ALL` is available.

    AWE_TERMINATE_ALL(device);

To turn off the all channels similary as SEQ_STOP_NOTE (with sustain effects), use `AWE_NOTEOFF_ALL`.

    AWE_RELEASE_ALL(device);

Also, to force to turn off the all channels without sustain effects, use `AWE_NOTEOFF_ALL`.

    AWE_NOTEOFF_ALL(device);

# 8. Other features

## 8.1. Debug options

The debug message is toggled on/off by the extended control `AWE_DEBUG_MODE`.

    AWE_DEBUG_MODE(device, mode);

The value zero means to turn off debugging messages, and values larger then zero means to output debugging messages on syslog, usually `/var/adm/syslog` or /var/adm/message (depending on the setting of `/etc/syslog.conf`).

## 8.2. Initialize Emu8000 chip

The emu8000 chip can be initialized explicitly by the extended control `AWE_INITIALIZE_CHIP`. This only re-initializes the AWE32, and doesn't affect other driver-internal parameters or effects.

    AWE_INITIALIZE_CHIP(seqfd, device);

This function uses ioctl, so the file descriptor of sequencer device is required.

## 8.3. Set miscellaneous operation modes

Many operation modes can be set via `AWE_MISC_MODE` control.

    AWE_MISC_MODE(device, type, value);

See `awe_voice.h` for each definition.

Takashi Iwai
iwai@dragon.mm.t.u-tokyo.ac.jp
http://bahamut.mm.t.u-tokyo.ac.jp/~iwai