Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Back to the Stick Bass,...uh Bull Fiddle


Jun02: C Programming

Al is DDJ's senior contributing editor. He can be contacted at [email protected].


In April, I described the effects of an audio algorithm designed to support a music education program. The program lets students listen to an ensemble performance and play along, muting the instrument they are playing to hear themselves in the company of a professional band and changing the balance and mix of the other instruments. The application's requirements dictate an approach allowing about 15 recorded tunes of about four minutes each on a CD-ROM. A quick calculation reveals that standard uncompressed audio technology does not support that number of independent channels playing that amount of music on one disc, not to mention the additional storage requirements for software and graphical renditions of musical score parts (sheet music) for each of the instruments. Those of you who have kept up with this column over the past several months know that I experimented with various center channel elimination approaches and audio compression algorithms before settling on this particular technique.

Here is some of what I said in April:

Begin with a standard .WAV file recorded at 16 bits per sample, 44,100 samples per second, two channels. The recording contains six instruments, three on each channel. You can play this file with any media player program. When you pass the file against my algorithm, you can do a full audio mix on its six logical audio channels, changing the volume and pan of any and all six channels in real time during playback.

When I described this algorithm to audio engineers, they declared it to be impossible. Therefore, I challenged you, my readers, to guess how I did it, promising a gift of a DDJ T-shirt to those readers who guessed correctly. Of the nine responses, six readers got it right or at least close enough to earn the prize. Only one reader declared it impossible, perhaps because he took my description too literally. The six lucky winners are Jukka Akkanen, Steve Weed, Justin Azoff, Tim G. English, Alex Shvedov, and Kit Adams.

I was gratified when that many readers guessed my secret algorithm because it proves what I've always known — programmers are smarter than other people, and DDJ readers are among the smartest.

This month, I'll describe the algorithm. I expect those who doubted me to react by saying, "Oh, that's not what he said he was doing." Those who were interested in knowing how I did it might react the way we do when a magic trick is explained by saying, "Oh, that's not so clever; it's obvious." Human nature.

The secret is in the mix. Although the .WAV file plays properly on a media player program, it's not your conventional audio .WAV file. It takes a bit of preparation to make it. The six audio channels are initially recorded independently to prevent audio cross talk among channels. I record them as independent monaural signals at 44,100 samples per second with 16-bit samples and save them as .WAV files. Then I run each .WAV file against a program I wrote named "downsamp.c" (Listing One), which copies the files into raw PCM format writing only every third sample. This procedure generates six one-channel audio files at 14,700 samples per second each. Next, I run another program I wrote just for this project named "mixpcm.c" (Listing Two), which merges the samples, interlacing one from each file as it goes along. The output file is written with a .WAV header that identifies it as a stereo file at 44,100 samples per second. Because the samples from each original channel are interlaced, the effect upon playback with a media player program is that three of the originals are in the left channel and three are in the right. The human ear cannot tell that the signals in each of the two channels are actually each an interlaced signal of three.

Why, you ask, are the two sample-fixing programs written in C and not C++? I must confess; when I write little programs, particularly ones with file input/output, I usually write them in C. There's no good reason for it other than that I intuitively remember the stdio functions more readily than I do the iostream classes, even though I've been writing C++ code for many years now.

The playback algorithm takes advantage of these interlaced samples to extract six logical channels from what seems to be a common stereo file. The algorithm reads the .WAV file and mixes the six logical channels into two physical channels according to the user's mixing instructions, and plays back the audio through the Win32 wave API at 14,700 samples per second instead of 44,100. If the playback device does not support that sample rate (so far, all the devices I tested do support it), the algorithm up-samples the signal to 44,100 by duplicating each sample value twice, making three adjacent copies of each sample. I implemented the algorithm in a class derived from the WavePlayer class I published here in February and March of this year. That code is specific to the application and would not be of interest outside that application.

I thought I might patent this algorithm merely as an exercise in software patents. When enough readers guessed my secret, I decided not to do that. It should not have surprised me. The technique is indeed obvious when you take it on as a challenge and do not suffer from some preconceived notion that it can't be done. It is humbling to realize that what took me several months of experiments to discover, so many programmers figured out in short order. The experience indicates that anyone who really needs this technique could hire a competent programmer to independently invent it. I now know at least six programmers besides myself who could do it. I've never seen the technique used before, perhaps because I'm the first person (in my realm of experience) who has needed this particular behavior in an audio application. Necessity is a mother.

