Comands for VAMP, 
    a program to generate MIDI sequences of contra dance music 

    Copyright 2002-2005, Stanley M. Swanson.
       last revised 24 February 2005

    This information is distributed under the terms of the 
    GNU Free Documentation License.  legalities

VAMP was written to generate contra and square dance accompaniment
from traditional melodies (public domain) specified with "abc" notation,
chord sequences (vamping), and a sequence of accents for the notes
in chords which indicate the rhythm (downbeat, etc.) and phrasing of
the music.  These three aspects (melody, chords, rhythm) can be
specified with simple text lines and varied independently.  There are
limitations to this structuring of the musical information, since
it is harder to tweak individual notes than in a GUI type composing
program, but the specifications are more compact and less tedious
to change.  Other aspects of a performance such as tempo, staccato,
and instrument selection can also be specified.  VAMP produces
a MIDI file which is played (or converted to WAV format for a CD)
by a multimedia player (I use Timidity++ on Linux).

                             
abc notation
      accidentals
      keys and modes
volumes and velocities
notes on using TiMidty++
melody 
vamp
chords
accent
phrase
rubato
events (variations)
generate
harmony
       details on harmony analysis
instruments
parameters, options, xtra
  instrumental styles
tempo
repeat
loops
quit

Input to the program is command line (text) oriented and can given
in immediate mode or taken from pre-edited files.  An introduction
with examples is in the file  vamp_intro.html.
You will be asked for a log file name at the beginning (useful to
keep track of interactive sessions, or record harmony output).
To exit the program use "quit".

Commands come in two flavors: 
one-liners with a command followed by data 
  ( "quit", "tempo", "instrument", "repeat", "generate", "harmony", 
    "param", "options", "xtra", "style" )
and container type commands where the data appears sandwiched
between a "command" line and its matching terminator "/command".
  ( "melody", "vamp", "chords", "accent", "phrase", "rubato",
    "events", "variations", "loops" )
The line oriented format of "abc" notation is retained for
data lines in "melody", and "vamp".

Commands can be abbreviated so long as they remain unambiguous
(presently single letters, except for "vamp", "variations" ).
Commands are case insensitive.  Id's, chord names, and file
names ARE case sensitive.

  The design philosophy with respect to syntax checking has been permissive:
  correct input should give the desired results; incorrect input may be
  detected, but may not be, and useful results are not guaranteed.  Some
  effort has been put into bounds checking for large arrays and protection
  against errors or conditions which will cause program aborts. 

There are several other commands which can be viewed as "one-liners":
the indirect file designator "@path/filename" which switches input 
immediately to the file until an EOF is read.  Indirect files can be 
nested up to 10 deep.  Except for reading parts of an "abc" archive,
an indirect file reference must occur at the top command level,
not within the data lines of container type commands.

