Exemplo n.º 1
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);
}
Exemplo n.º 2
0
	static AFfilehandle createTestFile(int sampleFormat, int sampleWidth)
	{
		AFfilesetup setup = afNewFileSetup();
		afInitFileFormat(setup, AF_FILE_AIFFC);
		afInitChannels(setup, AF_DEFAULT_TRACK, 1);
		afInitSampleFormat(setup, AF_DEFAULT_TRACK, sampleFormat, sampleWidth);
		AFfilehandle file = afOpenFile(kTestFileName, "w", setup);
		afFreeFileSetup(setup);
		return file;
	}
Exemplo n.º 3
0
	AFfilehandle createTestFile(int sampleWidth)
	{
		AFfilesetup setup = afNewFileSetup();
		afInitFileFormat(setup, AF_FILE_AIFFC);
		afInitChannels(setup, AF_DEFAULT_TRACK, 1);
		afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, sampleWidth);
		AFfilehandle file = afOpenFile(m_testFileName.c_str(), "w", setup);
		afFreeFileSetup(setup);
		return file;
	}
Exemplo n.º 4
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();
}
Exemplo n.º 5
0
void runTest(int fileFormat, int sampleFormat, int sampleWidth)
{
    IgnoreErrors ignoreErrors;

    std::string testFileName;
    ASSERT_TRUE(createTemporaryFile("InvalidSampleFormat", &testFileName));

    AFfilesetup setup = afNewFileSetup();
    afInitFileFormat(setup, fileFormat);
    afInitSampleFormat(setup, AF_DEFAULT_TRACK, sampleFormat, sampleWidth);
    afInitChannels(setup, AF_DEFAULT_TRACK, 1);
    ASSERT_TRUE(afOpenFile(testFileName.c_str(), "w", setup) == AF_NULL_FILEHANDLE);
    afFreeFileSetup(setup);

    ASSERT_EQ(::unlink(testFileName.c_str()), 0);
}
Exemplo n.º 6
0
static void testInvalidSampleFormat(int sampleFormat, int sampleWidth)
{
	std::string testFileName;
	ASSERT_TRUE(createTemporaryFile("ALAC", &testFileName));

	AFfilesetup setup = afNewFileSetup();
	afInitFileFormat(setup, AF_FILE_CAF);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, sampleFormat, sampleWidth);
	afInitCompression(setup, AF_DEFAULT_TRACK, AF_COMPRESSION_ALAC);
	AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup);
	ASSERT_FALSE(file);
	afFreeFileSetup(setup);

	ASSERT_EQ(::unlink(testFileName.c_str()), 0);
}
Exemplo n.º 7
0
static boolByte _openSampleSourceAiff(void *sampleSourcePtr, const SampleSourceOpenAs openAs) {
  SampleSource sampleSource = (SampleSource)sampleSourcePtr;
#if HAVE_LIBAUDIOFILE
  SampleSourceAudiofileData extraData = (SampleSourceAudiofileData)(sampleSource->extraData);
#else
  SampleSourcePcmData extraData = (SampleSourcePcmData)(sampleSource->extraData);
#endif

  if(openAs == SAMPLE_SOURCE_OPEN_READ) {
#if HAVE_LIBAUDIOFILE
    extraData->fileHandle = afOpenFile(sampleSource->sourceName->data, "r", NULL);
    if(extraData->fileHandle != NULL) {
      setNumChannels(afGetVirtualChannels(extraData->fileHandle, AF_DEFAULT_TRACK));
      setSampleRate((float)afGetRate(extraData->fileHandle, AF_DEFAULT_TRACK));
    }
#else
    logInternalError("Executable was not built with a library to read AIFF files");
#endif
  }
  else if(openAs == SAMPLE_SOURCE_OPEN_WRITE) {
#if HAVE_LIBAUDIOFILE
    AFfilesetup outfileSetup = afNewFileSetup();
    afInitFileFormat(outfileSetup, AF_FILE_AIFF);
    afInitByteOrder(outfileSetup, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
    afInitChannels(outfileSetup, AF_DEFAULT_TRACK, getNumChannels());
    afInitRate(outfileSetup, AF_DEFAULT_TRACK, getSampleRate());
    afInitSampleFormat(outfileSetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, DEFAULT_BITRATE);
    extraData->fileHandle = afOpenFile(sampleSource->sourceName->data, "w", outfileSetup);
#else
    logInternalError("Executable was not built with a library to write AIFF files");
#endif
  }
  else {
    logInternalError("Invalid type for openAs in AIFF file");
    return false;
  }

  if(extraData->fileHandle == NULL) {
    logError("AIFF file '%s' could not be opened for '%s'",
      sampleSource->sourceName->data, openAs == SAMPLE_SOURCE_OPEN_READ ? "reading" : "writing");
    return false;
  }

  sampleSource->openedAs = openAs;
  return true;
}
Exemplo n.º 8
0
PRIVATE int init_instance(Generator *g) {
  Data *data = safe_malloc(sizeof(Data));
  g->data = data;

  data->filename = NULL;
  data->output = NULL;
  data->setup = afNewFileSetup();
  data->frames_recorded = 0;

  afInitFileFormat(data->setup, AF_FILE_WAVE);
  afInitChannels(data->setup, AF_DEFAULT_TRACK, 2);
  afInitSampleFormat(data->setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);

  gen_register_realtime_fn(g, realtime_handler);

  return 1;
}
Exemplo n.º 9
0
TEST(ALAC, InvalidChannels)
{
	IgnoreErrors ignoreErrors;

	std::string testFileName;
	ASSERT_TRUE(createTemporaryFile("ALAC", &testFileName));

	AFfilesetup setup = afNewFileSetup();
	afInitFileFormat(setup, AF_FILE_CAF);
	afInitChannels(setup, AF_DEFAULT_TRACK, 9);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
	afInitCompression(setup, AF_DEFAULT_TRACK, AF_COMPRESSION_ALAC);
	AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup);
	ASSERT_FALSE(file);
	afFreeFileSetup(setup);

	ASSERT_EQ(::unlink(testFileName.c_str()), 0);
}
Exemplo n.º 10
0
static gboolean
file_open (void *dp)
{
    file_driver * const d = dp;
    AFfilesetup outfilesetup;

    outfilesetup = afNewFileSetup();
    afInitFileFormat(outfilesetup, AF_FILE_WAVE);
    afInitChannels(outfilesetup, AF_DEFAULT_TRACK, 2);
    afInitSampleFormat(outfilesetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);
    d->outfile = afOpenFile(d->filename, "w", outfilesetup);
    afFreeFileSetup(outfilesetup);

    if(!d->outfile) {
	error_error(_("Can't open file for writing."));
	goto out;
    }

    /* In case we're running setuid root... */
    chown(d->filename, getuid(), getgid());

    d->sndbuf_size = 16384;
    d->sndbuf = malloc(d->sndbuf_size);
    if(!d->sndbuf) {
	error_error("Can't allocate mix buffer.");
	goto out;
    }

    d->polltag = audio_poll_add(d->pipe[1], GDK_INPUT_WRITE, file_poll_ready_playing, d);
    d->firstpoll = TRUE;
    d->playtime = 0.0;

    return TRUE;

  out:
    file_release(dp);
    return FALSE;
}
Exemplo n.º 11
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;
}
Exemplo n.º 12
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);
}
Exemplo n.º 13
0
int main (void)
{
	AFfilehandle	file;
	AFfilesetup	setup;
	int32_t		*buffer, *readbuffer;
	int		i;
	AFframecount	frameswritten, framesread;

	setup = afNewFileSetup();
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 24);

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

	afFreeFileSetup(setup);

	buffer = malloc(sizeof (int32_t) * FRAME_COUNT);
	ensure(buffer != NULL, "could not allocate buffer for audio data");

	readbuffer = malloc(sizeof (int32_t) * FRAME_COUNT);
	ensure(readbuffer != NULL, "could not allocate buffer for audio data");

	for (i=0; i<FRAME_COUNT; i++)
	{
		if ((i%3) == 0)
			buffer[i] = -i;
		else
			buffer[i] = i;
	}

	frameswritten = afWriteFrames(file, AF_DEFAULT_TRACK, buffer, FRAME_COUNT);
	ensure(frameswritten == FRAME_COUNT, "incorrect number of frames written");

	afCloseFile(file);

	/*
		Now open file for reading and ensure that the data read
		is equal to the data written.
	*/
	file = afOpenFile(sTestFileName, "r", AF_NULL_FILESETUP);
	ensure(file != NULL, "could not open test file for reading");

	framesread = afReadFrames(file, AF_DEFAULT_TRACK, readbuffer, FRAME_COUNT);
	ensure(framesread == FRAME_COUNT, "incorrect number of frames read");

#ifdef DEBUG
	for (i=0; i<FRAME_COUNT; i++)
	{
		if (buffer[i] != readbuffer[i])
		{
			printf("buffer[%d] = %d, readbuffer[%d] = %d\n",
				i, buffer[i], i, readbuffer[i]);
		}
	}