C++ by Example

I don't usually review tutorial C++ books for several reasons. First, since I wrote such books myself, the smallest criticism could be interpreted as a conflict of interests, and the slightest praise could be interpreted as being less than in my own best interests. Second, to do a proper job I'd have to read the whole book and, since I already know the subject so well, entry-level C++ narrative puts me to sleep. There is, however, a new book from Que named "C++ By Example" that merits some mention not only because it is a delightfully written book, but also because I have some minor history with its development.

A while ago, an editor at Que asked my permission to include a program I wrote as part of a book project. The program is Quincy 2000, which I've discussed in this column many times. Quincy is an IDE that hosts the GCC and Borland compiler suites. I developed it to support my own C++ book projects and a tutorial CD-ROM that DDJ published. According to the editor, Steve Donovan, the author of C++ By Example (Que, 2001; ISBN 0789726769) had built his tutorial around Quincy and wanted to include it on the book's companion CD-ROM. Mr. Donovan includes a C++ subset interpreter named "UnderC" to support his tutorial examples and he had modified Quincy to serve as a front end to his command-line interpreter.

Although I usually encourage programmers to use my work any way they want, I had to refuse this permission. The book competes with my books and I have a publishing contract that prevents me from cooperating with direct competition. I checked with my publisher, who said only that he would be really unhappy if a competing book from another publisher used my work as one of its vital components. The editor at Que responded to my refusal by whining about how much work the author already had invested in adapting Quincy. I suggested that maybe they should have asked first, and the negotiation ended. So much for the history.

The book has now been published and a copy showed up in my mailbox the other day. Because it is a tutorial C++ book, I normally would not have even opened it. But because of my brief association with the project, I was naturally curious. One chapter explains how Quincy works and how to use it to run the exercises. The companion CD-ROM does not include Quincy, but the author's web site offers the modified version for download. Curious, I tried to download the modified Quincy executable and source code, but with no success. Something's wrong with the download site.

Throughout the book, the source-code examples are presented in the context of the UnderC interpreter's command line. The interpreter itself has no integrated editor. I did not test the interpreter beyond seeing that it loads and runs the simplest of commands. Mostly, I just thumbed through the book to get a feeling for its depth of coverage, style, and organization. What I found was readable text with good code, appropriate levels of detail, occasional touches of humor, and realistic case studies. It kind of reminds me of my own books.

Basso Profundo

The music application I mentioned earlier teaches instrumental jazz and involves the mix of six instruments: cornet, clarinet, trombone, piano, drums, and bass. I am able to keep project costs down by recording all but two of the parts myself. I would not know what to do with a clarinet or a set of drums. But I can play the others in that style of music.

Playing the bass is a recent thing. A short time ago, after a long layoff, I started again to play the bass, bass fiddle, upright bass, acoustic bass, bull fiddle, contra bass, double bass, string bass, bass viol, whatever you call it — I never knew anything with so many names. I played the bass professionally years ago and put it aside to concentrate on other things. My beat up old bass reposed in a closet for many years until I resurrected it last year, restrung it, amplified it, built up some chops, and began playing gigs with it again. One steady gig is in a joint called "Big Daddy's Jazz and Blues Club" in Cocoa, Florida. It's a small room upstairs above a restaurant. Up 24 stairs. Lugging a bass and amp. Then back down again at the end of the evening. A tough schlepp for an old dude. The bass is old, too, and rattles a lot, sounds like it's strung with rope, and won't fit in my Corvette even with the top down. The obstinate instrument keeps trying to eject its electronic pickup, too, as if a respectable old plywood acoustic shouldn't be amplified. It's more trouble than a two-year-old laptop. If I'm going to keep doing this, I need something newer, more reliable, and more portable. To that end, I bought an electric upright bass (commonly called a "stick" bass) from an eBay auction. It plays and sounds like an acoustic bass without the bulk and weight, although just the appearance of such a newfangled device often offends the purist jazz fans in my audiences. If you want to see what I bought, go to http://www.nedsteinberger.com/. If you are a jazz purist and this electronic simulator of the real thing offends you, I hereby invite you to come to Florida to be my volunteer, full-time roadie.

As it turns out, the eBay seller is JC Harris, a computer programmer and long-time DDJ reader. During our communication about the transaction, JC said:

