Esempio n. 1
0
int channel_write_adsi_channel(uc_t *uc, int chan, void *user_data, uint8_t *buf, int max_len)
{
    int16_t pcm_buf[1024];
    int len;
    int i;
    static int block = 0;
    uint8_t adsi_msg[256];
    int adsi_msg_len;

    if (++block == 100)
    {
        adsi_send_alert_tone(&(chan_stuff[chan].adsi_tx));
        printf("Alert tone sent\n");
        adsi_msg_len = adsi_create_message(&(chan_stuff[chan].adsi_tx), adsi_msg);
        if ((len = adsi_put_message(&(chan_stuff[chan].adsi_tx), adsi_msg, adsi_msg_len)) > 0)
            printf("Message put - %d bytes\n", len);
    }
    len = adsi_tx(&(chan_stuff[chan].adsi_tx), pcm_buf, max_len);
    afWriteFrames(txhandle,
                  AF_DEFAULT_TRACK,
                  pcm_buf,
                  len);
    for (i = 0;  i < len;  i++)
        buf[i] = linear_to_alaw(pcm_buf[i]);
    /*endfor*/
    return len;
}
Esempio n. 2
0
void writeMiscellaneous(int fileFormat, const std::string &testFileName)
{
	AFfilesetup setup = afNewFileSetup();
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitFileFormat(setup, fileFormat);
	int *miscIDs = new int[kNumMiscellaneous];
	for (int i=0; i<kNumMiscellaneous; i++)
		miscIDs[i] = kMiscellaneous[i].id;
	afInitMiscIDs(setup, miscIDs, kNumMiscellaneous);
	delete [] miscIDs;
	for (int i=0; i<kNumMiscellaneous; i++)
	{
		afInitMiscType(setup, kMiscellaneous[i].id, kMiscellaneous[i].type);
		afInitMiscSize(setup, kMiscellaneous[i].id, strlen(kMiscellaneous[i].data));
	}

	AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup);
	ASSERT_TRUE(file);
	afFreeFileSetup(setup);
	for (int i=0; i<kNumMiscellaneous; i++)
	{
		int result = afWriteMisc(file, kMiscellaneous[i].id,
			kMiscellaneous[i].data,
			strlen(kMiscellaneous[i].data));
		EXPECT_EQ(strlen(kMiscellaneous[i].data), result);
	}

	const int16_t samples[] = { 1, 2, 3, 4 };
	const int sampleCount = sizeof (samples) / sizeof (samples[0]);
	EXPECT_EQ(sampleCount, afWriteFrames(file, AF_DEFAULT_TRACK, samples, sampleCount));
	ASSERT_EQ(0, afCloseFile(file));
}
Esempio n. 3
0
int main (int argc, char **argv)
{
	int		filefmt;
	AFfilehandle	file;
	AFfilesetup	setup;
	int		miscids[] = {1, 2};
	int		result;

	if (argc < 3)
	{
		fprintf(stderr, "usage: %s <file format> <audio file>\n",
			argv[0]);
		exit(EXIT_FAILURE);
	}

	if (strcmp(argv[1], "aiff") == 0)
		filefmt = AF_FILE_AIFF;
	else if (strcmp(argv[1], "aifc") == 0)
		filefmt = AF_FILE_AIFFC;
	else if (strcmp(argv[1], "wave") == 0)
		filefmt = AF_FILE_WAVE;
	else
	{
		fprintf(stderr, "unrecognized file format '%s'\n", argv[1]);
		exit(EXIT_FAILURE);
	}

	setup = afNewFileSetup();
	afInitFileFormat(setup, filefmt);
	afInitMiscIDs(setup, miscids, 2);
	afInitMiscType(setup, 1, AF_MISC_COPY);
	afInitMiscType(setup, 2, AF_MISC_NAME);
	afInitMiscSize(setup, 1, strlen(copyright));
	afInitMiscSize(setup, 2, strlen(name));

	file = afOpenFile(argv[2], "w", setup);
	if (file == NULL)
	{
		fprintf(stderr, "could not open file '%s' for writing\n", argv[2]);
		exit(EXIT_FAILURE);
	}

	result = afWriteMisc(file, 1, copyright, strlen(copyright));
	DEBG("wrote miscellaneous data of type %d with length = %d\n",
		afGetMiscType(file, 1), result);
	result = afWriteMisc(file, 2, name, strlen(name));

	DEBG("wrote miscellaneous data of type %d with length = %d\n",
		afGetMiscType(file, 2), result);

	/* Write out two token frames of sample data. */
	afWriteFrames(file, AF_DEFAULT_TRACK, data, 2);

	afCloseFile(file);
	afFreeFileSetup(setup);

	return 0;
}
Esempio n. 4
0
void testChannelMatrixReading(int sampleFormat, int sampleWidth)
{
	// Create test file.
	const int channelCount = 2;
	const int frameCount = 10;
	const T samples[channelCount * frameCount] =
	{
		2, 3, 5, 7, 11,
		13, 17, 19, 23, 29,
		31, 37, 41, 43, 47,
		53, 59, 61, 67, 71
	};
	AFfilesetup setup = afNewFileSetup();
	afInitFileFormat(setup, AF_FILE_AIFFC);
	afInitChannels(setup, AF_DEFAULT_TRACK, 2);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, sampleFormat, sampleWidth);
	AFfilehandle file = afOpenFile(kTestFileName, "w", setup);
	afFreeFileSetup(setup);
	EXPECT_TRUE(file);

	AFframecount framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK,
		samples, frameCount);
	EXPECT_EQ(framesWritten, frameCount);

	EXPECT_EQ(afCloseFile(file), 0);

	// Open file for reading and read data using different channel matrices.
	file = afOpenFile(kTestFileName, "r", NULL);
	EXPECT_TRUE(file);

	EXPECT_EQ(afGetChannels(file, AF_DEFAULT_TRACK), 2);
	EXPECT_EQ(afGetFrameCount(file, AF_DEFAULT_TRACK), frameCount);

	afSetVirtualChannels(file, AF_DEFAULT_TRACK, 1);

	for (int c=0; c<2; c++)
	{
		double channelMatrix[2] = { 0, 0 };
		channelMatrix[c] = 1;
		afSetChannelMatrix(file, AF_DEFAULT_TRACK, channelMatrix);

		EXPECT_EQ(afSeekFrame(file, AF_DEFAULT_TRACK, 0), 0);

		T *readSamples = new T[frameCount]; 
		AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK,
			readSamples, frameCount);
		EXPECT_EQ(framesRead, frameCount);

		for (int i=0; i<frameCount; i++)
			EXPECT_EQ(readSamples[i], samples[2*i + c]);

		delete [] readSamples;
	}

	EXPECT_EQ(afCloseFile(file), 0);

	::unlink(kTestFileName);
}
Esempio n. 5
0
int channel_write_fax_channel(uc_t *uc, int chan, void *user_data, uint8_t *buf, int max_len)
{
    int len;

    len = t30_tx(&(chan_stuff[chan].fax), (int16_t *) buf, max_len >> 1);
    afWriteFrames(txhandle, AF_DEFAULT_TRACK, buf, len);
    if (len > 0)
        len <<= 1;
    return len;
}
Esempio n. 6
0
void testfloat (int fileFormat)
{
	AFfilesetup	setup;
	AFfilehandle	file;
	int		framesWritten, framesRead;
	const int 	frameCount = SAMPLE_COUNT/2;
	float		readsamples[SAMPLE_COUNT];
	int		i;
	int		sampleFormat, sampleWidth;

	setup = afNewFileSetup();

	afInitFileFormat(setup, fileFormat);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_FLOAT, 32);
	afInitChannels(setup, AF_DEFAULT_TRACK, 2);

	ensure(createTemporaryFile("testfloat", &sTestFileName),
		"could not create temporary file");
	file = afOpenFile(sTestFileName, "w", setup);
	ensure(file != AF_NULL_FILEHANDLE, "could not open file for writing");

	afFreeFileSetup(setup);

	framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples,
		frameCount);
	ensure(framesWritten == frameCount, "number of frames written does not match number of frames requested");

	ensure(afCloseFile(file) == 0, "error closing file");

	file = afOpenFile(sTestFileName, "r", AF_NULL_FILESETUP);
	ensure(file != AF_NULL_FILEHANDLE, "could not open file for reading");

	ensure(afGetChannels(file, AF_DEFAULT_TRACK) == 2,
		"file doesn't have exactly two channels");
	afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth);
	ensure(sampleFormat == AF_SAMPFMT_FLOAT && sampleWidth == 32,
		"file doesn't contain 32-bit floating-point data");
	ensure(afGetFileFormat(file, NULL) == fileFormat,
		"file format doesn't match format requested");

	framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readsamples,
		frameCount);
	ensure(framesRead == frameCount, "number of frames read does not match number of frames requested");

	for (i=0; i<SAMPLE_COUNT; i++)
	{
		ensure(readsamples[i] == samples[i],
			"data written to file doesn't match data read");
	}

	ensure(afCloseFile(file) == 0, "error closing file");

	cleanup();
}
Esempio n. 7
0
void channel_read_adsi_channel(uc_t *uc, int chan, void *user_data, uint8_t *buf, int len)
{
    int i;
    int xlen;
    int16_t pcm_buf[1024];
    char *s;
    int outframes;
    
    for (i = 0;  i < len;  i++)
        pcm_buf[i] = alaw_to_linear(buf[i]);
    /*endfor*/
    outframes = afWriteFrames(rxhandle,
                              AF_DEFAULT_TRACK,
                              pcm_buf,
                              len);
    if (outframes != len)
    {
        printf("Failed to write %d samples\n", len);
        exit(2);
    }
    
    dtmf_rx(&chan_stuff[chan].dtmf_state, pcm_buf, len);
    xlen = dtmf_rx_get(&chan_stuff[chan].dtmf_state,
                       chan_stuff[chan].dtmf + chan_stuff[chan].dtmf_ptr,
                       100 - chan_stuff[chan].dtmf_ptr);
    if (xlen > 0)
    {
        s = chan_stuff[chan].dtmf + chan_stuff[chan].dtmf_ptr;
        while (*s)
        {
            if (*s == '#')
            {
                uc_set_channel_read_callback(uc, 0, NULL, 0);
                uc_set_channel_write_callback(uc, 0, NULL, 0);
                if (uc_call_control(uc, UC_OP_DROPCALL, chan_stuff[chan].crn, (void *) UC_CAUSE_NORMAL_CLEARING))
                    printf ("A Drop Call failed\n");
                /*endif*/
                break;
            }
            /*endif*/
            s++;
        }
        /*endwhile*/
        printf("Got '%s'\n", chan_stuff[chan].dtmf);
        chan_stuff[chan].dtmf_ptr += xlen;
    }
    /*endif*/
    adsi_rx(&(chan_stuff[chan].adsi_rx), pcm_buf, len);
}
Esempio n. 8
0
/*
	Copy audio data from one file to another.  This function
	assumes that the virtual sample formats of the two files
	match.
*/
int copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid,
	AFframecount totalFrameCount)
{
	AFframecount totalFramesWritten = 0;
	void *buffer;
	int frameSize;
	bool ok = true, done = false;

	frameSize = afGetVirtualFrameSize(infile, trackid, 1);

	buffer = malloc(BUFFER_FRAME_COUNT * frameSize);

	while (!done)
	{
		AFframecount	framesToRead = BUFFER_FRAME_COUNT;
		AFframecount	framesRead, framesWritten;

		framesRead = afReadFrames(infile, trackid, buffer,
			framesToRead);

		if (framesRead < 0)
		{
			fprintf(stderr, "Bad read of audio track data.\n");
			ok = false;
			done = true;
		}

		framesWritten = afWriteFrames(outfile, trackid, buffer,
			framesRead);

		if (framesWritten < 0)
		{
			fprintf(stderr, "Bad write of audio track data.\n");
			ok = false;
			done = true;
		}
		else
		{
			totalFramesWritten += framesWritten;
		}

		if (totalFramesWritten == totalFrameCount)
			done = true;
	}

	free(buffer);

	return ok;
}
boolByte writeBlockToAudiofile(void* sampleSourcePtr, const SampleBuffer sampleBuffer) {
  SampleSource sampleSource = (SampleSource)sampleSourcePtr;
  SampleSourceAudiofileData extraData = (SampleSourceAudiofileData)(sampleSource->extraData);
  int result = 0;

  if(extraData->pcmBuffer == NULL) {
    extraData->pcmBuffer = (short*)malloc(sizeof(short) * getNumChannels() * getBlocksize());
  }
  memset(extraData->pcmBuffer, 0, sizeof(short) * getNumChannels() * getBlocksize());
  convertSampleBufferToPcmData(sampleBuffer, extraData->pcmBuffer, false);

  result = afWriteFrames(extraData->fileHandle, AF_DEFAULT_TRACK, extraData->pcmBuffer, getBlocksize());
  sampleSource->numSamplesProcessed += getBlocksize() * getNumChannels();
  return (result == 1);
}
Esempio n. 10
0
static void
file_poll_ready_playing (gpointer data,
			 gint source,
			 GdkInputCondition condition)
{
    file_driver * const d = data;

    if(!d->firstpoll) {
	afWriteFrames(d->outfile, AF_DEFAULT_TRACK, d->sndbuf, d->sndbuf_size / 4);
	d->playtime += (double)(d->sndbuf_size) / 4 / d->p_mixfreq;
    }

    d->firstpoll = FALSE;

    audio_mix(d->sndbuf, d->sndbuf_size / 4, d->p_mixfreq, ST_MIXER_FORMAT_S16_LE | ST_MIXER_FORMAT_STEREO);
}
Esempio n. 11
0
TEST_F(SignConversionTest, Int16)
{
	AFfilehandle file = createTestFile(16);
	const int16_t data[] = { kMinInt16, 0, kMaxInt16 };
	const int frameCount = sizeof (data) / sizeof (data[0]);
	AFframecount framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, data, frameCount);
	ASSERT_EQ(framesWritten, frameCount);
	afCloseFile(file);
	file = openTestFile(16);
	ASSERT_TRUE(file != NULL);
	uint16_t readData[frameCount];
	AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readData, frameCount);
	ASSERT_EQ(framesRead, frameCount);
	afCloseFile(file);
	const uint16_t expectedData[] = { 0, -kMinInt16, kMaxUInt16 };
	for (int i=0; i<frameCount; i++)
		EXPECT_EQ(readData[i], expectedData[i]);
}
Esempio n. 12
0
PRIVATE int output_fragment(AFfilehandle f, SAMPLE *l_buf, SAMPLE *r_buf, int length) {
  OUTPUTSAMPLE *outbuf;
  int buflen = length * sizeof(OUTPUTSAMPLE) * 2;
  int i;

  if (length <= 0)
    return 0;

  outbuf = g_alloca(buflen);

  for (i = 0; i < length; i++) {
    outbuf[i<<1]       = (OUTPUTSAMPLE) MIN(MAX(l_buf[i] * 32767, -32768), 32767);
    outbuf[(i<<1) + 1] = (OUTPUTSAMPLE) MIN(MAX(r_buf[i] * 32767, -32768), 32767);
  }

  i = afWriteFrames(f, AF_DEFAULT_TRACK, outbuf, length);
  return i;
}
Esempio n. 13
0
static inline void put_residue(int16_t amp)
{
    int outframes;

    residue_sound[residue_cur++] = amp;
    if (residue_cur >= SAMPLE_RATE)
    {
        outframes = afWriteFrames(residuehandle,
                                  AF_DEFAULT_TRACK,
                                  residue_sound,
                                  residue_cur);
        if (outframes != residue_cur)
        {
            fprintf(stderr, "    Error writing residue sound\n");
            exit(2);
        }
        residue_cur = 0;
    }
}
Esempio n. 14
0
static inline void put_residue(int16_t tx, int16_t residue)
{
    int outframes;

    residue_sound[residue_cur++] = tx;
    residue_sound[residue_cur++] = residue;
    if (residue_cur >= 8000)
    {
        residue_cur >>= 1;
        outframes = afWriteFrames(resulthandle,
                                  AF_DEFAULT_TRACK,
                                  residue_sound,
                                  residue_cur);
        if (outframes != residue_cur)
        {
            fprintf(stderr, "    Error writing residue sound\n");
            exit(2);
        }
        residue_cur = 0;
    }
Esempio n. 15
0
TEST_F(PCMMappingTest, Double)
{
	AFfilehandle file = createTestFile(AF_SAMPFMT_DOUBLE, 64);
	const double data[] = { -1, 0, 1 };
	const int frameCount = sizeof (data) / sizeof (data[0]);
	AFframecount framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, data, frameCount);
	ASSERT_EQ(framesWritten, frameCount);
	afCloseFile(file);
	file = openTestFile();
	ASSERT_TRUE(file != NULL);
	double slope = 2, intercept = 2, minClip = 0, maxClip = 4;
	afSetVirtualPCMMapping(file, AF_DEFAULT_TRACK, slope, intercept, minClip, maxClip);
	double readData[frameCount];
	AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readData, frameCount);
	ASSERT_EQ(framesRead, frameCount);
	afCloseFile(file);
	const double expectedData[] = { 0, 2, 4 };
	for (int i=0; i<frameCount; i++)
		EXPECT_EQ(readData[i], expectedData[i]);
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    plc_state_t plc;
    int inframes;
    int outframes;
    int16_t amp[1024];
    int block_no;
    int lost_blocks;
    int block_len;
    int loss_rate;
    int dropit;
    int block_real;
    int block_synthetic;
    int tone;
    int i;
    uint32_t phase_acc;
    int32_t phase_rate;

    loss_rate = 25;
    block_len = 160;
    block_real = FALSE;
    block_synthetic = FALSE;
    tone = -1;
    for (i = 1;  i < argc;  i++)
    {
        if (strcmp(argv[i], "-l") == 0)
        {
            loss_rate = atoi(argv[++i]);
            continue;
        }
        if (strcmp(argv[i], "-b") == 0)
        {
            block_len = atoi(argv[++i]);
            continue;
        }
        if (strcmp(argv[i], "-t") == 0)
        {
            tone = atoi(argv[++i]);
            continue;
        }
        if (strcmp(argv[i], "-r") == 0)
            block_real = TRUE;
        if (strcmp(argv[i], "-s") == 0)
            block_synthetic = TRUE;
    }
    if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
    {
        fprintf(stderr, "    Failed to create file setup\n");
        exit(2);
    }
    afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
    afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
    afInitFileFormat(filesetup, AF_FILE_WAVE);
    afInitChannels(filesetup, AF_DEFAULT_TRACK, 1);

    phase_rate = 0;
    inhandle = NULL;
    if (tone < 0)
    {
        if ((inhandle = afOpenFile(INPUT_FILE_NAME, "r", NULL)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Failed to open wave file '%s'\n", INPUT_FILE_NAME);
            exit(2);
        }
    }
    else
    {
        phase_rate = dds_phase_ratef((float) tone);
    }
    if ((outhandle = afOpenFile(OUTPUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open wave file '%s'\n", OUTPUT_FILE_NAME);
        exit(2);
    }
    plc_init(&plc);
    lost_blocks = 0;
    for (block_no = 0;  ;  block_no++)
    {
        if (tone < 0)
        {
            inframes = afReadFrames(inhandle,
                                    AF_DEFAULT_TRACK,
                                    amp,
                                    block_len);
            if (inframes != block_len)
                break;
        }
        else
        {
            if (block_no > 10000)
                break;
            for (i = 0;  i < block_len;  i++)
                amp[i] = (int16_t) dds_modf(&phase_acc, phase_rate, 10000.0, 0);
            inframes = block_len;
        }
        dropit = rand()/(RAND_MAX/100);
        if (dropit > loss_rate)
        {
            plc_rx(&plc, amp, inframes);
            if (block_real)
                memset(amp, 0, sizeof(int16_t)*inframes);
        }
        else
        {
            lost_blocks++;
            plc_fillin(&plc, amp, inframes);
            if (block_synthetic)
                memset(amp, 0, sizeof(int16_t)*inframes);
        }
        outframes = afWriteFrames(outhandle,
                                  AF_DEFAULT_TRACK,
                                  amp,
                                  inframes);
        if (outframes != inframes)
        {
            fprintf(stderr, "    Error writing out sound\n");
            exit(2);
        }
    }
    printf("Dropped %d of %d blocks\n", lost_blocks, block_no);
    if (tone < 0)
    {
        if (afCloseFile(inhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", INPUT_FILE_NAME);
            exit(2);
        }
    }
    if (afCloseFile(outhandle) != 0)
    {
        fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME);
        exit(2);
    }
    afFreeFileSetup(filesetup);
    return 0;
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
    fsk_tx_state_t *caller_tx;
    fsk_rx_state_t *caller_rx;
    fsk_tx_state_t *answerer_tx;
    fsk_rx_state_t *answerer_rx;
    bert_state_t caller_bert;
    bert_state_t answerer_bert;
    bert_results_t bert_results;
    power_meter_t caller_meter;
    power_meter_t answerer_meter;
    int16_t caller_amp[BLOCK_LEN];
    int16_t answerer_amp[BLOCK_LEN];
    int16_t caller_model_amp[BLOCK_LEN];
    int16_t answerer_model_amp[BLOCK_LEN];
    int16_t out_amp[2*BLOCK_LEN];
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    int outframes;    
    int i;
    int j;
    int samples;
    int test_bps;
    int noise_level;
    int noise_sweep;
    int bits_per_test;
    int line_model_no;
    int modem_under_test_1;
    int modem_under_test_2;
    int modems_set;
    int log_audio;
    int channel_codec;
    int rbs_pattern;
    int on_at;
    int off_at;
    tone_gen_descriptor_t tone_desc;
    tone_gen_state_t tone_tx;
    int opt;

    channel_codec = MUNGE_CODEC_NONE;
    rbs_pattern = 0;
    line_model_no = 0;
    decode_test_file = NULL;
    noise_sweep = FALSE;
    modem_under_test_1 = FSK_V21CH1;
    modem_under_test_2 = FSK_V21CH2;
    log_audio = FALSE;
    modems_set = 0;
    while ((opt = getopt(argc, argv, "c:dlm:nr:s:")) != -1)
    {
        switch (opt)
        {
        case 'c':
            channel_codec = atoi(optarg);
            break;
        case 'd':
            decode_test_file = optarg;
            break;
        case 'l':
            log_audio = TRUE;
            break;
        case 'm':
            line_model_no = atoi(optarg);
            break;
        case 'n':
            noise_sweep = TRUE;
            break;
        case 'r':
            rbs_pattern = atoi(optarg);
            break;
        case 's':
            switch (modems_set++)
            {
            case 0:
                modem_under_test_1 = atoi(optarg);
                break;
            case 1:
                modem_under_test_2 = atoi(optarg);
                break;
            }
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }

    if (modem_under_test_1 >= 0)
        printf("Modem channel 1 is '%s'\n", preset_fsk_specs[modem_under_test_1].name);
    if (modem_under_test_2 >= 0)
        printf("Modem channel 2 is '%s'\n", preset_fsk_specs[modem_under_test_2].name);

    outhandle = AF_NULL_FILEHANDLE;

    if (log_audio)
    {
        if ((outhandle = afOpenFile_telephony_write(OUTPUT_FILE_NAME, 2)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot create wave file '%s'\n", OUTPUT_FILE_NAME);
            exit(2);
        }
    }
    noise_level = -200;
    bits_per_test = 0;
    inhandle = NULL;

    memset(caller_amp, 0, sizeof(*caller_amp));
    memset(answerer_amp, 0, sizeof(*answerer_amp));
    memset(caller_model_amp, 0, sizeof(*caller_model_amp));
    memset(answerer_model_amp, 0, sizeof(*answerer_model_amp));
    power_meter_init(&caller_meter, 7);
    power_meter_init(&answerer_meter, 7);

    if (decode_test_file)
    {
        if ((inhandle = afOpenFile_telephony_read(decode_test_file, 1)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot open wave file '%s'\n", decode_test_file);
            exit(2);
        }
        caller_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_1], TRUE, put_bit, NULL);
        fsk_rx_set_modem_status_handler(caller_rx, rx_status, (void *) &caller_rx);
        test_bps = preset_fsk_specs[modem_under_test_1].baud_rate;

        for (;;)
        {
            samples = afReadFrames(inhandle,
                                   AF_DEFAULT_TRACK,
                                   caller_model_amp,
                                   BLOCK_LEN);
            if (samples < BLOCK_LEN)
                break;
            for (i = 0;  i < samples;  i++)
                power_meter_update(&caller_meter, caller_model_amp[i]);
            fsk_rx(caller_rx, caller_model_amp, samples);
        }

        if (afCloseFile(inhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", decode_test_file);
            exit(2);
        }
    }
    else
    {
        printf("Test cutoff level\n");
        caller_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_1], TRUE, cutoff_test_put_bit, NULL);
        fsk_rx_signal_cutoff(caller_rx, -30.0f);
        fsk_rx_set_modem_status_handler(caller_rx, cutoff_test_rx_status, (void *) &caller_rx);
        on_at = 0;
        for (i = -40;  i < -25;  i++)
        {
            make_tone_gen_descriptor(&tone_desc,
                                     1500,
                                     i,
                                     0,
                                     0,
                                     1,
                                     0,
                                     0,
                                     0,
                                     TRUE);
            tone_gen_init(&tone_tx, &tone_desc);
            for (j = 0;  j < 10;  j++)
            {
                samples = tone_gen(&tone_tx, caller_model_amp, 160);
                fsk_rx(caller_rx, caller_model_amp, samples);
            }
            if (cutoff_test_carrier)
               break;
        }
        on_at = i;
        off_at = 0;
        for (  ;  i > -40;  i--)
        {
            make_tone_gen_descriptor(&tone_desc,
                                     1500,
                                     i,
                                     0,
                                     0,
                                     1,
                                     0,
                                     0,
                                     0,
                                     TRUE);
            tone_gen_init(&tone_tx, &tone_desc);
            for (j = 0;  j < 10;  j++)
            {
                samples = tone_gen(&tone_tx, caller_model_amp, 160);
                fsk_rx(caller_rx, caller_model_amp, samples);
            }
            if (!cutoff_test_carrier)
                break;
        }
        off_at = i;
        printf("Carrier on at %d, off at %d\n", on_at, off_at);
        if (on_at < -29  ||  on_at > -26  
            ||
            off_at < -35  ||  off_at > -31)
        {
            printf("Tests failed.\n");
            exit(2);
        }
                
        printf("Test with BERT\n");
        test_bps = preset_fsk_specs[modem_under_test_1].baud_rate;
        if (modem_under_test_1 >= 0)
        {
            caller_tx = fsk_tx_init(NULL, &preset_fsk_specs[modem_under_test_1], (get_bit_func_t) bert_get_bit, &caller_bert);
            fsk_tx_set_modem_status_handler(caller_tx, tx_status, (void *) &caller_tx);
            answerer_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_1], TRUE, (put_bit_func_t) bert_put_bit, &answerer_bert);
            fsk_rx_set_modem_status_handler(answerer_rx, rx_status, (void *) &answerer_rx);
        }
        if (modem_under_test_2 >= 0)
        {
            answerer_tx = fsk_tx_init(NULL, &preset_fsk_specs[modem_under_test_2], (get_bit_func_t) bert_get_bit, &answerer_bert);
            fsk_tx_set_modem_status_handler(answerer_tx, tx_status, (void *) &answerer_tx);
            caller_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_2], TRUE, (put_bit_func_t) bert_put_bit, &caller_bert);
            fsk_rx_set_modem_status_handler(caller_rx, rx_status, (void *) &caller_rx);
        }
        test_bps = preset_fsk_specs[modem_under_test_1].baud_rate;

        bits_per_test = 500000;
        noise_level = -24;

        bert_init(&caller_bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
        bert_set_report(&caller_bert, 100000, reporter, (void *) (intptr_t) 1);
        bert_init(&answerer_bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
        bert_set_report(&answerer_bert, 100000, reporter, (void *) (intptr_t) 2);
        if ((model = both_ways_line_model_init(line_model_no, (float) noise_level, line_model_no, (float) noise_level, channel_codec, rbs_pattern)) == NULL)
        {
            fprintf(stderr, "    Failed to create line model\n");
            exit(2);
        }

        for (;;)
        {
            samples = fsk_tx(caller_tx, caller_amp, BLOCK_LEN);
            for (i = 0;  i < samples;  i++)
                power_meter_update(&caller_meter, caller_amp[i]);
            samples = fsk_tx(answerer_tx, answerer_amp, BLOCK_LEN);
            for (i = 0;  i < samples;  i++)
                power_meter_update(&answerer_meter, answerer_amp[i]);
            both_ways_line_model(model,
                                 caller_model_amp,
                                 caller_amp,
                                 answerer_model_amp,
                                 answerer_amp,
                                 samples);

            //printf("Powers %10.5fdBm0 %10.5fdBm0\n", power_meter_current_dbm0(&caller_meter), power_meter_current_dbm0(&answerer_meter));

            fsk_rx(answerer_rx, caller_model_amp, samples);
            for (i = 0;  i < samples;  i++)
                out_amp[2*i] = caller_model_amp[i];
            for (  ;  i < BLOCK_LEN;  i++)
                out_amp[2*i] = 0;

            fsk_rx(caller_rx, answerer_model_amp, samples);
            for (i = 0;  i < samples;  i++)
                out_amp[2*i + 1] = answerer_model_amp[i];
            for (  ;  i < BLOCK_LEN;  i++)
                out_amp[2*i + 1] = 0;
        
            if (log_audio)
            {
                outframes = afWriteFrames(outhandle,
                                          AF_DEFAULT_TRACK,
                                          out_amp,
                                          BLOCK_LEN);
                if (outframes != BLOCK_LEN)
                {
                    fprintf(stderr, "    Error writing wave file\n");
                    exit(2);
                }
            }

            if (samples < BLOCK_LEN)
            {
                bert_result(&caller_bert, &bert_results);
                fprintf(stderr, "%ddB AWGN, %d bits, %d bad bits, %d resyncs\n", noise_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
                if (!noise_sweep)
                {
                    if (bert_results.total_bits != bits_per_test - 43
                        ||
                        bert_results.bad_bits != 0
                        ||
                        bert_results.resyncs != 0)
                    {
                        printf("Tests failed.\n");
                        exit(2);
                    }
                }
                bert_result(&answerer_bert, &bert_results);
                fprintf(stderr, "%ddB AWGN, %d bits, %d bad bits, %d resyncs\n", noise_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
                if (!noise_sweep)
                {
                    if (bert_results.total_bits != bits_per_test - 43
                        ||
                        bert_results.bad_bits != 0
                        ||
                        bert_results.resyncs != 0)
                    {
                        printf("Tests failed.\n");
                        exit(2);
                    }
                    break;
                }
    
                /* Put a little silence between the chunks in the file. */
                memset(out_amp, 0, sizeof(out_amp));
                if (log_audio)
                {
                    for (i = 0;  i < 200;  i++)
                    {
                        outframes = afWriteFrames(outhandle,
                                                  AF_DEFAULT_TRACK,
                                                  out_amp,
                                                  BLOCK_LEN);
                    }
                }
                if (modem_under_test_1 >= 0)
                {
                    caller_tx = fsk_tx_init(NULL, &preset_fsk_specs[modem_under_test_1], (get_bit_func_t) bert_get_bit, &caller_bert);
                    fsk_tx_set_modem_status_handler(caller_tx, tx_status, (void *) &caller_tx);
                    answerer_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_1], TRUE, (put_bit_func_t) bert_put_bit, &answerer_bert);
                    fsk_rx_set_modem_status_handler(answerer_rx, rx_status, (void *) &answerer_rx);
                }
                if (modem_under_test_2 >= 0)
                {
                    answerer_tx = fsk_tx_init(NULL, &preset_fsk_specs[modem_under_test_2], (get_bit_func_t) bert_get_bit, &answerer_bert);
                    fsk_tx_set_modem_status_handler(answerer_tx, tx_status, (void *) &answerer_tx);
                    caller_rx = fsk_rx_init(NULL, &preset_fsk_specs[modem_under_test_2], TRUE, (put_bit_func_t) bert_put_bit, &caller_bert);
                    fsk_rx_set_modem_status_handler(caller_rx, rx_status, (void *) &caller_rx);
                }
                noise_level++;
                if ((model = both_ways_line_model_init(line_model_no, (float) noise_level, line_model_no, noise_level, channel_codec, 0)) == NULL)
                {
                    fprintf(stderr, "    Failed to create line model\n");
                    exit(2);
                }
                bert_init(&caller_bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
                bert_set_report(&caller_bert, 100000, reporter, (void *) (intptr_t) 1);
                bert_init(&answerer_bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
                bert_set_report(&answerer_bert, 100000, reporter, (void *) (intptr_t) 2);
            }
        }
        printf("Tests passed.\n");
    }
    if (log_audio)
    {
        if (afCloseFile(outhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME);
            exit(2);
        }
    }
    return  0;
}
Esempio n. 18
0
int main(int argc, char *argv[])
{
    v27ter_rx_state_t rx;
    v27ter_tx_state_t tx;
    bert_results_t bert_results;
    int16_t gen_amp[BLOCK_LEN];
    int16_t amp[BLOCK_LEN];
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    int outframes;
    int samples;
    int tep;
    int test_bps;
    int noise_level;
    int signal_level;
    int bits_per_test;
    int line_model_no;
    int block;
    int log_audio;
    int channel_codec;
    int rbs_pattern;
    float x;
    int opt;

    channel_codec = MUNGE_CODEC_NONE;
    rbs_pattern = 0;
    test_bps = 4800;
    tep = FALSE;
    line_model_no = 0;
    decode_test_file = NULL;
    use_gui = FALSE;
    noise_level = -70;
    signal_level = -13;
    bits_per_test = 50000;
    log_audio = FALSE;
    while ((opt = getopt(argc, argv, "b:c:d:glm:n:r:s:t")) != -1)
    {
        switch (opt)
        {
        case 'b':
            bits_per_test = atoi(optarg);
            break;
        case 'c':
            channel_codec = atoi(optarg);
            break;
        case 'd':
            decode_test_file = optarg;
            break;
        case 'g':
#if defined(ENABLE_GUI)
            use_gui = TRUE;
#else
            fprintf(stderr, "Graphical monitoring not available\n");
            exit(2);
#endif
            break;
        case 'l':
            log_audio = TRUE;
            break;
        case 'm':
            line_model_no = atoi(optarg);
            break;
        case 'n':
            noise_level = atoi(optarg);
            break;
        case 'r':
            rbs_pattern = atoi(optarg);
            break;
        case 's':
            signal_level = atoi(optarg);
            break;
        case 't':
            tep = TRUE;
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }
    argc -= optind;
    argv += optind;
    if (argc > 0)
    {
        if (strcmp(argv[0], "4800") == 0)
            test_bps = 4800;
        else if (strcmp(argv[0], "2400") == 0)
            test_bps = 2400;
        else
        {
            fprintf(stderr, "Invalid bit rate\n");
            exit(2);
        }
    }

    inhandle = NULL;
    outhandle = NULL;

    filesetup = AF_NULL_FILESETUP;
    if (log_audio)
    {
        if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
        {
            fprintf(stderr, "    Failed to create file setup\n");
            exit(2);
        }
        afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
        afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
        afInitFileFormat(filesetup, AF_FILE_WAVE);
        afInitChannels(filesetup, AF_DEFAULT_TRACK, 1);
        if ((outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot create wave file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
    }

    if (decode_test_file)
    {
        /* We will decode the audio from a wave file. */
        if ((inhandle = afOpenFile(decode_test_file, "r", NULL)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot open wave file '%s'\n", decode_test_file);
            exit(2);
        }
        if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0f)
        {
            printf("    Unexpected frame size in speech file '%s' (%f)\n", decode_test_file, x);
            exit(2);
        }
        if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE)
        {
            printf("    Unexpected sample rate in speech file '%s' (%f)\n", decode_test_file, x);
            exit(2);
        }
        if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0f)
        {
            printf("    Unexpected number of channels in speech file '%s' (%f)\n", decode_test_file, x);
            exit(2);
        }
    }
    else
    {
        /* We will generate V.27ter audio, and add some noise to it. */
        v27ter_tx_init(&tx, test_bps, tep, v27tergetbit, NULL);
        v27ter_tx_power(&tx, signal_level);
        v27ter_tx_set_modem_status_handler(&tx, v27ter_tx_status, (void *) &tx);
        /* Move the carrier off a bit */
        tx.carrier_phase_rate = dds_phase_ratef(1810.0f);

        bert_init(&bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
        bert_set_report(&bert, 10000, reporter, NULL);

        if ((line_model = one_way_line_model_init(line_model_no, (float) noise_level, channel_codec, rbs_pattern)) == NULL)
        {
            fprintf(stderr, "    Failed to create line model\n");
            exit(2);
        }
    }

    v27ter_rx_init(&rx, test_bps, v27terputbit, NULL);
    v27ter_rx_set_modem_status_handler(&rx, v27ter_rx_status, (void *) &rx);
    v27ter_rx_set_qam_report_handler(&rx, qam_report, (void *) &rx);
    span_log_set_level(&rx.logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW);
    span_log_set_tag(&rx.logging, "V.27ter-rx");

#if defined(ENABLE_GUI)
    if (use_gui)
    {
        qam_monitor = qam_monitor_init(2.0f, NULL);
        if (!decode_test_file)
        {
            start_line_model_monitor(129);
            line_model_monitor_line_model_update(line_model->near_filter, line_model->near_filter_len);
        }
    }
#endif

    memset(&latest_results, 0, sizeof(latest_results));
    for (block = 0;  ;  block++)
    {
        if (decode_test_file)
        {
            samples = afReadFrames(inhandle,
                                   AF_DEFAULT_TRACK,
                                   amp,
                                   BLOCK_LEN);
#if defined(ENABLE_GUI)
            if (use_gui)
                qam_monitor_update_audio_level(qam_monitor, amp, samples);
#endif
            if (samples == 0)
                break;
        }
        else
        {
            samples = v27ter_tx(&tx, gen_amp, BLOCK_LEN);
#if defined(ENABLE_GUI)
            if (use_gui)
                qam_monitor_update_audio_level(qam_monitor, gen_amp, samples);
#endif
            if (samples == 0)
            {
                printf("Restarting on zero output\n");

                /* Push a little silence through, to ensure all the data bits get out of the buffers */
                memset(amp, 0, BLOCK_LEN*sizeof(int16_t));
                v27ter_rx(&rx, amp, BLOCK_LEN);
                v27ter_rx(&rx, amp, BLOCK_LEN);
                v27ter_rx(&rx, amp, BLOCK_LEN);

                /* Note that we might get a few bad bits as the carrier shuts down. */
                bert_result(&bert, &bert_results);
                fprintf(stderr, "Final result %ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
                fprintf(stderr, "Last report  %ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, latest_results.total_bits, latest_results.bad_bits, latest_results.resyncs);
                /* See if bit errors are appearing yet. Also check we are getting enough bits out of the receiver. The last regular report
                   should be error free, though the final report will generally contain bits errors as the carrier was dying. The total
                   number of bits out of the receiver should be at least the number we sent. Also, since BERT sync should have occurred
                   rapidly at the start of transmission, the last report should have occurred at not much less than the total number of
                   bits we sent. */
                if (bert_results.total_bits < bits_per_test
                    ||
                    latest_results.total_bits < bits_per_test - 100
                    ||
                    latest_results.bad_bits != 0)
                {
                    break;
                }
                memset(&latest_results, 0, sizeof(latest_results));
                signal_level--;
                v27ter_tx_restart(&tx, test_bps, tep);
                v27ter_tx_power(&tx, signal_level);
                v27ter_rx_restart(&rx, test_bps, FALSE);
                bert_init(&bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
                bert_set_report(&bert, 10000, reporter, NULL);
                one_way_line_model_release(line_model);
                if ((line_model = one_way_line_model_init(line_model_no, (float) noise_level, channel_codec, 0)) == NULL)
                {
                    fprintf(stderr, "    Failed to create line model\n");
                    exit(2);
                }
            }

            if (log_audio)
            {
                outframes = afWriteFrames(outhandle,
                                          AF_DEFAULT_TRACK,
                                          gen_amp,
                                          samples);
                if (outframes != samples)
                {
                    fprintf(stderr, "    Error writing wave file\n");
                    exit(2);
                }
            }
            one_way_line_model(line_model, amp, gen_amp, samples);
        }
#if defined(ENABLE_GUI)
        if (use_gui  &&  !decode_test_file)
            line_model_monitor_line_spectrum_update(amp, samples);
#endif
        v27ter_rx(&rx, amp, samples);
        if (decode_test_file == NULL  &&  block%500 == 0)
            printf("Noise level is %d\n", noise_level);
    }
    if (!decode_test_file)
    {
        bert_result(&bert, &bert_results);
        fprintf(stderr, "At completion:\n");
        fprintf(stderr, "Final result %ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
        fprintf(stderr, "Last report  %ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, latest_results.total_bits, latest_results.bad_bits, latest_results.resyncs);
        one_way_line_model_release(line_model);
        if (signal_level > -43)
        {
            printf("Tests failed.\n");
            exit(2);
        }

        printf("Tests passed.\n");
    }
#if defined(ENABLE_GUI)
    if (use_gui)
        qam_wait_to_end(qam_monitor);
#endif
    if (log_audio)
    {
        if (afCloseFile(outhandle))
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
        afFreeFileSetup(filesetup);
    }
    return  0;
}
Esempio n. 19
0
TEST(Seek, Seek)
{
	std::string testFileName;
	ASSERT_TRUE(createTemporaryFile("Seek", &testFileName));

	const int kFrameCount = 2000;
	const int kPadFrameCount = kFrameCount + 5;
	const int kDataLength = kFrameCount * sizeof (int16_t);

	int16_t data[kFrameCount];
	int16_t readData[kPadFrameCount];

	AFfilesetup setup = afNewFileSetup();
	ASSERT_TRUE(setup);

	afInitFileFormat(setup, AF_FILE_AIFF);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);

	AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup);
	ASSERT_TRUE(file) << "could not open file for writing";

	afFreeFileSetup(setup);

	/* Initialize data to a nontrivial test pattern. */
	for (int i=0; i<kFrameCount; i++)
	{
		if ((i%2) != 0)
			data[i] = i;
		else
			data[i] = -i;
	}

	ASSERT_EQ(afWriteFrames(file, AF_DEFAULT_TRACK, data, kFrameCount),
		kFrameCount);

	afCloseFile(file);

	file = afOpenFile(testFileName.c_str(), "r", AF_NULL_FILESETUP);
	ASSERT_TRUE(file) << "Could not open file for reading";

	/*
		For each position in the file, seek to that position and
		read to the end of the file, checking that the data read
		matches the data written.
	*/
	for (int i=0; i<kFrameCount; i++)
	{
		memset(readData, 0, kDataLength);

		AFfileoffset currentposition = afSeekFrame(file, AF_DEFAULT_TRACK, i);
		ASSERT_EQ(currentposition, i) << "Incorrect seek position";

		AFframecount framesread = afReadFrames(file, AF_DEFAULT_TRACK,
			readData + i, kPadFrameCount);
		ASSERT_EQ(framesread, kFrameCount - i) <<
			"Incorrect number of frames read";

		ASSERT_TRUE(!memcmp(data + i, readData + i,
			framesread * sizeof (int16_t))) <<
			"Error in data read";
	}

	afCloseFile(file);

	ASSERT_EQ(::unlink(testFileName.c_str()), 0);
}
Esempio n. 20
0
int main (int argc, char **argv)
{
	AFfilesetup	setup;
	AFfilehandle	file;
	int16_t		samples[SAMPLE_COUNT] = {-1,3,9,2,-5,4,8,-3,6,21,11,-2};
	int		output = 0;

	setup = afNewFileSetup();

	afInitFileFormat(setup, AF_FILE_RAWDATA);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
	afInitChannels(setup, AF_DEFAULT_TRACK, 2);
	afInitRate(setup, AF_DEFAULT_TRACK, 44100);
#ifdef WORDS_BIGENDIAN
	afInitByteOrder(setup, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
#else
	afInitByteOrder(setup, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
#endif

	if (argc > 1 && !strcmp(argv[1], "out"))
		output = 1;

	if (output)
	{
		AFframecount	framesWritten;

		file = afOpenFD(1, "w", setup);

		afFreeFileSetup(setup);

		framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples,
			FRAME_COUNT);

		ensure(framesWritten == FRAME_COUNT,
			"incorrect number of frames written");

		fprintf(stderr, "pipe write passed\n");
	}
	else
	{
		AFframecount	framesRead;
		int16_t		samplesRead[SAMPLE_COUNT];

		file = afOpenFD(0, "r", setup);

		afFreeFileSetup(setup);

		framesRead = afReadFrames(file, AF_DEFAULT_TRACK, samplesRead,
			FRAME_COUNT);

		ensure(framesRead == FRAME_COUNT,
			"incorrect number of frames read");

		ensure(memcmp(samplesRead, samples,
			SAMPLE_COUNT * sizeof (int16_t)) == 0,
			"samples read do not match samples written");

		fprintf(stderr, "pipe read passed\n");
	}

	afCloseFile(file);

	exit(EXIT_SUCCESS);
}
Esempio n. 21
0
int main (int argc, char *argv[])
{
    int i;
    int j;
    int level;
    int clip_high;
    int clip_low;
    int total_samples;
    int seed = 1234567;
    int outframes;
    int16_t value;
    double total;
    double x;
    double p;
    double o;
    int bins[65536];
    int16_t amp[1024];
    noise_state_t noise_source;
    AFfilehandle outhandle;
    AFfilesetup filesetup;

    if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
    {
        fprintf(stderr, "    Failed to create file setup\n");
        exit(2);
    }
    afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
    afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
    afInitFileFormat(filesetup, AF_FILE_WAVE);
    afInitChannels(filesetup, AF_DEFAULT_TRACK, 1);
    if ((outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Cannot create wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }

    /* Generate AWGN at several RMS levels between -50dBOv and 0dBOv. Noise is
       generated for a large number of samples (1,000,000), and the RMS value
       of the noise is calculated along the way. If the resulting level is
       close to the requested RMS level, at least the scaling of the noise
       should be Ok. At high levels some clipping may distort the result a
       little. */
    printf("Testing with quality 7 AWGN\n");
    for (level = -50;  level <= 0;  level += 5)
    {
        clip_high = 0;
        clip_low = 0;
        total = 0.0;
        noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_AWGN, 7);
        total_samples = 1000000;
        for (i = 0;  i < total_samples;  i++)
        {
            value = noise(&noise_source);
            if (value == 32767)
                clip_high++;
            else if (value == -32768)
                clip_low++;
            total += ((double) value)*((double) value);
        }
        printf ("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n",
                log10(sqrt(total/total_samples)/32768.0)*20.0,
                level,
                100.0*(1.0 - sqrt(total/total_samples)/(pow(10.0, level/20.0)*32768.0)),
                clip_low,
                clip_high);
        if (level < -5  &&  fabs(log10(sqrt(total/total_samples)/32768.0)*20.0 - level) > 0.2)
        {
            printf("Test failed\n");
            exit(2);
        }
    }

    printf("Testing with quality 20 AWGN\n");
    for (level = -50;  level <= 0;  level += 5)
    {
        clip_high = 0;
        clip_low = 0;
        total = 0.0;
        noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_AWGN, 20);
        total_samples = 1000000;
        for (i = 0;  i < total_samples;  i++)
        {
            value = noise(&noise_source);
            if (value == 32767)
                clip_high++;
            else if (value == -32768)
                clip_low++;
            total += ((double) value)*((double) value);
        }
        printf ("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n",
                log10(sqrt(total/total_samples)/32768.0)*20.0,
                level,
                100.0*(1.0 - sqrt(total/total_samples)/(pow(10.0, level/20.0)*32768.0)),
                clip_low,
                clip_high);
        if (level < -5  &&  fabs(log10(sqrt(total/total_samples)/32768.0)*20.0 - level) > 0.2)
        {
            printf("Test failed\n");
            exit(2);
        }
    }

    /* Now look at the statistical spread of the results, by collecting data in
       bins from a large number of samples. Use a fairly high noise level, but
       low enough to avoid significant clipping. Use the Gaussian model to
       predict the real probability, and present the results for graphing. */
    memset(bins, 0, sizeof(bins));
    clip_high = 0;
    clip_low = 0;
    level = -15;
    noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_AWGN, 7);
    total_samples = 10000000;
    for (i = 0;  i < total_samples;  i++)
    {
        value = noise(&noise_source);
        if (value == 32767)
            clip_high++;
        else if (value == -32768)
            clip_low++;
        bins[value + 32768]++;
    }
    /* Find the RMS power level to expect */
    o = pow(10.0, level/20.0)*(32768.0*0.70711);
    for (i = 0;  i < 65536 - 10;  i++)
    {
        x = i - 32768;
        /* Find the real probability for this bin */
        p = (1.0/(o*sqrt(2.0*M_PI)))*exp(-(x*x)/(2.0*o*o));
        /* Now do a little smoothing on the real data to get a reasonably
           steady answer */
        x = 0;
        for (j = 0;  j < 10;  j++)
            x += bins[i + j];
        x /= 10.0;
        x /= total_samples;
        /* Now send it out for graphing. */
        if (p > 0.0000001)
            printf("%6d %.7f %.7f\n", i - 32768, x, p);
    }

    printf("Generating AWGN at -15dBOv to file\n");
    for (j = 0;  j < 50;  j++)
    {
        for (i = 0;  i < 1024;  i++)
            amp[i] = noise(&noise_source);
        outframes = afWriteFrames(outhandle,
                                  AF_DEFAULT_TRACK,
                                  amp,
                                  1024);
        if (outframes != 1024)
        {
            fprintf(stderr, "    Error writing wave file\n");
            exit(2);
        }
    }

    /* Generate AWGN at several RMS levels between -50dBm and 0dBm. Noise is
       generated for a large number of samples (1,000,000), and the RMS value
       of the noise is calculated along the way. If the resulting level is
       close to the requested RMS level, at least the scaling of the noise
       should be Ok. At high levels some clipping may distort the result a
       little. */
    printf("Testing with quality 7 Hoth noise.\n");
    for (level = -50;  level <= 0;  level += 5)
    {
        clip_high = 0;
        clip_low = 0;
        total = 0.0;
        noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_HOTH, 7);
        total_samples = 1000000;
        for (i = 0;  i < total_samples;  i++)
        {
            value = noise(&noise_source);
            if (value == 32767)
                clip_high++;
            else if (value == -32768)
                clip_low++;
            total += ((double) value)*((double) value);
        }
        printf ("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n",
                log10(sqrt(total/total_samples)/32768.0)*20.0,
                level,
                100.0*(1.0 - sqrt(total/total_samples)/(pow(10.0, level/20.0)*32768.0)),
                clip_low,
                clip_high);
        if (level < -5  &&  fabs(log10(sqrt(total/total_samples)/32768.0)*20.0 - level) > 0.2)
        {
            printf("Test failed\n");
            exit(2);
        }
    }
    
    printf("Generating Hoth noise at -15dBOv to file\n");
    level = -15;
    noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_HOTH, 7);
    for (j = 0;  j < 50;  j++)
    {
        for (i = 0;  i < 1024;  i++)
            amp[i] = noise(&noise_source);
        outframes = afWriteFrames(outhandle,
                                  AF_DEFAULT_TRACK,
                                  amp,
                                  1024);
        if (outframes != 1024)
        {
            fprintf(stderr, "    Error writing wave file\n");
            exit(2);
        }
    }

    if (afCloseFile(outhandle))
    {
        fprintf(stderr, "    Cannot close wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    afFreeFileSetup(filesetup);
    
    printf("Tests passed.\n");
    return  0;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
    bell_mf_tx_state_t *gen;
    int16_t amp[16384];
    int len;
    AFfilehandle outhandle;
    int outframes;
    int add_digits;

    if ((outhandle = afOpenFile_telephony_write(OUTPUT_FILE_NAME, 1)) == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Cannot open wave file '%s'\n", OUTPUT_FILE_NAME);
        exit(2);
    }

    gen = bell_mf_tx_init(NULL);
    len = bell_mf_tx(gen, amp, 16384);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "123", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 16384);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "456", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "789", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "*#", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    add_digits = 1;
    do
    {
        len = bell_mf_tx(gen, amp, 160);
        printf("Generated %d samples\n", len);
        if (len > 0)
        {
            outframes = afWriteFrames(outhandle,
                                      AF_DEFAULT_TRACK,
                                      amp,
                                      len);
        }
        if (add_digits)
        {
            if (bell_mf_tx_put(gen, "1234567890", -1))
            {
                printf("Digit buffer full\n");
                add_digits = 0;
            }
        }
    }
    while (len > 0);

    bell_mf_tx_init(gen);
    len = bell_mf_tx(gen, amp, 16384);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "123", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 16384);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "456", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "789", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "0*#", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    if (bell_mf_tx_put(gen, "ABC", -1))
        printf("Ooops\n");
    len = bell_mf_tx(gen, amp, 160);
    printf("Generated %d samples\n", len);
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              len);
    add_digits = 1;
    do
    {
        len = bell_mf_tx(gen, amp, 160);
        printf("Generated %d samples\n", len);
        if (len > 0)
        {
            outframes = afWriteFrames(outhandle,
                                      AF_DEFAULT_TRACK,
                                      amp,
                                      len);
        }
        if (add_digits)
        {
            if (bell_mf_tx_put(gen, "1234567890", -1))
            {
                printf("Digit buffer full\n");
                add_digits = 0;
            }
        }
    }
    while (len > 0);

    if (afCloseFile(outhandle) != 0)
    {
        fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME);
        exit (2);
    }

    return  0;
}
Esempio n. 23
0
static void testADPCM(int fileFormat, int compressionFormat, int channelCount,
	int bytesPerPacket, int framesPerPacket, int frameCount, int threshold)
{
	std::string testFileName;
	ASSERT_TRUE(createTemporaryFile("ADPCM", &testFileName));

	AFfilesetup setup = afNewFileSetup();
	afInitFileFormat(setup, fileFormat);
	afInitChannels(setup, AF_DEFAULT_TRACK, channelCount);
	afInitCompression(setup, AF_DEFAULT_TRACK, compressionFormat);
	AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup);
	ASSERT_TRUE(file);
	afFreeFileSetup(setup);

	int16_t *data = new int16_t[frameCount * channelCount];
	for (int i=0; i<frameCount; i++)
		for (int c=0; c<channelCount; c++)
			data[i*channelCount + c] = i * ((c&1) ? -1 : 1);
	
	AFframecount framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, data, frameCount);
	ASSERT_EQ(framesWritten, frameCount);

	ASSERT_EQ(afCloseFile(file), 0);

	file = afOpenFile(testFileName.c_str(), "r", AF_NULL_FILESETUP);
	ASSERT_TRUE(file);
	ASSERT_EQ(afGetCompression(file, AF_DEFAULT_TRACK), compressionFormat);
	ASSERT_EQ(afGetFrameCount(file, AF_DEFAULT_TRACK), frameCount);
	ASSERT_EQ(afGetTrackBytes(file, AF_DEFAULT_TRACK),
		(bytesPerPacket * frameCount) / framesPerPacket);

	int16_t *readData = new int16_t[frameCount * channelCount];
	AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readData, frameCount);
	ASSERT_EQ(framesRead, frameCount);

	for (int i=0; i<frameCount; i++)
		for (int c=0; c<channelCount; c++)
			EXPECT_LE(std::abs(data[i*channelCount + c] - readData[i*channelCount + c]), threshold);

	int16_t *offsetReadData = new int16_t[frameCount * channelCount];

	// Read entire file with a seek before each read operation.
	for (AFframecount offset = 0; offset < frameCount; offset += framesPerPacket + 3)
	{
		ASSERT_EQ(afSeekFrame(file, AF_DEFAULT_TRACK, offset), offset);

		AFframecount framesToRead = 1091;
		framesRead = afReadFrames(file, AF_DEFAULT_TRACK, offsetReadData, framesToRead);
		ASSERT_EQ(framesRead, std::min(framesToRead, frameCount - offset));

		for (int i=0; i<framesRead; i++)
			for (int c=0; c<channelCount; c++)
				EXPECT_EQ(readData[(i+offset)*channelCount + c],
					offsetReadData[i*channelCount + c]);
	}

	// Read entire file sequentially in multiple read operations.
	ASSERT_EQ(afSeekFrame(file, AF_DEFAULT_TRACK, 0), 0);

	AFframecount framesToRead = 1087;
	for (AFframecount offset = 0; offset < frameCount; offset += framesToRead)
	{
		framesRead = afReadFrames(file, AF_DEFAULT_TRACK, offsetReadData, framesToRead);
		ASSERT_EQ(framesRead, std::min(framesToRead, frameCount - offset));

		for (int i=0; i<framesRead; i++)
			for (int c=0; c<channelCount; c++)
				EXPECT_EQ(readData[(i+offset)*channelCount + c],
					offsetReadData[i*channelCount + c]);
	}

	ASSERT_EQ(afCloseFile(file), 0);

	delete [] data;
	delete [] readData;
	delete [] offsetReadData;

	ASSERT_EQ(::unlink(testFileName.c_str()), 0);
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    power_meter_t power_meter;
    int outframes;
    int i;
    int block;
    int pre;
    int post;
    int alaw_failures;
    int ulaw_failures;
    float worst_alaw;
    float worst_ulaw;
    float tmp;
    
    if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
    {
        fprintf(stderr, "    Failed to create file setup\n");
        exit(2);
    }
    afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
    afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
    afInitFileFormat(filesetup, AF_FILE_WAVE);
    afInitChannels(filesetup, AF_DEFAULT_TRACK, 1);

    if ((outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Cannot create wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }

    printf("Conversion accuracy tests.\n");
    alaw_failures = 0;
    ulaw_failures = 0;
    worst_alaw = 0.0;
    worst_ulaw = 0.0;
    for (block = 0;  block < 1;  block++)
    {
        for (i = 0;  i < 65536;  i++)
        {
            pre = i - 32768;
            post = alaw_to_linear(linear_to_alaw(pre));
            if (abs(pre) > 140)
            {
                tmp = (float) abs(post - pre)/(float) abs(pre);
                if (tmp > 0.10)
                {
                    printf("A-law: Excessive error at %d (%d)\n", pre, post);
                    alaw_failures++;
                }
                if (tmp > worst_alaw)
                    worst_alaw = tmp;
            }
            else
            {
                /* Small values need different handling for sensible measurement */
                if (abs(post - pre) > 15)
                {
                    printf("A-law: Excessive error at %d (%d)\n", pre, post);
                    alaw_failures++;
                }
            }
            amp[i] = post;
        }
        outframes = afWriteFrames(outhandle,
                                  AF_DEFAULT_TRACK,
                                  amp,
                                  65536);
        if (outframes != 65536)
        {
            fprintf(stderr, "    Error writing wave file\n");
            exit(2);
        }
        for (i = 0;  i < 65536;  i++)
        {
            pre = i - 32768;
            post = ulaw_to_linear(linear_to_ulaw(pre));
            if (abs(pre) > 40)
            {
                tmp = (float) abs(post - pre)/(float) abs(pre);
                if (tmp > 0.10)
                {
                    printf("u-law: Excessive error at %d (%d)\n", pre, post);
                    ulaw_failures++;
                }
                if (tmp > worst_ulaw)
                    worst_ulaw = tmp;
            }
            else
            {
                /* Small values need different handling for sensible measurement */
                if (abs(post - pre) > 4)
                {
                    printf("u-law: Excessive error at %d (%d)\n", pre, post);
                    ulaw_failures++;
                }
            }
            amp[i] = post;
        }
        outframes = afWriteFrames(outhandle,
                                  AF_DEFAULT_TRACK,
                                  amp,
                                  65536);
        if (outframes != 65536)
        {
            fprintf(stderr, "    Error writing wave file\n");
            exit(2);
        }
    }
    printf("Worst A-law error (ignoring small values) %f%%\n", worst_alaw*100.0);
    printf("Worst u-law error (ignoring small values) %f%%\n", worst_ulaw*100.0);
    if (alaw_failures  ||  ulaw_failures)
    {
        printf("%d A-law values with excessive error\n", alaw_failures);
        printf("%d u-law values with excessive error\n", ulaw_failures);
        printf("Tests failed\n");
        exit(2);
    }
    
    printf("Reference power level tests.\n");
    power_meter_init(&power_meter, 7);

    for (i = 0;  i < 8000;  i++)
    {
        amp[i] = ulaw_to_linear(ulaw_1khz_sine[i & 7]);
        power_meter_update(&power_meter, amp[i]);
    }
    printf("Reference u-law 1kHz tone is %fdBm0\n", power_meter_dbm0(&power_meter));
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              8000);
    if (outframes != 8000)
    {
        fprintf(stderr, "    Error writing wave file\n");
        exit(2);
    }
    if (0.1f < fabs(power_meter_dbm0(&power_meter)))
    {
        printf("Test failed.\n");
        exit(2);
    }

    for (i = 0;  i < 8000;  i++)
    {
        amp[i] = alaw_to_linear(alaw_1khz_sine[i & 7]);
        power_meter_update(&power_meter, amp[i]);
    }
    printf("Reference A-law 1kHz tone is %fdBm0\n", power_meter_dbm0(&power_meter));
    outframes = afWriteFrames(outhandle,
                              AF_DEFAULT_TRACK,
                              amp,
                              8000);
    if (outframes != 8000)
    {
        fprintf(stderr, "    Error writing wave file\n");
        exit(2);
    }
    if (0.1f < fabs(power_meter_dbm0(&power_meter)))
    {
        printf("Test failed.\n");
        exit(2);
    }

    /* Check the transcoding functions. */
    printf("Testing transcoding A-law -> u-law -> A-law\n");
    for (i = 0;  i < 256;  i++)
    {
        if (alaw_to_ulaw(ulaw_to_alaw(i)) != i)
        {
            if (abs(alaw_to_ulaw(ulaw_to_alaw(i)) - i) > 1)
            {
                printf("u-law -> A-law -> u-law gave %d -> %d\n", i, alaw_to_ulaw(ulaw_to_alaw(i)));
                printf("Test failed\n");
                exit(2);
            }
        }
    }

    printf("Testing transcoding u-law -> A-law -> u-law\n");
    for (i = 0;  i < 256;  i++)
    {
        if (ulaw_to_alaw(alaw_to_ulaw(i)) != i)
        {
            if (abs(alaw_to_ulaw(ulaw_to_alaw(i)) - i) > 1)
            {
                printf("A-law -> u-law -> A-law gave %d -> %d\n", i, ulaw_to_alaw(alaw_to_ulaw(i)));
                printf("Test failed\n");
                exit(2);
            }
        }
    }
    
    if (afCloseFile(outhandle))
    {
        fprintf(stderr, "    Cannot close wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    afFreeFileSetup(filesetup);

    printf("Tests passed.\n");
    return 0;
}
Esempio n. 25
0
int testmarkers (int fileformat)
{
	AFfilehandle	file;
	AFfilesetup	setup;
	int		markids[] = {1, 2, 3, 4};
	AFframecount	markpositions[] = {14, 54, 23, 101};
	const char	*marknames[] = {"one", "two", "three", "four"};
	short		frames[FRAME_COUNT * 2] = {0};
	int		readmarkcount;
	int		readmarkids[4];
	AFframecount	frameswritten;

	setup = afNewFileSetup();
	ensure(setup != AF_NULL_FILESETUP, "Could not create file setup");

	afInitFileFormat(setup, fileformat);
	afInitChannels(setup, AF_DEFAULT_TRACK, 2);

	afInitMarkIDs(setup, AF_DEFAULT_TRACK, markids, 4);

	afInitMarkName(setup, AF_DEFAULT_TRACK, markids[0], marknames[0]);
	afInitMarkName(setup, AF_DEFAULT_TRACK, markids[1], marknames[1]);
	afInitMarkName(setup, AF_DEFAULT_TRACK, markids[2], marknames[2]);
	afInitMarkName(setup, AF_DEFAULT_TRACK, markids[3], marknames[3]);

	file = afOpenFile(sTestFileName, "w", setup);
	ensure(file != AF_NULL_FILEHANDLE, "Could not open file for writing");

	afFreeFileSetup(setup);

	frameswritten = afWriteFrames(file, AF_DEFAULT_TRACK, frames, FRAME_COUNT);
	ensure(frameswritten == FRAME_COUNT, "Error writing audio data");

	afSetMarkPosition(file, AF_DEFAULT_TRACK, markids[0], markpositions[0]);
	afSetMarkPosition(file, AF_DEFAULT_TRACK, markids[1], markpositions[1]);
	afSetMarkPosition(file, AF_DEFAULT_TRACK, markids[2], markpositions[2]);
	afSetMarkPosition(file, AF_DEFAULT_TRACK, markids[3], markpositions[3]);

	afCloseFile(file);

	file = afOpenFile(sTestFileName, "r", NULL);
	ensure(file != AF_NULL_FILEHANDLE, "Could not open file for reading");

	readmarkcount = afGetMarkIDs(file, AF_DEFAULT_TRACK, NULL);
	ensure(readmarkcount == 4, "Number of markers is not correct");

	afGetMarkIDs(file, AF_DEFAULT_TRACK, readmarkids);

	for (int i=0; i<readmarkcount; i++)
		ensure(readmarkids[i] = markids[i],
			"Marker identification numbers do not match");

	for (int i=0; i<readmarkcount; i++)
	{
		AFframecount	readmarkposition;
		const char	*readmarkname;

		readmarkposition = afGetMarkPosition(file, AF_DEFAULT_TRACK, readmarkids[i]);

		readmarkname = afGetMarkName(file, AF_DEFAULT_TRACK, readmarkids[i]);

		ensure(readmarkposition == markpositions[i],
			"Marker positions do not match");
		ensure(strcmp(readmarkname, marknames[i]) == 0,
			"Marker names do not match");
	}

	afCloseFile(file);

	return EXIT_SUCCESS;
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
    int16_t caller_amp[BLOCK_LEN];
    int16_t answerer_amp[BLOCK_LEN];
    int16_t caller_model_amp[BLOCK_LEN];
    int16_t answerer_model_amp[BLOCK_LEN];
    int16_t out_amp[2*BLOCK_LEN];
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    int outframes;
    int samples;
    int i;
    int test_bps;
    int line_model_no;
    int bits_per_test;
    int noise_level;
    int signal_level;
    int log_audio;
    int channel_codec;
    int opt;
    
    channel_codec = MUNGE_CODEC_NONE;
    test_bps = 2400;
    line_model_no = 0;
    noise_level = -70;
    signal_level = -13;
    bits_per_test = 50000;
    log_audio = FALSE;
    while ((opt = getopt(argc, argv, "b:c:glm:n:s:")) != -1)
    {
        switch (opt)
        {
        case 'b':
            bits_per_test = atoi(optarg);
            break;
        case 'c':
            channel_codec = atoi(optarg);
            break;
        case 'g':
#if defined(ENABLE_GUI)
            use_gui = TRUE;
#else
            fprintf(stderr, "Graphical monitoring not available\n");
            exit(2);
#endif
            break;
        case 'l':
            log_audio = TRUE;
            break;
        case 'm':
            line_model_no = atoi(optarg);
            break;
        case 'n':
            noise_level = atoi(optarg);
            break;
        case 's':
            signal_level = atoi(optarg);
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }
    argc -= optind;
    argv += optind;
    if (argc > 0)
    {
        if (strcmp(argv[0], "2400") == 0)
            test_bps = 2400;
        else if (strcmp(argv[0], "1200") == 0)
            test_bps = 1200;
        else
        {
            fprintf(stderr, "Invalid bit rate\n");
            exit(2);
        }
    }
    filesetup = AF_NULL_FILESETUP;
    outhandle = AF_NULL_FILEHANDLE;
    if (log_audio)
    {
        if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
        {
            fprintf(stderr, "    Failed to create file setup\n");
            exit(2);
        }
        afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
        afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
        afInitFileFormat(filesetup, AF_FILE_WAVE);
        afInitChannels(filesetup, AF_DEFAULT_TRACK, 2);

        if ((outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot create wave file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
    }
    v22bis_init(&caller, test_bps, 2, TRUE, v22bis_getbit, v22bis_putbit, &caller);
    v22bis_tx_power(&caller, signal_level);
    /* Move the carrier off a bit */
    caller.tx.carrier_phase_rate = dds_phase_ratef(1207.0f);
    v22bis_init(&answerer, test_bps, 2, FALSE, v22bis_getbit, v22bis_putbit, &answerer);
    v22bis_tx_power(&answerer, signal_level);
    answerer.tx.carrier_phase_rate = dds_phase_ratef(2407.0f);
    v22bis_set_qam_report_handler(&caller, qam_report, (void *) &qam_caller);
    v22bis_set_qam_report_handler(&answerer, qam_report, (void *) &qam_answerer);
    span_log_set_level(&caller.logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_SHOW_TAG | SPAN_LOG_FLOW);
    span_log_set_tag(&caller.logging, "caller");
    span_log_set_level(&answerer.logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_SHOW_TAG | SPAN_LOG_FLOW);
    span_log_set_tag(&answerer.logging, "answerer");

    qam_caller.s = &caller;
    qam_caller.smooth_power = 0.0f;
    qam_caller.symbol_no = 0;

    qam_answerer.s = &answerer;
    qam_answerer.smooth_power = 0.0f;
    qam_answerer.symbol_no = 0;

#if defined(ENABLE_GUI)
    if (use_gui)
    {
        qam_caller.qam_monitor = qam_monitor_init(6.0f, "Calling modem");
        qam_answerer.qam_monitor = qam_monitor_init(6.0f, "Answering modem");
    }
#endif

    if ((model = both_ways_line_model_init(line_model_no, (float) noise_level, line_model_no, (float) noise_level, channel_codec, 0)) == NULL)
    {
        fprintf(stderr, "    Failed to create line model\n");
        exit(2);
    }
    for (;;)
    {
        samples = v22bis_tx(&caller, caller_amp, BLOCK_LEN);
#if defined(ENABLE_GUI)
        if (use_gui)
            qam_monitor_update_audio_level(qam_caller.qam_monitor, caller_amp, samples);
#endif
        if (samples == 0)
        {
            printf("Restarting on zero output\n");
            v22bis_restart(&caller, test_bps);
            rx_ptr = 0;
            tx_ptr = 0;
        }

        samples = v22bis_tx(&answerer, answerer_amp, BLOCK_LEN);
#if defined(ENABLE_GUI)
        if (use_gui)
            qam_monitor_update_audio_level(qam_answerer.qam_monitor, answerer_amp, samples);
#endif
        if (samples == 0)
        {
            printf("Restarting on zero output\n");
            v22bis_restart(&answerer, test_bps);
            rx_ptr = 0;
            tx_ptr = 0;
        }

        both_ways_line_model(model, 
                             caller_model_amp,
                             caller_amp,
                             answerer_model_amp,
                             answerer_amp,
                             samples);

        v22bis_rx(&answerer, caller_model_amp, samples);
        for (i = 0;  i < samples;  i++)
            out_amp[2*i] = caller_model_amp[i];
        for (  ;  i < BLOCK_LEN;  i++)
            out_amp[2*i] = 0;

        v22bis_rx(&caller, answerer_model_amp, samples);
        for (i = 0;  i < samples;  i++)
            out_amp[2*i + 1] = answerer_model_amp[i];
        for (  ;  i < BLOCK_LEN;  i++)
            out_amp[2*i + 1] = 0;

        if (log_audio)
        {
            outframes = afWriteFrames(outhandle,
                                      AF_DEFAULT_TRACK,
                                      out_amp,
                                      BLOCK_LEN);
            if (outframes != BLOCK_LEN)
            {
                fprintf(stderr, "    Error writing wave file\n");
                exit(2);
            }
        }
    }
    if (log_audio)
    {
        if (afCloseFile(outhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
        afFreeFileSetup(filesetup);
    }
    return  0;
}
Esempio n. 27
0
int main (int argc, char **argv)
{
	AFfilehandle	file;
	AFfilesetup	setup;
	int8_t		samples[] = {11, 51, 101, -101, -54, 120, -15, 99};
	int		i;
	int		sampleFormat, sampleWidth;
	int		framesRead, framesWritten;

	setup = afNewFileSetup();
	afInitFileFormat(setup, AF_FILE_IFF_8SVX);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 8);

	file = afOpenFile(TEST_FILE, "w", setup);
	ensure(file != AF_NULL_FILEHANDLE, "unable to open file for writing");

	framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples, 7);
	ensure(framesWritten == 7,
		"number of frames written does not match number of frames requested");

	ensure(afCloseFile(file) == 0, "error closing file");
	afFreeFileSetup(setup);

	file = afOpenFile(TEST_FILE, "r", NULL);
	ensure(file != AF_NULL_FILEHANDLE, "unable to open file for reading");

	ensure(afGetFileFormat(file, NULL) == AF_FILE_IFF_8SVX,
		"test file not created as IFF/8SVX");

	afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth);
	ensure(sampleFormat == AF_SAMPFMT_TWOSCOMP,
		"test file not two's complement");
	ensure(sampleWidth == 8,
		"test file sample format is not 8-bit");

	ensure(afGetChannels(file, AF_DEFAULT_TRACK) == 1,
		"test file doesn't have exactly one channel");

	ensure(afGetByteOrder(file, AF_DEFAULT_TRACK) == AF_BYTEORDER_BIGENDIAN,
		"test file not big-endian");

	for (i=0; i<7; i++)
	{
		int8_t	temporary;

		framesRead = afReadFrames(file, AF_DEFAULT_TRACK, &temporary, 1);
		ensure(framesRead == 1,
			"number of frames read does not match number of frames requested");

		ensure(temporary == samples[i],
			"data written to file doesn't match data read from file");
	}

	ensure(afCloseFile(file) == 0, "error closing file");

	cleanup();

	printf("writeiff test passed.\n");

	exit(0);
}
Esempio n. 28
0
void testalaw (int fileFormat)
{
	AFfilehandle	file;
	AFfilesetup	setup;
	uint16_t	samples[] = {8, 24, 88, 120, 184, 784, 912, 976,
                        1120, 1440, 1888, 8960, 9984, 16128, 19968, 32256};
	uint16_t	readsamples[SAMPLE_COUNT];
	AFframecount	framesWritten, framesRead;
	int		i;

	setup = afNewFileSetup();

	afInitCompression(setup, AF_DEFAULT_TRACK, AF_COMPRESSION_G711_ALAW);
	afInitFileFormat(setup, fileFormat);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);

	file = afOpenFile(TEST_FILE, "w", setup);
	afFreeFileSetup(setup);

	ensure(afGetCompression(file, AF_DEFAULT_TRACK) ==
		AF_COMPRESSION_G711_ALAW,
		"test file not created with G.711 A-law compression");

	ensure(file != AF_NULL_FILEHANDLE, "unable to open file for writing");

	framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples,
		FRAME_COUNT);

	ensure(framesWritten == FRAME_COUNT,
		"number of frames requested does not match number of frames written");
	afCloseFile(file);

	/* Open the file for reading and verify the data. */
	file = afOpenFile(TEST_FILE, "r", NULL);
	ensure(file != AF_NULL_FILEHANDLE, "unable to open file for reading");

	ensure(afGetFileFormat(file, NULL) == fileFormat,
		"test file format incorrect");

	ensure(afGetCompression(file, AF_DEFAULT_TRACK) ==
		AF_COMPRESSION_G711_ALAW,
		"test file not opened with G.711 A-law compression");

	framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readsamples,
		FRAME_COUNT);

	ensure(framesRead == FRAME_COUNT,
		"number of frames read does not match number of frames requested");

#ifdef DEBUG
	for (i=0; i<SAMPLE_COUNT; i++)
		printf("readsamples[%d]: %d\n", i, readsamples[i]);
	for (i=0; i<SAMPLE_COUNT; i++)
		printf("samples[%d]: %d\n", i, samples[i]);
#endif

	for (i=0; i<SAMPLE_COUNT; i++)
	{
		ensure(samples[i] == readsamples[i],
			"data written does not match data read");
	}

	/* G.711 compression uses one byte per sample. */
	ensure(afGetTrackBytes(file, AF_DEFAULT_TRACK) == SAMPLE_COUNT,
		"track byte count is incorrect");

	ensure(afGetFrameCount(file, AF_DEFAULT_TRACK) == FRAME_COUNT,
		"frame count is incorrect");

	ensure(afGetChannels(file, AF_DEFAULT_TRACK) == 1,
		"channel count is incorrect");

	ensure(afCloseFile(file) == 0, "error closing file");

	cleanup();
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
    AFfilehandle inhandle;
    AFfilehandle refhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    int frames;
    int outframes;
    float x;
    double pre_energy;
    double post_energy;
    double ref_energy;
    double diff_energy;
    int16_t pre_amp[BLOCKS_PER_READ*BLOCK_LEN];
    int16_t post_amp[BLOCKS_PER_READ*BLOCK_LEN];
    int16_t ref_amp[BLOCKS_PER_READ*BLOCK_LEN];
    int16_t log_amp[BLOCKS_PER_READ*BLOCK_LEN*3];
    uint8_t lpc10_data[BLOCKS_PER_READ*7];
    double xx;
    lpc10_encode_state_t *lpc10_enc_state;
    lpc10_decode_state_t *lpc10_dec_state;
    int i;
    int block_no;
    int log_error;
    int compress;
    int decompress;
    const char *in_file_name;
    int compress_file;
    int decompress_file;
    int len;
    int enc_len;
    int dec_len;

    compress = FALSE;
    decompress = FALSE;
    log_error = TRUE;
    in_file_name = IN_FILE_NAME;
    for (i = 1;  i < argc;  i++)
    {
        if (strcmp(argv[i], "-c") == 0)
        {
            compress = TRUE;
            continue;
        }
        if (strcmp(argv[i], "-d") == 0)
        {
            decompress = TRUE;
            continue;
        }
        if (strcmp(argv[i], "-i") == 0)
        {
            in_file_name = argv[++i];
            continue;
        }
        if (strcmp(argv[i], "-l") == 0)
        {
            log_error = FALSE;
            continue;
        }
    }

    compress_file = -1;
    decompress_file = -1;
    inhandle = AF_NULL_FILEHANDLE;
    refhandle = AF_NULL_FILEHANDLE;
    outhandle = AF_NULL_FILEHANDLE;
    if (!decompress)
    {
        if ((inhandle = afOpenFile(in_file_name, "r", 0)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot open wave file '%s'\n", in_file_name);
            exit(2);
        }
        if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0)
        {
            fprintf(stderr, "    Unexpected frame size in wave file '%s'\n", in_file_name);
            exit(2);
        }
        if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE)
        {
            fprintf(stderr, "    Unexpected sample rate in wave file '%s'\n", in_file_name);
            exit(2);
        }
        if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0)
        {
            fprintf(stderr, "    Unexpected number of channels in wave file '%s'\n", in_file_name);
            exit(2);
        }
        if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
        {
            fprintf(stderr, "    Failed to create file setup\n");
            exit(2);
        }

        if ((refhandle = afOpenFile(REF_FILE_NAME, "r", 0)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot open wave file '%s'\n", REF_FILE_NAME);
            exit(2);
        }
        if ((x = afGetFrameSize(refhandle, AF_DEFAULT_TRACK, 1)) != 2.0)
        {
            fprintf(stderr, "    Unexpected frame size in wave file '%s'\n", REF_FILE_NAME);
            exit(2);
        }
        if ((x = afGetRate(refhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE)
        {
            fprintf(stderr, "    Unexpected sample rate in wave file '%s'\n", REF_FILE_NAME);
            exit(2);
        }
        if ((x = afGetChannels(refhandle, AF_DEFAULT_TRACK)) != 1.0)
        {
            fprintf(stderr, "    Unexpected number of channels in wave file '%s'\n", REF_FILE_NAME);
            exit(2);
        }
    }
    else
    {
        if ((decompress_file = open(DECOMPRESS_FILE_NAME, O_RDONLY)) < 0)
        {
            fprintf(stderr, "    Cannot open decompressed data file '%s'\n", DECOMPRESS_FILE_NAME);
            exit(2);
        }
    }

    if ((filesetup = afNewFileSetup()) == AF_NULL_FILESETUP)
    {
        fprintf(stderr, "    Failed to create file setup\n");
        exit(2);
    }
    afInitSampleFormat(filesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
    afInitRate(filesetup, AF_DEFAULT_TRACK, (float) SAMPLE_RATE);
    afInitFileFormat(filesetup, AF_FILE_WAVE);
    afInitChannels(filesetup, AF_DEFAULT_TRACK, 1);

    if ((outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Cannot create wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    
    if ((lpc10_enc_state = lpc10_encode_init(NULL, TRUE)) == NULL)
    {
        fprintf(stderr, "    Cannot create encoder\n");
        exit(2);
    }
            
    if ((lpc10_dec_state = lpc10_decode_init(NULL, TRUE)) == NULL)
    {
        fprintf(stderr, "    Cannot create decoder\n");
        exit(2);
    }

    if (compress)
    {
        if ((compress_file = open(COMPRESS_FILE_NAME, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
        {
            fprintf(stderr, "    Cannot create compressed data file '%s'\n", COMPRESS_FILE_NAME);
            exit(2);
        }
    }

    pre_energy = 0.0;
    post_energy = 0.0;
    ref_energy = 0.0;
    diff_energy = 0.0;

    if (decompress)
    {
        while ((len = read(decompress_file, lpc10_data, BLOCKS_PER_READ*7)) > 0)
        {
            lpc10_decode(lpc10_dec_state, post_amp, lpc10_data, len/7);
            outframes = afWriteFrames(outhandle, AF_DEFAULT_TRACK, post_amp, BLOCK_LEN*len/7);
        }
    }
    else
    {
        block_no = 0;
        while ((frames = afReadFrames(inhandle, AF_DEFAULT_TRACK, pre_amp, BLOCKS_PER_READ*BLOCK_LEN)) == BLOCKS_PER_READ*BLOCK_LEN
                &&
                (frames = afReadFrames(refhandle, AF_DEFAULT_TRACK, ref_amp, BLOCKS_PER_READ*BLOCK_LEN)) == BLOCKS_PER_READ*BLOCK_LEN)
        {
            enc_len = lpc10_encode(lpc10_enc_state, lpc10_data, pre_amp, BLOCKS_PER_READ*BLOCK_LEN);
            if (compress)
                write(compress_file, lpc10_data, enc_len);
            dec_len = lpc10_decode(lpc10_dec_state, post_amp, lpc10_data, enc_len);
            for (i = 0;  i < dec_len;  i++)
            {
                pre_energy += (double) pre_amp[i]*(double) pre_amp[i];
                post_energy += (double) post_amp[i]*(double) post_amp[i];
                ref_energy += (double) ref_amp[i]*(double) ref_amp[i];
                /* The reference file has some odd clipping, so eliminate this from the
                   energy measurement. */
                if (ref_amp[i] == 32767  ||  ref_amp[i] == -32768)
                    xx = 0.0;
                else
                    xx = post_amp[i] - ref_amp[i];
                diff_energy += (double) xx*(double) xx;
                log_amp[i] = xx;
            }
            block_no++;
            if (log_error)
                outframes = afWriteFrames(outhandle, AF_DEFAULT_TRACK, log_amp, dec_len);
            else
                outframes = afWriteFrames(outhandle, AF_DEFAULT_TRACK, post_amp, dec_len);
        }
        if (afCloseFile(inhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", in_file_name);
            exit(2);
        }
        if (afCloseFile(refhandle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", REF_FILE_NAME);
            exit(2);
        }
    }
    
    if (afCloseFile(outhandle) != 0)
    {
        fprintf(stderr, "    Cannot close wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    afFreeFileSetup(filesetup);
    if (compress)
        close(compress_file);
    if (decompress)
        close(decompress_file);
    lpc10_encode_release(lpc10_enc_state);
    lpc10_decode_release(lpc10_dec_state);

    if (!decompress)
    {
        printf("Output energy is %f%% of input energy.\n", 100.0*post_energy/pre_energy);
        printf("Difference energy is %f%% of the total.\n", 100.0*diff_energy/ref_energy);
        if (fabs(1.0 - post_energy/pre_energy) > 0.05
            ||
            fabs(diff_energy/post_energy) > 0.03)
        {
            printf("Tests failed.\n");
            exit(2);
        }
        printf("Tests passed.\n");
    }
    return 0;
}
Esempio n. 30
0
int main (int argc, char **argv)
{
	AFfilesetup	setup;
	if ((setup = afNewFileSetup()) == AF_NULL_FILESETUP)
	{
		fprintf(stderr, "Could not allocate file setup.\n");
		exit(EXIT_FAILURE);
	}

	afInitFileFormat(setup, AF_FILE_IRCAM);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_FLOAT, 32);

	char *testFileName;
	if (!createTemporaryFile("floatto24", &testFileName))
	{
		fprintf(stderr, "Could not create temporary file.\n");
		exit(EXIT_FAILURE);
	}

	AFfilehandle file = afOpenFile(testFileName, "w", setup);
	if (file == AF_NULL_FILEHANDLE)
	{
		printf("could not open file for writing\n");
		exit(EXIT_FAILURE);
	}

	afFreeFileSetup(setup);

	AFframecount framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples,
		frameCount);

	if (framesWritten != frameCount)
	{
		fprintf(stderr, "Wrong number of frames read.\n");
		exit(EXIT_FAILURE);
	}

	if (afCloseFile(file) != 0)
	{
		fprintf(stderr, "Closing file returned non-zero status.\n");
		exit(EXIT_FAILURE);
	}

	file = afOpenFile(testFileName, "r", AF_NULL_FILESETUP);
	if (file == AF_NULL_FILEHANDLE)
	{
		fprintf(stderr, "Could not open file for writing.\n");
		exit(EXIT_FAILURE);
	}

	if (afSetVirtualSampleFormat(file, AF_DEFAULT_TRACK,
		AF_SAMPFMT_TWOSCOMP, 24) != 0)
	{
		fprintf(stderr, "afSetVirtualSampleFormat returned non-zero status.\n");
		exit(EXIT_FAILURE);
	}

	int readSamples[frameCount];
	for (int i=0; i<frameCount; i++)
		readSamples[i] = -1000 - i;
	AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readSamples,
		frameCount);

	if (framesRead != frameCount)
	{
		fprintf(stderr, "Wrong number of frames read.\n");
		exit(EXIT_FAILURE);
	}

	for (int i=0; i<framesRead; i++)
	{
#ifdef DEBUG
		printf("[%d] = %d\n", i, readSamples[i]);
#endif

		if (readSamples[i] == -1000 - i)
		{
			fprintf(stderr, "Data in destination array untouched.\n");
			exit(EXIT_FAILURE);
		}

		/*
			Ensure that the high-order 8 bits represent
			sign extension: only 0x00 (+) or 0xff (-) is
			valid.
		*/
		if ((readSamples[i] & 0xff000000) != 0x000000 &&
			(readSamples[i] & 0xff000000) != 0xff000000)
		{
			fprintf(stderr, "Data is not within range of "
				"{-2^23, ..., 2^23-1}.\n");
			exit(EXIT_FAILURE);
		}

		if (readSamples[i] != referenceConvertedSamples[i])
		{
			fprintf(stderr, "Data doesn't match reference data.\n");
			exit(EXIT_FAILURE);
		}
	}

	if (afCloseFile(file) != 0)
	{
		fprintf(stderr, "Closing file returned non-zero status.\n");
		exit(EXIT_FAILURE);
	}

	unlink(testFileName);
	free(testFileName);

	exit(EXIT_SUCCESS);
}