#endif

	ensure(!memcmp(buffer, readbuffer, sizeof (int32_t) * FRAME_COUNT),
		"data read does not match data written");

	afCloseFile(file);

	free(buffer);
	free(readbuffer);

	cleanup();
	return 0;
}
Exemplo n.º 14
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);
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
    int16_t t38_amp_a[SAMPLES_PER_CHUNK];
    int16_t t30_amp_a[SAMPLES_PER_CHUNK];
    int16_t out_amp[2*SAMPLES_PER_CHUNK];
    int t38_len_a;
    int t30_len_a;
    int msg_len;
    uint8_t msg[1024];
    int log_audio;
    int outframes;
    int t38_version;
    int use_ecm;
    AFfilesetup filesetup;
    AFfilehandle wave_handle;
    const char *input_file_name;
    int i;
    int seq_no;

    log_audio = FALSE;
    t38_version = 1;
    use_ecm = FALSE;
    input_file_name = INPUT_FILE_NAME;
    simulate_incrementing_repeats = FALSE;
    for (i = 1;  i < argc;  i++)
    {
        if (strcmp(argv[i], "-e") == 0)
        {
            use_ecm = TRUE;
            continue;
        }
        if (strcmp(argv[i], "-i") == 0)
        {
            i++;
            input_file_name = argv[i];
            continue;
        }
        if (strcmp(argv[i], "-I") == 0)
        {
            simulate_incrementing_repeats = TRUE;
            continue;
        }
        if (strcmp(argv[i], "-l") == 0)
        {
            log_audio = TRUE;
            continue;
        }
        if (strcmp(argv[i], "-v") == 0)
        {
            i++;
            t38_version = atoi(argv[i]);
            continue;
        }
    }

    printf("Using T.38 version %d\n", t38_version);
    if (use_ecm)
        printf("Using ECM\n");

    filesetup = AF_NULL_FILESETUP;
    wave_handle = 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);

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

    if ((path_a_to_b = ip_network_model_init(800, 2000, 0)) == NULL)
    {
        fprintf(stderr, "Failed to start IP network path model\n");
        exit(2);
    }
    if ((path_b_to_a = ip_network_model_init(800, 2000, 0)) == NULL)
    {
        fprintf(stderr, "Failed to start IP network path model\n");
        exit(2);
    }

    fax_init(&fax_state_a, TRUE);
    t30_set_local_ident(&fax_state_a.t30_state, "11111111");
    t30_set_tx_file(&fax_state_a.t30_state, input_file_name, -1, -1);
    t30_set_phase_b_handler(&fax_state_a.t30_state, phase_b_handler, (void *) (intptr_t) 'A');
    t30_set_phase_d_handler(&fax_state_a.t30_state, phase_d_handler, (void *) (intptr_t) 'A');
    t30_set_phase_e_handler(&fax_state_a.t30_state, phase_e_handler, (void *) (intptr_t) 'A');
    t30_set_ecm_capability(&fax_state_a.t30_state, use_ecm);
    if (use_ecm)
        t30_set_supported_compressions(&fax_state_a.t30_state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
    span_log_set_level(&fax_state_a.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_a.logging, "FAX-A ");
    span_log_set_level(&fax_state_a.t30_state.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_a.t30_state.logging, "FAX-A ");
    memset(t30_amp_a, 0, sizeof(t30_amp_a));

    if (t38_gateway_init(&t38_state_a, tx_packet_handler_a, &t38_state_b) == NULL)
    {
        fprintf(stderr, "Cannot start the T.38 channel\n");
        exit(2);
    }
    t38_set_t38_version(&t38_state_a.t38, t38_version);
    t38_gateway_ecm_control(&t38_state_a, use_ecm);
    span_log_set_level(&t38_state_a.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_a.logging, "T.38-A");
    span_log_set_level(&t38_state_a.t38.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_a.t38.logging, "T.38-A");
    memset(t38_amp_a, 0, sizeof(t38_amp_a));

    if (t38_terminal_init(&t38_state_b, FALSE, tx_packet_handler_b, &t38_state_a) == NULL)
    {
        fprintf(stderr, "Cannot start the T.38 channel\n");
        exit(2);
    }
    t38_set_t38_version(&t38_state_b.t38, t38_version);
    span_log_set_level(&t38_state_b.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_b.logging, "T.38-B");
    span_log_set_level(&t38_state_b.t38.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_b.t38.logging, "T.38-B");
    span_log_set_level(&t38_state_b.t30_state.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_b.t30_state.logging, "T.38-B");

    t30_set_local_ident(&t38_state_b.t30_state, "22222222");
    t30_set_rx_file(&t38_state_b.t30_state, OUTPUT_FILE_NAME, -1);
    t30_set_phase_b_handler(&t38_state_b.t30_state, phase_b_handler, (void *) (intptr_t) 'B');
    t30_set_phase_d_handler(&t38_state_b.t30_state, phase_d_handler, (void *) (intptr_t) 'B');
    t30_set_phase_e_handler(&t38_state_b.t30_state, phase_e_handler, (void *) (intptr_t) 'B');
    t30_set_ecm_capability(&t38_state_b.t30_state, use_ecm);
    if (use_ecm)
        t30_set_supported_compressions(&t38_state_b.t30_state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);

    for (;;)
    {
        span_log_bump_samples(&fax_state_a.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&fax_state_a.t30_state.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_a.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_a.t38.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_b.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_b.t38.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_b.t30_state.logging, SAMPLES_PER_CHUNK);
        memset(out_amp, 0, sizeof(out_amp));

        t38_terminal_send_timeout(&t38_state_b, SAMPLES_PER_CHUNK);

        t30_len_a = fax_tx(&fax_state_a, t30_amp_a, SAMPLES_PER_CHUNK);
        /* The receive side always expects a full block of samples, but the
           transmit side may not be sending any when it doesn't need to. We
           may need to pad with some silence. */
        if (t30_len_a < SAMPLES_PER_CHUNK)
        {
            memset(t30_amp_a + t30_len_a, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t30_len_a));
            t30_len_a = SAMPLES_PER_CHUNK;
        }
        if (log_audio)
        {
            for (i = 0;  i < t30_len_a;  i++)
                out_amp[2*i] = t30_amp_a[i];
        }
        if (t38_gateway_rx(&t38_state_a, t30_amp_a, t30_len_a))
            break;
    
        t38_len_a = t38_gateway_tx(&t38_state_a, t38_amp_a, SAMPLES_PER_CHUNK);
        if (t38_len_a < SAMPLES_PER_CHUNK)
        {
            memset(t38_amp_a + t38_len_a, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t38_len_a));
            t38_len_a = SAMPLES_PER_CHUNK;
        }
        if (log_audio)
        {
            for (i = 0;  i < t38_len_a;  i++)
                out_amp[2*i + 1] = t38_amp_a[i];
        }
        if (fax_rx(&fax_state_a, t38_amp_a, SAMPLES_PER_CHUNK))
            break;

        while ((msg_len = ip_network_model_get(path_a_to_b, SAMPLES_PER_CHUNK, msg, 1024, &seq_no)) >= 0)
            t38_core_rx_ifp_packet(&t38_state_b.t38, seq_no, msg, msg_len);
        while ((msg_len = ip_network_model_get(path_b_to_a, SAMPLES_PER_CHUNK, msg, 1024, &seq_no)) >= 0)
            t38_core_rx_ifp_packet(&t38_state_a.t38, seq_no, msg, msg_len);

        if (log_audio)
        {
            outframes = afWriteFrames(wave_handle, AF_DEFAULT_TRACK, out_amp, SAMPLES_PER_CHUNK);
            if (outframes != SAMPLES_PER_CHUNK)
                break;
        }

        if (done[0]  &&  done[1])
            break;
    }
    if (log_audio)
    {
        if (afCloseFile(wave_handle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME_WAVE);
            exit(2);
        }
        afFreeFileSetup(filesetup);
    }
    if (!succeeded[0]  ||  !succeeded[1])
    {
        printf("Tests failed\n");
        exit(2);
    }
    printf("Tests passed\n");
    return  0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
    int i;
    int16_t amp[SAMPLES_PER_CHUNK];
    int16_t out_amp[2*SAMPLES_PER_CHUNK];
    v8_state_t v8_caller;
    v8_state_t v8_answerer;
    int outframes;
    int samples;
    int remnant;
    int caller_available_modulations;
    int answerer_available_modulations;
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    int opt;
    char *decode_test_file;
    float x;
    
    decode_test_file = NULL;
    while ((opt = getopt(argc, argv, "d:")) != -1)
    {
        switch (opt)
        {
        case 'd':
            decode_test_file = optarg;
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }

    caller_available_modulations = V8_MOD_V17
                                 | V8_MOD_V21
                                 | V8_MOD_V22
                                 | V8_MOD_V23HALF
                                 | V8_MOD_V23
                                 | V8_MOD_V26BIS
                                 | V8_MOD_V26TER
                                 | V8_MOD_V27TER
                                 | V8_MOD_V29
                                 | V8_MOD_V32
                                 | V8_MOD_V34HALF
                                 | V8_MOD_V34
                                 | V8_MOD_V90
                                 | V8_MOD_V92;
    answerer_available_modulations = V8_MOD_V17
                                   | V8_MOD_V21
                                   | V8_MOD_V22
                                   | V8_MOD_V23HALF
                                   | V8_MOD_V23
                                   | V8_MOD_V26BIS
                                   | V8_MOD_V26TER
                                   | V8_MOD_V27TER
                                   | V8_MOD_V29
                                   | V8_MOD_V32
                                   | V8_MOD_V34HALF
                                   | V8_MOD_V34
                                   | V8_MOD_V90
                                   | V8_MOD_V92;
    
    if (decode_test_file == NULL)
    {
        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(OUTPUT_FILE_NAME, "w", filesetup)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot create wave file '%s'\n", OUTPUT_FILE_NAME);
            exit(2);
        }
    
        v8_init(&v8_caller, TRUE, caller_available_modulations, handler, (void *) "caller");
        v8_init(&v8_answerer, FALSE, answerer_available_modulations, handler, (void *) "answerer");
        span_log_set_level(&v8_caller.logging, SPAN_LOG_FLOW | SPAN_LOG_SHOW_TAG);
        span_log_set_tag(&v8_caller.logging, "caller");
        span_log_set_level(&v8_answerer.logging, SPAN_LOG_FLOW | SPAN_LOG_SHOW_TAG);
        span_log_set_tag(&v8_answerer.logging, "answerer");
        for (i = 0;  i < 1000;  i++)
        {
            samples = v8_tx(&v8_caller, amp, SAMPLES_PER_CHUNK);
            if (samples < SAMPLES_PER_CHUNK)
            {
                memset(amp + samples, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - samples));
                samples = SAMPLES_PER_CHUNK;
            }
            remnant = v8_rx(&v8_answerer, amp, samples);
            for (i = 0;  i < samples;  i++)
                out_amp[2*i] = amp[i];
            
            samples = v8_tx(&v8_answerer, amp, SAMPLES_PER_CHUNK);
            if (samples < SAMPLES_PER_CHUNK)
            {
                memset(amp + samples, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - samples));
                samples = SAMPLES_PER_CHUNK;
            }
            if (v8_rx(&v8_caller, amp, samples)  &&  remnant)
                break;
            for (i = 0;  i < samples;  i++)
                out_amp[2*i + 1] = amp[i];
    
            outframes = afWriteFrames(outhandle,
                                      AF_DEFAULT_TRACK,
                                      out_amp,
                                      samples);
            if (outframes != samples)
            {
                fprintf(stderr, "    Error writing wave file\n");
                exit(2);
            }
        }
        if (afCloseFile(outhandle))
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME);
            exit(2);
        }
        afFreeFileSetup(filesetup);
        
        v8_release(&v8_caller);
        v8_release(&v8_answerer);
        
        if (negotiations_ok != 2)
        {
            printf("Tests failed.\n");
            exit(2);
        }
        printf("Tests passed.\n");
    }
    else
    {
        printf("Decode file '%s'\n", decode_test_file);
        v8_init(&v8_answerer, FALSE, answerer_available_modulations, handler, (void *) "answerer");
        span_log_set_level(&v8_answerer.logging, SPAN_LOG_FLOW | SPAN_LOG_SHOW_TAG);
        span_log_set_tag(&v8_answerer.logging, "decoder");
        if ((inhandle = afOpenFile(decode_test_file, "r", 0)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot open speech file '%s'\n", decode_test_file);
            exit (2);
        }
        /*endif*/
        if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0)
        {
            fprintf(stderr, "    Unexpected frame size in speech file '%s'\n", decode_test_file);
            exit (2);
        }
        /*endif*/
        if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE)
        {
            fprintf(stderr, "    Unexpected sample rate in speech file '%s'\n", decode_test_file);
            exit(2);
        }
        /*endif*/
        if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0)
        {
            fprintf(stderr, "    Unexpected number of channels in speech file '%s'\n", decode_test_file);
            exit(2);
        }
        /*endif*/
        while ((samples = afReadFrames(inhandle, AF_DEFAULT_TRACK, amp, SAMPLES_PER_CHUNK)))
        {
            remnant = v8_rx(&v8_answerer, amp, samples);
        }
        /*endwhile*/
        v8_release(&v8_answerer);
        if (afCloseFile(inhandle) != 0)
        {
            fprintf(stderr, "    Cannot close speech file '%s'\n", decode_test_file);
            exit(2);
        }
        /*endif*/
    }
    return  0;
}
Exemplo n.º 17
0
int main (int argc, char **argv)
{
	AFfilehandle	file;
	AFfilesetup	setup;
	uint16_t	samples[] = {11, 51, 101, 501, 1001, 5001, 10001, 50001};
	int		i;
	int		sampleFormat, sampleWidth;
	int		framesRead, framesWritten;
	int		nativeByteOrder;

#ifdef WORDS_BIGENDIAN
	nativeByteOrder = AF_BYTEORDER_BIGENDIAN;
#else
	nativeByteOrder = AF_BYTEORDER_LITTLEENDIAN;
#endif

	setup = afNewFileSetup();
	afInitFileFormat(setup, AF_FILE_RAWDATA);
	afInitChannels(setup, AF_DEFAULT_TRACK, 1);
	afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16);

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

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

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

	file = afOpenFile(sTestFileName, "r", setup);
	ensure(file != AF_NULL_FILEHANDLE, "unable to open file for reading");
	afFreeFileSetup(setup);

	ensure(afGetFileFormat(file, NULL) == AF_FILE_RAWDATA,
		"test file not created as raw audio data file");

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

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

	ensure(afGetByteOrder(file, AF_DEFAULT_TRACK) == nativeByteOrder,
		"test file not in native byte order");

	for (i=0; i<8; i++)
	{
		uint16_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("writeraw test passed.\n");

	exit(EXIT_SUCCESS);
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;
    int frames;
    int new_frames;
    int out_frames;
    int count;
    time_scale_t state;
    float x;
    float rate;
    int16_t in[BLOCK_LEN];
    int16_t out[5*BLOCK_LEN];
    
    if ((inhandle = afOpenFile(IN_FILE_NAME, "r", 0)) == AF_NULL_FILEHANDLE)
    {
        printf("    Cannot open wave file '%s'\n", IN_FILE_NAME);
        exit(2);
    }
    if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0)
    {
        printf("    Unexpected frame size in wave file '%s'\n", IN_FILE_NAME);
        exit(2);
    }
    if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE)
    {
        printf("    Unexpected sample rate in wave file '%s'\n", IN_FILE_NAME);
        exit(2);
    }
    if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0)
    {
        printf("    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);
    }
    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);
    }

    rate = 1.8;

    time_scale_init(&state, rate);
    count = 0;
    while ((frames = afReadFrames(inhandle, AF_DEFAULT_TRACK, in, BLOCK_LEN)))
    {
        new_frames = time_scale(&state, out, in, frames);
        out_frames = afWriteFrames(outhandle, AF_DEFAULT_TRACK, out, new_frames);
        if (out_frames != new_frames)
        {
            fprintf(stderr, "    Error writing wave file\n");
            exit(2);
        }
        if (++count > 100)
        {
            if (rate > 0.5)
            {
                rate -= 0.1;
                if (rate >= 0.99  &&  rate <= 1.01)
                    rate -= 0.1;
                printf("Rate is %f\n", rate);
                time_scale_init(&state, rate);
            }
            count = 0;
        }
    }
    if (afCloseFile(inhandle) != 0)
    {
        printf("    Cannot close wave file '%s'\n", IN_FILE_NAME);
        exit(2);
    }
    if (afCloseFile(outhandle) != 0)
    {
        printf("    Cannot close wave file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    afFreeFileSetup(filesetup);
    return 0;
}
Exemplo n.º 19
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);
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
    echo_can_state_t *ctx;
    awgn_state_t local_noise_source;
    awgn_state_t far_noise_source;
    int i;
    int clean;
    int residue;
    int16_t rx;
    int16_t tx;
    int j;
    int k;
    tone_gen_descriptor_t tone_desc;
    tone_gen_state_t tone_state;
    int16_t local_sound[40000];
    int local_max;
    int local_cur;
    int16_t hoth_noise;
    //int16_t far_sound[SAMPLE_RATE];
    //int16_t result_sound[64000];
    //int32_t coeffs[200][128];
    //int coeff_index;
    int far_cur;
    int result_cur;
    //int far_tx;
    AFfilehandle resulthandle;
    AFfilesetup filesetup;
    AFfilesetup filesetup2;
    //int outframes;
    time_t now;
    int tone_burst_step;
    level_measurement_device_t *power_meter_1;
    level_measurement_device_t *power_meter_2;
    float pp1;
    float pp2;
    int model_number;
    int use_gui;

    power_meter_1 = NULL;
    power_meter_2 = NULL;
    /* Check which tests we should run */
    if (argc < 2)
        fprintf(stderr, "Usage: echo tests <list of test numbers>\n");
    test_list = 0;
    model_number = 0;
    use_gui = FALSE;
    for (i = 1;  i < argc;  i++)
    {
        if (strcasecmp(argv[i], "2a") == 0)
            test_list |= PERFORM_TEST_2A;
        else if (strcasecmp(argv[i], "2b") == 0)
            test_list |= PERFORM_TEST_2B;
        else if (strcasecmp(argv[i], "2c") == 0)
            test_list |= PERFORM_TEST_2C;
        else if (strcasecmp(argv[i], "3a") == 0)
            test_list |= PERFORM_TEST_3A;
        else if (strcasecmp(argv[i], "3b") == 0)
            test_list |= PERFORM_TEST_3B;
        else if (strcasecmp(argv[i], "3c") == 0)
            test_list |= PERFORM_TEST_3C;
        else if (strcasecmp(argv[i], "4") == 0)
            test_list |= PERFORM_TEST_4;
        else if (strcasecmp(argv[i], "5") == 0)
            test_list |= PERFORM_TEST_5;
        else if (strcasecmp(argv[i], "6") == 0)
            test_list |= PERFORM_TEST_6;
        else if (strcasecmp(argv[i], "7") == 0)
            test_list |= PERFORM_TEST_7;
        else if (strcasecmp(argv[i], "8") == 0)
            test_list |= PERFORM_TEST_8;
        else if (strcasecmp(argv[i], "9") == 0)
            test_list |= PERFORM_TEST_9;
        else if (strcasecmp(argv[i], "10a") == 0)
            test_list |= PERFORM_TEST_10A;
        else if (strcasecmp(argv[i], "10b") == 0)
            test_list |= PERFORM_TEST_10B;
        else if (strcasecmp(argv[i], "10c") == 0)
            test_list |= PERFORM_TEST_10C;
        else if (strcasecmp(argv[i], "11") == 0)
            test_list |= PERFORM_TEST_11;
        else if (strcasecmp(argv[i], "12") == 0)
            test_list |= PERFORM_TEST_12;
        else if (strcasecmp(argv[i], "13") == 0)
            test_list |= PERFORM_TEST_13;
        else if (strcasecmp(argv[i], "14") == 0)
            test_list |= PERFORM_TEST_14;
        else if (strcasecmp(argv[i], "15") == 0)
            test_list |= PERFORM_TEST_15;
        else if (strcmp(argv[i], "-m") == 0)
        {
            if (++i < argc)
                model_number = atoi(argv[i]);
        }
        else if (strcmp(argv[i], "-g") == 0)
        {
            use_gui = TRUE;
        }
        else
        {
            fprintf(stderr, "Unknown test '%s' specified\n", argv[i]);
            exit(2);
        }
    }
    if (test_list == 0)
    {
        fprintf(stderr, "No tests have been selected\n");
        exit(2);
    }
    time(&now);
    tone_burst_step = 0;
    ctx = echo_can_create(TEST_EC_TAPS, 0);
    awgn_init_dbm0(&far_noise_source, 7162534, -50.0f);

    signal_load(&local_css, "sound_c1_8k.wav");
    signal_load(&far_css, "sound_c3_8k.wav");

    filesetup = afNewFileSetup();
    if (filesetup == 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, 6);

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

    resulthandle = afOpenFile("result_sound.wav", "w", filesetup);
    if (resulthandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open result file\n");
        exit(2);
    }

    residuehandle = afOpenFile("residue_sound.wav", "w", filesetup2);
    if (residuehandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open residue file\n");
        exit(2);
    }
    local_cur = 0;
    far_cur = 0;
    result_cur = 0;
    if (channel_model_create(model_number))
    {
        fprintf(stderr, "    Failed to create line model\n");
        exit(2);
    }