....when I saw the FL address, I wondered, "is this 'the' Al Stevens?" Of course I recognize you from your Dr. Dobb's columns. I learned a ton of C programming from you. I have not read Dr. Dobb's for a long time as most of their topics diverged from my meat-and-potatoes field (accounting software) a long time ago. But I still have a database management program I worked out month by month from your columns! If nothing else, I am glad this has given me a chance to thank you for your columns.

You're very welcome, JC, and thanks for making my day with those kind words and for saving my poor ol' aching back by making that stick bass available. Maybe we can lure you back to be a regular reader again.

DDJ

Listing One

#include <stdio.h>
#include <string.h>

short getsample(FILE**ch)
{
    short sample = 0;
    if (*ch)    {
        if (feof(*ch))  {
            fclose(*ch);
            *ch = NULL;
        }
        else
            fread(&sample, sizeof(short), 1, *ch);
    }
    return sample;        
} 
void downsample(FILE* ch1, char* fn)
{
    FILE* fo = fopen(fn, "wb");
    if (fo != NULL) {
        while (ch1)  {
            short sample;
            sample = getsample(&ch1);
            fwrite(&sample, sizeof(short), 1, fo);
            sample = getsample(&ch1);
            sample = getsample(&ch1);
        }
        fclose(fo);
    }
}
int main(int argc, char* argv[])
{
    if (argc > 1)   {
        FILE *fi;
        char* fn = argv[1];
        fi = fopen(fn, "rb");
        if (fi) {
            strcpy(fn + strlen(fn) - 3, "pcm");
            fseek(fi, 44, SEEK_SET);
            downsample(fi, fn);
        }
    }
    return 0;
}

Back to Article

Listing Two

// mix six 14700/1/16 pcms into one 44100/2/16 Hz tune.wav
#include <stdio.h>

short getsample(FILE**ch)
{
    short sample = 0;
    if (*ch)    {
        if (feof(*ch))  {
            fclose(*ch);
            *ch = NULL;
        }
        else
            fread(&sample, sizeof(short), 1, *ch);
    }
    return sample;        
} 
void mix(FILE* ch1, FILE* ch2, FILE* ch3, FILE* ch4, FILE* ch5, FILE* ch6)
{
FILE* fo = fopen("tune.wav", "wb");
    if (fo != NULL)  {
        struct wavhdr {
            char riff[4];
            int wfchsize;
            char wave[4];
            char fmt[4];
            int fmtchsize;
            short tag;
            short nch;
            int rate;
            int bps;
            short align;
            short sampsize;
            char data[4];
            int datasize;
        } wh = {
            "RIFF",
            sizeof(struct wavhdr)-8,
            "WAVE",
            "fmt ",
            16,
            1,
            2,
            44100,
            176400,
            4,
            16,
            "data",
            0
        };
        fwrite(&wh, sizeof wh, 1, fo);
        while (ch1 || ch2 || ch3 || ch4 || ch5 || ch6)  {
            short sample;
            sample = getsample(&ch1);
            fwrite(&sample, sizeof(short), 1, fo);
            sample = getsample(&ch2);
            fwrite(&sample, sizeof(short), 1, fo);
            sample = getsample(&ch3);
            fwrite(&sample, sizeof(short), 1, fo);
            sample = getsample(&ch4);
            fwrite(&sample, sizeof(short), 1, fo);          
            sample = getsample(&ch5);
            fwrite(&sample, sizeof(short), 1, fo);
            sample = getsample(&ch6);
            fwrite(&sample, sizeof(short), 1, fo);
            wh.wfchsize += sizeof(short) * 6;
            wh.datasize += sizeof(short) * 6;
        }
        fseek(fo, 0, SEEK_SET);
        fwrite(&wh, sizeof wh, 1, fo);
        fclose(fo);
    }
}
int main()
{
    FILE *ftrombone, *fcornet, *fclarinet, *fpiano, *fdrums, *fbass;
    ftrombone = fopen("trombone.pcm", "rb");
    fcornet   = fopen("cornet.pcm",   "rb");
    fclarinet = fopen("clarinet.pcm", "rb");
    fpiano    = fopen("piano.pcm",    "rb");
    fdrums    = fopen("drums.pcm",    "rb");
    fbass     = fopen("bass.pcm",     "rb");
    mix(ftrombone, fcornet, fclarinet, fpiano, fdrums, fbass);
    return 0;
}

Back to Article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.