SBaGen - Sequenced BinAural Generator
-------------------------------------

This is a utility, released under the GPL (see the file COPYING), that
generates pink noise and binaural tones through your soundcard in
real-time according to a 24-hour programmed sequence read from a file.
It can also be used to play a sequence immediately, rather than
according to the clock, or even a combination of the two.

The original idea was to program a set of tones to play overnight as I
slept, hoping to improve dreaming, and dream-recall.  This way, I can
also program a sequence to bring me up into alpha rhythms to hopefully
have a good start to the day.  I'm still experimenting with all of
this, by the way.

Some of the more interesting uses (for me) of binaural tones I've read
about include: improving dream-recall, entering lucid dreaming,
facilitating meditation, accessing intuition, exploring consciousness.

USE AND EXPERIMENT AT YOUR OWN RISK !

If you make any changes or improvements to the code, let me know so
that I can keep a master copy of all the best bits.  Also, if you come
up with any interesting tone-sets or sequences that you would like to
share, along with their story, let me know or post them on the mailing
list (see http://sbagen.sf.net/).  I'm considering collecting people's
experiences together onto the site, if there is enough interest.

Jim Peters, Jan 1999                                     <jim@uazu.net>
 (updated Sept 2001)                      <http://www.uazu.net/sbagen/>



Theory
------

The basic idea of binaural beats is that by applying slightly
different frequency sine waves to each ear, a beating affect is
created in the mind itself, due to the internal wiring of the brain.
If, in the presence of these tones, you relax and let your mind go,
your mind will naturally synchronize with the beat frequency.  In this
way it is possible to accurately get into various brain-states, once
you know what the frequencies are.

It is also possible to play several different tones together, giving
several different beat frequencies, and programming quite a complex
brain-state based on several frequencies (in several different bands).
These complex mixtures of frequencies are the basis of the Hemi-Sync
(TM) process from the Monroe Institute <http://www.monroeinstitute.org>.

For the complete theory of binaural beats and how they affect the
mind, it's best to see the Monroe Institute site, particularly the
pages at <http://www.monroeinstitute.org/programs/hemi-sync.html>.  I
know little more about binaural beats than what is explained in these
pages, so take a look.

I am just starting to experiment with this stuff, and I wrote this
utility to help me set up sounds and sequences to experiment on
myself.  If you want to experiment with this, feel free to use my
utility, but don't blame me if you program it wrong and lose your job
because you were chilling comfortably in Theta until 11:00am and then
missed a vital meeting at work, or something like that.

You know what I'm saying - USE AT YOUR OWN RISK !  If a little bit of
fun/risk puts you off, I believe that The Monroe Institute sells pre-
packaged tapes (although I've never tried them).

Some more theory.  The oscillations in the brain are split into four
`bands' according to frequency:

Delta (0.5 to 4 Hz).  This is normally generated in deep sleep, or
when unconsious.  Those experienced in deep trance states can generate
these waves whilst remaining conscious.

Theta (4 to 8 Hz).  This is the region between sleep and wakefulness,
in which *dreaming* and other dream-like (or `hypnagogic') experiences
occur.  It's that bit just before you actually fall asleep at night,
or just before you are really awake in the morning.  They say it's in
this band that the unconscious talks to the conscious mind.  It also
seems to be connected with psychic or ESP-type functioning.

Alpha (8 to 13 Hz).  This is produced when you are awake and fully
conscious, but with your awareness focussed inside, such as when
trying to remember something, or when your eyes are closed.

Beta (13 to 30 Hz).  This is normally generated when you are awake,
with the attention focussed outside, dealing with the outside world.
It is also generated when you are solving logical problems, such as
mental arithmetic.

It is interesting to note that in normal dreams, a combination of
Theta, Alpha and Beta waves are produced, just as if the person was
awake.

Anyway, it looks like Theta is the place to be, connected with all
kinds of ESP functioning, such as direct `knowing', and other such
stuff.  I'm sure I've been there many times, but I'm looking to
explore this area much further now using this utility.

References:

My source for a lot of the information on brain waves is the book:
"How to build a lie detector, brain wave monitor and other secret
parapsychological electronics projects" by Mike and Ruth Wolverton,
TAB books, 1981.

I became interested in The Monroe Institute and their activities
through the writings of Ken Eagle Feather, and from attending one
course of his.  He talks briefly about Hemi-Sync (TM) in "Tracking
Freedom", mentioning some of the `Focus Levels' (tone-sets) discovered
by the Monroe Institute, which include ones related to out-of-body
experiences and even `other worlds'.  I believe he also talks about
some of his experiences on Monroe Institute workshops in his first
book "Travelling with Power", although I've not read it (yet).



Building the utility
--------------------

Windows users don't need to build anything - sbagen.exe is pre-built
for you, so skip ahead to `invocation' below.

The Linux executable can be built using the little `mk' script:

  ./mk

The `mk' script assumes GCC on Linux-i386.  If you're using something
else, please check it and adjust it as necessary.  There is also a
script `mk-ansi' which strips out non-ANSI C stuff before compiling,
which may work if you don't have GCC.  The other `mk-*' scripts cover
other possibilities - see the comments in the files for more details.

At the moment the code handles output to a stereo /dev/dsp device
using either 16-bit signed or 8-bit unsigned samples.  Hopefully this
covers almost everybody's sound card, but if you have something else,
you will either have to modify the code yourself, or suggest
modifications to me.  You can also output to a file, or to standard
output, if you wish - see below.

Note that on low-spec machines, any heavy jobs running may take CPU
time away from the sound-generation, and cause gaps in the output.
You could try adjusting priorities with nice and renice to improve the
situation.

On my old Pentium-75, I could generate 16-bit 44100Hz output on all 8
channels, and still only use 66% CPU-time, so even with very old
machines, you should be able to get some output, even if this means
lowering the output rate using the -r option.

Once built, on UNIX you can test the utility quickly using some of the
t-* scripts which generate various different tone-sets.



Invocation
----------

One quick thing to note before we start - whether you play these
binaural beats through headphones (as recommended by the Monroe
Institute), or through speakers (as I've been using them), play them
relatively quietly.  From my experience I can say that playing them
too loud doesn't improve the effect at all - it just gives me a
headache.

So, here we go.  Windows users will need to fire up a DOS Prompt and
CD to the directory in which SBaGen was unzipped.  The following
example commands should be typed at the prompt.

>> sbagen

This gives the usage information, showing the version number and the
full list of options.  Check this for any new features.
 
>> sbagen prog-1

This runs the sequence in file `prog-1', starting playing whatever
should be playing at the current moment, according to the clock time.
The status-line at the bottom of the screen shows the current time,
and currently-playing tones/noise.  The two lines immediately above
show the period of the sequence which is being played - these lines
scroll up the screen as one period moves into the next.

For Windows users, the utility can be stopped by pressing Ctrl-C.
This works for UNIX too, naturally - it's just that UNIX users mostly
already know about this !

To test a sequence (without waiting the full 24 hours for it to play
through), run with the -q option:

>> sbagen -q 480 prog-1

This example runs the sequence at 480 times the normal speed.  This is
quite useful to check that a new sequence is going to do what you
expect it to do.

To check that SBaGen has interpreted your sequence-file correctly, use
the -D option, which dumps a listing of the interpreted sequence
instead of playing it:

>> sbagen -D prog-1

To quickly test a particular tone-set continuously, use the -i
immediate option:

>> sbagen -i pink/40 100+1.5/20 200-4/36 400+8/2

This incidentally, is an example of a complex brain-state built from
pink noise, to which is added three frequencies (1.5Hz, 4Hz and 8Hz)
each on an independant carrier (100, 200 and 400 Hz), at different
amplitudes (20, 36 and 2).  This combination is supposedly something
like "body-asleep, brain-awake", assuming I've reproduced it
correctly.

While you're at it, try the alternate `spin' effect.  Not everyone
likes this, but in any case it's there if you want to use it:

>> sbagen -i spin:300+4.2/80

If you're having trouble with your soundcard or CPU usage, use the -r
option to run at a lower output rate.  The tones still come out really
well even at 8000Hz, on my sound card at least, although the noise
suffers.  For example:

>> sbagen -r 8000 -i pink/40 100+1.5/20 200+6/30

If your sound card doesn't support 16-bit output, you'll need to use
the -b option to select 8-bit output, for example:

>> sbagen -b 8 -i pink/40 100+1.5/20 200+6/30

For UNIX, you'll find that all the executable tone-set scripts (t-*)
accept additional options and pass them onto SBaGen, so you can use
the same options with these as well.  Try out some of these scripts to
get an idea of some of the possibilities.

For Windows, the tone-set files (t-*) are still useful - read them
using EDIT or NotePad or something.  You should be able to pick out
the tone-sets to try out using `sbagen -i ...'.

For both UNIX and Windows, the sequence files (prog-*) can be used in
the same way:

>> sbagen prog-whatever

Have a play with these sequences.  Many of them are designed to run at
night.  You can play them immediately using `-q 1':

>> sbagen -q 1 prog-whatever



Outputting to a pipe or a file
------------------------------

You don't need to read this section if you will only be outputting
directly to the soundcard. 

If you wish to pipe output on to some other utility, use the -O
option.  When this is used, the real time is no longer checked, so you
can output to both real-time devices (such as a mixer daemon), or to a
file or effect utility.  It is assumed that the eventual output device
will use exactly the frequency specified, or otherwise all the
frequencies and timings will be out.

The -o option can also be used to output directly to a file.  In both
cases headerless raw data is output (to write a WAV file, see the -W
option below).  For example, to pipe to bplay under UNIX, you could
use the following:

>> sbagen -r 8000 -O -i 100+0.92/30 200+4.2/15 | bplay -S -s 8000 -b 16

The -L option allows a time-limit to be set on the output.  So, for
example, to output 45 minutes of data to a file, and then play it with
bplay, use:

>> sbagen -r 8000 -o out.raw -L 0:45 -i 100+0.92/30 200+4.2/15
>> bplay -S -s 8000 -b 16 out.raw

As an alternative to using -L, it is possible to use -S and -E to
indicate that the output starts at the start of the sequence file
rather than the real time (-S), and/or ends at the end of the sequence
file rather than going on forever (-E).

A WAV file can be output if one of these options is used (-L or -S/-E)
using the -W option.  This is used in conjunction with -o or -O.
Repeating the examples above using WAV files, we have:

>> sbagen -r 8000 -WO -L 1:00 -i 100+0.92/30 200+4.2/15 | bplay

and:

>> sbagen -r 8000 -Wo out.wav -L 0:45 -i 100+0.92/30 200+4.2/15
>> bplay out.wav

The -Q option may be useful to turn off the information that the
utility normally writes to the screen.

If you are using another utility (perl or whatever) to generate the
sequence-file, you can pipe it directly to the utility, and use `-' as
the filename.  For example:

>> cat prog-1 | sbagen -

For those pushing the utility past its design limits, you may wish to
use the following options: 

`-R rate' specifies the rate at which the sound parameters are
recalculated in Hz, the default being 10Hz.  10Hz is fine for a slide
that takes a minute, but if you are doing quick (1 sec) fades in and
out, you'll need a faster refresh to avoid clicks.

`-F fade_interval' specifies the time in ms over which a fade in or
out takes place.  This is normally one minute (60000ms), which is fine
for slowly changing tone-sets, but you may wish to adjust this value
according to your needs.



Sequence-file format
--------------------

This section describes the format of the sequence files (the prog-*
files, for example).  You'll need this if you want to modify these
files, or create your own sequences.  For Windows users, you can edit
these files using EDIT or NotePad (or any simple text editor).

Within the sequence file, blank lines, and any leading/trailing white
space are ignored.  Comments are introduced with a `#', and extend to
the end of the line.

There are several types of entries that may appear in the file:

  * Tone-set definition lines
  * Time-sequence lines
  * Block definition lines

These are described below.  The example sequence-files (prog-*) are
useful to see how all these work together.

* The tone-set definition line.  This takes the form of:

    <name>: <tone-spec> <tone-spec> ...

  Examples:

    theta6: pink/40 150+6/30
    test10: pink/40 100+1.5/30 200-4/27 400+8/1.5
    all-off: -

  The name starts with a letter, and may continue with letters,
  numbers, `_' or `-'.  Following the colon is a list of one or more
  tone-specifications.  There are a maximum of 8 of these.  There are
  five types:

      -					# Channel not in use
      pink/<amp>			# Pink noise
      <carrier><sign><freq>/<amp>	# Binaural tones
      bell+<freq>/<amp>                 # Bell sound
      spin:<width>+<freq>/<amp>		# Spinning phase shifted pink noise
      wave<num>:<carrier><sign><freq>/<amp> 	# Binaural tones using a user- 
						# defined waveform (see later)

  The amplitudes are expressed on a scale 0-100.  The total of all the
  amplitudes <amp> in a tone-set should not exceed 100, or else there
  will be distortion on output as the waveforms are clipped.

  The pink noise is probably not 100% pure pink noise - but it is
  fairly pink, with everything from rumbling to hissing, and it
  doesn't have too many noticeable distractions such as repeating
  cycles or distant melodies or whatever.  If you listen really hard,
  though, you may be able to hear the fairies playing by the
  waterfall.

  The binaural tones are based on a carrier frequency (in Hz), which
  should be in the range 100 to 1000.  Frequencies above 1000-1500 or
  so are of no use because the brain does not react to higher pitches
  in the same way (see the Monroe Institute pages).  The actual beat
  frequency <freq> (which the brain responds to) should be in the
  range 0.5 to 30 Hz.  This corresponds to the ranges for Delta up to
  Beta as described above.

  The two tones generated are different by <freq>Hz, equally spaced
  either side of <carrier>.  The <sign> should be + or -, and this
  decides which channel carries the higher frequency.  I don't think
  this matters, but in case it does, you can change it here.  So, for
  example, 100+4/20 generates tones of 102 and 98 Hz, whereas 100-4/20
  generates tones of 98 and 102 Hz. 

  The bell sound can be used to give cues and signals during the
  sequence.  A simple `ping' is generated at the given frequency at
  the start of the period in which the tone-set is used.

  The spinning pink noise generates a binaural effect in a completely
  different way, by shifting the phase of pink noise in opposite
  directions for each ear, at a given beat frequency.  In this case,
  the first number is the width of the maximum phase shift from centre
  in microseconds.  Values from 100 to 500 seem good to me, although
  you might want to experiment with this.  The second number is the
  beat frequency and the third is the amplitude, as above.

  Binaural tones generated using wave<num> work just the same way as
  normal binaural tones.  See the section later on for details.

  Once a tone-set has been defined, it may be used in time-sequence
  lines.

* Time-sequence lines.  These take the form of:

    <time-spec> [<fade-in-fade-out>] <tone-set-name> [->]
    <time-spec> <block-name>

  Examples:
  
    16:00 theta6
    NOW theta6
    +00:03:30 == theta4 ->
    NOW+04:00 <> theta4
    12:00 theta-bursts

  In it's simplest form, this specifies a clock time, and which
  tone-set should be played at that time.  This tone-set continues
  until the next clock-time that is specified.

  Time-sequence lines should always appear in order - you will get an
  error if things appear out of order.

  More complex examples give time relative to the program start time
  (NOW, or NOW+04:00), or relative to the last absolute time mentioned
  (+00:03:30).  They also use different varieties of fade-in or
  fade-out (== or <>), and use `->' to slide to the next time-
  sequence.  You can also name blocks instead of tone-sets.  These
  more complex options are described below.

  Take a simple example such as this one:
  
    11:00 theta6
    12:00 alpha8
    13:00 alpha10
    14:00 off

  This indicates three tone-sets that will play for an hour each
  between 11am and 2pm.  The tone-sets do not change suddenly on the
  hour.  Rather, SBAGEN starts to fade out one tone-set 30 secs before
  the hour, fading in the next for the first 30 secs of the next hour.

  By default, SBAGEN will attempt to keep common things playing from
  one tone-set to the next.  So if, for example, all of them use pink
  noise on the first channel, then this will keep on playing the whole
  time, whilst the tones that change will fade out and in.

  To change the fading in/out behaviour, include a <fade-in-fade-out>
  specification before the name.  This consists of two characters, one
  for fading in this tone-set, the second for fading it out.  The
  fade-in character may be:

    <      Always fade in from silence.

    -      Fade from previous to this, fading out all tones not
           continuing, fading in all new tones, and adjusting the
           amplitude of any tones continuing.

    =      Slide from previous to this, fading out all tones ending,
           fading in all new tones, and sliding the frequency and
           adjusting the amplitude of all other tones.

  As an example, using `=' you can smoothly slide from a 4 Hz
  frequency all the way up to a 12 Hz frequency, rather than fading
  one out, and fading a new one in.  The fade-out characters are
  similar, and may be:

    >      Fade out to silence
    -      Fade to next, as above
    =      Slide to next, as above

  What fades/slides actually occur between two tone-sets depends on
  what both of them are asking for.  If one wants to fade out to
  silence, then the other one can't slide to it.  They both have to
  want to slide for this to occur.

  The default <fade-in-fade-out> specification is `--', which means
  keep playing anything that is the same frequency (adjusting the
  amplitude if necessary), but fade everything else in or out.

  By default fading and sliding only occur during the 60 second period
  within 30 seconds either side of the change-over time.  However,
  using `->', the entire period from the start time to the time on the
  next time-sequence line becomes a transition period.  This way you
  can have a gentle frequency slide that goes on for an hour, if you
  like:

    15:00 == theta4 ->
    16:00 == alpha10

  Assuming these tone-sets do what their names suggest, this will
  produce a gentle change in binaural beat frequency from 4 Hz up to
  10 Hz over the hour from 3pm to 4pm.

  The time-specification in its simplest form may be in the form
  `hh:mm' or `hh:mm:ss'.  This counts as an absolute time.  

  Another form of time-specification is `NOW' which indicates the time
  at which SBAGEN was started.  This is useful for sequence-files that
  are intended to play from the time that they are run, rather than
  always at the same time of day.  `NOW' is another absolute time.

  The other form of time-spec is a relative time, either `+hh:mm' or
  `+hh:mm:ss'.  This, if used alone, is taken relative to the
  last-mentioned absolute time, for example the three relative times
  below are all relative to `NOW', the last-mentioned absolute time:

    NOW+00:10 theta4
    +00:20    off
    +00:30    theta4
    +00:40    off

  Any number of relative times may also be used with an absolute time,
  to modify it, for example `NOW+04:00+01:12:04' or `12:00+00:00:20'.

* The block definition line.  This introduces a set of lines, and
  takes the form:

    <block-name>: {
      <time-sequence-line>
      ::
    }

  For example:

    theta-burst: {
      +00:00 theta4
      +00:10 off
    }

  A block definition associates a name with a group of time-sequence
  lines.  All the time-specs on these lines should be relative,
  because when the block is called on, all the times will be combined
  with the time-spec from the calling line.

  For example, using the above definition:

    NOW theta-burst

  expands to:

    NOW+00:00 theta4
    NOW+00:10 off

  Or for another example:

    +01:00 theta-burst

  expands to:

    +01:00+00:00 theta4
    +01:00+00:10 off

--------------------------------------------------------------------------------



EXPERIMENTAL FEATURE: User-defined waveforms
--------------------------------------------

This is a more complex form of binaural synthesis, and right at this
moment, I'm not sure whether it works or not, so this section is only
for die-hard bleeding-edge hackers and experimenters.  The code is in
place to do this synthesis, but it might still have bugs or other
problems.  If you're still interested, read on ...

The purest form of binaural beat synthesis is based on two sine waves
of slightly differing frequency.  The interference between these two
within the brain generates a resultant wave with a slow modulation.
Assuming the interference within the brain is similar to normal wave
interference, then the resultant amplitude wave is shaped by what
looks like a full-wave rectified sine wave (like the +ve half of a
sine wave repeated endlessly).

There is a line of thinking that suggests that if we replace this
amplitude envelope with one based on the shape of a measured
brain-wave, then we should be able to reproduce that brain-wave in the
brain - i.e. we play a measured alpha wave to entrain the brain
precisely to an alpha wave.  Does this work ?  I really don't know.

This is how it is used in the sequence-file.  You provide the shape of
the brain-wave to the program in a waveform definition line:

  wave<2-digits>: <list of samples>

There can be at most 100 waveforms defined in a sequence, numbered 00
to 99.  For example:

  wave00: 0 5.5 10 8 10 7.2 4.7 2 

The samples are values from the waveform shape taken at regular
intervals over one cycle.  They can be in any units you wish -
floating point numbers, negative, whatever - and there may be as many
samples as you wish (currently only limited by line length).  They
will be rescaled to fit between the amplitudes of 0% and 100% and
smoothed using a sin(x)/x function.  See here for more details on the
smoothing used:

  http://www-ccrma.stanford.edu/~jos/resample/

This waveform now becomes the amplitude envelope of any binaural tones
generated from it:

  wave00:200+4/50

This is just the same as 200+4/50, except it uses the new waveform for
the amplitude envelope.

That's all you need to know to be able to use it.  All you have to do
now (according to the theory, at least) is to go and measure some
waveforms - off the 'net if like most of us you don't have an EEG -
feed them into waveNN: lines, and then play them at appropriate
beat-frequencies.

Well, that's the theory, but not everything seems to be working
according to plan from my experiments.  Here is the basis on which the
code works to generate the tones:

If you take the 0-100% scaled and smoothed amplitude waveform, and
draw it twice, and invert the second version, you have a wave that can
be played at audio frequencies.  If you play this in the left ear at
102Hz (for example), and in the right ear you play the same thing at
98Hz BUT WITH THE SAMPLE REVERSED, then in theory you should get the
correct amplitude envelope.  Here is the mathematical basis for this
(from the mailing list):

> Let's say we have a brain-wave waveform of f(T) (T is theta),
> expressed as a fourier series (using complex maths because it's
> easier):
> 
>   f(T) = sigma(n= -inf to +inf) ( Cn . e^(inT) )
> 
> What we want to end up with is a resultant function something like
> this:
> 
>   g(t) = sigma(n= -inf to +inf) ( Cn . e^(inbt) . 2 cos nat )
> 
> where `a' is the resultant carrier frequency (in rad/s here), and `b'
> is the beat frequency.  This means that the phase information is
> connected with the beat waveform, and the phase of the carriers are
> fixed.  The factor 2 comes in handy lower down:
> 
>   g(t) = sigma(n= -inf to +inf) ( Cn . e^(inbt) . (e^(inat) + e^(-inat)) )
> 
>   g(t) = sigma(n= -inf to +inf) ( Cn . e^(in(b+a)t) + Cn . e^(in(b-a)t) )
> 
>   g(t) = f((b+a)t) + f((b-a)t)
> 
> So we just need to play the original waveform at frequencies (b+a) and
> (b-a).  But `b' will typically be small (1-30Hz), and `a' will be
> large (100-1500Hz).  So (b-a) is negative, which means playing the
> sample backwards.
> 
> So if we play the required brainwave forwards at the higher
> frequency, and backwards at the lower frequency, it should all come
> out with what we want.

However, with my experiments I don't get the expected resultant
amplitude envelope.  I get bits of it, but not a perfect result.
What's going on, I don't know.  Anyway, if you're up for experimenting
with this, at least the code is there now for you to play with and
modify.  If you make any progress, let me have the improved code, and
I'll include it in the next release.

Cheers -

Jim

--------------------------------------------------------------------------------