#if defined(ENABLE_GUI)
    if (use_gui)
    {
        start_echo_can_monitor(TEST_EC_TAPS);
        echo_can_monitor_line_model_update(line_model.coeffs, line_model.taps);
    }
#endif
    power_meter_1 = level_measurement_device_create(0);
    power_meter_2 = level_measurement_device_create(0);

    level_measurement_device(power_meter_1, 0);

#if 0
    echo_can_flush(ctx);
    /* Converge the canceller */
    signal_restart(&local_css);
    for (i = 0;  i < 800*2;  i++)
    {
        clean = echo_can_update(ctx, 0, 0);
        put_residue(clean);
    }
    for (i = 0;  i < SAMPLE_RATE*5;  i++)
    {
        tx = signal_amp(&local_css);
        channel_model(&tx, &rx, tx, 0);
        clean = echo_can_update(ctx, tx, rx);
        put_residue(clean);
    }
    echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION | ECHO_CAN_USE_NLP | ECHO_CAN_USE_CNG);
    for (i = 0;  i < SAMPLE_RATE*5;  i++)
    {
        tx = signal_amp(&local_css);
        channel_model(&tx, &rx, tx, 0);
        clean = echo_can_update(ctx, tx, rx);
        put_residue(clean);
    }
    echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
    
    for (i = 0;  i < SAMPLE_RATE*10;  i++)
    {
        tx = signal_amp(&local_css);
#if 0
        if ((i/10000)%10 == 9)
        {
            /* Inject a burst of far sound */
            if (far_cur >= far_max)
            {
                far_max = afReadFrames(farhandle, AF_DEFAULT_TRACK, far_sound, SAMPLE_RATE);
                if (far_max < 0)
                {
                    fprintf(stderr, "    Error reading far sound\n");
                    exit(2);
                }
                if (far_max == 0)
                    break;
                far_cur = 0;
            }
            far_tx = far_sound[far_cur++];
        }
        else
        {
            far_tx = 0;
        }
#else
        far_sound[0] = 0;
        far_tx = 0;
#endif
        channel_model(&tx, &rx, tx, far_tx);
        //rx += awgn(&far_noise_source);
        //tx += awgn(&far_noise_source);
        clean = echo_can_update(ctx, tx, rx);

#if defined(XYZZY)
        if (i%SAMPLE_RATE == 0)
        {
            if (coeff_index < 200)
            {
                for (j = 0;  j < ctx->taps;  j++)
                    coeffs[coeff_index][j] = ctx->fir_taps32[j];
                coeff_index++;
            }
        }
#endif
        result_sound[result_cur++] = tx;
        result_sound[result_cur++] = rx;
        result_sound[result_cur++] = clean - far_tx;
        //result_sound[result_cur++] = ctx->tx_power[2];
        //result_sound[result_cur++] = ctx->tx_power[1];
        result_sound[result_cur++] = (ctx->tx_power[1] > 64)  ?  SAMPLE_RATE  :  -SAMPLE_RATE;
        //result_sound[result_cur++] = ctx->tap_set*SAMPLE_RATE;
        //result_sound[result_cur++] = (ctx->nonupdate_dwell > 0)  ?  SAMPLE_RATE  :  -SAMPLE_RATE;
        //result_sound[result_cur++] = ctx->latest_correction >> 8;
        //result_sound[result_cur++] = level_measurement_device(tx)/(16.0*65536.0);
        //result_sound[result_cur++] = level_measurement_device(tx)/4096.0;
        result_sound[result_cur++] = (ctx->tx_power[1] > ctx->rx_power[0])  ?  SAMPLE_RATE  :  -SAMPLE_RATE;
        //result_sound[result_cur++] = (ctx->tx_power[1] > ctx->rx_power[0])  ?  SAMPLE_RATE  :  -SAMPLE_RATE;
        //result_sound[result_cur++] = (ctx->narrowband_score)*5; //  ?  SAMPLE_RATE  :  -SAMPLE_RATE;
        //result_sound[result_cur++] = ctx->tap_rotate_counter*10;
        result_sound[result_cur++] = ctx->vad;
        
        put_residue(clean - far_tx);
        if (result_cur >= 6*SAMPLE_RATE)
        {
            outframes = afWriteFrames(resulthandle,
                                      AF_DEFAULT_TRACK,
                                      result_sound,
                                      result_cur/6);
            if (outframes != result_cur/6)
            {
                fprintf(stderr, "    Error writing result sound\n");
                exit(2);
            }
            result_cur = 0;
        }
    }
    if (result_cur > 0)
    {
        outframes = afWriteFrames(resulthandle,
                                  AF_DEFAULT_TRACK,
                                  result_sound,
                                  result_cur/6);
        if (outframes != result_cur/4)
        {
            fprintf(stderr, "    Error writing result sound\n");
            exit(2);
        }
    }
