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); } }
static int audiofile_get_duration(const char *file) { int total_time; AFfilehandle af_fp = afOpenFile(file, "r", NULL); if (af_fp == AF_NULL_FILEHANDLE) { return -1; } total_time = (int) ((double)afGetFrameCount(af_fp, AF_DEFAULT_TRACK) / afGetRate(af_fp, AF_DEFAULT_TRACK)); afCloseFile(af_fp); return total_time; }
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); }
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; }
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; }
static enum audiotap_status audiofile_read_init(struct audiotap **audiotap, const char *file, struct tapenc_params *params, uint8_t machine, uint8_t videotype, uint8_t *halfwaves){ uint32_t freq; enum audiotap_status error = AUDIOTAP_LIBRARY_ERROR; AFfilehandle fh; if (status.audiofile_init_status != LIBRARY_OK || status.tapencoder_init_status != LIBRARY_OK) return AUDIOTAP_LIBRARY_UNAVAILABLE; fh=afOpenFile(file,"r", NULL); if (fh == AF_NULL_FILEHANDLE) return AUDIOTAP_LIBRARY_ERROR; do{ if ( (freq=(uint32_t)afGetRate(fh, AF_DEFAULT_TRACK)) == -1) break; if (afSetVirtualChannels(fh, AF_DEFAULT_TRACK, 1) == -1) break; if (afSetVirtualSampleFormat(fh, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 32) == -1) break; if (afGetVirtualFrameSize(fh, AF_DEFAULT_TRACK, 0) != 4) break; error = AUDIOTAP_OK; }while(0); if(error != AUDIOTAP_OK){ afCloseFile(fh); return error; } *halfwaves = 1; return audio2tap_audio_open_common(audiotap, freq, params, machine, videotype, &audiofile_read_functions, fh); }
/* 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[]) { 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; }
static void audiofile_stream_decode(struct decoder *decoder, struct input_stream *is) { AFvirtualfile *vf; int fs, frame_count; AFfilehandle af_fp; int bits; struct audio_format audio_format; float total_time; uint16_t bit_rate; int ret, current = 0; char chunk[CHUNK_SIZE]; enum decoder_command cmd; if (!is->seekable) { g_warning("not seekable"); return; } vf = setup_virtual_fops(is); af_fp = afOpenVirtualFile(vf, "r", NULL); if (af_fp == AF_NULL_FILEHANDLE) { g_warning("failed to input stream\n"); return; } afGetSampleFormat(af_fp, AF_DEFAULT_TRACK, &fs, &bits); if (!audio_valid_sample_format(bits)) { g_debug("input file has %d bit samples, converting to 16", bits); bits = 16; } afSetVirtualSampleFormat(af_fp, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, bits); afGetVirtualSampleFormat(af_fp, AF_DEFAULT_TRACK, &fs, &bits); audio_format.bits = (uint8_t)bits; audio_format.sample_rate = (unsigned int)afGetRate(af_fp, AF_DEFAULT_TRACK); audio_format.channels = (uint8_t)afGetVirtualChannels(af_fp, AF_DEFAULT_TRACK); if (!audio_format_valid(&audio_format)) { g_warning("Invalid audio format: %u:%u:%u\n", audio_format.sample_rate, audio_format.bits, audio_format.channels); afCloseFile(af_fp); return; } frame_count = afGetFrameCount(af_fp, AF_DEFAULT_TRACK); total_time = ((float)frame_count / (float)audio_format.sample_rate); bit_rate = (uint16_t)(is->size * 8.0 / total_time / 1000.0 + 0.5); fs = (int)afGetVirtualFrameSize(af_fp, AF_DEFAULT_TRACK, 1); decoder_initialized(decoder, &audio_format, true, total_time); do { ret = afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk, CHUNK_SIZE / fs); if (ret <= 0) break; current += ret; cmd = decoder_data(decoder, NULL, chunk, ret * fs, (float)current / (float)audio_format.sample_rate, bit_rate, NULL); if (cmd == DECODE_COMMAND_SEEK) { current = decoder_seek_where(decoder) * audio_format.sample_rate; afSeekFrame(af_fp, AF_DEFAULT_TRACK, current); decoder_command_finished(decoder); cmd = DECODE_COMMAND_NONE; } } while (cmd == DECODE_COMMAND_NONE); afCloseFile(af_fp); }
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; }
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[]) { 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[]) { 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; }
main (int argc, char **argv) { AFfilehandle file; AFframecount count, frameCount; int channelCount, sampleFormat, sampleWidth; float frameSize; void *buffer; double sampleRate; ALport outport; ALconfig outportconfig; if (argc < 2) usage(); file = afOpenFile(argv[1], "r", NULL); if (file == AF_NULL_FILEHANDLE) { fprintf(stderr, "Could not open file %s.\n", argv[1]); exit(EXIT_FAILURE); } frameCount = afGetFrameCount(file, AF_DEFAULT_TRACK); frameSize = afGetVirtualFrameSize(file, AF_DEFAULT_TRACK, 1); channelCount = afGetVirtualChannels(file, AF_DEFAULT_TRACK); sampleRate = afGetRate(file, AF_DEFAULT_TRACK); afGetVirtualSampleFormat(file, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); if (sampleFormat == AF_SAMPFMT_UNSIGNED) { afSetVirtualSampleFormat(file, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, sampleWidth); } printf("frame count: %lld\n", frameCount); printf("frame size: %d bytes\n", (int) frameSize); printf("channel count: %d\n", channelCount); printf("sample rate: %.2f Hz\n", sampleRate); buffer = malloc(BUFFERED_FRAME_COUNT * frameSize); outportconfig = alNewConfig(); setwidth(outportconfig, sampleWidth); setsampleformat(outportconfig, sampleFormat); alSetChannels(outportconfig, channelCount); count = afReadFrames(file, AF_DEFAULT_TRACK, buffer, BUFFERED_FRAME_COUNT); outport = alOpenPort("irixread", "w", outportconfig); setrate(outport, sampleRate); do { printf("count = %lld\n", count); alWriteFrames(outport, buffer, count); count = afReadFrames(file, AF_DEFAULT_TRACK, buffer, BUFFERED_FRAME_COUNT); } while (count > 0); waitport(outport); alClosePort(outport); alFreeConfig(outportconfig); afCloseFile(file); }
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; }
static void audiofile_stream_decode(struct decoder *decoder, struct input_stream *is) { GError *error = NULL; AFvirtualfile *vf; int fs, frame_count; AFfilehandle af_fp; struct audio_format audio_format; float total_time; uint16_t bit_rate; int ret; char chunk[CHUNK_SIZE]; enum decoder_command cmd; if (!is->seekable) { g_warning("not seekable"); return; } vf = setup_virtual_fops(is); af_fp = afOpenVirtualFile(vf, "r", NULL); if (af_fp == AF_NULL_FILEHANDLE) { g_warning("failed to input stream\n"); return; } if (!audio_format_init_checked(&audio_format, afGetRate(af_fp, AF_DEFAULT_TRACK), audiofile_setup_sample_format(af_fp), afGetVirtualChannels(af_fp, AF_DEFAULT_TRACK), &error)) { g_warning("%s", error->message); g_error_free(error); afCloseFile(af_fp); return; } frame_count = afGetFrameCount(af_fp, AF_DEFAULT_TRACK); total_time = ((float)frame_count / (float)audio_format.sample_rate); bit_rate = (uint16_t)(is->size * 8.0 / total_time / 1000.0 + 0.5); fs = (int)afGetVirtualFrameSize(af_fp, AF_DEFAULT_TRACK, 1); decoder_initialized(decoder, &audio_format, true, total_time); do { ret = afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk, CHUNK_SIZE / fs); if (ret <= 0) break; cmd = decoder_data(decoder, NULL, chunk, ret * fs, bit_rate); if (cmd == DECODE_COMMAND_SEEK) { AFframecount frame = decoder_seek_where(decoder) * audio_format.sample_rate; afSeekFrame(af_fp, AF_DEFAULT_TRACK, frame); decoder_command_finished(decoder); cmd = DECODE_COMMAND_NONE; } } while (cmd == DECODE_COMMAND_NONE); afCloseFile(af_fp); }
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; }
//*************************************************************************** bool Kwave::AudiofileDecoder::open(QWidget *widget, QIODevice &src) { metaData().clear(); Q_ASSERT(!m_source); if (m_source) qWarning("AudiofileDecoder::open(), already open !"); // try to open the source if (!src.open(QIODevice::ReadOnly)) { qWarning("AudiofileDecoder::open(), failed to open source !"); return false; } // source successfully opened m_source = &src; m_src_adapter = new Kwave::VirtualAudioFile(*m_source); Q_ASSERT(m_src_adapter); if (!m_src_adapter) return false; m_src_adapter->open(m_src_adapter, 0); AFfilehandle fh = m_src_adapter->handle(); if (!fh || (m_src_adapter->lastError() >= 0)) { QString reason; switch (m_src_adapter->lastError()) { case AF_BAD_NOT_IMPLEMENTED: reason = i18n("Format or function is not implemented"); break; case AF_BAD_MALLOC: reason = i18n("Out of memory"); break; case AF_BAD_HEADER: reason = i18n("File header is damaged"); break; case AF_BAD_CODEC_TYPE: reason = i18n("Invalid codec type"); break; case AF_BAD_OPEN: reason = i18n("Opening the file failed"); break; case AF_BAD_READ: reason = i18n("Read access failed"); break; case AF_BAD_SAMPFMT: reason = i18n("Invalid sample format"); break; default: reason = reason.number(m_src_adapter->lastError()); } QString text= i18n("An error occurred while opening the "\ "file:\n'%1'", reason); Kwave::MessageBox::error(widget, text); return false; } AFframecount length = afGetFrameCount(fh, AF_DEFAULT_TRACK); unsigned int tracks = qMax(afGetVirtualChannels(fh, AF_DEFAULT_TRACK), 0); unsigned int bits = 0; double rate = 0.0; int af_sample_format; afGetVirtualSampleFormat(fh, AF_DEFAULT_TRACK, &af_sample_format, reinterpret_cast<int *>(&bits)); Kwave::SampleFormat::Format fmt; switch (af_sample_format) { case AF_SAMPFMT_TWOSCOMP: fmt = Kwave::SampleFormat::Signed; break; case AF_SAMPFMT_UNSIGNED: fmt = Kwave::SampleFormat::Unsigned; break; case AF_SAMPFMT_FLOAT: fmt = Kwave::SampleFormat::Float; break; case AF_SAMPFMT_DOUBLE: fmt = Kwave::SampleFormat::Double; break; default: fmt = Kwave::SampleFormat::Unknown; break; } // get sample rate, with fallback to 8kHz rate = afGetRate(fh, AF_DEFAULT_TRACK); if (rate < 1.0) { qWarning("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"\ "WARNING: file has no sample rate!\n"\ " => using 8000 samples/sec as fallback\n"\ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); rate = 8000.0; } Kwave::SampleFormat::Map sf; QString sample_format_name = sf.description(Kwave::SampleFormat(fmt), true); if (static_cast<signed int>(bits) < 0) bits = 0; int af_compression = afGetCompression(fh, AF_DEFAULT_TRACK); const Kwave::Compression compression( Kwave::Compression::fromAudiofile(af_compression) ); Kwave::FileInfo info(metaData()); info.setRate(rate); info.setBits(bits); info.setTracks(tracks); info.setLength(length); info.set(INF_SAMPLE_FORMAT, Kwave::SampleFormat(fmt).toInt()); info.set(Kwave::INF_COMPRESSION, compression.toInt()); metaData().replace(Kwave::MetaDataList(info)); qDebug("-------------------------"); qDebug("info:"); qDebug("compression = %d", af_compression); qDebug("channels = %d", info.tracks()); qDebug("rate = %0.0f", info.rate()); qDebug("bits/sample = %d", info.bits()); qDebug("length = %lu samples", static_cast<unsigned long int>(info.length())); qDebug("format = %d (%s)", af_sample_format, DBG(sample_format_name)); qDebug("-------------------------"); // set up libaudiofile to produce Kwave's internal sample format #if Q_BYTE_ORDER == Q_BIG_ENDIAN afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN); #else afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN); #endif afSetVirtualSampleFormat(fh, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, SAMPLE_STORAGE_BITS); return true; }
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; }
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)); }