












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













1 What is it?
It's a method of encoding data onto either an audio signal, or on a logic-level
signal path. Its characteristics include: - self clocking; you don't need to know
the data rate to decode it - average DC is zero; capacitively coupled audio signals
will still decode properly - robust; it depends on phase-inversions to identify bits
wide range of data rates - able to be safely decoded on changing data rates -
e.g. from a spooling tape
The signal is dened such that there is a phase change in the level of the
signal at the end of each bit. If the bit is a one, then there is a further phase
change in the centre of the bit period. So, a continuing stream of zeros at a
1kbit/s data rate would be a 500Hz signal; a continuing stream of ones would
be a 1kHz signal. Normal data would have a mixture of both; it has a very
distinctive sound.
Biphase-mark encoding is widely used in the broadcasting industry for the
distribution and recording of linear time-code; the audio signal is recorded on
analogue video or audio tapes and can be read both during normal playback
and while spooling quickly. It's also often distributed around studio areas as a
source of time-of-day data; a reader can be plugged into a jack and the time
can be immediately displayed.
Another surprisingly common place to nd biphase-mark encoding is in the
SP-DIF digital connection (and of course the closely related AES-EBU digital
audio).
2 The software
In the attached les, I have included the source code for an encoder - biphase.c -
and a decoder - unbiphase.c. Rather than try and provide an example for AVR
of AVR chosen, resources required by other parts of the program, and so on - I
have provided generic C programs for a PC. They are written for GCC under
Linux though they should work with minimal changes - if any - on any of the
MS C compilers. The only point to note is that they require variables of int=
bits, short=16 bits, and char = 8 bits.
Caveat
It should be noted that neither of these programs is robust enough for pro-
duction software. Both have far too little error checking, particularly when
opening, reading from, or writing to les; neither behave properly in respect of
the Microsoft RIFF format les.
providing an ideal inter-block idle state.
The audio format is mono WAVE format, 16,000 bits per second, sixteen
bits per sample. Since I am recording a square wave, this is excessive but means
I can perform other unpleasantries on the audio data - ltration, compression
etc - with standard tools.
4 RIFF les
RIFF les are a Microsoft standard packaging stream for - usually - multimedia
storage. They may contain audio, video, random data, and metadata, contained
in chunks. The WAVE format is reserved for audio applications.
A chunk consists of a four-byte ascii header with the name of the chunk, four
bytes (unsigned long) to give the length of the chunk data, and then the chunk
data itself. A chunk can contain sub-chunks to any number or level, though it
is unusual to get any deeper than three levels. Note that the WAVE ident does
not have an immediate data length following it. Although MS refer to this as
a chunk, my feeling is that it should be considered as part of the data - so the
chunk consists of the WAVE identier and a minimum of two subchunks - the
fmt and data chunks.
The start of a minimal WAVE le looks like:
The fmt chunk data describes the format of the data (PCM, MP3, or other
compression), mono or stereo, bit rate, sample rate and so on. The audio data
needs to be understood in the terms of this header. In this case, we're going for
a straight-forward PCM mono signal at sixteen bits; hard to get wrong.
I should stress that the method I have used to create the le is not rec-
ommended by Microsoft (or me, really) in that all I do is preload the chunk
structure as a single 'waveheader' structure. This produces a legal le, and I
haven't come across any software which can't read it, but modern wave struc-
tures include extra elds. The le reader I provide in unbiphase.c can cheerfully
read this format, but may break on other wave les - though it will not crash,
you may nd that you're treating the extra elds (or indeed, extra chunks) as
audio data.
The ocial way to deal with these les is to use Microsoft's RIFF API;
creating chunks on demand to write and 'walking the chunks' to nd the chunks
in which you are interested and ignoring the rest. However, that option is not
immediately available in the GCC libraries, and would distract from the point
of the examples.
5 Coding and decoding
Coding biphase mark data is simple; one needs to arrange a phase change at
the bit rate and another phase change in the middle of that period, for the '1'.
How that is arranged is up to the programmer. In this version, I've just used an
integer number of audio samples to time the phase change. Alternate approaches
might include timer interrupts every half a bit period, with a routine that decides
whether or not a phase change is required at any particular interrupt. It can
also be derived in hardware, using a couple of ip-ops.
Decoding is also reasonably simple, depending on whether you know the data
rate and that it will be stable. If you do know it, then it's as easy as looking at
the interval since the last phase change. If it's more than 3/4 of the bit period,
you've just received a zero; otherwise, you got half of a one. If you already had
the rst half, this is the second half and you can return a one; otherwise, ag
this as a rst-half received. Note that because you don't necessarily know the
phasing of an arbitrary stream of ones, it's possible that the following half-cycle
might be a zero; this unambiguously identies the zero but data prior to that
must be considered suspect.
If you don't know the bit rate, it's a little more complex. Now, you need not
only the period of the current half-cycle but that of the previous half-cycle. If
these two are the same (within 0.75 and 1.5 times) then we can safely assume
that we have another of what we previously had... but we might not know yet
what it is. If the current period is more than 1.5 times the previous, then we
have denitely received a zero. If instead, it is less than 0.75 times the previous
period, then we have denitely received the rst half of a one. Only after such
an event can we unambiguously decode the continuing bit stream. Once the bit
stream is identied, ones and zeros will follow automatically, even if the data
rate changes, provided the change is less than approximately one sixth of a bit
period per bit.
6 Biphase
Biphase requires two parameters: the name of the le to be encoded, and the
le for the output data. It will produce a (quite large) audio le as described
above. You will need to provide the complete lename; I recommend .wav as
the sux. The input le can be anything; text, executables, whatever. Note
that the output le will cheerfully overwrite anything already existing with the
same lename.
be done several ways. If actual audio is being decoded, then the ADC complete
interrupt can be used as a regular tick, or a logic-level signal can be used to
drive an interrupt pin. An internal timer/counter is stored after every interrupt,
and reset for the next period (the interrupt sense can be inverted after every
interrupt).
The main routine simply calls get_byte() while there are still audio samples
remaining.
8 Performance
Having shown that the data can be successfully encoded and decoded, I decided
to see how much abuse the signal could take before it fell over.
The original audio le test.wav was created by encoding the source code for
biphase.c; all further processing was done within Audacity under Kubuntu linux
using the standard defaults. There are a touch under ten thousand characters
in the original text le.
'di' was used to check the accuracy of the transcription; the audio after
processing was exported from Audacity as a .wav le and then decoded using
unbiphase.
Remember that these are all being decoded with the basic version of the
code, with simplistic zero crossing/edge detection.
Test 1 - no processing (test.wav)
On inspection, the audio has a classic square wave signal shape. As expected,
the le produced no change between the input and the output.
Test 2 - Low Pass (testlopass.wav)
This Audacity process - with the corner frequency set at 993Hz - shows classic
exponential rise-times of the square wave after ltration. However, the decoded
audio once again had no errors.
Test 3 - High Pass (testhipass.wav)
This Audacity process results, as expected, in a le full of spikes at each bit edge
and little DC component; however, once again, the result decodes perfectly.
Since the coding survives basic frequency response changes successfully, let's
have a look at more extreme changes to the signal. In all these cases, we're
deliberately inducing distortions in the signal. In these tests, we use Audacity to
speed up and slow down the signal, changing the pitch. I don't know the method
used by Audacity, but the normal translation method involves oversampling the
original signal, digital ltration to the desired bandwidth, and resampling the
resulting le. So not only do we have data edges arriving at the wrong speed,
but they're likely to have added jitter - since they're now unlikely to be at exact
integer multiples of samples. On top of that, we won't have exact square waves
any more - as an examination of the waveform will soon show.
Test 4 - Speeding it up (testfast15.wav)
Well, well, well... it can cope with this; no errors on decoding. At 25% (test
le not included) it doesn't work at all well, though. I had expected it to cope
with 25% fast, and I believe the errors are rather to do with the extra jitter and
sample position rather than the limits of the decoding - remember that we are
still using the simple decoder which is expecting a xed data rate.
Test 5 - slowing it down (testslow25.wav)
And sure enough, once again there are no errors. Much slower than this, though,
and this version will fail. However, using an adaptive decoder, where the previ-
ous bit periods are used to detect one/zero dierences.
Ok, we've demonstrated that it can cope with a fair amount of mangling;
what happens if we try compressing the signal?
Well, it happens that zip or rar will actually compress the original un-
meddled-with square-wave signal very well indeed; it only contains two dierent
values for the audio signal. However, more general audio compression methods
are psycho-acoustic models; rather than trying to reproduce the original wave-
form they endeavour to produce a signal which the ear will accept as similar
to the original. In this process, both the phase of the signal components, and
some of the original components themselves, are lost.
Therefore, we might reasonably expect the data to be somewhat mangled
after it's been through this type of perceptual encoding. In this experiment, I
treat it to both mp3 coding and ogg coding. Using the default parameters for
Audacity, the mp3 le is compressed at a lower bitrate than the ogg le; the
original 2.3MB le compresses to about 220kB in mp3, and 400kB in ogg.
In both cases, we compress the original audio using Audacity, close the le,
reopen the resultant .ogg or .mp3 le, and export the result as a .wav le - so
this has tested both the compression and decompression paths.
Note that the attachment regime on AVRFreaks does not allow posting of
ogg or mpg les directly; also, if I try and rar the decoded wav les they end up
the same size as the original, so instead I have renamed the original ogg andmp
les with a .txt sux; remove this and save before decoding.
Test 6 - MP3 - the people's favourite
A curious result. What we see is that the data has failed horribly - but not
as might be expected. Instead of a complete failure, or randomly correct bytes
throughout the le, we nd that it appears to have worked in short bursts - rst
a few dozen random garbage characters, then a few dozen error free. I don't
10 Conclusion
So, here it is. I think I've demonstrated that biphase mark encoding is a ver-
satile, robust, and easy method of moving data or commands around. It's easy
to decode on an AVR (there are only fteen lines of actual code in the routine
described above!) and uses very little processor time. It will work over a huge
range of speeds, and over very long distances (I've actually used it over an audio
circuit between the BBC's Delhi oce and Bush House in London). It can be
carried as a logic signal, as audio, over wire, optical bre, or radio.
It's not as fast as USB2, or even I2C. The AVR can manage RS232 data
remarkably faster, certainly faster than you could decode biphase mark - but
biphase mark is much more robust in terms of data rate, jitter, and changing
clock rates.
In a production environment, you'd want to stien things up a little. You'd
probably want to use an algorithm which compares the length of a previous
cycle to decide whether a particular bit is a one or a zero, rather than using
an absolute length. You'd probably want to provide some sort of packaging for
the message - framing information, a more complex protocol, whatever. This
is what you would do anyway in any comms method where you don't have full
control over both ends of the link, and the link itself.
Enjoy.
11 The source code
11.1 Makele
biphase.o: biphase.c gcc -c biphase.c unbiphase.o: unbiphase.c gcc -c unbiphase.c biphase: biphase.o gcc -Wall -o biphase biphase.o unbiphase: unbiphase.o gcc -Wall -o unbiphase unbiphase.o
11.2 biphase.c
// biphase.c // // (c) Nailed_Barnacle (Neil Barnes) 2007 // // Released under LGPL conditions - see www.gnu.org for details. // // convert an input data file to an output .wav file, coding the data as // biphase-mark data at a 1000bps data rate // // the signal is coded using RS232-type conventions; idle is high, // a low start bit, eight data bits, and a high stop bit // // the bits themselves are coded such that there is a phase change // at the end of every bit period, with a further phase change in // the centre of the period in the case of a '1'. A zero (space) // is therefore represented by a single high or low period of 1ms // and a one (mark) by two 500us periods either low-high or high-low. // // the audio is coded onto a standard windows mono .wav file // at a sample rate of sixteen ksps (it would work at any sample rate // over about 8k, but 16k is convenient) and is sixteen bit; the
// signal used is 6dB down on peak amplitude so ranges from 0x4000 (high) // to 0xc000 (low). The original signal is square wave but this may be modified // by compression, noise addition, filtration etc // // Note that the method of creating the _waveheader structure implies // 32-bit integers, 16-bit shorts, and 8-bit chars
#include <stdio.h> #include <string.h> #include <stdlib.h>
// note that this is not the MS approved way to make RIFF headers // they'd much rather you use their RIFF chunk management API which // is, quite frankly, a pain in the rear // // And since I'm writing in linux, it's not immediately available // This method produces legal wav files without the headaches // // What we should have is RIFF chunk containing a WAVE chunk // containing a 'fmt ' chunk and a 'data' chunk
// this will deliver it, providing we remember to fill in the missing bits later
struct _waveheader { char riff[4]; int block_size; char wave[4]; char fmt[4]; int chunk_size; short tag; short channels; int samples_per_sec; int bytes_per_sec; short block_align; short bits_per_sample; char data[4]; int data_size; };
struct _waveheader wh; // header for wave files FILE * fo; // file handles FILE * fi;
#define SAMPLERATE 16000
// prototypes int write_0 (FILE * file, int sample_rate, int last); int write_1 (FILE * file, int sample_rate, int last); int write_byte (FILE * file, int byte, int sample_rate, int last);
int main (int argc, char * argv[]) { static unsigned int count; // number of bytes in block int q; int r; short s; // the variable that holds the byte to be written to the .wav file int t; short last; // the value of the last phase of the signal char input; // byte read from the input file
if (argc < 3) { printf("Please specify input and output filename...\n"); printf("Usage: biphase infile outfile\n"); exit(1); }
fclose(fo); }
int write_0 (FILE * file, int sample_rate, int last) { // write a half a squarewave to the audio output file // number of samples written = samplerate/ // value of sample = inverse of 'last' // returns value of sample written short count; short s; int q;
count = sample_rate/1000; // to give a 1ms bit period if (last == 0x4000) { s = 0xc000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); return 0xc000; } else { s = 0x4000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); return 0x4000; } }
int write_1 (FILE * file, int sample_rate, int last) { // write a squarewave to the audio output file // number of samples written = samplerate/ // half these samples are high, half are low // value of sample = inverse of 'last' // returns value of sample written short count; short s; int q;
count = sample_rate/2000; // to give a 500us half-bit period if (last == 0x4000) { s = 0xc000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); s = 0x4000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); return 0x4000; } else { s = 0x4000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); s = 0xc000; for (q = 0; q< count; q++) fwrite (&s,sizeof(s),1,fo); return 0xc000; } }
int write_byte (FILE * file, int byte, int sample_rate, int last) {
// write a byte to the output file in the format // start bit = 0 // data bit 0-7 low bit first // stop bit = 0 // returns the last level written
int q;
// the start bit last = write_0(fo, SAMPLERATE, last);
// the data bits for (q=0; q<8; q++) { if (byte & 1) { last = write_1(fo, SAMPLERATE, last); } else { last = write_0(fo, SAMPLERATE, last); } byte /= 2; }
// the stop bit last = write_1(fo, SAMPLERATE, last); return last; }
11.3 unbiphase.c
// biphase.c // // (c) Nailed_Barnacle (Neil Barnes) 2007 // // Released under LGPL conditions - see www.gnu.org for details. // // convert an input .wav file containing a biphase-mark encoded audio // file to an output binary file - no assumption is made about the // actual data encoded. // // this program is built as a demonstration model only. In particular, // it is deficient in verification of valid files, and in a real // application a more robust packaging protocol would be used; possibly // blocks protected with addresses, counts, and/or checksums. // // the signal is coded using RS232-type conventions; idle is high, // a low start bit, eight data bits, and a high stop bit // // the bits themselves are coded such that there is a phase change // at the end of every bit period, with a further phase change in // the centre of the period in the case of a '1'. A zero (space) // is therefore represented by a single high or low period of 1ms // and a one (mark) by two 500us periods either low-high or high-low. // // the audio is coded onto a standard windows mono .wav file // at a sample rate of sixteen ksps (it would work at any sample rate // over about 8k, but 16k is convenient) and is sixteen bit; the // signal used is 6dB down on peak amplitude so ranges from 0x4000 (high) // to 0xc000 (low). The original signal is square wave but this may be modified // by compression, noise addition, filtration etc // // Note that the method of creating the _waveheader structure implies // 32-bit integers, 16-bit shorts, and 8-bit chars
printf("Can't open one of the input or output files... quiting\n."); fcloseall(); exit (1); }
// note - this is an unsafe way of reading RIFF files in general // it assumes that the header will match exactly of the format // defined by the _waveheader structure // // this is of course the case for the file we wrote in biphase, and // with older files, but more modern files have more information in // the header file and will not read correctly as some of the pointers // will no longer align. // // so when you write your own routines, read the MS spec first
fread(&wh, sizeof(wh), 1, fi); // read the first eight bytes
// see if it's a RIFF file if (strncmp("RIFF",wh.riff,4) != 0) { // not a riff file printf("Sorry, that's not a riff file...\n"); fcloseall(); exit(1); }
// good start, let's see if it's a WAVE file if (strncmp("WAVE",wh.wave,4) != 0) { // not a wave file printf("Sorry, that's not a wave file...\n"); fcloseall(); exit(1); }
if (wh.channels != 1) { // but it has to be mono... printf("Sorry, it must be a mono file...\n"); fcloseall(); exit(1); }
// ok, that's enough checking for our purposes // we'll assume then that the read pointer is pointing at the start of the data
int tmp = 0; while ((tmp = get_byte(fi)) != -1000) { fprintf(fo,"%c",(char)tmp); } printf("All done!\n"); fclose(fo); }
int is_edge (FILE * file) { // we return 0 if the sample we read from the audio file is the same phase // as the last sample we got (i.e. both were greater or lesser than zero) // return 1 if it was different and -1 if we ran out of file // our samples are all sixteen bits - short
static short last_sample = 1;
short sample;
if ((fread(&sample,sizeof(short),1,file)) != 0) { if (((last_sample > 0) && (sample > 0)) || ((last_sample <= 0) && (sample <= 0))) { // no change in sign, therefore no edge last_sample = sample; return 0; } else { // signs different, therefore an edge last_sample = sample; return 1; } } else { // ah, ran out of file... return -1; } }
int get_period (FILE * file) { // get a single bit or half-bit - return the number of samples // to the next phase change // return -1 if we ran out of file
int count = 0; int edge = 0;
while (edge == 0) { edge = is_edge(file); count++; } // ok, found an edge, check that we didn't run out of file if (edge == -1) return -1; // set the end flag else return count; }
int get_bit( FILE * file ) { // recall that all bits have a transition at the end of each bit period; // '1's have a further transition in the centre of the period // // this means that we can unambigiously decode 1 or 0 irrespective of // baud rate - a simple state machine will allow us to decode a single bit // and pass it back to a calling routine // // in this particular case, we know our data is topped and tailed with a // short sequence of '1's, representing the idle state of the 232 data // // if we don't know a starting state, we have to guess, and we can't // correct a long sequence of 1 or 0 until we get a bit change - this might // mean that there is data which is missed until synchronisation is // achieved, hence a need for rather better packeting/encapsulation than // is presented here // // we return 1 or 0 if the bit is decoded, or -1 if we have a file error int period; static int first_half = 0; // this is set if we think we're in the
// we're waiting for a start bit while ((bit = get_bit(file)) == 1) { // wait and do nothing }
if (bit == -1) return -1000; // ran out of file
// otherwise we got a start bit, probably, so get the rest of the word // the data arrives bit 0 first for (q=0; q<8; q++) { bit = get_bit(file); if (bit == -1) return -1000; result |= (bit < < 8); result > >= 1; } // we could check that the next bit is a one - the stop bit - but // instead we detect it while waiting for the start bit return result; }
11.4 biphase for AVR
// biphase.c // // (c) neil barnes / [email protected] 2007 // // released under LGPL - see www.gnu.org for details // // this is a demo program purely for the fun of it... // it reads an incoming audio signal with biphase mark (bpm) coded // data, as described in the AVRfreaks thread // // it requires a logic level bpm signal delivered to INT0/PD // this can be generated by playing an audio signal from the PC // generated with the code on the AVRfreaks thread; convert it // to logic level using an opamp or comparator. // // the received bpm code - expected at 1kb/s - is output on TX0/PD // as a serial data stream at 1kb/s. No data translation or verification // takes place.
#include <stdio.h> #include <avr/io.h> #include <string.h> #include <avr/signal.h> #include <avr/interrupt.h>
int main (void) { // set the output port DDRD = 0x01; // all input except PD
// set the interrupt mask and mode MCUCR &= 0b11111100; // clear the INT0 bits MCUCR |= 0b00000001; // any logic change cause interrupt GICR |= 0b01000000; // enable int
// set up a timer to give a useful count // we're expecting an interrupt every 4,000 to 8,000 counts // we can usefully clock timer 1 for that // the control bits are spread between TCCR1A and 1B
TCCR1A = 0b00000000; // normal counter, no output TCCR1B = 0b00000001; // normal counter, no prescale
sei(); // enable interrupts
while (1) { // if you have anything useful to do, here is where to do it } return 0; // just kidding... }
// we arrive here in the vain hope of having received an // interrupt from INT0/PD
int period; // somewhere to keep the period static int first = 0; // has the first half been received?
// we need to know how long it was since the last interrupt period = TCNT1; // this grabs all sixteen bits TCNT1 = 0; // so clear the count for the next bit
if (period > 6000) { // definitely a zero... PORTD &= 0b11111110; // so clear the output first = 0; return; } else { // hmm, a zero, but which half? if (first == 1) { // then it's the second half PORTD |= 0b00000001; // set the output first = 0; return; } else { // it's just the first half first = 1; } }
}