#endif

    /* Test 1 - Steady state residual and returned echo level test */
    /* This functionality has been merged with test 2 in newer versions of G.168,
       so test 1 no longer exists. */

    /* Test 2 - Convergence and steady state residual and returned echo level test */
    if ((test_list & PERFORM_TEST_2A))
    {
        printf("Performing test 2A - Convergence with NLP enabled\n");
        /* Test 2A - Convergence with NLP enabled */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION | ECHO_CAN_USE_NLP);
        /* Converge the canceller */
        signal_restart(&local_css);
        for (i = 0;  i < 800*2;  i++)
        {
            clean = echo_can_update(ctx, 0, 0);
            put_residue(clean);
        }
        for (i = 0;  i < SAMPLE_RATE*50;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            pp1 = level_measurement_device(power_meter_1, rx);
            pp2 = level_measurement_device(power_meter_2, clean);
            residue = 100.0*pp1/pp2;
            put_residue(residue);
#if defined(ENABLE_GUI)
            if (use_gui)
                echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_2B))
    {
        printf("Performing test 2B - Convergence with NLP disabled\n");
        /* Test 2B - Convergence with NLP disabled */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge a canceller */
        signal_restart(&local_css);
        for (i = 0;  i < 800*2;  i++)
        {
            clean = echo_can_update(ctx, 0, 0);
            put_residue(clean);
        }
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
#if defined(ENABLE_GUI)
            if (use_gui)
                echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_2C))
    {
        printf("Performing test 2C - Convergence with background noise present\n");
        /* Test 2C - Convergence with background noise present */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge a canceller */
        signal_restart(&local_css);
        for (i = 0;  i < 800*2;  i++)
        {
            clean = echo_can_update(ctx, 0, 0);
            put_residue(clean);
        }
        /* TODO: This uses a crude approx. to Hoth noise. We need the real thing. */
        awgn_init_dbm0(&far_noise_source, 7162534, -40.0f);
        hoth_noise = 0;
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            hoth_noise = hoth_noise*0.625 + awgn(&far_noise_source)*0.375;
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, hoth_noise);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Now freeze adaption, and measure the echo. */
        echo_can_adaption_mode(ctx, 0);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    /* Test 3 - Performance under double talk conditions */
    if ((test_list & PERFORM_TEST_3A))
    {
        printf("Performing test 3A - Double talk test with low cancelled-end levels\n");
        /* Test 3A - Double talk test with low cancelled-end levels */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        signal_restart(&local_css);
        signal_restart(&far_css);
        /* Apply double talk, with a weak far end signal */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            rx = signal_amp(&far_css)/20;
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean - rx);
        }
        /* Now freeze adaption. */
        echo_can_adaption_mode(ctx, 0);
        for (i = 0;  i < 800*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Now measure the echo */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_3B))
    {
        printf("Performing test 3B - Double talk test with high cancelled-end levels\n");
        /* Test 3B - Double talk test with high cancelled-end levels */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        signal_restart(&local_css);
        signal_restart(&far_css);
        /* Converge the canceller */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Apply double talk */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            rx = signal_amp(&far_css);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean - rx);
        }
        /* Now freeze adaption. */
        echo_can_adaption_mode(ctx, 0);
        for (i = 0;  i < 800*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Now measure the echo */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_3C))
    {
        printf("Performing test 3C - Double talk test with simulated conversation\n");
        /* Test 3C - Double talk test with simulated conversation */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        signal_restart(&local_css);
        signal_restart(&far_css);
        /* Apply double talk */
        for (i = 0;  i < 800*56;  i++)
        {
            tx = signal_amp(&local_css);
            rx = signal_amp(&far_css);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean - rx);
        }
        /* Stop the far signal */
        for (i = 0;  i < 800*14;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Continue measuring the resulting echo */
        for (i = 0;  i < 800*50;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Reapply double talk */
        signal_restart(&far_css);
        for (i = 0;  i < 800*56;  i++)
        {
            tx = signal_amp(&local_css);
            rx = signal_amp(&far_css);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean - rx);
        }
        /* Now the far signal only */
        for (i = 0;  i < 800*56;  i++)
        {
            tx = 0;
            rx = signal_amp(&far_css);
            channel_model(&tx, &rx, 0, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean - rx);
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_4))
    {
        printf("Performing test 4 - Leak rate test\n");
        /* Test 4 - Leak rate test */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge a canceller */
        signal_restart(&local_css);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Put 2 minutes of silence through it */
        for (i = 0;  i < SAMPLE_RATE*120;  i++)
        {
            clean = echo_can_update(ctx, 0, 0);
            put_residue(clean);
        }
        /* Now freeze it, and check if it is still well adapted. */
        echo_can_adaption_mode(ctx, 0);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_5))
    {
        printf("Performing test 5 - Infinite return loss convergence test\n");
        /* Test 5 - Infinite return loss convergence test */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge the canceller */
        signal_restart(&local_css);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Now stop echoing, and see we don't do anything unpleasant as the
           echo path is open looped. */
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            rx = 0;
            tx = codec_munge(tx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_6))
    {
        printf("Performing test 6 - Non-divergence on narrow-band signals\n");
        /* Test 6 - Non-divergence on narrow-band signals */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge the canceller */
        signal_restart(&local_css);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        /* Now put 5s bursts of a list of tones through the converged canceller, and check
           that bothing unpleasant happens. */
        for (k = 0;  tones_6_4_2_7[k][0];  k++)
        {
            make_tone_gen_descriptor(&tone_desc,
                                     tones_6_4_2_7[k][0],
                                     -11,
                                     tones_6_4_2_7[k][1],
                                     -9,
                                     1,
                                     0,
                                     0,
                                     0,
                                     1);
            tone_gen_init(&tone_state, &tone_desc);
            j = 0;
            for (i = 0;  i < 5;  i++)
            {
                local_max = tone_gen(&tone_state, local_sound, SAMPLE_RATE);
                for (j = 0;  j < SAMPLE_RATE;  j++)
                {
                    tx = local_sound[j];
                    channel_model(&tx, &rx, tx, 0);
                    clean = echo_can_update(ctx, tx, rx);
                    put_residue(clean);
                }
#if defined(ENABLE_GUI)
                if (use_gui)
                {
                    echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
                    echo_can_monitor_update_display();
                    usleep(100000);
                }
#endif
            }
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_7))
    {
        printf("Performing test 7 - Stability\n");
        /* Test 7 - Stability */
        /* Put tones through an unconverged canceller, and check nothing unpleasant
           happens. */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        make_tone_gen_descriptor(&tone_desc,
                                 tones_6_4_2_7[0][0],
                                 -11,
                                 tones_6_4_2_7[0][1],
                                 -9,
                                 1,
                                 0,
                                 0,
                                 0,
                                 1);
        tone_gen_init(&tone_state, &tone_desc);
        j = 0;
        for (i = 0;  i < 120;  i++)
        {
            local_max = tone_gen(&tone_state, local_sound, SAMPLE_RATE);
            for (j = 0;  j < SAMPLE_RATE;  j++)
            {
                tx = local_sound[j];
                channel_model(&tx, &rx, tx, 0);
                clean = echo_can_update(ctx, tx, rx);
                put_residue(clean);
            }
#if defined(ENABLE_GUI)
            if (use_gui)
            {
                echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
                echo_can_monitor_update_display();
                usleep(100000);
            }
#endif
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    if ((test_list & PERFORM_TEST_8))
    {
        printf("Performing test 8 - Non-convergence on No 5, 6, and 7 in-band signalling\n");
        /* Test 8 - Non-convergence on No 5, 6, and 7 in-band signalling */
        fprintf(stderr, "Test 8 not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_9))
    {
        printf("Performing test 9 - Comfort noise test\n");
        /* Test 9 - Comfort noise test */
        /* Test 9 part 1 - matching */
        echo_can_flush(ctx);
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION);
        /* Converge the canceller */
        signal_restart(&local_css);
        for (i = 0;  i < SAMPLE_RATE*5;  i++)
        {
            tx = signal_amp(&local_css);
            channel_model(&tx, &rx, tx, 0);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        echo_can_adaption_mode(ctx, ECHO_CAN_USE_ADAPTION | ECHO_CAN_USE_NLP | ECHO_CAN_USE_CNG);
        awgn_init_dbm0(&far_noise_source, 7162534, -45.0f);
        for (i = 0;  i < SAMPLE_RATE*30;  i++)
        {
            tx = 0;
            rx = awgn(&far_noise_source);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        awgn_init_dbm0(&local_noise_source, 1234567, -10.0f);
        for (i = 0;  i < SAMPLE_RATE*2;  i++)
        {
            tx = awgn(&local_noise_source);
            rx = awgn(&far_noise_source);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }

        /* Test 9 part 2 - adjust down */
        awgn_init_dbm0(&far_noise_source, 7162534, -55.0f);
        for (i = 0;  i < SAMPLE_RATE*10;  i++)
        {
            tx = 0;
            rx = awgn(&far_noise_source);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
        for (i = 0;  i < SAMPLE_RATE*2;  i++)
        {
            tx = awgn(&local_noise_source);
            rx = awgn(&far_noise_source);
            channel_model(&tx, &rx, tx, rx);
            clean = echo_can_update(ctx, tx, rx);
            put_residue(clean);
        }
#if defined(ENABLE_GUI)
        if (use_gui)
            echo_can_monitor_can_update(ctx->fir_taps16[ctx->tap_set], TEST_EC_TAPS);
#endif
    }

    /* Test 10 - FAX test during call establishment phase */
    if ((test_list & PERFORM_TEST_10A))
    {
        printf("Performing test 10A - Canceller operation on the calling station side\n");
        /* Test 10A - Canceller operation on the calling station side */
        fprintf(stderr, "Test 10A not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_10B))
    {
        printf("Performing test 10B - Canceller operation on the called station side\n");
        /* Test 10B - Canceller operation on the called station side */
        fprintf(stderr, "Test 10B not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_10C))
    {
        printf("Performing test 10C - Canceller operation on the calling station side during page\n"
               "transmission and page breaks (for further study)\n");
        /* Test 10C - Canceller operation on the calling station side during page
                      transmission and page breaks (for further study) */
        fprintf(stderr, "Test 10C not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_11))
    {
        printf("Performing test 11 - Tandem echo canceller test (for further study)\n");
        /* Test 11 - Tandem echo canceller test (for further study) */
        fprintf(stderr, "Test 11 not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_12))
    {
        printf("Performing test 12 - Residual acoustic echo test (for further study)\n");
        /* Test 12 - Residual acoustic echo test (for further study) */
        fprintf(stderr, "Test 12 not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_13))
    {
        printf("Performing test 13 - Performance with ITU-T low-bit rate coders in echo path (Optional, under study)\n");
        /* Test 13 - Performance with ITU-T low-bit rate coders in echo path
                     (Optional, under study) */
        fprintf(stderr, "Test 13 not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_14))
    {
        printf("Performing test 14 - Performance with V-series low-speed data modems\n");
        /* Test 14 - Performance with V-series low-speed data modems */
        fprintf(stderr, "Test 14 not yet implemented\n");
    }

    if ((test_list & PERFORM_TEST_15))
    {
        printf("Performing test 15 - PCM offset test (Optional)\n");
        /* Test 15 - PCM offset test (Optional) */
        fprintf(stderr, "Test 15 not yet implemented\n");
    }

    echo_can_free(ctx);

    signal_free(&local_css);
    signal_free(&far_css);

    if (afCloseFile(resulthandle) != 0)
    {
        fprintf(stderr, "    Cannot close speech file '%s'\n", "result_sound.wav");
        exit(2);
    }
    if (afCloseFile(residuehandle) != 0)
    {
        fprintf(stderr, "    Cannot close speech file '%s'\n", "residue_sound.wav");
        exit(2);
    }
    afFreeFileSetup(filesetup);
    afFreeFileSetup(filesetup2);

#if defined(XYZZY)
    for (j = 0;  j < ctx->taps;  j++)
    {
        for (i = 0;  i < coeff_index;  i++)
            fprintf(stderr, "%d ", coeffs[i][j]);
        fprintf(stderr, "\n");
    }
#endif
    printf("Run time %lds\n", time(NULL) - now);
    
#if defined(ENABLE_GUI)
    if (use_gui)
        echo_can_monitor_wait_to_end();
#endif

    if (power_meter_1)
        level_measurement_device_release(power_meter_1);
    if (power_meter_2)
        level_measurement_device_release(power_meter_2);

    printf("Tests passed.\n");
    return  0;
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
int main(int argc, char *argv[]) 
{
    pthread_attr_t attr;
    struct zt_bufferinfo b;
    struct zt_gains g;
    int chan;
    int chanx;
    char dev_name[20];
    AFfilesetup filesetup;
    int j;

    filesetup = afNewFileSetup();
    if (filesetup == 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);
    rxhandle = afOpenFile("rxadsi.wav", "w", filesetup);
    if (rxhandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open adsi audio file\n");
        exit(2);
    }
    txhandle = afOpenFile("txadsi.wav", "w", filesetup);
    if (txhandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open adsi audio file\n");
        exit(2);
    }

    uc_start();    
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    if (argc < 1)
    {
        fprintf(stderr, "Usage: testcall [call]\n");
        exit(1);
    }
    /*endif*/
    for (chan = 0;  chan < 1/*30*/;  chan++)
    {
        chan_stuff[chan].sig_fd = open("/dev/zap/channel", O_RDWR | O_NONBLOCK);
        if (chan_stuff[chan].sig_fd < 0)
        {
            fprintf(stderr, "Failed to open channel: %s\n", strerror(errno));
            exit(1);
        }
        /*endif*/
        chan_stuff[chan].fd = chan_stuff[chan].sig_fd;
        
        /* Allow for the missing channel at TS16 */
        if (chan < 15)
            chanx = chan + 1;
        else
            chanx = chan + 2;
        /*endif*/
        if (ioctl(chan_stuff[chan].fd, ZT_SPECIFY, &chanx))
        {
            fprintf(stderr, "Failed to specify channel %d: %s\n", chanx, strerror(errno));
            exit(1);
        }
        /*endif*/
        if (ioctl(chan_stuff[chan].fd, ZT_GET_BUFINFO, &b))
        {
            fprintf(stderr, "Unable to get buffer info on channel %d: %s\n", chanx, strerror(errno));
            exit(1);
        }
        /*endif*/
        printf ("%d %d %d %d %d %d\n",
                b.rxbufpolicy,
                b.txbufpolicy,
                b.numbufs,
                b.bufsize,
                b.readbufs,
                b.writebufs);
        b.rxbufpolicy = ZT_POLICY_IMMEDIATE;
        b.txbufpolicy = ZT_POLICY_IMMEDIATE;
        b.numbufs = 4;
        b.bufsize = 160;
        if (ioctl(chan_stuff[chan].fd, ZT_SET_BUFINFO, &b))
        {
            fprintf(stderr, "Unable to set buffer info on channel %d: %s\n", chanx, strerror(errno));
            exit(1);
        }
        /*endif*/
        if (ioctl(chan_stuff[chan].fd, ZT_GET_BUFINFO, &b))
        {
            fprintf(stderr, "Unable to get buffer info on channel %d: %s\n", chanx, strerror(errno));
            exit(1);
        }
        /*endif*/
        for (j = 0;  j < 256;  j++)
        {
            g.rxgain[j] = j;
            g.txgain[j] = j;
        }
        ioctl(chan_stuff[chan].fd, ZT_SETGAINS, &g);
        printf("%d %d %d %d %d %d\n",
               b.rxbufpolicy,
               b.txbufpolicy,
               b.numbufs,
               b.bufsize,
               b.readbufs,
               b.writebufs);

        if (argc > 1)
            caller_mode = TRUE;
        /*endif*/
        chan_stuff[chan].chan = chan;
        sprintf(dev_name, "Chan %2d:", chanx);
        chan_stuff[chan].tag = strdup(dev_name);
        sprintf(chan_stuff[chan].originating_number, "%d", 987654321 + chan);
        sprintf(chan_stuff[chan].destination_number, "%d", 1234 + chan);
        
        printf("Thread for channel %d\n", chan);
        if (pthread_create(&chan_stuff[chan].thread, &attr, run_uc, &chan_stuff[chan].chan))
            exit(2);
        /*endif*/
    }
    /*endfor*/
    for (;;)
    {
        sleep(5);
        printf("Main thread\n");
    }
    /*endfor*/
    exit(0);

    return 0;
}
Exemplo n.º 23
0
static void dynamic_buffer_tests(void)
{
    playout_state_t *s;
    playout_frame_t frame;
    playout_frame_t *p;
    plc_state_t plc;
    time_scale_state_t ts;
    int16_t *amp;
    int16_t fill[BLOCK_LEN];
    int16_t buf[20*BLOCK_LEN];
    int16_t out[10*BLOCK_LEN];
    timestamp_t time_stamp;
    timestamp_t next_actual_receive;
    timestamp_t next_scheduled_receive;
    int near_far_time_offset;
    int rng;
    int i;
    int j;
    int ret;
    int len;
    int inframes;
    int outframes;
    AFfilehandle inhandle;
    AFfilehandle outhandle;
    AFfilesetup filesetup;

    filesetup = afNewFileSetup();
    if (filesetup == 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);

    inhandle = afOpenFile(INPUT_FILE_NAME, "r", NULL);
    if (inhandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to open wave file '%s'\n", INPUT_FILE_NAME);
        exit(2);
    }
    outhandle = afOpenFile(OUTPUT_FILE_NAME, "w", filesetup);
    if (outhandle == AF_NULL_FILEHANDLE)
    {
        fprintf(stderr, "    Failed to create wave file '%s'\n", OUTPUT_FILE_NAME);
        exit(2);
    }

    near_far_time_offset = 54321;
    time_stamp = 12345;
    next_actual_receive = time_stamp + near_far_time_offset;
    next_scheduled_receive = 0;
    for (i = 0;  i < BLOCK_LEN;  i++)
        fill[i] = 32767;

    if ((s = playout_new(2*BLOCK_LEN, 15*BLOCK_LEN)) == NULL)
        return;
    plc_init(&plc);
    time_scale_init(&ts, 1.0);
    for (i = 0;  i < 1000000;  i++)
    {
        if (i >= next_actual_receive)
        {
            amp = malloc(BLOCK_LEN*sizeof(int16_t));
            inframes = afReadFrames(inhandle,
                                    AF_DEFAULT_TRACK,
                                    amp,
                                    BLOCK_LEN);
            if (inframes < BLOCK_LEN)
                break;
            ret = playout_put(s,
                              amp,
                              PLAYOUT_TYPE_SPEECH,
                              inframes,
                              time_stamp,
                              next_actual_receive);
#if 0
            switch (ret)
            {
            case PLAYOUT_OK:
                printf("<< Record\n");
                break;
            case PLAYOUT_ERROR:
                printf("<< Error\n");
                break;
            default:
                printf("<< Eh?\n");
                break;
            }
#endif
            rng = rand() & 0xFF;
            if (i < 100000)
                rng = (rng*rng) >> 7;
            else if (i < 200000)
                rng = (rng*rng) >> 6;
            else if (i < 300000)
Exemplo n.º 24
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;
}
Exemplo n.º 25
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;
}
Exemplo n.º 26
0
static boolByte _openSampleSourceWave(void *sampleSourcePtr, const SampleSourceOpenAs openAs) {
  SampleSource sampleSource = (SampleSource)sampleSourcePtr;
#if HAVE_LIBAUDIOFILE
  SampleSourceAudiofileData extraData = sampleSource->extraData;
#else
  SampleSourcePcmData extraData = (SampleSourcePcmData)sampleSource->extraData;
#endif

  if(openAs == SAMPLE_SOURCE_OPEN_READ) {
#if HAVE_LIBAUDIOFILE
    extraData->fileHandle = afOpenFile(sampleSource->sourceName->data, "r", NULL);
    if(extraData->fileHandle != NULL) {
      setNumChannels(afGetVirtualChannels(extraData->fileHandle, AF_DEFAULT_TRACK));
      setSampleRate((float)afGetRate(extraData->fileHandle, AF_DEFAULT_TRACK));
    }
#else
    extraData->fileHandle = fopen(sampleSource->sourceName->data, "rb");
    if(extraData->fileHandle != NULL) {
      if(_readWaveFileInfo(sampleSource->sourceName->data, extraData)) {
        setNumChannels(extraData->numChannels);
        setSampleRate(extraData->sampleRate);
      }
      else {
        fclose(extraData->fileHandle);
        extraData->fileHandle = NULL;
      }
    }
#endif
  }
  else if(openAs == SAMPLE_SOURCE_OPEN_WRITE) {
#if HAVE_LIBAUDIOFILE
    AFfilesetup outfileSetup = afNewFileSetup();
    afInitFileFormat(outfileSetup, AF_FILE_WAVE);
    afInitByteOrder(outfileSetup, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
    afInitChannels(outfileSetup, AF_DEFAULT_TRACK, getNumChannels());
    afInitRate(outfileSetup, AF_DEFAULT_TRACK, getSampleRate());
    afInitSampleFormat(outfileSetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, DEFAULT_BITRATE);
    extraData->fileHandle = afOpenFile(sampleSource->sourceName->data, "w", outfileSetup);
#else
    extraData->fileHandle = fopen(sampleSource->sourceName->data, "wb");
    if(extraData->fileHandle != NULL) {
      extraData->numChannels = (unsigned short)getNumChannels();
      extraData->sampleRate = (unsigned int)getSampleRate();
      extraData->bitsPerSample = 16;
      if(!_writeWaveFileInfo(extraData)) {
        fclose(extraData->fileHandle);
        extraData->fileHandle = NULL;
      }
    }
#endif
  }
  else {
    logInternalError("Invalid type for openAs in WAVE file");
    return false;
  }

  if(extraData->fileHandle == NULL) {
    logError("WAVE file '%s' could not be opened for %s",
      sampleSource->sourceName->data, openAs == SAMPLE_SOURCE_OPEN_READ ? "reading" : "writing");
    return false;
  }

  sampleSource->openedAs = openAs;
  return true;
}
Exemplo n.º 27
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;
}
Exemplo n.º 28
0
int main(int argc, char *argv[])
{
    int16_t silence[SAMPLES_PER_CHUNK];
    int16_t t30_amp_a[SAMPLES_PER_CHUNK];
    int16_t t38_amp_a[SAMPLES_PER_CHUNK];
    int16_t t38_amp_b[SAMPLES_PER_CHUNK];
    int16_t t30_amp_b[SAMPLES_PER_CHUNK];
    int16_t out_amp[SAMPLES_PER_CHUNK*4];
    int t30_len_a;
    int t38_len_a;
    int t38_len_b;
    int t30_len_b;
    int log_audio;
    int msg_len;
    uint8_t msg[1024];
    int outframes;
    AFfilesetup filesetup;
    AFfilehandle wave_handle;
    int use_ecm;
    int use_tep;
    int use_transmit_on_idle;
    int t38_version;
    const char *input_file_name;
    int i;
    int seq_no;
    int model_no;
    int speed_pattern_no;
    double tx_when;
    double rx_when;
    int use_gui;
    int opt;

    log_audio = FALSE;
    use_ecm = FALSE;
    t38_version = 1;
    input_file_name = INPUT_FILE_NAME;
    simulate_incrementing_repeats = FALSE;
    model_no = 0;
    speed_pattern_no = 1;
    use_gui = FALSE;
    use_tep = FALSE;
    use_transmit_on_idle = TRUE;
    while ((opt = getopt(argc, argv, "egi:Ilm:s:tv:")) != -1)
    {
        switch (opt)
        {
        case 'e':
            use_ecm = TRUE;
            break;
        case 'g':
            use_gui = TRUE;
            break;
        case 'i':
            input_file_name = optarg;
            break;
        case 'I':
            simulate_incrementing_repeats = TRUE;
            break;
        case 'l':
            log_audio = TRUE;
            break;
        case 'm':
            model_no = optarg[0] - 'A' + 1;
            break;
        case 's':
            speed_pattern_no = atoi(optarg);
            break;
        case 't':
            use_tep = TRUE;
            break;
        case 'v':
            t38_version = atoi(optarg);
            break;
        }
    }

    printf("Using T.38 version %d\n", t38_version);
    if (use_ecm)
        printf("Using ECM\n");

    filesetup = AF_NULL_FILESETUP;
    wave_handle = 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, 4);
        if ((wave_handle = afOpenFile(OUTPUT_FILE_NAME_WAVE, "w", filesetup)) == AF_NULL_FILEHANDLE)
        {
            fprintf(stderr, "    Cannot create wave file '%s'\n", OUTPUT_FILE_NAME_WAVE);
            exit(2);
        }
    }
    memset(silence, 0, sizeof(silence));
 
    srand48(0x1234567);
    if ((path_a_to_b = g1050_init(model_no, speed_pattern_no, 100, 33)) == NULL)
    {
        fprintf(stderr, "Failed to start IP network path model\n");
        exit(2);
    }
    if ((path_b_to_a = g1050_init(model_no, speed_pattern_no, 100, 33)) == NULL)
    {
        fprintf(stderr, "Failed to start IP network path model\n");
        exit(2);
    }

    if (fax_init(&fax_state_a, TRUE) == NULL)
    {
        fprintf(stderr, "Cannot start FAX\n");
        exit(2);
    }
    fax_set_transmit_on_idle(&fax_state_a, use_transmit_on_idle);
    fax_set_tep_mode(&fax_state_a, use_tep);
    //t30_set_supported_modems(&(fax_state_a.t30_state), T30_SUPPORT_V27TER | T30_SUPPORT_V29);
    t30_set_local_ident(&fax_state_a.t30_state, "11111111");
    t30_set_tx_file(&fax_state_a.t30_state, input_file_name, -1, -1);
    t30_set_phase_b_handler(&fax_state_a.t30_state, phase_b_handler, (void *) (intptr_t) 'A');
    t30_set_phase_d_handler(&fax_state_a.t30_state, phase_d_handler, (void *) (intptr_t) 'A');
    t30_set_phase_e_handler(&fax_state_a.t30_state, phase_e_handler, (void *) (intptr_t) 'A');
    t30_set_local_nsf(&fax_state_a.t30_state, (const uint8_t *) "\x50\x00\x00\x00Spandsp\x00", 12);
    t30_set_ecm_capability(&fax_state_a.t30_state, use_ecm);
    if (use_ecm)
        t30_set_supported_compressions(&fax_state_a.t30_state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
    span_log_set_level(&fax_state_a.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_a.logging, "FAX-A ");
    span_log_set_level(&fax_state_a.t30_state.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_a.t30_state.logging, "FAX-A ");
    memset(t30_amp_a, 0, sizeof(t30_amp_a));

    if (t38_gateway_init(&t38_state_a, tx_packet_handler_a, &t38_state_b) == NULL)
    {
        fprintf(stderr, "Cannot start the T.38 channel\n");
        exit(2);
    }
    t38_gateway_set_transmit_on_idle(&t38_state_a, use_transmit_on_idle);
    //t38_gateway_set_supported_modems(&t38_state_a, T30_SUPPORT_V27TER | T30_SUPPORT_V29);
    //t38_gateway_set_nsx_suppression(&t38_state_a, FALSE);
    t38_set_t38_version(&t38_state_a.t38, t38_version);
    t38_gateway_set_ecm_capability(&t38_state_a, use_ecm);
    span_log_set_level(&t38_state_a.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_a.logging, "T.38-A");
    span_log_set_level(&t38_state_a.t38.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_a.t38.logging, "T.38-A");
    memset(t38_amp_a, 0, sizeof(t38_amp_a));

    if (t38_gateway_init(&t38_state_b, tx_packet_handler_b, &t38_state_a) == NULL)
    {
        fprintf(stderr, "Cannot start the T.38 channel\n");
        exit(2);
    }
    t38_gateway_set_transmit_on_idle(&t38_state_b, use_transmit_on_idle);
    //t38_gateway_set_supported_modems(&t38_state_b, T30_SUPPORT_V27TER | T30_SUPPORT_V29);
    //t38_gateway_set_nsx_suppression(&t38_state_b, FALSE);
    t38_set_t38_version(&t38_state_b.t38, t38_version);
    t38_gateway_set_ecm_capability(&t38_state_b, use_ecm);
    span_log_set_level(&t38_state_b.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_b.logging, "T.38-B");
    span_log_set_level(&t38_state_b.t38.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&t38_state_b.t38.logging, "T.38-B");
    memset(t38_amp_b, 0, sizeof(t38_amp_b));

    if (fax_init(&fax_state_b, FALSE) == NULL)
    {
        fprintf(stderr, "Cannot start FAX\n");
        exit(2);
    }
    fax_set_transmit_on_idle(&fax_state_b, use_transmit_on_idle);
    fax_set_tep_mode(&fax_state_b, use_tep);
    t30_set_local_ident(&fax_state_b.t30_state, "22222222");
    t30_set_rx_file(&fax_state_b.t30_state, OUTPUT_FILE_NAME, -1);
    t30_set_phase_b_handler(&fax_state_b.t30_state, phase_b_handler, (void *) (intptr_t) 'B');
    t30_set_phase_d_handler(&fax_state_b.t30_state, phase_d_handler, (void *) (intptr_t) 'B');
    t30_set_phase_e_handler(&fax_state_b.t30_state, phase_e_handler, (void *) (intptr_t) 'B');
    t30_set_local_nsf(&fax_state_b.t30_state, (const uint8_t *) "\x50\x00\x00\x00Spandsp\x00", 12);
    t30_set_ecm_capability(&fax_state_b.t30_state, use_ecm);
    if (use_ecm)
        t30_set_supported_compressions(&fax_state_b.t30_state, T30_SUPPORT_T4_1D_COMPRESSION | T30_SUPPORT_T4_2D_COMPRESSION | T30_SUPPORT_T6_COMPRESSION);
    span_log_set_level(&fax_state_b.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_b.logging, "FAX-B ");
    span_log_set_level(&fax_state_b.t30_state.logging, SPAN_LOG_DEBUG | SPAN_LOG_SHOW_TAG | SPAN_LOG_SHOW_SAMPLE_TIME);
    span_log_set_tag(&fax_state_b.t30_state.logging, "FAX-B ");
    memset(t30_amp_b, 0, sizeof(t30_amp_b));

#if defined(ENABLE_GUI)
    if (use_gui)
        start_media_monitor();
#endif
    for (;;)
    {
        span_log_bump_samples(&fax_state_a.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&fax_state_a.t30_state.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_a.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_a.t38.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_b.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&t38_state_b.t38.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&fax_state_b.logging, SAMPLES_PER_CHUNK);
        span_log_bump_samples(&fax_state_b.t30_state.logging, SAMPLES_PER_CHUNK);
        memset(out_amp, 0, sizeof(out_amp));

        t30_len_a = fax_tx(&fax_state_a, t30_amp_a, SAMPLES_PER_CHUNK);
        if (!use_transmit_on_idle)
        {
            /* The receive side always expects a full block of samples, but the
               transmit side may not be sending any when it doesn't need to. We
               may need to pad with some silence. */
            if (t30_len_a < SAMPLES_PER_CHUNK)
            {
                memset(t30_amp_a + t30_len_a, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t30_len_a));
                t30_len_a = SAMPLES_PER_CHUNK;
            }
        }
        if (log_audio)
        {
            for (i = 0;  i < t30_len_a;  i++)
                out_amp[i*4] = t30_amp_a[i];
        }
        if (t38_gateway_rx(&t38_state_a, t30_amp_a, t30_len_a))
            break;

        t38_len_a = t38_gateway_tx(&t38_state_a, t38_amp_a, SAMPLES_PER_CHUNK);
        if (!use_transmit_on_idle)
        {
            if (t38_len_a < SAMPLES_PER_CHUNK)
            {
                memset(t38_amp_a + t38_len_a, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t38_len_a));
                t38_len_a = SAMPLES_PER_CHUNK;
            }
        }
        if (log_audio)
        {
            for (i = 0;  i < t38_len_a;  i++)
                out_amp[i*4 + 1] = t38_amp_a[i];
        }
        if (fax_rx(&fax_state_a, t38_amp_a, SAMPLES_PER_CHUNK))
            break;

        t30_len_b = fax_tx(&fax_state_b, t30_amp_b, SAMPLES_PER_CHUNK);
        if (!use_transmit_on_idle)
        {
            /* The receive side always expects a full block of samples, but the
               transmit side may not be sending any when it doesn't need to. We
               may need to pad with some silence. */
            if (t30_len_b < SAMPLES_PER_CHUNK)
            {
                memset(t30_amp_b + t30_len_b, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t30_len_b));
                t30_len_b = SAMPLES_PER_CHUNK;
            }
        }
        if (log_audio)
        {
            for (i = 0;  i < t30_len_b;  i++)
                out_amp[i*4 + 3] = t30_amp_b[i];
        }
        if (t38_gateway_rx(&t38_state_b, t30_amp_b, t30_len_b))
            break;

        t38_len_b = t38_gateway_tx(&t38_state_b, t38_amp_b, SAMPLES_PER_CHUNK);
        if (!use_transmit_on_idle)
        {
            if (t38_len_b < SAMPLES_PER_CHUNK)
            {
                memset(t38_amp_b + t38_len_b, 0, sizeof(int16_t)*(SAMPLES_PER_CHUNK - t38_len_b));
                t38_len_b = SAMPLES_PER_CHUNK;
            }
        }
        if (log_audio)
        {
            for (i = 0;  i < t38_len_b;  i++)
                out_amp[i*4 + 2] = t38_amp_b[i];
        }
        if (fax_rx(&fax_state_b, t38_amp_b, SAMPLES_PER_CHUNK))
            break;

        when += 0.02;

        while ((msg_len = g1050_get(path_a_to_b, msg, 1024, when, &seq_no, &tx_when, &rx_when)) >= 0)
        {
#if defined(ENABLE_GUI)
            if (use_gui)
                media_monitor_rx(seq_no, tx_when, rx_when);
#endif
            t38_core_rx_ifp_packet(&t38_state_b.t38, msg, msg_len, seq_no);
        }
        while ((msg_len = g1050_get(path_b_to_a, msg, 1024, when, &seq_no, &tx_when, &rx_when)) >= 0)
        {
#if defined(ENABLE_GUI)
            if (use_gui)
                media_monitor_rx(seq_no, tx_when, rx_when);
#endif
            t38_core_rx_ifp_packet(&t38_state_a.t38, msg, msg_len, seq_no);
        }
        if (log_audio)
        {
            outframes = afWriteFrames(wave_handle, AF_DEFAULT_TRACK, out_amp, SAMPLES_PER_CHUNK);
            if (outframes != SAMPLES_PER_CHUNK)
                break;
        }

        if (done[0]  &&  done[1])
            break;
#if defined(ENABLE_GUI)
        if (use_gui)
            media_monitor_update_display();
#endif
    }
    if (log_audio)
    {
        if (afCloseFile(wave_handle) != 0)
        {
            fprintf(stderr, "    Cannot close wave file '%s'\n", OUTPUT_FILE_NAME_WAVE);
            exit(2);
        }
        afFreeFileSetup(filesetup);
    }
    if (!succeeded[0]  ||  !succeeded[1])
    {
        printf("Tests failed\n");
        exit(2);
    }
    printf("Tests passed\n");
    return  0;
}
Exemplo 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;
}
Exemplo n.º 30
0
int main (int argc, char **argv)
{
	int	i = 1;
	char	*infilename, *outfilename;
	int	fileFormat, outFileFormat = AF_FILE_UNKNOWN;

	AFfilehandle	infile, outfile;
	AFfilesetup	outfilesetup;
	int		sampleFormat, sampleWidth, channelCount;
	double		sampleRate;
	int		outSampleFormat = -1, outSampleWidth = -1,
			outChannelCount = -1;
	double		outMaxAmp = 1.0;

	AFframecount	totalFrames;

	if (argc == 2)
	{
		if (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-v"))
		{
			printversion();
			exit(EXIT_SUCCESS);
		}

		if (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))
		{
			printusage();
			exit(EXIT_SUCCESS);
		}
	}

	if (argc < 3)
		usageerror();

	infilename = argv[1];
	outfilename = argv[2];

	i = 3;

	while (i < argc)
	{
		if (!strcmp(argv[i], "format"))
		{
			if (i + 1 >= argc)
				usageerror();
			if (!strcmp(argv[i+1], "aiff"))
				outFileFormat = AF_FILE_AIFF;
			else if (!strcmp(argv[i+1], "aifc"))
				outFileFormat = AF_FILE_AIFFC;
			else if (!strcmp(argv[i+1], "wave"))
				outFileFormat = AF_FILE_WAVE;
			else if (!strcmp(argv[i+1], "next"))
				outFileFormat = AF_FILE_NEXTSND;
			else if (!strcmp(argv[i+1], "bics"))
				outFileFormat = AF_FILE_BICSF;
			else if (!strcmp(argv[i+1], "voc"))
				outFileFormat = AF_FILE_VOC;
			else if (!strcmp(argv[i+1], "nist"))
				outFileFormat = AF_FILE_NIST_SPHERE;
			else if (!strcmp(argv[i+1], "caf"))
				outFileFormat = AF_FILE_CAF;
			else
			{
				fprintf(stderr, "sfconvert: Unknown format %s.\n", argv[i+1]);
				exit(EXIT_FAILURE);
			}

			/* Increment for argument. */
			i++;
		}
		else if (!strcmp(argv[i], "channels"))
		{
			if (i + 1 >= argc)
				usageerror();

			outChannelCount = atoi(argv[i+1]);
			if (outChannelCount < 1)
				usageerror();

			/* Increment for argument. */
			i++;
		}
		else if (!strcmp(argv[i], "float"))
		{
			if (i + 1 >= argc)
				usageerror();

			outSampleFormat = AF_SAMPFMT_FLOAT;
			outSampleWidth = 32;
			outMaxAmp = atof(argv[i+1]);

			/* Increment for argument. */
			i++;
		}
		else if (!strcmp(argv[i], "integer"))
		{
			if (i + 2 >= argc)
				usageerror();

			outSampleWidth = atoi(argv[i+1]);
			if (outSampleWidth < 1 || outSampleWidth > 32)
				usageerror();

			if (!strcmp(argv[i+2], "2scomp"))
				outSampleFormat = AF_SAMPFMT_TWOSCOMP;
			else if (!strcmp(argv[i+2], "unsigned"))
				outSampleFormat = AF_SAMPFMT_UNSIGNED;
			else
				usageerror();

			/* Increment for arguments. */
			i += 2;
		}
		else
		{
			printf("Unrecognized command %s\n", argv[i]);
		}

		i++;
	}

	infile = afOpenFile(infilename, "r", AF_NULL_FILESETUP);
	if (infile == AF_NULL_FILEHANDLE)
	{
		printf("Could not open file '%s' for reading.\n", infilename);
		return 1;
	}

	/* Get audio format parameters from input file. */
	fileFormat = afGetFileFormat(infile, NULL);
	totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);
	channelCount = afGetChannels(infile, AF_DEFAULT_TRACK);
	sampleRate = afGetRate(infile, AF_DEFAULT_TRACK);
	afGetSampleFormat(infile, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth);

	/* Initialize output audio format parameters. */
	outfilesetup = afNewFileSetup();

	if (outFileFormat == -1)
		outFileFormat = fileFormat;

	if (outSampleFormat == -1 || outSampleWidth == -1)
	{
		outSampleFormat = sampleFormat;
		outSampleWidth = sampleWidth;
	}

	if (outChannelCount == -1)
		outChannelCount = channelCount;

	afInitFileFormat(outfilesetup, outFileFormat);
	afInitSampleFormat(outfilesetup, AF_DEFAULT_TRACK, outSampleFormat,
		outSampleWidth);
	afInitChannels(outfilesetup, AF_DEFAULT_TRACK, outChannelCount);
	afInitRate(outfilesetup, AF_DEFAULT_TRACK, sampleRate);

	outfile = afOpenFile(outfilename, "w", outfilesetup);
	if (outfile == AF_NULL_FILEHANDLE)
	{
		printf("Could not open file '%s' for writing.\n", outfilename);
		return 1;
	}

	/*
		Set the output file's virtual audio format parameters
		to match the audio format parameters of the input file.
	*/
	afSetVirtualChannels(outfile, AF_DEFAULT_TRACK, channelCount);
	afSetVirtualSampleFormat(outfile, AF_DEFAULT_TRACK, sampleFormat,
		sampleWidth);

	afFreeFileSetup(outfilesetup);

	copyaudiodata(infile, outfile, AF_DEFAULT_TRACK, totalFrames);

	afCloseFile(infile);
	afCloseFile(outfile);

	printfileinfo(infilename);
	putchar('\n');
	printfileinfo(outfilename);

	return EXIT_SUCCESS;
}