TEST(NeXT, UnspecifiedLength) { std::string testFileName; ASSERT_TRUE(createTemporaryFile("NeXT", &testFileName)); int fd = ::open(testFileName.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0644); ASSERT_GT(fd, -1); ASSERT_EQ(::write(fd, kDataUnspecifiedLength, sizeof (kDataUnspecifiedLength)), sizeof (kDataUnspecifiedLength)); ::close(fd); AFfilehandle file = afOpenFile(testFileName.c_str(), "r", NULL); EXPECT_TRUE(file); int sampleFormat, sampleWidth; afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); EXPECT_TRUE(sampleFormat == AF_SAMPFMT_TWOSCOMP); EXPECT_EQ(sampleWidth, 16); EXPECT_EQ(afGetChannels(file, AF_DEFAULT_TRACK), 1); EXPECT_EQ(afGetTrackBytes(file, AF_DEFAULT_TRACK), kFrameCount * sizeof (int16_t)); EXPECT_EQ(afGetFrameCount(file, AF_DEFAULT_TRACK), kFrameCount); int16_t *data = new int16_t[kFrameCount]; AFframecount framesRead = afReadFrames(file, AF_DEFAULT_TRACK, data, kFrameCount); EXPECT_EQ(framesRead, kFrameCount); for (int i=0; i<kFrameCount; i++) EXPECT_EQ(data[i], kFrames[i]); delete [] data; afCloseFile(file); ASSERT_EQ(::unlink(testFileName.c_str()), 0); }
static void signal_load(signal_source_t *sig, const char *name) { float x; sig->name = name; if ((sig->handle = afOpenFile(sig->name, "r", 0)) == AF_NULL_FILEHANDLE) { fprintf(stderr, " Cannot open wave file '%s'\n", sig->name); exit(2); } if ((x = afGetFrameSize(sig->handle, AF_DEFAULT_TRACK, 1)) != 2.0) { fprintf(stderr, " Unexpected frame size in wave file '%s'\n", sig->name); exit(2); } if ((x = afGetRate(sig->handle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE) { printf(" Unexpected sample rate in wave file '%s'\n", sig->name); exit(2); } if ((x = afGetChannels(sig->handle, AF_DEFAULT_TRACK)) != 1.0) { printf(" Unexpected number of channels in wave file '%s'\n", sig->name); exit(2); } sig->max = afReadFrames(sig->handle, AF_DEFAULT_TRACK, sig->signal, SAMPLE_RATE); if (sig->max < 0) { fprintf(stderr, " Error reading sound file '%s'\n", sig->name); exit(2); } }
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); }
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(); }
SoundSample::SoundSample(std::string name, int rev) { uMin = rev; samples = NULL; #ifdef HAVE_AUDIOFILE lowPitchOffset = highPitchOffset = 1.0; lowVolumeOffset = highVolumeOffset = 1.0; lastDir = 0; lastValue = 0; file = afOpenFile(name.c_str(), "r", 0); if (file == AF_NULL_FILEHANDLE) { QMessageBox::critical(theWindow, "Error", "SoundSample::afOpenFD() - failed!", QMessageBox::Ok, QMessageBox::Ok); } else { afSetVirtualSampleFormat(file, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16); //afSetVirtualSampleFormat(file, AF_DEFAULT_TRACK, AF_SAMPFMT_FLOAT, 32); channels = afGetChannels(file, AF_DEFAULT_TRACK); samplesPerSec = (int)afGetRate(file, AF_DEFAULT_TRACK); numSamples = afGetFrameCount(file, AF_DEFAULT_TRACK); sampleBlocksize = (int)afGetVirtualFrameSize(file, AF_DEFAULT_TRACK, 1); bytesPerSample = (int)afGetVirtualFrameSize(file, AF_DEFAULT_TRACK, 1) / channels; if (channels != 2) { std::strstream buf; buf << "SoundSample::not a stereo sound file" << name; std::string s; buf >> s; QMessageBox::critical(theWindow, "Error", s.c_str(), QMessageBox::Ok, QMessageBox::Ok); } if (samplesPerSec != 48000) { std::strstream buf; buf << "SoundSample::48kHz required but " << name << " has " << samplesPerSec; std::string s; buf >> s; QMessageBox::critical(theWindow, "Error", s.c_str(), QMessageBox::Ok, QMessageBox::Ok); }
int SoundSampleGetData(const char *file, SoundSampleData * ssd) { AFfilehandle in_file; int in_format, in_width, bytes_per_frame, frame_count; int frames_read; in_file = afOpenFile(file, "r", NULL); if (!in_file) return -1; frame_count = afGetFrameCount(in_file, AF_DEFAULT_TRACK); ssd->channels = afGetChannels(in_file, AF_DEFAULT_TRACK); ssd->rate = (unsigned int)(afGetRate(in_file, AF_DEFAULT_TRACK) + .5); afGetSampleFormat(in_file, AF_DEFAULT_TRACK, &in_format, &in_width); ssd->bit_per_sample = in_width; #ifdef WORDS_BIGENDIAN afSetVirtualByteOrder(in_file, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN); #else afSetVirtualByteOrder(in_file, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN); #endif if (EDebug(EDBUG_TYPE_SOUND)) Eprintf("SoundSampleGetData chan=%d width=%d rate=%d\n", ssd->channels, ssd->bit_per_sample, ssd->rate); bytes_per_frame = (ssd->bit_per_sample * ssd->channels) / 8; ssd->size = frame_count * bytes_per_frame; ssd->data = EMALLOC(unsigned char, ssd->size); frames_read = afReadFrames(in_file, AF_DEFAULT_TRACK, ssd->data, frame_count); afCloseFile(in_file); if (frames_read <= 0) { ssd->size = 0; _EFREE(ssd->data); return -1; } return 0; }
/* 0.73s 44100.00 aiff 1ch 16b -- flute.aif */ bool printshortinfo (const char *filename) { AFfilehandle file = afOpenFile(filename, "r", NULL);; if (!file) return false; int fileFormat = afGetFileFormat(file, NULL); double sampleRate = afGetRate(file, AF_DEFAULT_TRACK); double duration = afGetFrameCount(file, AF_DEFAULT_TRACK) / sampleRate; const char *labelString = (const char *) afQueryPointer(AF_QUERYTYPE_FILEFMT, AF_QUERY_LABEL, fileFormat, 0, 0); int channels = afGetChannels(file, AF_DEFAULT_TRACK); int sampleFormat, sampleWidth; afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); int compressionType = afGetCompression(file, AF_DEFAULT_TRACK); const char *compressionName = "--"; if (compressionType != AF_COMPRESSION_NONE) { compressionName = (const char *) afQueryPointer(AF_QUERYTYPE_COMPRESSION, AF_QUERY_NAME, compressionType, 0, 0); if (!compressionName) compressionName = "unk"; } printf("%8.2fs %8.2f %4s %2dch %2db %s %s\n", duration, sampleRate, labelString, channels, sampleWidth, compressionName, filename); afCloseFile(file); return true; }
void getASBDForFile (AFfilehandle file, int track, AudioStreamBasicDescription *asbd) { int sampleFormat, sampleWidth, channelCount; double rate; afGetVirtualSampleFormat(file, track, &sampleFormat, &sampleWidth); channelCount = afGetChannels(file, track); rate = afGetRate(file, track); asbd->mSampleRate = rate; asbd->mFormatID = kAudioFormatLinearPCM; switch (sampleFormat) { case AF_SAMPFMT_TWOSCOMP: asbd->mFormatFlags = kAudioFormatFlagIsSignedInteger; asbd->mBitsPerChannel = sampleWidth; break; case AF_SAMPFMT_UNSIGNED: asbd->mFormatFlags = 0; asbd->mBitsPerChannel = sampleWidth; break; case AF_SAMPFMT_FLOAT: asbd->mFormatFlags = kAudioFormatFlagIsFloat; asbd->mBitsPerChannel = 32; break; case AF_SAMPFMT_DOUBLE: asbd->mFormatFlags = kAudioFormatFlagIsFloat; asbd->mBitsPerChannel = 64; break; } asbd->mChannelsPerFrame = channelCount; asbd->mFramesPerPacket = 1; asbd->mBytesPerFrame = ceilf(afGetVirtualFrameSize(file, track, 1)); asbd->mBytesPerPacket = asbd->mBytesPerFrame; if (afGetVirtualByteOrder(file, track) == AF_BYTEORDER_BIGENDIAN) asbd->mFormatFlags |= kAudioFormatFlagIsBigEndian; }
int main(int argc, char *argv[]) { g726_state_t enc_state; g726_state_t dec_state; int len2; int len3; int i; int test; int bits_per_code; int itutests; int bit_rate; int bad_samples; AFfilehandle inhandle; AFfilehandle outhandle; AFfilesetup filesetup; int16_t amp[1024]; int frames; int outframes; int conditioning_samples; int samples; int conditioning_adpcm; int adpcm; int packing; float x; i = 1; bit_rate = 32000; itutests = TRUE; packing = G726_PACKING_NONE; while (argc > i) { if (strcmp(argv[i], "-16") == 0) { bit_rate = 16000; itutests = FALSE; i++; } else if (strcmp(argv[i], "-24") == 0) { bit_rate = 24000; itutests = FALSE; i++; } else if (strcmp(argv[i], "-32") == 0) { bit_rate = 32000; itutests = FALSE; i++; } else if (strcmp(argv[i], "-40") == 0) { bit_rate = 40000; itutests = FALSE; i++; } else if (strcmp(argv[i], "-l") == 0) { packing = G726_PACKING_LEFT; i++; } else if (strcmp(argv[i], "-r") == 0) { packing = G726_PACKING_RIGHT; i++; } else { fprintf(stderr, "Unknown parameter %s specified.\n", argv[i]); exit(2); } } len2 = 0; conditioning_samples = 0; if (itutests) { for (test = 0; itu_test_sets[test].rate; test++) { printf("Test %2d: '%s' + '%s'\n" " -> '%s' + '%s'\n" " -> '%s' [%d, %d, %d]\n", test, itu_test_sets[test].conditioning_pcm_file, itu_test_sets[test].pcm_file, itu_test_sets[test].conditioning_adpcm_file, itu_test_sets[test].adpcm_file, itu_test_sets[test].output_file, itu_test_sets[test].rate, itu_test_sets[test].compression_law, itu_test_sets[test].decompression_law); switch (itu_test_sets[test].rate) { case 16000: bits_per_code = 2; break; case 24000: bits_per_code = 3; break; case 32000: default: bits_per_code = 4; break; case 40000: bits_per_code = 5; break; } if (itu_test_sets[test].compression_law != G726_ENCODING_NONE) { /* Test the encode side */ g726_init(&enc_state, itu_test_sets[test].rate, itu_test_sets[test].compression_law, G726_PACKING_NONE); if (itu_test_sets[test].conditioning_pcm_file[0]) { conditioning_samples = get_test_vector(itu_test_sets[test].conditioning_pcm_file, xlaw, MAX_TEST_VECTOR_LEN); printf("Test %d: Homing %d samples at %dbps\n", test, conditioning_samples, itu_test_sets[test].rate); } else { conditioning_samples = 0; } samples = get_test_vector(itu_test_sets[test].pcm_file, xlaw + conditioning_samples, MAX_TEST_VECTOR_LEN); memcpy(itudata, xlaw, samples + conditioning_samples); printf("Test %d: Compressing %d samples at %dbps\n", test, samples, itu_test_sets[test].rate); len2 = g726_encode(&enc_state, adpcmdata, itudata, conditioning_samples + samples); } /* Test the decode side */ g726_init(&dec_state, itu_test_sets[test].rate, itu_test_sets[test].decompression_law, G726_PACKING_NONE); if (itu_test_sets[test].conditioning_adpcm_file[0]) { conditioning_adpcm = get_test_vector(itu_test_sets[test].conditioning_adpcm_file, unpacked, MAX_TEST_VECTOR_LEN); printf("Test %d: Homing %d octets at %dbps\n", test, conditioning_adpcm, itu_test_sets[test].rate); } else { conditioning_adpcm = 0; } adpcm = get_test_vector(itu_test_sets[test].adpcm_file, unpacked + conditioning_adpcm, MAX_TEST_VECTOR_LEN); if (itu_test_sets[test].compression_law != G726_ENCODING_NONE) { /* Test our compressed version against the reference compressed version */ printf("Test %d: Compressed data check - %d/%d octets\n", test, conditioning_adpcm + adpcm, len2); if (conditioning_adpcm + adpcm == len2) { for (bad_samples = 0, i = conditioning_samples; i < len2; i++) { if (adpcmdata[i] != unpacked[i]) { bad_samples++; printf("Test %d: Compressed mismatch %d %x %x\n", test, i, adpcmdata[i], unpacked[i]); } } if (bad_samples > 0) { printf("Test failed\n"); exit(2); } printf("Test passed\n"); } else { printf("Test %d: Length mismatch - ref = %d, processed = %d\n", test, conditioning_adpcm + adpcm, len2); exit(2); } } len3 = g726_decode(&dec_state, outdata, unpacked, conditioning_adpcm + adpcm); /* Get the output reference data */ samples = get_test_vector(itu_test_sets[test].output_file, xlaw, MAX_TEST_VECTOR_LEN); memcpy(itu_ref, xlaw, samples); /* Test our decompressed version against the reference decompressed version */ printf("Test %d: Decompressed data check - %d/%d samples\n", test, samples, len3 - conditioning_adpcm); if (samples == len3 - conditioning_adpcm) { for (bad_samples = 0, i = 0; i < len3; i++) { if (itu_ref[i] != ((uint8_t *) outdata)[i + conditioning_adpcm]) { bad_samples++; printf("Test %d: Decompressed mismatch %d %x %x\n", test, i, itu_ref[i], ((uint8_t *) outdata)[i + conditioning_adpcm]); } } if (bad_samples > 0) { printf("Test failed\n"); exit(2); } printf("Test passed\n"); } else { printf("Test %d: Length mismatch - ref = %d, processed = %d\n", test, samples, len3 - conditioning_adpcm); exit(2); } } printf("Tests passed.\n"); } else { 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); outhandle = afOpenFile(OUT_FILE_NAME, "w", filesetup); if (outhandle == AF_NULL_FILEHANDLE) { fprintf(stderr, " Cannot create wave file '%s'\n", OUT_FILE_NAME); exit(2); } printf("ADPCM packing is %d\n", packing); g726_init(&enc_state, bit_rate, G726_ENCODING_LINEAR, packing); g726_init(&dec_state, bit_rate, G726_ENCODING_LINEAR, packing); while ((frames = afReadFrames(inhandle, AF_DEFAULT_TRACK, amp, 159))) { adpcm = g726_encode(&enc_state, adpcmdata, amp, frames); frames = g726_decode(&dec_state, amp, adpcmdata, adpcm); outframes = afWriteFrames(outhandle, AF_DEFAULT_TRACK, amp, frames); } 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); printf("'%s' transcoded to '%s' at %dbps.\n", IN_FILE_NAME, OUT_FILE_NAME, bit_rate); } return 0; }
Result process() { if (const YAML::Node *n = m_entry.FindValue(kSkip)) return kSkipped; if (const YAML::Node *n = m_entry.FindValue(kPath)) { n->GetScalar(m_path); } else { logerr("no path specified, line %d", n->GetMark().line); return kManifestError; } if (const YAML::Node *n = m_entry.FindValue(kMD5Sum)) { std::string md5 = md5sum(m_path); std::string expectedMD5; n->GetScalar(expectedMD5); if (md5 != expectedMD5) { logerr("md5 checksum differs from expected value"); return kFailure; } } AFfilehandle file = afOpenFile(m_path.c_str(), "r", NULL); if (const YAML::Node *n = m_entry.FindValue(kInvalid)) { if (!file) return kSuccess; logerr("opening invalid file did not fail as expected"); return kFailure; } if (!file) { logerr("could not open file"); return kFailure; } for (YAML::Iterator i = m_entry.begin(); i != m_entry.end(); ++i) { std::string key = i.first().to<std::string>(); std::string value = i.second().to<std::string>(); if (key == kFileFormat) { const char *fileFormat = (const char *) afQueryPointer(AF_QUERYTYPE_FILEFMT, AF_QUERY_LABEL, afGetFileFormat(file, NULL), 0, 0); assert(fileFormat); expect(key, std::string(fileFormat), value); } else if (key == kChannels) { int expectedChannels = atoi(value.c_str()); expect(key, expectedChannels, afGetChannels(file, AF_DEFAULT_TRACK)); } else if (key == kByteOrder) { int expectedByteOrder; if (value == kByteOrder_Big) expectedByteOrder = AF_BYTEORDER_BIGENDIAN; else if (value == kByteOrder_Little) expectedByteOrder = AF_BYTEORDER_LITTLEENDIAN; else { logerr("bad value for byte order: %s, line %d", value.c_str(), i.second().GetMark().line); return kManifestError; } expect(key, expectedByteOrder, afGetByteOrder(file, AF_DEFAULT_TRACK)); } else if (key == kSampleRate) { double expectedSampleRate = atof(value.c_str()); expect(key, expectedSampleRate, afGetRate(file, AF_DEFAULT_TRACK)); } else if (key == kSampleFormat) { std::string width = value.substr(1, value.length() - 1); char format = value[0]; int expectedSampleWidth = atoi(width.c_str()); bool isValidSampleWidth = (expectedSampleWidth >= 1 && expectedSampleWidth <= 32) || expectedSampleWidth == 64; if (!isValidSampleWidth) { logerr("bad value for sample format: %s, line %d", value.c_str(), i.second().GetMark().line); return kManifestError; } int expectedSampleFormat = -1; switch (format) { case 's': expectedSampleFormat = AF_SAMPFMT_TWOSCOMP; break; case 'u': expectedSampleFormat = AF_SAMPFMT_UNSIGNED; break; case 'f': if (expectedSampleWidth == 32) expectedSampleFormat = AF_SAMPFMT_FLOAT; else if (expectedSampleWidth == 64) expectedSampleFormat = AF_SAMPFMT_DOUBLE; break; default: logerr("bad value for sample format: %s, line %d", value.c_str(), i.second().GetMark().line); return kManifestError; } int sampleFormat, sampleWidth; afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); expect(key, expectedSampleFormat, sampleFormat); expect(key, expectedSampleWidth, sampleWidth); } else if (key == kCompression) { int expectedCompression; if (value == kCompression_None) expectedCompression = AF_COMPRESSION_NONE; else if (value == kCompression_IMA_ADPCM) expectedCompression = AF_COMPRESSION_IMA; else if (value == kCompression_MS_ADPCM) expectedCompression = AF_COMPRESSION_MS_ADPCM; else if (value == kCompression_ulaw) expectedCompression = AF_COMPRESSION_G711_ULAW; else if (value == kCompression_alaw) expectedCompression = AF_COMPRESSION_G711_ALAW; else if (value == kCompression_FLAC) expectedCompression = AF_COMPRESSION_FLAC; else if (value == kCompression_ALAC) expectedCompression = AF_COMPRESSION_ALAC; else { logerr("bad value for compression: %s, line %d", value.c_str(), i.second().GetMark().line); return kManifestError; } expect(key, expectedCompression, afGetCompression(file, AF_DEFAULT_TRACK)); } else if (key == kFrames) { AFframecount expectedFrameCount = atoll(value.c_str()); expect(key, expectedFrameCount, afGetFrameCount(file, AF_DEFAULT_TRACK)); int bufferFrameCount = 1024; int channels = afGetChannels(file, AF_DEFAULT_TRACK); int maxBytesPerFrame = 8; char *buffer = new char[channels * bufferFrameCount * maxBytesPerFrame]; AFframecount framesRead = 0; while (framesRead < expectedFrameCount) { AFframecount framesToRead = std::min<AFframecount>(bufferFrameCount, expectedFrameCount - framesRead); AFframecount result = afReadFrames(file, AF_DEFAULT_TRACK, buffer, framesToRead); if (result != framesToRead) { m_failures++; break; } framesRead += result; } delete [] buffer; } else if (key == kBytes) { AFfileoffset expectedTrackBytes = atoll(value.c_str()); expect(key, expectedTrackBytes, afGetTrackBytes(file, AF_DEFAULT_TRACK)); } } afCloseFile(file); return m_failures == 0 ? kSuccess : kFailure; }
main() { LS_DATA ls_data; FILE *fp; double gains[MAX_CHANNELS]; int azimuth=-10; int elevation=14; double *gainptr, gain; short *inptr,*outptr; short out[BUFFER_LENGTH][MAX_CHANNELS]; ALconfig c; AFfilehandle fh; ALport p; short *in; long frames; int i,j,k; int numchannels = 8; /* change this according your output device*/ int ls_set_dim = 3; int ls_num = 8; int ls_dirs[MAX_FIELD_AM]={-30,0, 30,0, -45,45, 45,45, -90,0, 90,0, 180,0, 180,45}; /* change these according to your loudspeaker positioning*/ /* defining loudspeaker data */ define_loudspeakers(&ls_data, ls_set_dim, ls_num, ls_dirs); /* ls_data is a struct containing matrices etc ls_set_dim is 2 if loudspeakers are on a (horizontal) plane ls_set_dim is 3 if also elevated or descended loudpeakers exist ls_num is the number of loudspeakers ls_dirs is an array containing the angular directions of loudsp*/ /* gain factors for virtual source in direction (int azimuth, int elevation) */ vbap(gains, &ls_data, azimuth, elevation); /* panning monophonic stream float *in to multiple outputs float *out[] with gain factors float *gains */ /* input audio*/ if((fh=afOpenFile("myaiff.aiff","r",0))==NULL){ fprintf(stderr, "Could not open file myaiff.aiff\n"); exit(-1); } frames=AFgetframecnt(fh,AF_DEFAULT_TRACK); if(afGetChannels(fh, AF_DEFAULT_TRACK) != 1){ fprintf(stderr, "Supports only mono aiff-files\n"); exit(-1); } in= malloc(frames*sizeof(short)*2); afReadFrames(fh,AF_DEFAULT_TRACK,in,frames); /*opening the audio port*/ c = alNewConfig(); if (!c) { printf("Couldn't create ALconfig:%s\n", alGetErrorString(oserror())); exit(-1); } alSetChannels(c,numchannels); ALsetqueuesize(c,BUFFER_LENGTH); p = alOpenPort("alVBAP example","w",c); if (!p) { printf("port open failed:%s\n", alGetErrorString(oserror())); exit(-1); } fprintf(stderr,"\nPanning audio"); for(j=0;j<(frames/BUFFER_LENGTH);j++){ inptr = &(in[j*BUFFER_LENGTH]); /* audio to be panned */ outptr= out[0]; for (i=0; i<BUFFER_LENGTH; i++){ /* panning */ gainptr=gains; for (k=0; k<numchannels; k++){ *outptr++ = (short) ((double) *inptr * *gainptr++); } inptr++; } alWriteFrames(p, out, BUFFER_LENGTH); /* write frames */ fprintf(stderr,"."); } /*write rest samples out*/ inptr = &(in[j*BUFFER_LENGTH]); /* partial buffer */ outptr= out[0]; for (i=0; i<(frames-BUFFER_LENGTH*j); i++){ /* panning */ gainptr=gains; for (k=0; k<numchannels; k++){ *outptr++ = (short) ((double) *inptr * *gainptr++); } inptr++; } for (;i<BUFFER_LENGTH; i++){ /* zeros */ for (k=0; k<numchannels; k++){ *outptr++ = 0; } } alWriteFrames(p, out, BUFFER_LENGTH); /* write frames */ fprintf(stderr,"."); printf("\n\nDone!\n\n"); }
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; }
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; }
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); }
VeSound *veSoundLoadFile_AudioFile(char *file) { AFfilehandle fh; VeSound *snd; int nchan, nframe; int fsz, i, n; float *buf; if (!(fh = afOpenFile(file,"r",0))) { veError(MODULE,"audiofile library could not open sound file '%s'", file); return NULL; } afSetVirtualSampleFormat(fh,AF_DEFAULT_TRACK,AF_SAMPFMT_FLOAT,4); // Hack. // afSetVirtualRate(fh,AF_DEFAULT_TRACK,(double)veAudioGetSampFreq()); nchan = afGetChannels(fh,AF_DEFAULT_TRACK); if (nchan < 1) { veError(MODULE,"sound file has no tracks?"); afCloseFile(fh); return NULL; } if (nchan > 2) { veError(MODULE,"sound file has more than 2 tracks - rejecting it"); afCloseFile(fh); return NULL; } nframe = afGetFrameCount(fh,AF_DEFAULT_TRACK); fsz = veAudioGetFrameSize(); snd = veAllocObj(VeSound); snd->nframes = nframe/fsz; if (n % fsz) snd->nframes++; snd->data = veAlloc(snd->nframes*sizeof(float)*fsz,0); buf = veAlloc(2*fsz*sizeof(float),0); for (i = 0; i < snd->nframes; i++) { memset(buf,0,fsz*sizeof(float)); /* zero buffer */ n = afReadFrames(fh,AF_DEFAULT_TRACK,buf,fsz); if (n == -1) { veError(MODULE,"sound file read failed for '%s': %s", file, strerror(errno)); afCloseFile(fh); veFree(buf); veFree(snd->data); veFree(snd); return NULL; } if (nchan == 1) /* remember: snd->data is a (float *) */ memcpy(snd->data+fsz*i,buf,fsz*sizeof(float)); else { /* downmix stereo to mono (trivial) */ int k; for (k = 0; k < fsz; k++) snd->data[fsz*i+k] = (buf[2*k] + buf[2*k+1])/2.0; } } afCloseFile(fh); veFree(buf); snd->file = veDupString(file); /* initialize other fields */ snd->id = -1; snd->name = NULL; return snd; }
void runTestWithChannels(int fileFormat, int channelCount) { std::string testFileName; ASSERT_TRUE(createTemporaryFile("PCMData", &testFileName)); const int numFrames = 20; const int numSamples = numFrames * channelCount; T samples[numSamples]; for (int i=0; i<numFrames; i++) for (int c=0; c<channelCount; c++) samples[i*channelCount + c] = static_cast<T>(i*i + 3*c + 1); AFfilesetup setup = afNewFileSetup(); afInitFileFormat(setup, fileFormat); afInitChannels(setup, AF_DEFAULT_TRACK, channelCount); afInitSampleFormat(setup, AF_DEFAULT_TRACK, kSampleFormat, kBitsPerSample); AFfilehandle file = afOpenFile(testFileName.c_str(), "w", setup); ASSERT_TRUE(file) << "Could not open file for writing"; afFreeFileSetup(setup); PCMMapping mapping, defaultMapping; getDefaultPCMMapping(kSampleFormat, kBitsPerSample, defaultMapping); afGetPCMMapping(file, AF_DEFAULT_TRACK, &mapping.slope, &mapping.intercept, &mapping.minClip, &mapping.maxClip); ASSERT_EQ(mapping.slope, defaultMapping.slope); ASSERT_EQ(mapping.intercept, defaultMapping.intercept); ASSERT_EQ(mapping.minClip, defaultMapping.minClip); ASSERT_EQ(mapping.maxClip, defaultMapping.maxClip); afGetVirtualPCMMapping(file, AF_DEFAULT_TRACK, &mapping.slope, &mapping.intercept, &mapping.minClip, &mapping.maxClip); ASSERT_EQ(mapping.slope, defaultMapping.slope); ASSERT_EQ(mapping.intercept, defaultMapping.intercept); ASSERT_EQ(mapping.minClip, defaultMapping.minClip); ASSERT_EQ(mapping.maxClip, defaultMapping.maxClip); ASSERT_EQ(afWriteFrames(file, AF_DEFAULT_TRACK, samples, numFrames), numFrames) << "Number of frames written does not match number of frames requested"; ASSERT_EQ(afCloseFile(file), 0) << "Error closing file"; file = afOpenFile(testFileName.c_str(), "r", NULL); ASSERT_TRUE(file) << "Could not open file for reading"; ASSERT_EQ(afGetFileFormat(file, NULL), fileFormat) << "Incorrect file format"; int sampleFormat, sampleWidth; afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); ASSERT_EQ(sampleFormat, kSampleFormat) << "Incorrect sample format"; ASSERT_EQ(sampleWidth, kBitsPerSample) << "Incorrect sample width"; ASSERT_EQ(afGetChannels(file, AF_DEFAULT_TRACK), channelCount) << "Incorrect number of channels"; afGetPCMMapping(file, AF_DEFAULT_TRACK, &mapping.slope, &mapping.intercept, &mapping.minClip, &mapping.maxClip); ASSERT_EQ(mapping.slope, defaultMapping.slope); ASSERT_EQ(mapping.intercept, defaultMapping.intercept); ASSERT_EQ(mapping.minClip, defaultMapping.minClip); ASSERT_EQ(mapping.maxClip, defaultMapping.maxClip); afGetVirtualPCMMapping(file, AF_DEFAULT_TRACK, &mapping.slope, &mapping.intercept, &mapping.minClip, &mapping.maxClip); ASSERT_EQ(mapping.slope, defaultMapping.slope); ASSERT_EQ(mapping.intercept, defaultMapping.intercept); ASSERT_EQ(mapping.minClip, defaultMapping.minClip); ASSERT_EQ(mapping.maxClip, defaultMapping.maxClip); T *samplesRead = new T[numSamples]; ASSERT_EQ(afReadFrames(file, AF_DEFAULT_TRACK, samplesRead, numFrames), numFrames) << "Number of frames read does not match number of frames requested"; for (int i=0; i<numSamples; i++) ASSERT_EQ(samplesRead[i], samples[i]) << "Data read from file does not match data written"; delete [] samplesRead; ASSERT_EQ(afCloseFile(file), 0) << "Error closing file"; ASSERT_EQ(::unlink(testFileName.c_str()), 0); }
void testalaw (int fileFormat) { AFfilehandle file; AFfilesetup setup; uint16_t samples[] = {8, 24, 88, 120, 184, 784, 912, 976, 1120, 1440, 1888, 8960, 9984, 16128, 19968, 32256}; uint16_t readsamples[SAMPLE_COUNT]; AFframecount framesWritten, framesRead; int i; setup = afNewFileSetup(); afInitCompression(setup, AF_DEFAULT_TRACK, AF_COMPRESSION_G711_ALAW); afInitFileFormat(setup, fileFormat); afInitChannels(setup, AF_DEFAULT_TRACK, 1); file = afOpenFile(TEST_FILE, "w", setup); afFreeFileSetup(setup); ensure(afGetCompression(file, AF_DEFAULT_TRACK) == AF_COMPRESSION_G711_ALAW, "test file not created with G.711 A-law compression"); ensure(file != AF_NULL_FILEHANDLE, "unable to open file for writing"); framesWritten = afWriteFrames(file, AF_DEFAULT_TRACK, samples, FRAME_COUNT); ensure(framesWritten == FRAME_COUNT, "number of frames requested does not match number of frames written"); afCloseFile(file); /* Open the file for reading and verify the data. */ file = afOpenFile(TEST_FILE, "r", NULL); ensure(file != AF_NULL_FILEHANDLE, "unable to open file for reading"); ensure(afGetFileFormat(file, NULL) == fileFormat, "test file format incorrect"); ensure(afGetCompression(file, AF_DEFAULT_TRACK) == AF_COMPRESSION_G711_ALAW, "test file not opened with G.711 A-law compression"); framesRead = afReadFrames(file, AF_DEFAULT_TRACK, readsamples, FRAME_COUNT); ensure(framesRead == FRAME_COUNT, "number of frames read does not match number of frames requested"); #ifdef DEBUG for (i=0; i<SAMPLE_COUNT; i++) printf("readsamples[%d]: %d\n", i, readsamples[i]); for (i=0; i<SAMPLE_COUNT; i++) printf("samples[%d]: %d\n", i, samples[i]); #endif for (i=0; i<SAMPLE_COUNT; i++) { ensure(samples[i] == readsamples[i], "data written does not match data read"); } /* G.711 compression uses one byte per sample. */ ensure(afGetTrackBytes(file, AF_DEFAULT_TRACK) == SAMPLE_COUNT, "track byte count is incorrect"); ensure(afGetFrameCount(file, AF_DEFAULT_TRACK) == FRAME_COUNT, "frame count is incorrect"); ensure(afGetChannels(file, AF_DEFAULT_TRACK) == 1, "channel count is incorrect"); ensure(afCloseFile(file) == 0, "error closing file"); cleanup(); }
int main(int argc, char *argv[]) { int x; int16_t amp[8000]; int sample; int frames; awgn_state_t noise_source; super_tone_rx_state_t *super; super_tone_rx_descriptor_t desc; 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) { 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); } super_tone_rx_make_descriptor(&desc); #if defined(HAVE_LIBXML2) get_tone_set(&desc, "../spandsp/global-tones.xml", (argc > 1) ? argv[1] : "hk"); #endif super_tone_rx_fill_descriptor(&desc); if ((super = super_tone_rx_init(NULL, &desc, wakeup, (void *) "test")) == NULL) { printf(" Failed to create detector.\n"); exit(2); } super_tone_rx_segment_callback(super, tone_segment); awgn_init_dbm0(&noise_source, 1234567, -30.0f); printf("Processing file\n"); while ((frames = afReadFrames(inhandle, AF_DEFAULT_TRACK, amp, 8000))) { /* Add some noise to the signal for a more meaningful test. */ //for (sample = 0; sample < frames; sample++) // amp[sample] += saturate(amp[sample] + awgn (&noise_source)); for (sample = 0; sample < frames; ) { x = super_tone_rx(super, amp + sample, frames - sample); sample += x; } } if (afCloseFile(inhandle)) { fprintf(stderr, " Cannot close audio file '%s'\n", IN_FILE_NAME); exit(2); } #if 0 /* Test for voice immunity */ for (j = 0; bellcore_files[j][0]; j++) { if ((inhandle = afOpenFile(bellcore_files[j], "r", 0)) == AF_NULL_FILEHANDLE) { printf(" Cannot open wave file '%s'\n", bellcore_files[j]); exit(2); } if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0) { printf(" Unexpected frame size in wave file '%s'\n", bellcore_files[j]); exit(2); } if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE) { printf(" Unexpected sample rate in wave file '%s'\n", bellcore_files[j]); exit(2); } if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0) { printf(" Unexpected number of channels in wave file '%s'\n", bellcore_files[j]); exit(2); } while ((frames = afReadFrames(inhandle, AF_DEFAULT_TRACK, amp, 8000))) { for (sample = 0; sample < frames; ) { x = super_tone_rx(super, amp + sample, frames - sample); sample += x; } } if (afCloseFile(inhandle) != 0) { printf(" Cannot close speech file '%s'\n", bellcore_files[j]); exit(2); } } #endif super_tone_rx_free(super); printf("Done\n"); return 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; }
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); }
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; }
libspectrum_error libspectrum_wav_read( libspectrum_tape *tape, const char *filename ) { libspectrum_byte *buffer; size_t length; libspectrum_byte *tape_buffer; size_t tape_length; size_t data_length; libspectrum_tape_block *block = NULL; int frames; /* Our filehandle from libaudiofile */ AFfilehandle handle; /* The track we're using in the file */ int track = AF_DEFAULT_TRACK; if( !filename ) { libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC, "libspectrum_wav_read: no filename provided - wav files can only be loaded from a file" ); return LIBSPECTRUM_ERROR_LOGIC; } handle = afOpenFile( filename, "r", NULL ); if( handle == AF_NULL_FILEHANDLE ) { libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC, "libspectrum_wav_read: audiofile failed to open file:%s", filename ); return LIBSPECTRUM_ERROR_LOGIC; } if( afSetVirtualSampleFormat( handle, track, AF_SAMPFMT_UNSIGNED, 8 ) ) { afCloseFile( handle ); libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC, "libspectrum_wav_read: audiofile failed to set virtual sample format" ); return LIBSPECTRUM_ERROR_LOGIC; } if( afSetVirtualChannels( handle, track, 1 ) ) { afCloseFile( handle ); libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC, "libspectrum_wav_read: audiofile failed to set virtual channel count" ); return LIBSPECTRUM_ERROR_LOGIC; } length = afGetFrameCount( handle, track ); tape_length = length; if( tape_length%8 ) tape_length += 8 - (tape_length%8); buffer = libspectrum_new0( libspectrum_byte, tape_length * afGetChannels(handle, track) ); frames = afReadFrames( handle, track, buffer, length ); if( frames == -1 ) { libspectrum_free( buffer ); afCloseFile( handle ); libspectrum_print_error( LIBSPECTRUM_ERROR_CORRUPT, "libspectrum_wav_read: can't calculate number of frames in audio file" ); return LIBSPECTRUM_ERROR_CORRUPT; } if( !length ) { libspectrum_free( buffer ); afCloseFile( handle ); libspectrum_print_error( LIBSPECTRUM_ERROR_CORRUPT, "libspectrum_wav_read: empty audio file, nothing to load" ); return LIBSPECTRUM_ERROR_CORRUPT; } if( frames != length ) { libspectrum_free( buffer ); afCloseFile( handle ); libspectrum_print_error( LIBSPECTRUM_ERROR_CORRUPT, "libspectrum_wav_read: read %d frames, but expected %lu\n", frames, (unsigned long)length ); return LIBSPECTRUM_ERROR_CORRUPT; } block = libspectrum_tape_block_alloc( LIBSPECTRUM_TAPE_BLOCK_RAW_DATA ); /* 44100 Hz 79 t-states 22050 Hz 158 t-states */ libspectrum_tape_block_set_bit_length( block, 3500000/afGetRate( handle, track ) ); libspectrum_set_pause_ms( block, 0 ); libspectrum_tape_block_set_bits_in_last_byte( block, length % LIBSPECTRUM_BITS_IN_BYTE ? length % LIBSPECTRUM_BITS_IN_BYTE : LIBSPECTRUM_BITS_IN_BYTE ); data_length = tape_length / LIBSPECTRUM_BITS_IN_BYTE; libspectrum_tape_block_set_data_length( block, data_length ); tape_buffer = libspectrum_new0( libspectrum_byte, data_length ); libspectrum_byte *from = buffer; libspectrum_byte *to = tape_buffer; length = tape_length; do { libspectrum_byte val = 0; int i; for( i = 7; i >= 0; i-- ) { if( *from++ > 127 ) val |= 1 << i; } *to++ = val; } while ((length -= 8) > 0); libspectrum_tape_block_set_data( block, tape_buffer ); libspectrum_tape_append_block( tape, block ); if( afCloseFile( handle ) ) { libspectrum_free( buffer ); libspectrum_print_error( LIBSPECTRUM_ERROR_UNKNOWN, "libspectrum_wav_read: failed to close audio file" ); return LIBSPECTRUM_ERROR_UNKNOWN; } libspectrum_free( buffer ); /* Successful completion */ return LIBSPECTRUM_ERROR_NONE; }
bool printfileinfo (const char *filename) { AFfilehandle file = afOpenFile(filename, "r", NULL); if (!file) return false; int fileFormat = afGetFileFormat(file, NULL); const char *formatstring = (const char *) afQueryPointer(AF_QUERYTYPE_FILEFMT, AF_QUERY_DESC, fileFormat, 0, 0); const char *labelstring = (const char *) afQueryPointer(AF_QUERYTYPE_FILEFMT, AF_QUERY_LABEL, fileFormat, 0, 0); if (!formatstring || !labelstring) return false; printf("File Name %s\n", filename); printf("File Format %s (%s)\n", formatstring, labelstring); int sampleFormat, sampleWidth; afGetSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); int byteOrder = afGetByteOrder(file, AF_DEFAULT_TRACK); printf("Data Format "); int compressionType = afGetCompression(file, AF_DEFAULT_TRACK); if (compressionType == AF_COMPRESSION_NONE) { switch (sampleFormat) { case AF_SAMPFMT_TWOSCOMP: printf("%d-bit integer (2's complement, %s)", sampleWidth, byteOrder == AF_BYTEORDER_BIGENDIAN ? "big endian" : "little endian"); break; case AF_SAMPFMT_UNSIGNED: printf("%d-bit integer (unsigned, %s)", sampleWidth, byteOrder == AF_BYTEORDER_BIGENDIAN ? "big endian" : "little endian"); break; case AF_SAMPFMT_FLOAT: printf("single-precision (32-bit) floating point, %s", byteOrder == AF_BYTEORDER_BIGENDIAN ? "big endian" : "little endian"); break; case AF_SAMPFMT_DOUBLE: printf("double-precision (64-bit) floating point, %s", byteOrder == AF_BYTEORDER_BIGENDIAN ? "big endian" : "little endian"); break; default: printf("unknown"); break; } } else { const char *compressionName = (const char *) afQueryPointer(AF_QUERYTYPE_COMPRESSION, AF_QUERY_NAME, compressionType, 0, 0); if (!compressionName) printf("unknown compression"); else printf("%s compression", compressionName); } printf("\n"); printf("Audio Data %jd bytes begins at offset %jd (%jx hex)\n", (intmax_t) afGetTrackBytes(file, AF_DEFAULT_TRACK), (intmax_t) afGetDataOffset(file, AF_DEFAULT_TRACK), (uintmax_t) afGetDataOffset(file, AF_DEFAULT_TRACK)); printf(" %d channel%s, %jd frames\n", afGetChannels(file, AF_DEFAULT_TRACK), afGetChannels(file, AF_DEFAULT_TRACK) > 1 ? "s" : "", (intmax_t) afGetFrameCount(file, AF_DEFAULT_TRACK)); printf("Sampling Rate %.2f Hz\n", afGetRate(file, AF_DEFAULT_TRACK)); printf("Duration %.3f seconds\n", afGetFrameCount(file, AF_DEFAULT_TRACK) / afGetRate(file, AF_DEFAULT_TRACK)); char *copyright = copyrightstring(file); if (copyright) { printf("Copyright %s\n", copyright); free(copyright); } afCloseFile(file); return true; }
int main(int argc, char *argv[]) { fsk_rx_state_t *fsk; v17_rx_state_t *v17; v29_rx_state_t *v29; v27ter_rx_state_t *v27ter; int16_t amp[SAMPLES_PER_CHUNK]; AFfilehandle inhandle; int len; const char *filename; float x; logging_state_t *logging; filename = "fax_samp.wav"; if (argc > 1) filename = argv[1]; if ((inhandle = afOpenFile(filename, "r", NULL)) == AF_NULL_FILEHANDLE) { fprintf(stderr, " Cannot open wave file '%s'\n", filename); exit(2); } if ((x = afGetFrameSize(inhandle, AF_DEFAULT_TRACK, 1)) != 2.0) { printf(" Unexpected frame size in speech file '%s' (%f)\n", filename, x); exit(2); } if ((x = afGetRate(inhandle, AF_DEFAULT_TRACK)) != (float) SAMPLE_RATE) { printf(" Unexpected sample rate in speech file '%s' (%f)\n", filename, x); exit(2); } if ((x = afGetChannels(inhandle, AF_DEFAULT_TRACK)) != 1.0) { printf(" Unexpected number of channels in speech file '%s' (%f)\n", filename, x); exit(2); } memset(&t30_dummy, 0, sizeof(t30_dummy)); span_log_init(&t30_dummy.logging, SPAN_LOG_FLOW, NULL); span_log_set_protocol(&t30_dummy.logging, "T.30"); hdlc_rx_init(&hdlcrx, FALSE, TRUE, 5, hdlc_accept, NULL); fsk = fsk_rx_init(NULL, &preset_fsk_specs[FSK_V21CH2], TRUE, v21_put_bit, NULL); v17 = v17_rx_init(NULL, 14400, v17_put_bit, NULL); v29 = v29_rx_init(NULL, 9600, v29_put_bit, NULL); //v29 = v29_rx_init(NULL, 7200, v29_put_bit, NULL); v27ter = v27ter_rx_init(NULL, 4800, v27ter_put_bit, NULL); fsk_rx_signal_cutoff(fsk, -45.5); v17_rx_signal_cutoff(v17, -45.5); v29_rx_signal_cutoff(v29, -45.5); v27ter_rx_signal_cutoff(v27ter, -40.0); #if 1 logging = v17_rx_get_logging_state(v17); span_log_init(logging, SPAN_LOG_FLOW, NULL); span_log_set_protocol(logging, "V.17"); span_log_set_level(logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_SHOW_TAG | SPAN_LOG_FLOW); logging = v29_rx_get_logging_state(v29); span_log_init(logging, SPAN_LOG_FLOW, NULL); span_log_set_protocol(logging, "V.29"); span_log_set_level(logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_SHOW_TAG | SPAN_LOG_FLOW); logging = v27ter_rx_get_logging_state(v27ter); span_log_init(logging, SPAN_LOG_FLOW, NULL); span_log_set_protocol(logging, "V.27ter"); span_log_set_level(logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_SHOW_TAG | SPAN_LOG_FLOW); #endif if (t4_rx_init(&t4_state, "fax_decode.tif", T4_COMPRESSION_ITU_T4_2D) == NULL) { fprintf(stderr, "Failed to init\n"); exit(0); } for (;;) { len = afReadFrames(inhandle, AF_DEFAULT_TRACK, amp, SAMPLES_PER_CHUNK); if (len < SAMPLES_PER_CHUNK) break; fsk_rx(fsk, amp, len); v17_rx(v17, amp, len); v29_rx(v29, amp, len); //v27ter_rx(v27ter, amp, len); } t4_rx_release(&t4_state); if (afCloseFile(inhandle) != 0) { fprintf(stderr, " Cannot close wave file '%s'\n", filename); exit(2); } return 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; }
void print_power (char *filename) { AFfilehandle file; double *sums, *frames; int channelCount, windowSize, frameCount; int i, c; struct smooth *powsmooth; int winStart, winEnd; int lastWindow = FALSE; double pow, maxpow; double level, peak, minSample = 1, maxSample = -1; file = afOpenFile(filename, "r", NULL); if (file == AF_NULL_FILEHANDLE) { fprintf(stderr, "Could not open file %s.\n", filename); return; } channelCount = afGetChannels(file, AF_DEFAULT_TRACK); windowSize = afGetRate(file, AF_DEFAULT_TRACK) / 100; frameCount = afGetFrameCount(file, AF_DEFAULT_TRACK); sums = calloc(channelCount, sizeof (double)); for (c=0; c<channelCount; c++) sums[c] = 0; frames = calloc(channelCount * windowSize, sizeof (double)); afSetVirtualSampleFormat(file, AF_DEFAULT_TRACK, AF_SAMPFMT_DOUBLE, sizeof (double)); powsmooth = calloc(channelCount, sizeof (struct smooth)); for (c=0; c<channelCount; c++) { /* Use a 100-element (1 second) window. */ powsmooth[c].length = 100; powsmooth[c].buf = calloc(powsmooth[c].length, sizeof (double)); powsmooth[c].start = 0; powsmooth[c].n = 0; } winStart = 0; winEnd = 0; lastWindow = FALSE; maxpow = 0; do { winEnd = winStart + windowSize; if (winEnd >= frameCount) { winEnd = frameCount; lastWindow = TRUE; } afReadFrames(file, AF_DEFAULT_TRACK, frames, windowSize); for (c=0; c<channelCount; c++) { sums[c] = 0; for (i=0; i < winEnd - winStart; i++) { double sample; sample = frames[i*channelCount + c]; sums[c] += sample*sample; if (sample > maxSample) maxSample = sample; if (sample < minSample) minSample = sample; } } /* Compute power for each channel. */ for (c=0; c<channelCount; c++) { double pow; int end; pow = sums[c] / (winEnd - winStart); end = (powsmooth[c].start + powsmooth[c].n) % powsmooth[c].length; powsmooth[c].buf[end] = pow; if (powsmooth[c].n == powsmooth[c].length) { powsmooth[c].start = (powsmooth[c].start + 1) % powsmooth[c].length; pow = get_smoothed_data(&powsmooth[c]); if (pow > maxpow) maxpow = pow; } else { powsmooth[c].n++; } } winStart += windowSize; } while (!lastWindow); for (c = 0; c < channelCount; c++) { pow = get_smoothed_data(&powsmooth[c]); if (pow > maxpow) maxpow = pow; } free(sums); free(frames); for (c=0; c<channelCount; c++) free(powsmooth[c].buf); free(powsmooth); level = sqrt(maxpow); afCloseFile(file); printf("file: %s\n", filename); printf("level (dB): %f\n", 20 * log10(level)); printf("peak-: %f\n", minSample); printf("peak+: %f\n", maxSample); peak = abs(minSample); if (peak < abs(maxSample)) peak = abs(maxSample); printf("peak (dB): %f\n", 20 * log10(peak)); }