The "abc" convention of "%" marking the rest of a line as comment 
is generally observed (but there may be contexts where it doesn't work).

The first two comment lines beginning with "#" before a "generate"
command are saved as text in the MIDI file.  If you want to put
copyright information into a MIDI file, either of the following work:

#copyright date Name (other text)
#(c) date Name (etc.)
                                       contents
--------------------------
                                
ABC Parsing Incomplete:

My implementation of "abc" parsing is not complete.  Generally a character
will be correctly interpreted, or rejected (ignored) with a message
"undecodable character ...".

The music itself is given by letters separated by bar lines "|".
An ascending seven note  scale starting with middle C is given with
capital letters: "CDEFGAB"; the octave above that is in lower case:
"cdefgab".  The total range recognized by VAMP is six octaves, specified
by appending commas to lower notes and apostrophes to higher notes:

 C,,, ... B,,,C,, ... B,,C, ... B,C ... Bc ... bc' ... b'c'' ... b'' .

Thus if C4 is middle C, C5 the C above that (lower case c in "abc"-ese),
the range of notes represented is from C1 through B7.

This discussion is not meant to be a tutorial on "abc" notation.
For a complete specification, see the web site of Chris Walshaw, who
originated the notation:  www.gre.ac.uk/~c.walshaw/abc

Most of the information lines (except T: L: M: K: X:) are ignored
and treated as comments. (X:n is used for indirect subfile input: see above.)

Trailing dots (dotted notes e.g. "A.B..") are not recognized but one 
can use ">", "<", "/" (for /2), "/m", or "n/m" (for single digits n,m).
Only simple sequences like "a>b", "f<c" are decoded; something
like "g2>f2" is not -- use "g3f" instead.

Repeats and alternate endings are encoded into "abc" internal
information, and are now used for building a complete tune out of fragments.
( It recognizes ":" "[1" "[2" "[3" and the shorthand symbols "|1" "|2" "|3" .) 
I have added an alternate final ending "[3" which substitutes for "[2" on the
last repeat of a tune.

Repeats, etc. are encoded as a sequence of melodic fragments.  An 
initial repeat sign (:) will be supplied if the number of colons is odd.
Only two possible partial sequences are legal:  " |: .... :|"
and "|: ... [1 ... :| [2 ... ".  A final " [2 ... [3..." is treated
as "[2... ||" for the purposes of all repeats except the last, and 
will be played as " [1...:|[3...||" for the last time through.

Guitar chords ("A7", etc.) are ignored (don't generate musical output).
They are stored as strings and are accessed by the harmony analysis code 
(printed for human reference, and compared to assigned chords).

Slurs "(notes)" and ties "-" have been implemented, but must have
a disjoint range with chord bracketing "[notes]".   (Ties may be useful
in harmony analysis so that a note does not span the half measure boundary.)

Grace notes "{notes}", ornaments "~", and staccato "."  are unimplemented.
Staccato is controlled with the staccato parameter, with the rubato 
and accent commands, and eventually with instrumental style commands.  

Only triples ( e.g. "(3abc" ) are implemented of the possible tuples.

All notes in a chord typically have the same length.  The time from
the start of a chord to the next note after the chord is now the
duration of the shortest note in the chord;  thus some overlapping of
notes or other chords is possible.

                             
ACCIDENTALS 

    Any explicit accidental sign preceding a note
( "^", "_", "=") has effect for that note and for the rest of the measure.
Explicit accidentals are referenced to the piano white notes (K: C), so
most sharps and flats will put you onto the black notes ( however cases like
 ^B or _C are legal ).  Double accidentals ("^^" or "__") are treated
as a single accidental and an undecoded character.

                                   
KEYS and MODES

The key line "K: key" determines global accidentals. 
   (e.g. K: G means that F is interpreted as ^F,  
         K:Eb means that E denotes Eb (_E) and B denotes Bb (_B)  )
 
Modes (ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian) 
are recognized, as are "major" and "minor". Without further qualification, 
the key is assumed major.  Modes are used to distinguish the tonal center 
from the major key designated by the key signature.  The command
"harmony center" as well as the final note in the tune or phrase may
help in deciding the mode.

This can be of importance in assigning chords. For example, 
K:A would designate A major with 3 sharps and a tonal center of A, 
while K:Dmixolydian designates a tonal center of D but in
a key signature of G (D is a fifth above G).

                                       contents
-------------------------------------
                                
"melody ... /melody": musical note input in "abc" format:

For insertion of music description in abc format, we retain the 
historical .abc line oriented file format, but bracket
the abc text with a "melody" and a "/melody" line:
                                
melody [m-id]
T: Title
K:A  % key
 |   | ...  % here are the abc notation lines
 ....
/melody
                                
The optional melody identifier "m-id" is used for keeping 
track of different tunes so that medleys can be generated.
If "m-id" is not present, an identifier of the form "tune##" is
generated, with "##" in the range 01 to 99.

The "abc" data can be in a separate indirect file between brackets,
                                
melody
@indirect_abc_file  [n]
/melody
                                
or the indirect file can contain the bracketing lines (and other data). 
The optional number [n] serves to pick out the abc tune designated
by the index X:n in a file containing multiple tunes.
                                       contents 
----------------------
                                
Vamp sequences:

Vamping is a term out of the jazz lexicon which means to produce
a simple, typically improvised,  accompaniment to a melody.  There
is a characteristic "boom chick boom chick" sound for dance
accompaniment which comes from a unison chord on the beat and 
a triad chord on the offbeat.  For contra music, the dancers take 
a step on each "boom".  Peter Barnes has written a comprehensive 
discussion of basic vamping and variations in his book 
"Interview with a Vamper".

Typically the contents of one measure (two beats for reels and jigs, 
three for waltzes, etc.) of vamping accompaniment will be specified in 
slightly specialized abc lines containing a "macro" name followed by 
a measure of abc writing out the notes in the chords.  The macro name
provides a shorthand for designating the accompaniment in the "chords" 
command.
                                
vamp  [v-id] 
L:1/8
K:C
intro | [C] [z] [C] [z] | [C] [z] [C] [z] |
 c    | [C,,C,] [CEG] [G,,,G,,] [CEG]   |
 g    | [G,,G,] [GBD] [D,,D,]   [GBD]   |
 cg   | [C,,C,] [CEG] [G,,G,]   [GBD]   |   % c and g vamps combined
/vamp
                                
Typical vamp measures (cf. Peter Barnes' book, "Interview with a Vamper")
have unison chords in the first and third places and triads in the 
second and fourth.  E.g.
                                
c   | [C,,C,] [CEG] [G,,,G,,] [CEG] |
                                
The sequence "intro" is a mechanism to introduce pre-melody "potatoes"
and any lead-in notes to the melody (before the first "chorded" measure).
To be recognized it must be the first vamp "abc" line to be input.  However,
By using an "events" list, any designated vamp macro may be used as the 
introduction.

The designator "cg" for the combined C and G chords in one measure is
purely for mnemonic value: it could have been "x" or "whatever".

Although I have typically used a single vamp macro to correspond
to a single melody measure, the substitution is not so limited.
The length can be longer (c.f. "intro" above) or shorter.  The combined
"cg" above could have been coded as
                                
 C   | [C,,C,] [CEG] |   % half measure C vamp
 G   | [G,,G,] [GBD] |   % half measure G vamp
                                
 and entered on a chord line as "C G" rather than "cg".

It is the user's responsibility to include the proper number of 
notes in the right places so that the timing comes out as intended 
and synchronized between "melody" and "chords".  The total number
of measures and ticks is printed out after each generated MIDI
track;  these should be equal for all music tracks in a MIDI file.

                                       contents
--------------------
                                
Chords:

Chord sequences will be given in an abbreviated manner, and macro substitution
from the "vamp" information generates a MIDI track for chords.  The chord 
identifier "c-id" is used in an "events" list for medleys or for changing 
accompaniments for different repetitions of the melody.  If "c-id" is not 
present, an identifier of the form "chords##" is generated, with "##" 
in the range 01 to 99. 

No repeat structure is presently implemented for chords, so chords 
for repeat sequences must be explicitly stated.

If only one vamp name is given for each measure of the melody, multiple 
chords in a measure must be manually combined  as "cg" was above.  
Alternatively, shortened chords can be used as discussed above.
In the example below, the second and forth eight beat phrases produce 
identical chords.
                                
chords [c-id]
  c c g c   c c cg g     c c g c    c c C G g  ...
/chords
                                
                                       contents
------------------
                                
Volume and velocity:

Control of volume (related to MIDI velocity) can be employed
for a number of purposes: to distinguish beats within a phrase
with a hypermeter applied to chords (accent command), to accent
the beats in a melody (phrasing command), to vary the volume level
during repeats of a tune (_volume_ in event command), and to
emphasize particular beats or phrases in synchrony with dance
events (e.g. the balance before a swing by use of a phrase event).  

Mixing (relative loudness of instruments) is perhaps better 
handled by adjusting patch volumes (timidity.cfg) or by using stereo 
channels (pan in param command) and adjusting the balance on the amplifier.

In addition, volume changes on specific voices can be used as a switch
to pick out melody instruments (e.g. to mark alternate phrases by
changing instruments to affect timbre).  Chord rendition can be changed 
from the basic boom-chuck on a piano to a bass strum on the beat by modifying 
the accent to supress the triad on the offbeat.

Since these changes have different scopes (beat, phrase, tune repeat,
entire piece) and conceptually may be applied independently, some easy 
way to combine their effects is needed.  In many MIDI implementations,
velocity is proportional to the logarithm of the volume, which is 
consistent with our perception of volume where constant ratios of 
amplitude or power correspond to similar perceived changes at different 
absolute volume levels (c.f. decibels).  The default scaling in TiMidity 
takes about 21 velocity units to change the waveform amplitude by a 
factor of 2 (which gives a factor of 64, or 36 dB, change from 127 to 0).

Thus to increase the overall volume, all velocities would be incremented by 
the same amount.  Unfortunately, versions of TiMidity before 2.13.0 used a 
linear velocity conversion table; my velocity values were empirically derived, 
but did not work with additive changes.  An accent command which emphasizes
the hypermeter for chords in a phrase based on the linear relationship:

accent volume
 120  60  80  60   90  60  80  60    100  60  80  60   90  60  80  60
/accent 

is replaced with the following (based on logarithmic velocities):

accent velocity
 136 120 124 120  128 120 124 120    132 120 124 120  128 120 124 120  
/accent

in order to get the same final volumes.  Details of the numerical 
signal amplitudes are given in columns 1-3 in this table:

linear      linear      logarithmic   2 note    3 note chords
"velocity"  amplitude   velocity      (+11)       (+17)

120         0.9449        125          136              (effective log vel
100         0.7874        120          131               compensated for 
 90         0.7087        116          127               by chord_delta)
 80         0.6299        113          124
 60         0.4724        104                     121
 40         0.3150         92                     109
 
There is another complication, in that several independent notes 
sounded in a chord are louder than a single note at a given
volume (or velocity). The effective velocities for two and three note
chords are given in columns 4-5 above. The corrections shown below are 
now subtracted from the input velocity (which indicates the total
volume of the chord) to get velocities for the separate notes.

n    sqrt(n)   delta velocity (cf. def_vol_table[])
1    1.000         0.0
2    1.414        10.6
3    1.732        16.8
4    2.000        21.2
5    2.236        24.6
6    2.449        27.4
7    2.646        29.7

Thus a velocity greater than the MIDI limit of 127 may be input,
assuming that it will be decremented for mulitple notes;  any
velocity > 127 for a single note will be limited to 127 when the
MIDI file is generated.

Thus when playing the basic vamp of a two note unison followed by a
triad chord, we can replace the empirical linear volume accents:

 120  60  80  60   90  60  80  60    100  60  80  60   90  60  80  60

with the logarithmic set:

 136 120 124 120  128 120 124 120    132 120 124 120  128 120 124 120  

and get similar chord volumes with a new version of TiMidity.
The overall velocity of the new set can be reduced from fff (120)
to pp (24) with _volume_ events (an overall velocity decrement) and 
still retain the same volume relationships within the phrase. This 
was not possible when "velocities" had a linear relation to amplitude.

With other MIDI to .wav converters, some experimentation will be
required.  I have modified my TiMidity-2.11.3 to have logarithmic
velocities and expect the 2.13.0 or 2.13.1 distribution will
conform to this scheme by default (after a chorus bug correction).

Internally, VAMP uses logarithmic velocites to facilitate combining
velocities from different sources (emphasis, phrasing, accent).
The options command has a parameter, VEL_CURVE, which determines
the relationship of the MIDI file velocities to amplitude.  The
default is logarithmic [0], but quadratic [2] for the MS Media Player
and linear [1] (Timidity before 2.13) are available. 
                                       contents
------------------
                                
Feb. 2005:
Discuss interrelationship of mix, phrasing, accent, rubato...
to produce rhythm, riffs, and phrasing...

Note accents (phrasing):

Phrasing was first approached by specifying the MIDI velocity
(proportional to the logarithm of volume, see above discussion)
for at least the 16 chords in an 8 beat phrase.  Comparison of alternative
phrasing can be tried with information for several 8 beat phrases.
An accent identifer "a-id" is implemented for changes in the rhythmic 
structure in a MIDI file specifed with the "events"/"variations" command.  
If "a-id" is not present, an identifier of the form "accent##" is
generated, with "##" in the range 01 to 99.

An new syntax has been introduced for the "accent" data, supplementing
the older "isvvv" numbers.  Instrument changes are designated by "{i}",
where the number "i" refers to the MIDI instrument given in the i-th
place in the "instrument" command.  Velocity is still given by a number
"vvv", but the staccato is indicated by the number of leading periods
( consistent with the use of leading periods for staccato in "abc").
Thus "{2} 90" translates into "20090" and "..80" represents "2080".

[****************(June 10, 2004)
[ Note that the values given in the following examples are based
[ on velocities proportional to volume, not logarithmically related.
[
[ The empirical linear volume accents:
[   120  60  80  60   90  60  80  60    100 60  80  60   90  60  80  60
[ are related  (for a basic vamp) to the logarithmic set:
[   136 120 124 120  128 120 124 120   132 120 124 120  128 120 124 120  
[
[ The velocities associated with fff, ff, ... pp, ppp in the phrase command 
[ were assigned assuming logarthmic velocities.
[****************

                                
accent  [a-id]
 100 60 70 60  80 60 70 60    90 60 70 60  80 60 70 60   
/accent
                                
This plays the unison chords (onbeat) at varying and higher velocities
(100 70 80 70 90 70 80 70) than the triads (offbeat) at volume 60.
The specified sequence of accents is reused as needed.

The current limitation is 4096 accents. The numbers may have up to 5 decimal 
digits "isvvv".  The rightmost 3 digits (units, tens, hundreds "vvv") are the 
velocity (0-127),  the thousands digit "s" is the staccato multiplier to 
shorten a chord note by a given number of ticks = s*staccato.  Default 
staccato==0, and can be changed with a field in the "param" command.
The left most digit "i" is an index into the instrument list, allowing 
change of the rhythm instrument on demand or whim.

A more complicated example, alternating between piano and guitar
and shortening the triad chords:
                                
instrument 111 1 25   
           % melody: fiddle (111), accompaniment: piano (1) and guitar (25) 
parameter 5 10
accent  [a-id]
 20100 1060 70 1050  80 2060 70 2055   30090 1060 70 1060  80 3060 70 3055   
/accent

% new syntax
% {2} 100 .60 70 .50 80 ..60 70 ..55  {3} 90 .60 70 .60 80 ...60 70 ...55

                                
The 20000 in 20100 sets the instrument to piano for 8 chords after which
the 30000 in 30090 switches to guitar.  If the length of a chord note is
60 MIDI ticks (an eighth note), then 1060 plays at volume(velocity) 60
and for 60-1*10 == 50 ticks (followed by a 10 tick "rest"), 2055 plays
for 60-2*10 == 40 ticks at velocity 55, etc.

The default velocity for melody and intro is 104 (==ff: this can be set
with "mix_mel" and "mix_ch" in the "parameter" command).  Staccato shortening 
of a note is limited: at least 1/4 of the nominal duration will remain.

                                       contents
------------------
                                

The phrase command specifies the number of beats in a musical phrase and
also longer term volume changes. The simplest data specifies the number
of beats in a phrase, separated by semicolons:

                                
phrase  [phrase-id]
  8; 8; 16; 8; 8; 16;
/phrase
                                

Contra dance music usually has eight phrases of eight beats each, for a
total of 64 beats (or steps) for each repeat of the melody.  The example above
has all 64 beats, but could have been cut short at " 8; 8; 16; ", with
the pattern being re-used in a loop.
 
The number of beats in a phrase is used in harmony analysis and in placing
additional accents (down beat, up beat and off beat) on the general dynamic
contour specified by a more complicated phrase statement.

                                
phrase [phrase-id]
 f 8; < 4 > 4; < fff 4 > 12; mf 8; p 8; f 8 ff 8;
/phrase
                                

The standard symbols "fff  ff  f  mf  mp  p pp ppp" are used to designate MIDI
velocity levels of    120 104 88  72  56 40 24   8   respectively.  For other
values, the symbol "vnnn" can be used. where "nnn" denotes a decimal integer
between 0 and 127.   (NB, the upper limit has been removed to accommodate 
velocity adjustments for chords, but 127 is enforced for individual notes
when MIDI data is generated.)  The bracket symbols "<" and ">" indicate either 
an increment of 16 and and a decrement of 16 in the velocity level (when no other 
velocity symbol is given), or a change from the velocity level given (or implicit) 
before the symbol to that given afterwards.  The beat count specifies the period 
over which the velocity changes linearly.  Beat counts are summed until a ";" 
indicates the end of a phrase.  

In the example above, 8 beats occur at forte, then the level increases to 
ff in 4 beats, decreases back to f in 4 beats (the end of the second phrase.  
In the third (16 beat) phrase, the velocity changes from f to fff in 4 beats, 
then back to ff in 12 beats.  In the second 32 beats, the velocity level  
changes stepwise in 8 beat sections, mf to p to f to fff.

If one wants the ramped change to extend over more than one phrase, a negative
number can be used to adjust the beat count.  E.g. if one had wanted the
"< fff 4 > 12 ;" to span two eight beat phrases, it could have been written
"< fff 4 > 12 - 8; 8;" 

The note durations in melody are not as regular as in the chord accompaniment.
The general dynamic contour is computed on each beat from the information above.
Then the MIDI generation routine tracks the notes in the melody and decides
whether they start on the down beat (beats 1, 3, 5, 7 ... in the phrase), 
the up beat  (beats 2, 4, 6, 8, ...) or in between on the off beat.  
A velocity increment (or decrement) will be combined with the contour level
(defaults +8 for down beat, 0 for up beat, -8 for off beat; which follows
 the general scheme used for chord accents).

The delta values for a down beat, up beat, and off beat may be changed
by entering three values in square brackets on a separate line in a
"phrase" command [default values are 0 0 0]:

                                
phrase [phrase-id]
 [ 4 0 -4 ]
% ... other phrase data ...
/phrase
                                

                                       contents
-----------------------------
                                
                                
rubato [rubato-id]
  ticks shift duration1 delay1 dur2 delay2 ....
/rubato
                                

Rubato is the changing of note duration locally while still maintaining
strict meter on the larger time scale of beat or measure.  Any time
added to one note must be given back soon so that the regular pulse
required by the metric tempo is preserved.  Rubato can be used to
implement synchopation and swing.  The duration of a note in the
input "abc" format corresponds to the sum of duration-n and delay-n
in this command, so that delay corresponds to the staccato parameter.

The initial "ticks" normally corresponds to the number of ticks in
the default "abc" note (given in an L: line); then each duration+delay
pair maps metric time onto actual MIDI playing time.  In the case of
longer or shorter input notes, summing or interpolation is performed.
When both accent and rubato are active for a melodic repeat, the
accent pointer is incremented for each duration of length "ticks",
rather than for each note or chord.  A note receives the accent 
corresponding to the accent pointer when the note begins, even if
the accent value changes during a note.

"shift" allows one to offset the initial note from the metronomic
position, either delay (>0) or anticipation (<0).  The usual choice
would be no shift [0].

Normally delays will be positive, corresponding to a staccato shortening
of a note.  However, a series of negative delays can be used for 
special effects, such as an arpeggiated guitar chord.

--- need examples ---
                                       contents
-----------------------------
                                

Events/variations ...  

The repeat command will be supplemented or replaced by an event list which
can specify when tunes change, chords change, instruments change, etc.
An optional voice specifier may be used for more than two parts.

% events
% time   event-id  [voice]
% time   _special_action_ [data] 
%/events
                                
events  
r:m:t   melody-id [ or chord-id or accent-id or phrase-id or vamp_name(for intro)]
r:m:t   _volume_  vel (int)  [to set the relative master velocity(volume)]
r:m:t   _tempo_ bpm (float)  [to change tempo between repeats]
r:m:t   _end_  [defaults to last given r]
/events
                                
The time designator r:m:t specifies which repeat (r == (-1) 0 1 ... n),
which measure (m) in that repeat, and which tick (t) in the measure.
"r" will be mandatory, m and t will default to -1. Note that r,m, and t
are integers and there are no spaces between them and the separating ":".
Initial implementation is granular at the "r" level, ignoring m and t.
[ Synchronization between voices is the responsibity of the user.
[ The program generates the amount of music specified without checking
[ whether melody length matches chord length for each repeat...
[ This freedom allows some special effects, but can be disasterous
[ if mistakes are made.
[ The user should check the number of ticks generated per track.

After a melody-id, chord-id, accent-id, or phrase-id, an optional
voice number may be given (in the range 1 ... 16).  Melodies and phrases
default to 1, chords and accents default to 2. The voice number maps
directly onto the instrument list (and the MIDI channel (+1)).
The special action commands "_volume_", "_tempo_", and "_end_" act 
on every voice.
                       [ examples .... ? ]
Current intent is that full measures in a melody will be 1 ... 32
and measure 0 is for set-up events (e.g. instrument changes)
before the tune starts and for lead-in notes, etc.  The "intro"
sequence will come at r== (-1).

A phrase chunk introduced at r==0 with voice 0 will be used to 
impart overall dynamics (e.g. emphasis of a balance before a swing)
for all voices and all repeats.  It will be referenced to its median
velocity and used as differences.

Event information is sorted as it is input so that a parallel scan
of the events can be made as one loops the repeats, taking all
events with the same 'r' value as initializers for repeat 'r'
( e.g. tempo or accent change, melody or chord change ). 

The syntax and format of an "event" command is somewhat
tedious.  As an example consider 4 repeats of the tune
Lamplighters hornpipe (lamp):
                                
@lamp.in               % read definitions of melody, chords, etc.
instruments 111 72 1   % fiddle, clarinet, piano
events
 -1 potatoes           % conventional intro for dance
  1 lamp      1        % melody on fiddle   [voice 1]
  1 lamp      2        % melody on clarinet [voice 2]
  1 best      3        % chords on piano    [voice 3]
  1 odd       1        % play phrase 1, 3, 5, 7 on fiddle
  1 even      2        % play phrase 2, 4, 6, 8 on clarinet
  1 boomchuck 3        % accent (hypermeter) for piano
  2 half      3        % another set of chords (half measures)
  3 root      3        % chords prefered by harmony 55
  4 last      3        % modify chords for coda at end
/events
                                
A perl script, "dyn" has been written to translate a more compact 
specification into an events list.  This syntax has now been
incorporated directly into VAMP.  

The above "events" list can now be generated by the statements:
                                
/events
-1 potatoes
melody lamp
 fiddle odd
 clarinet even
chords best half root last
 piano boomchuck
/events
                                
Note that lines in the old syntax (line beginning with a numeric time) 
may be intermingled.

In this example, the fiddle and clarinet play alternate 
phrases in the melody; this is coded in the phrasing commands
"odd" and "even".  Four different (but similar) chord sequences
"best", "half", "root", and "last" are used.

The repeat number is deduced from the position in the list.
 (Presently, an explicitly repeated element determines the total
  number of repeats (i.e. "last" above or an "_end_") when "vamp" 
  generates a MIDI file from the events list.)

The voice number is assigned by the order of the appearance of
 of the instrument line ('iname').

The general format of the this condensed input is:

 "topic word"  "list with optional repeat counts [rep]".

dynamics 'velocity1' [rep] 'velocity2' [rep] ...
melody    melody-id [rep] ...
  'iname' phrase-id [rep] ...
chords    chord-id1 [rep] chord-id2 [rep] ...
  'iname' accent-id [rep] ...

The optional repeat count [rep] has a default value of 1.
If more than one repetition of a list item is desired, it may
be followed by a number giving the total number of repeats
(c.f. "dynamics" below).  The last item is implicitly repeated
until the end of the piece (e.g. "melody lamp" and "melody lamp 4"
would be equivalent in this example which has 4 chord sequences).

The topic words "melody", "chords", and "dynamics" serve to introduce
lists of melodies, chords, and volume levels which change at a
time granularity of a tune repeat.

'iname' is an instrument name (piano, fiddle, guitar, bass, sax, clarinet,
           recorder, banjo, dulcimer are recognized) or the phrase
        "instrument n", with n being a MIDI instrument number.

The instruments following a "melody" line play the designated
melodies, with phrasing specified by the list of phrase-id's.

The instruments following a "chords" line play the designated
chord sequences, with accents specified by the list of accent-id's.

Multiple "chords" lines are possible, if the chords vary by instrument.
It is hard to see why one would want multiple melodies (except perhaps
to transpose for a given instrument), but one might want a medley 
(with several melody-id's given in the "melody" line).

The instruments are assigned to voices in the order of their
appearance, and replace the instrument list as if an explicit
"INSTRUMENT" command had been given.

To change the overall volume as the tune is repeated, a
"dynamics" line may be used.

'Volume' levels use the "fff ff ... ppp" symbols, as introduced 
in the "phrase" command.  The general "vnnn" designator is available.
N.B. the repeat count syntax differs slightly from the phrase beat
syntax of the "phrase" command where no implicit beats are assumed.

Adding a line to the above input:
                                
dynamics f 2 mf ff
                                
would intercalate these velocity/volume commands into the events list:
                                
  1 _volume_   88
  3 _volume_   72
  4 _volume_  104
                                
             -------------------------------

The initial implementation is limited to changes at the repeat boundaries. 

[ (035.17) Translation from r:m:t to ticks from the beginning is
[ problematical since the number of measures in the intro, or in the
[ melody is not fixed.  Moreover if a medley mixes a reel and a jig,
[ changing the tempo and ticks/measure, this info will have to be
[ recorded for each melody and chord sequence...
[
[ Limitations imposed by note start and stop times  make fine grained 
[ special events imprecise and difficult to properly program. 
[
[ (043.01) May consider converting r:m:t to r:b specification...
[ with granularity to the nearest beat, using pedometer() to track.


                                       contents
---------------------
                                
                                
generate n file.out     %  determine output according to "n" 

generate filename       %  use event list to specify output
                                

Generate the designated MIDI file and spawn Timidity to play it unless
"verbose"<0 in the "xtra" command or one is running in Windows. 
The digit n (0,1,2) specifies melody only (0), chords only (1) or both (2).
Presently melody and chords are generated as separate tracks (with option 2).
The file name is arbitrary and does not have to have the extension ".midi" .

If an introductory sequence ("potatoes" lead in notes) is specified as 
a vamp line named "intro" or with the "events/variations" command,
it will be generated before either the melody or chords (i.e. for each voice).

The old-style "gen [012] filename" command operates on the last input
melody, chords, or accent.  The event command is intended to give 
finer and more versatile control of this process by specifying 
melodies, chords and accents with their identifying strings.

[ Synchronization between voices is the responsibity of the user.
[ The program generates the amount of music specified without checking
[ whether melody length matches accompaniment length for each repeat...
[ This freedom allows some special effects, but can be disasterous
[ if mistakes are made (e.g. a chord symbol left undefined).
[ The user should check the number of ticks and measures generated per track.

                                       contents
----------------------------
An as yet incompletely specified set of commands will be used to specify and 
modify repeated instances of the basic 64 beat dance tune.  At minimum, I want
control over instrumentation, tempo, number of repetitions, and output file 
name.  Probably also need comment field specifiers....

-----
                                
                                
instruments  i j k ...   % blank separated list
                                
  Instrument numbers are the correct external MIDI range [1-128]; internally,
one is subtracted to give the byte value for program change.  A command
"instrument 0 " using the number "0" (which is not a valid MIDI instrument) 
suppresses the MIDI "program-change" command for that voice, so that the
timidity option "-I n" can be used to select an instrument when playing.
Present convention is that the first number is the melody instrument,
the second is the default vamp/chord instrument, and the others can be 
designated by the "i" digit in a number in the "accent" command, or used
by additional voices in an "events" command.

Now that voices can be designated in the "event" command, positions in the
instrument list correspond directly to the voice and the MIDI channel
(the first number is the instrument for voice 1 (and channel 0), the 
second for voice 2 (and channel 1), and so on).  Instrument change 
("accent" command) is accomplished by changing the MIDI channel within
a MIDI track.

[ Need to check out percussion ]

---
                                
                                
tempo bpm(float) [ ticks_per_quarter_note ] 
                                
Gives the tempo in beats per minute (can be decimal fraction such as 124.2),
and MIDI ticks per quarter note.  Ticks_per_quarter_note [default 120] 
should be  given only once per session, before any abc sequences are 
input, since it determines the internal duration of notes in the database.

  N.B. This replaces the "abc" information field "Q:  "  which is ignored.

-----
                                
                                
repeat n
                                
Where n gives the number of times a tune is played.  This affects the
"gen [012]" commands only.  For a "gen" command, the number of repeats
is determined from the "events" list.

                                       contents
---------------------------
                                
There are now three commands to enter "global" parameters which affect
some aspects of MIDI generation.  The exact nature of the parameters
and their positions in the commands is somewhat fluid, thus occasionally
obsoleting old input files.  It is hoped to rationalize and systematize
these, along with introducing a "style" command which will specify
things like mixing volume, staccato, panning, slur and chop behavior,
arpeggiation of chords (e.g. for guitar), and transposition on an
instrument by instrument or voice by voice basis. 

                                
parameters  stac_m  stac_c  vel_m  vel_c  pan_m  pan_c
                                
Specifies staccato (note shortening) in ticks for melody (stac_m)
and chords (stac_c).  All melody notes are shortened, only those marked
in the accent list will be shorted for chords (see discussion in
the section on "accent" above). 

Only as many numbers as given will change the variables. A "param" with
no numbers simply prints out the present values.

[  Overall velocity for melody (vel_m), and chords (vel_c) can be given.  
[  An explicit "B chan 7 vel" may override the -A option in timidity,
[  so I will experiment with offsets in the midi generation.
[  vel_m sets the melody velocity in the absence of detailed information
[  from a phrase command.  Normally chord velocities are set with
[  an accent command and vel_c is used for the introductory potatoes.

[  Pan gives a mechanism to locate the voices (melody 0, chords 1,2,..)
[  in either left or right speakers.  Need to experiment with this.
[  035.08  timidity may only allow left, right, center [+mystery???]]


---------------------
                                
xtra  verbose blur TESTA  TESTB  transpose_m transpose_c
                                
A catchall command for new parameter entry.

  "Verbose" controls the level of debug printout [default 1].
If "verbose" is entered as a negative number, the immediate playing
of the MIDI file by spawning Timidity is supressed.  Debug printout is
now limited to modules by the verbosity class (ten's digit), and the unit's
digit (0, 1, ... 9) controls the amount of printout as before (see source).

  "Blur" gives the number of milliseconds of imprecision for note starts and 
stops relative to the exact metronome [ default 0, usable range up to 20 or so ].
Adding a flag in the hundreds place selects some experimental options:
+000: blur every note, +100: don't blur first note in phrase, +200: positive blur
to melody notes only (leads chords), +300: negative blur (melody lags chords). 

  "TESTA" and "TESTB" are globally defined variables accessible from all 
source modules and used for experimental purposes. 

(046.10: TESTA is used to scale the delta_velocity for chord notes.
          default is 8 which gives 0 -11 -17 ... ; 
          0 results in no decrement (the previous behavior)       )



  "transpose_m" and "transpose_c" specify transposition of melody or chords by 
the given number of half steps [12 is up an octave, -12 is down an octave, 
7 is up a fifth, etc. ]

---------------------
                                
options  VERBOSE slur chop VEL_CURVE
                                
The options command is planned for program states which are less
related to MIDI concerns.  VERBOSE will migrate from "xtra".

  "Verbose" controls the level of debug printout [default 1].
If "verbose" is entered as a negative number, the immediate playing
of the MIDI file by spawning Timidity is supressed.  Debug printout is
now limited to modules by the verbosity class (ten's digit), and the unit's
digit (0, 1, ... 9) controls the amount of printout as before (see source).

The parameter VEL_CURVE determines the relationship of the internal 
logarithmic velocities to the output MIDI file velocities.  The
default is logarithmic [0], but quadratic [2] for the MS Media Player,
and linear [1] (old Timidity) are available. 

"slur" governs the number of ticks for the change between note center
pitches.  This is useful for string instruments.  A choice of 2 works
ok for 120 ticks/quarternote at 120 beats per minute.  Disabled by
default [value 0].

"chop" specifies the number of ticks to sharply attenuate the sound
amplitude at the end of a note; this better imitates strings and
woodwinds than the long decay used in Timidity by default [which
is great for piano or guitar with independent strings for each note].
Default is 0 [no chop], a value of 4 works ok.

 fiddle discussion 

---------------------
                                
style instrument[or voice?] slur chop arpeg ... ? .. stac mix pan transpose ...
                                
"Style" is not yet implemented (as of 24 Feb 2005), but is needed
along with the multivoice nature of the event command so that behavior
of different melodic or backup voices can be independently controlled
rather than relying on the more global nature of the commands
"parameter", "xtra", and "options" which were designed earlier when only
two voices (melody and chords) were envisioned.

                                       contents
----------------------------
                                
Harmony analysis, expanded syntax:
                                
harmony [?] [details,nodetails] [log] [interactive] 
        [guitar] [#number#] 
        [restrict] [all,accented,bounding] [measure,half] 
        [center] [phrase,entire] 
        [statistics] 
                                
One problem with traditional melodies is that they usually do not have 
any chords specified.  These harmony analysis tools attempt to provide 
some guidance in the assignment of chords (and achieve something like 
70 to 80% agreement with human selections), but the ultimate test is 
musical acceptability.

As a result of collaboration with Matt Kaufmann, detailed rules
for chord preferences have been implemented.  For more discussion
click on the following links:

detailed discussion
    guide to keywords
    weights and preferences
    example(guitar)
    example(old scheme)


                                       contents
----------------
                                
Loop oriented experiments:
  (A separate command container with options to investigate MIDI behavior.) 
   
[ ---- this section needs more work ---- ]

The "loops" command is useful for studying the characteristics of the 
MIDI commands and options, such as playing a short tune on all possible 
instruments, or at many different volume (velocity) levels.  

Presently loop options are single letters only.  The basically line oriented 
loop options are bracketed in a container "loops" .... "/loops":
                                
loops   
%  a simple loop example to play the tune in r,t,v for instruments i
i ...    % instrument (list or "for-loop")
r ...    % rhythm  (duration of tones in ticks)
t ...    % MIDI numeric tones
v ...    % numeric velocites
g        % generate
%          currently the r and t lines must have the same number of elements
/loops


 @loops_file      % given as an indirect file
                                

More details about input options between ("loops ... /loops"):


? help:   print this list
# comment: gives text which goes to output file
% comment: ignore text to end of line (abc convention)
r rhythm (sequence of note lengths in MIDI ticks)
t tone (MIDI note is this value + key base)
v velocity/volume for r/t sequence (add 2000 or 1000 for accent)
  numbers are a space separated list e.g.  12 20 1 3
          or 'for' parameters: '=' start end incr
i instruments (1-128 are general MIDI, 135-181 map to 35-81 in the drum bank)
a accent used if velocity has +2000, +1000
g [file]:  generate MIDI file
p play [current]/n/sequence
k key: base notes [default 0] added to tune values
o order of looping [default: r l a i ]
l loop repetitions [lid] [default: 1]
c (MIDI) code_insert: lid c1 c2 ... cn (unimplemented)
d dump lists (unimplemented)

Numbers for i,r,t,v,a,k,l can be given as a blank separated list
(e.g.  1 3 2 6) , or as a for-loop designator (e.g. = 0 6 2 which
translates to (for j=0; j<6; j += 2)  ). 


Sample "loops" input:
                                
# play C E G  c  on piano, fiddle
# observe that some notes have velocity 0 and do not sound
loops
i 1 111   % piano, fiddle
r 120 120 120 120 120 120 120 120 360
t  60  62  64  65  67  69  71  72  60
v  90   0  90   0  90   0   0  90   0
g  loop.midi
/loops
loop
# play C E G on  every fourth instrument
o  r i     % change nesting of loops
i =1 127 4
r 120 120 120 120 120 120 120
t  60  62  64  65  67  69  71
v  90   0  90   0  90   0   0
g  instrum.midi
/loop
# play one note on each drum: 35 thru 81
loop
  i =135 181 1
r 120 120
t  60  62
v  90   0
g  drums.midi
/loop
quit   %  with esound daemon, all three files play at once
                                

                                       contents
                                
-------------------

TIPS on using TiMidity++ (tested on versions 2.10, 2.11.3)

    It turns out that the exact choice of velocity levels depends on the
transformation of velocity to volume used by the MIDI player.  Versions of
TiMidity before 13.0 used a linear table (I had supposed it to be logarithmic)
and implicitly a linear table for chorus voices.  As of June 6, 2004,
the chorus routines in playmidi.c were not correct in 2.13.0 either 
(bug report submitted).

I am using a personally corrected version 2.11.3 to produce my second demo CD.


Useful command line options:  (see timidity man page for fuller discussion)

-A volume          percent change of volume level  <=800, >= 0

-T tempo           percent change of tempo  ( <100 slower, >100 faster)

-I n-1             change program to MIDI instrument n 
                   (where instrument 0 was specified in vamp.  
                    format changes in version 2.13.0)

-c file.cfg        additional patch/soundfont configuration information
                   (supercedes contents of /etc/timidity.cfg  or 
                                      /usr/local/share/timidity/timidity.cfg )

-idv,-idvv,-idvvv  debug printout at variable verbosity
 
-s rate            samples per second (set to 44100 for making CD's)

-Ow -o wav.out     make .wav output file  (default stereo)

-OwM -o file       monophonic output (smaller file, works with play, scope)

-EFchorus=0        turns off chorus effect (makes 2-13.0 logarithmic)

--------------------------------------( cf vamp folder 029.13-4reverse)
Making .wav files with timidity:
 
timidity -A 200 -s 44100 -Ow -o out.wav in.midi
 
-A (amplitude 0 - 800 % ) 200 == x2.0
-s 44100   44k1 samples/second 
          (stereo is default, gets CD wav file immediately)
          [order of this option may not be correct]
-Ow  [ make Microsoft RIFF .wav file output ]
-o  out.wav   [specify output file]
 
- - - - - -
 
sox in.wav -r 44100 out.wav
 
 
convert in.wav to 44100 samples/sec for standard CD tracks.
 
-------------------------------(032.09)
Recipe to circumvent esound default on havasu (works on sbigraf)

timidity [-A 200] -B 8,12 -Od -s 48000  file.midi
 
-Od uses /dev/dsp rather than esd.. (see timidity -h, not on man page)
-B 8,12 to forstall crash with float overflow/exception on havasu
-s 48000  default is 32000 which causes warning on havasu
 
will put this in midivamp for spawn.
 
-------------------
consider using ogg-vorbis for compression [ogg123, oggenc] 
since mp3 is proprietary.

                                       contents
-------------------

Acknowledgements

I am grateful to a number of musicians who have tolerated "dumb"
questions and educated me while I developed this program.
Among them are Matt Kaufmann, Ann Winget, Lee Couch, Roy Wilhite,
Max Cappleman, Susan Barnes, Carrie Eskenazi, Holly Bell, Mimi Rogers,
and Allison Hicks.  
I also appreciate the feedback from people who have listened to various 
versions of the tunes generated by the program, especially Rosemarie Swanson.

                                

    Copyright 2002-2005, Stanley M. Swanson.
      12 Sept. 2002; revised 24 Dec. 2002, 10 Feb. 2003, 17 May 2003,
                     31 July 2003, 8 Aug 2003, 1 Mar. 2004, 17 Apr. 2004,
		     10 May 2004, 10 June 2004, 14 July 2004, 24 Feb 2005

    This information is distributed under the terms of the 
    GNU Free Documentation License (with no invariant sections and no
    cover requirements).  The accompanying program, VAMP,
    is distributed under the terms of the GNU General Public License,
    version 2 or later (GPL v2).
    NO WARANTEES are made for either the documentation or the software.
    For the full text of the licenses, refer to the Free Software Foundation,
     GNU licenses