Need help compiling jpegtran.c code from libjpeg - c++

See bottom for updates
I am running into a number of odd problems. For starters, I'm using the latest Eclipse CDT and before implementing do_rot_180, the compiler linked the folder projectName/include but after it now requires specific include/*.h specified below.
Related to that issue, in the project explorer, it seems to think libjpeg.h is missing or invalid despite it being in the folder on the disk.
I am working with libjpeg-9.
Includes (included what transupp.c and example.c included):
Functions (do_rot_180 is from transupp.c and read_JPEG_file is from example.c):
See updated code block below under Edit 2 (pretty much just jpegtran.c code)
This is the rotate function which is unused in jpegtran.c:
//LOCAL(void)
//do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
// JDIMENSION x_crop_offset, JDIMENSION y_crop_offset,
// jvirt_barray_ptr *src_coef_arrays,
// jvirt_barray_ptr *dst_coef_arrays)
///* 180 degree rotation is equivalent to
// * 1. Vertical mirroring;
// * 2. Horizontal mirroring.
// * These two steps are merged into a single processing routine.
// */
//{
// JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
// JDIMENSION x_crop_blocks, y_crop_blocks;
// int ci, i, j, offset_y;
// JBLOCKARRAY src_buffer, dst_buffer;
// JBLOCKROW src_row_ptr, dst_row_ptr;
// JCOEFPTR src_ptr, dst_ptr;
// jpeg_component_info *compptr;
//
// MCU_cols = srcinfo->output_width /
// (dstinfo->max_h_samp_factor * dstinfo->min_DCT_h_scaled_size);
// MCU_rows = srcinfo->output_height /
// (dstinfo->max_v_samp_factor * dstinfo->min_DCT_v_scaled_size);
//
// for (ci = 0; ci < dstinfo->num_components; ci++) {
// compptr = dstinfo->comp_info + ci;
// comp_width = MCU_cols * compptr->h_samp_factor;
// comp_height = MCU_rows * compptr->v_samp_factor;
// x_crop_blocks = x_crop_offset * compptr->h_samp_factor;
// y_crop_blocks = y_crop_offset * compptr->v_samp_factor;
// for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
// dst_blk_y += compptr->v_samp_factor) {
// dst_buffer = (*srcinfo->mem->access_virt_barray)
// ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
// (JDIMENSION) compptr->v_samp_factor, TRUE);
// if (y_crop_blocks + dst_blk_y < comp_height) {
// /* Row is within the vertically mirrorable area. */
// src_buffer = (*srcinfo->mem->access_virt_barray)
// ((j_common_ptr) srcinfo, src_coef_arrays[ci],
// comp_height - y_crop_blocks - dst_blk_y -
// (JDIMENSION) compptr->v_samp_factor,
// (JDIMENSION) compptr->v_samp_factor, FALSE);
// } else {
// /* Bottom-edge rows are only mirrored horizontally. */
// src_buffer = (*srcinfo->mem->access_virt_barray)
// ((j_common_ptr) srcinfo, src_coef_arrays[ci],
// dst_blk_y + y_crop_blocks,
// (JDIMENSION) compptr->v_samp_factor, FALSE);
// }
// for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
// dst_row_ptr = dst_buffer[offset_y];
// if (y_crop_blocks + dst_blk_y < comp_height) {
// /* Row is within the mirrorable area. */
// src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
// for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
// dst_ptr = dst_row_ptr[dst_blk_x];
// if (x_crop_blocks + dst_blk_x < comp_width) {
// /* Process the blocks that can be mirrored both ways. */
// src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1];
// for (i = 0; i < DCTSIZE; i += 2) {
// /* For even row, negate every odd column. */
// for (j = 0; j < DCTSIZE; j += 2) {
// *dst_ptr++ = *src_ptr++;
// *dst_ptr++ = - *src_ptr++;
// }
// /* For odd row, negate every even column. */
// for (j = 0; j < DCTSIZE; j += 2) {
// *dst_ptr++ = - *src_ptr++;
// *dst_ptr++ = *src_ptr++;
// }
// }
// } else {
// /* Any remaining right-edge blocks are only mirrored vertically. */
// src_ptr = src_row_ptr[x_crop_blocks + dst_blk_x];
// for (i = 0; i < DCTSIZE; i += 2) {
// for (j = 0; j < DCTSIZE; j++)
// *dst_ptr++ = *src_ptr++;
// for (j = 0; j < DCTSIZE; j++)
// *dst_ptr++ = - *src_ptr++;
// }
// }
// }
// } else {
// /* Remaining rows are just mirrored horizontally. */
// src_row_ptr = src_buffer[offset_y];
// for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
// if (x_crop_blocks + dst_blk_x < comp_width) {
// /* Process the blocks that can be mirrored. */
// dst_ptr = dst_row_ptr[dst_blk_x];
// src_ptr = src_row_ptr[comp_width - x_crop_blocks - dst_blk_x - 1];
// for (i = 0; i < DCTSIZE2; i += 2) {
// *dst_ptr++ = *src_ptr++;
// *dst_ptr++ = - *src_ptr++;
// }
// } else {
// /* Any remaining right-edge blocks are only copied. */
// jcopy_block_row(src_row_ptr + dst_blk_x + x_crop_blocks,
// dst_row_ptr + dst_blk_x,
// (JDIMENSION) 1);
// }
// }
// }
// }
// }
// }
//}
On top of that, I can't actually find where jcopy_block_row is defined. I've looked through all of the include files and their .c counterparts.
I commented out the error handling stuff in the read_JPEG_file function and want to call do_rot_180 from within but I haven't gotten that far yet.
The only clue I've found is this in transupp.c:
Additional note: jpegtran.exe works separately with the compiled .DLL so it's got to be somewhere.
Edit - copied jpegint.h over into include/ which resolved the include issues.
#ifdef JPEG_INTERNALS
#include "jpegint.h" /* fetch private declarations */
#include "jerror.h" /* fetch error codes too */
#endif
Now it's unable to compile even though they all seem to be declared in jpeglib.h or jpegint.h:
Edit 2 - code now contains jpegtran.c stuff for just being able to rotate 180 degrees. Updated code block:
/*********************************************************************************/
/* Defines */
/*********************************************************************************/
#define JPEG_INTERNALS
/*********************************************************************************/
/* Includes */
/*********************************************************************************/
#include <stdio.h>
#include <iostream>
#include "jinclude.h"
#include "jpeglib.h"
#include "cdjpeg.h"
#include "transupp.h"
#include "jerror.h"
#include <ctype.h>
#include <setjmp.h>
//using namespace std;
static char * infilename;
static char * outfilename;
static JCOPY_OPTION copyoption;
static jpeg_transform_info transformoption;
FILE * infile;
FILE * outfile;
void openFile(char file) {
if(file == 'i') {
infile = fopen(infilename, "rb");
}
else if(file == 'o') {
outfile = fopen(outfilename, "wb");
}
}
/*********************************************************************************/
/* Main Execution Block */
/*********************************************************************************/
int main() {
struct jpeg_decompress_struct srcinfo;
struct jpeg_compress_struct dstinfo;
struct jpeg_error_mgr jsrcerr, jdsterr;
jvirt_barray_ptr * src_coef_arrays;
jvirt_barray_ptr * dst_coef_arrays;
//int file_index;
srcinfo.err = jpeg_std_error(&jsrcerr);
jpeg_create_decompress(&srcinfo);
dstinfo.err = jpeg_std_error(&jdsterr);
jpeg_create_compress(&dstinfo);
jsrcerr.trace_level = jdsterr.trace_level;
srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;
//
outfilename = NULL;
copyoption = JCOPYOPT_DEFAULT;
transformoption.transform = JXFORM_NONE;
transformoption.trim = FALSE;
transformoption.force_grayscale = FALSE;
transformoption.transform = JXFORM_ROT_180;
//
std::cout << "Enter a filename to rotate 180 degrees." << std::endl;
std::cin >> infilename;
openFile('i');
std::cout << "Enter the output filename." << std::endl;
std::cin >> outfilename;
openFile('o');
//
jpeg_stdio_src(&srcinfo, infile);
jcopy_markers_setup(&srcinfo, copyoption);
(void) jpeg_read_header(&srcinfo, TRUE);
jtransform_request_workspace(&srcinfo, &transformoption);
src_coef_arrays = jpeg_read_coefficients(&srcinfo);
jpeg_copy_critical_parameters(&srcinfo, &dstinfo);
dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
src_coef_arrays,
&transformoption);
jpeg_stdio_dest(&dstinfo, outfile);
jpeg_write_coefficients(&dstinfo, dst_coef_arrays);
jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);
jtransform_execute_transformation(&srcinfo, &dstinfo,
src_coef_arrays,
&transformoption);
jpeg_finish_compress(&dstinfo);
jpeg_destroy_compress(&dstinfo);
(void) jpeg_finish_decompress(&srcinfo);
jpeg_destroy_decompress(&srcinfo);
//
if (infile != stdin)
fclose(infile);
if (outfile != stdout)
fclose(outfile);
return 0;
}
/*********************************************************************************/
/* End of Program */
/*********************************************************************************/
Edit 3 - Made the changes Jeff mentioned and I am running into this problem when compiling it (in Eclipse):
cannot find -lC:\Users\tmp\workspace2\jpegManipulator\lib\libjpeg.a jpegManipulator C/C++ Problem
Invalid project path: Duplicate path entries found (/jpegManipulator [Include path] base-path:jpegManipulator isSystemInclude:true includePath:include), path: [/jpegManipulator].jpegManipulator pathentry Path Entry Problem
I have workspace directory /lib set as library source and also the specific libjpeg.a library set in the libraries tab - It is definitely in the directory.
If I don't include the specific libjpeg.a file, it complains about missing function references but if I do include it, it complains saying that there is no libjpeg.a to be found. This is for both v9 and v6b.
cannot find -lC:\Users\tmp\workspace2\jpeg6bmanip\libs\libjpeg.a jpeg6bmanip C/C++ Problem
cannot find -lC:\Users\tmp\workspace2\jpeg6bmanip\libs\libjpeg.la jpeg6bmanip C/C++ Problem
Solution to Edit 3 problem: https://stackoverflow.com/q/14692302/1666510 but new problem after that. Can't run the program or debug it because it claims it cannot find jpeglib.h.

I had something similar happen when developing with MinGW a couple of years ago. I had to download the source for libjpeg and build it on my machine in order to get the libjpeg.a file. The source can be found here:
http://www.ijg.org/
The problem that I found when I built this library was that when I executed 'nm libjpeg.a' it became clear that the symbols in cdjpeg.h and transupp.h were not being compiled into the library. I couldn't find a way to do it via configure since I didn't see anything obvious when I did 'configure --help'. Instead I edited the Makefile.in file where it defines the am__objects_1 list of .lo files. I added cdjpeg and transupp at the end like this:
am__objects_1 = jaricom.lo jcapimin.lo jcapistd.lo jcarith.lo \
jccoefct.lo jccolor.lo jcdctmgr.lo jchuff.lo jcinit.lo \
jcmainct.lo jcmarker.lo jcmaster.lo jcomapi.lo jcparam.lo \
jcprepct.lo jcsample.lo jctrans.lo jdapimin.lo jdapistd.lo \
jdarith.lo jdatadst.lo jdatasrc.lo jdcoefct.lo jdcolor.lo \
jddctmgr.lo jdhuff.lo jdinput.lo jdmainct.lo jdmarker.lo \
jdmaster.lo jdmerge.lo jdpostct.lo jdsample.lo jdtrans.lo \
jerror.lo jfdctflt.lo jfdctfst.lo jfdctint.lo jidctflt.lo \
jidctfst.lo jidctint.lo jquant1.lo jquant2.lo jutils.lo \
jmemmgr.lo cdjpeg.lo transupp.lo #MEMORYMGR#.lo
Then I did a 'make' and a 'make install' and the symbols were present in the library. At that point I was able to get your code to build. An autotools expert may be able to come up with a better way to do it but this will at least get you going.

Related

What's the difference between initializing a vector in Class Header or Class constructor body?

I encountered a strange behavior in my C++ program that I don't understand and I don't know how to search for more information. So I ask for advice here hoping someone might know.
I have a class Interface that has a 2 dimensional vector that I initialize in the header :
class Interface {
public:
// code...
const unsigned short int SIZE_X_ = 64;
const unsigned short int SIZE_Y_ = 32;
std::vector<std::vector<bool>> screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code...
};
Here I expect that I have a SIZE_X_ x SIZE_Y_ vector filled with false booleans.
Later in my program I loop at a fixed rate like so :
void Emulator::loop() {
const milliseconds intervalPeriodMillis{static_cast<int>((1. / FREQ) * 1000)};
//Initialize the chrono timepoint & duration objects we'll be //using over & over inside our sleep loop
system_clock::time_point currentStartTime{system_clock::now()};
system_clock::time_point nextStartTime{currentStartTime};
while (!stop) {
currentStartTime = system_clock::now();
nextStartTime = currentStartTime + intervalPeriodMillis;
// ---- Stuff happens here ----
registers_->trigger_timers();
interface_->toogle_buzzer();
interface_->poll_events();
interface_->get_keys();
romParser_->step();
romParser_->decode();
// ---- ------------------ ----
stop = stop || interface_->requests_close();
std::this_thread::sleep_until(nextStartTime);
}
}
But then during the execution I get a segmentation fault
[1] 7585 segmentation fault (core dumped) ./CHIP8 coin.ch8
I checked with the debugger and some part of the screen_memory_ cannot be accessed anymore. And it seems to happen at random time.
But when I put the initialization of the vector in the constructor body like so :
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
// code ...
screen_memory_ =
std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
// code ...
}
The segmentation fault doesn't happen anymore. So the solution is just to initialize the vector in the constructor body.
But why ? what is happening there ?
I don't understand what I did wrong, I'm sure someone knows.
Thanks for your help !
[Edit] I found the source of the bug (Or at least what to change so it doesnt give me a segfault anymore).
In my class Interface I use the SDL and SDL_audio libraries to create the display and the buzzer sound. Have a special look where I set the callback want_.callback, the callback Interface::forward_audio_callback and Interface::audio_callback. Here's the code :
// (c) 2021 Maxandre Ogeret
// Licensed under MIT License
#include "Interface.h"
Interface::Interface(const std::shared_ptr<reg::RegisterManager> & registers, bool hidden)
: registers_(registers) {
if (SDL_Init(SDL_INIT_AUDIO != 0) || SDL_Init(SDL_INIT_VIDEO) != 0) {
throw std::runtime_error("Unable to initialize rendering engine.");
}
want_.freq = SAMPLE_RATE;
want_.format = AUDIO_S16SYS;
want_.channels = 1;
want_.samples = 2048;
want_.callback = Interface::forward_audio_callback;
want_.userdata = &sound_userdata_;
if (SDL_OpenAudio(&want_, &have_) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to open audio: %s", SDL_GetError());
}
if (want_.format != have_.format) {
SDL_LogError(SDL_LOG_CATEGORY_AUDIO, "Failed to get the desired AudioSpec");
}
window = SDL_CreateWindow("CHIP8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SIZE_X_ * SIZE_MULTIPLIER_, SIZE_Y_ * SIZE_MULTIPLIER_,
hidden ? SDL_WINDOW_HIDDEN : 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
bpp_ = SDL_GetWindowSurface(window)->format->BytesPerPixel;
SDL_Delay(1000);
// screen_memory_ = std::vector<std::vector<bool>>(SIZE_X_, std::vector<bool>(SIZE_Y_, false));
}
Interface::~Interface() {
SDL_CloseAudio();
SDL_DestroyWindow(window);
SDL_Quit();
}
// code ...
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
sample_length_ = bytes / 2;
int & sample_nr(*(int *) user_data);
for (int i = 0; i < sample_length_; i++, sample_nr++) {
double time = (double) sample_nr / (double) SAMPLE_RATE;
audio_buffer_[i] = static_cast<Sint16>(
AMPLITUDE * (2 * (2 * floor(220.0f * time) - floor(2 * 220.0f * time)) + 1));
}
}
void Interface::forward_audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
static_cast<Interface *>(user_data)->audio_callback(user_data, raw_buffer, bytes);
}
}
In the function Interface::audio_callback, replacing the class variable assignation :
sample_length_ = bytes / 2;
By an int creation and assignation :
int sample_length = bytes / 2;
which gives :
void Interface::audio_callback(void * user_data, Uint8 * raw_buffer, int bytes) {
audio_buffer_ = reinterpret_cast<Sint16 *>(raw_buffer);
int sample_length = bytes / 2;
int &sample_nr(*(int*)user_data);
for(int i = 0; i < sample_length; i++, sample_nr++)
{
double time = (double)sample_nr / (double)SAMPLE_RATE;
audio_buffer_[i] = (Sint16)(AMPLITUDE * sin(2.0f * M_PI * 441.0f * time)); // render 441 HZ sine wave
}
}
The class variable sample_length_ is defined and initialized as private in the header like so :
int sample_length_ = 0;
So I had an idea and I created the variable sample_length_ as public and it works ! So the problem was definitely a scope problem of the class variable sample_length_. But it doesn't explain why the segfault disappeared when I moved the init of some other variable in the class constructor... Did I hit some undefined behavior with my callback ?
Thanks for reading me !

Multiple markers at this line(C++) Regarding function

I'm getting the above error in my code.
File Scope Prototypes
static void pressure_val_update(void);
The above prototype is been used in below function
void ui_vcr_menu_update(const MENU_CONTROL_T *p, UINT8 HAL)
{
pressure_val_update();
ratio_val_update();
pressure_unit_update();
}
Below is the function definition
static void pressure_val_update(void)
{
UINT8 fl_pressure_value_U8;
/* Get the Pressure value from RTE */
Rte_Read_rpVCRDisplayValue_Pressure(&fl_pressure_value_U8);
/* Case 1 : Step 0 - Step 16 */
if(fl_pressure_value_U8 < 17U)
{
l_pressure_value_S16 = (-270 + (fl_pressure_value_U8 * 5.4));
rbmp_U8 = DISABLE
l_pressure_lbbmp_U8 = IMAGE_ENABLE;
l_pressure_ltbmp_U8 = DISABLE
}
/* Case 2 : Step 17 - Step 33 */
else if((fl_pressure_value_U8 >= 17U) && (fl_pressure_value_U8 < 34U))
{
l_pressure_value_S16 = (-270 + (fl_pressure_value_U8 * 5.4));
rbmp_U8 = DISABLE
l_pressure_lbbmp_U8 = IMAGE_ENABLE;
l_pressure_ltbmp_U8 = IMAGE_ENABLE;
}
/* Case 3 : Step 34 - Step 50 */
else if((fl_pressure_value_U8 >= 34U) && (fl_pressure_value_U8 < 51U))
{
l_pressure_value_S16 = (-270 + (fl_pressure_value_U8 * 5.4));
rbmp_U8 = IMAGE_ENABLE;
l_pressure_lbbmp_U8 = IMAGE_ENABLE;
l_pressure_ltbmp_U8 = IMAGE_ENABLE;
}
else
{
l_pressure_value_S16 = -270;
rbmp_U8 = DISABLE
l_pressure_lbbmp_U8 = DISABLE
l_pressure_ltbmp_U8 = DISABLE
}
}
/*
How to solve this, Why do it get multiple markers at this line (static void pressure_val_update(void)).
I am working application projects and facing this issue.
I have gone through other internet solutions but those are not related to me.
Please let me know the exact reason why we will get this warning (I got this warning in coverity analysis)

Audio distorted with VST plugin

I had to plug into a pre-existing software, managing ASIO audio streams, a simple VST host. Despite of lack of some documentation, I managed to do so however once I load the plugin I get a badly distorted audio signal back.
The VST I'm using works properly (with other VST Hosts) so it's probably some kind of bug in the code I made, however when I disable the "PROCESS" from the plugin (my stream goes through the plugin, it simply does not get processed) it gets back as I sent without any noise or distortion on it.
One thing I'm slightly concerned about is the type of the data used as the ASIO driver fills an __int32 buffer while the plugins wants some float buffer.
That's really depressing as I reviewed zillions of times my code and it seems to be fine.
Here is the code of the class I'm using; please note that some numbers are temporarily hard-coded to help debugging.
VSTPlugIn::VSTPlugIn(const char* fullDirectoryName, const char* ID)
: plugin(NULL)
, blocksize(128) // TODO
, sampleRate(44100.0F) // TODO
, hostID(ID)
{
this->LoadPlugin(fullDirectoryName);
this->ConfigurePluginCallbacks();
this->StartPlugin();
out = new float*[2];
for (int i = 0; i < 2; ++i)
{
out[i] = new float[128];
memset(out[i], 0, 128);
}
}
void VSTPlugIn::LoadPlugin(const char* path)
{
HMODULE modulePtr = LoadLibrary(path);
if(modulePtr == NULL)
{
printf("Failed trying to load VST from '%s', error %d\n", path, GetLastError());
plugin = NULL;
}
// vst 2.4 export name
vstPluginFuncPtr mainEntryPoint = (vstPluginFuncPtr)GetProcAddress(modulePtr, "VSTPluginMain");
// if "VSTPluginMain" was not found, search for "main" (backwards compatibility mode)
if(!mainEntryPoint)
{
mainEntryPoint = (vstPluginFuncPtr)GetProcAddress(modulePtr, "main");
}
// Instantiate the plugin
plugin = mainEntryPoint(hostCallback);
}
void VSTPlugIn::ConfigurePluginCallbacks()
{
// Check plugin's magic number
// If incorrect, then the file either was not loaded properly, is not a
// real VST plugin, or is otherwise corrupt.
if(plugin->magic != kEffectMagic)
{
printf("Plugin's magic number is bad. Plugin will be discarded\n");
plugin = NULL;
}
// Create dispatcher handle
this->dispatcher = (dispatcherFuncPtr)(plugin->dispatcher);
// Set up plugin callback functions
plugin->getParameter = (getParameterFuncPtr)plugin->getParameter;
plugin->processReplacing = (processFuncPtr)plugin->processReplacing;
plugin->setParameter = (setParameterFuncPtr)plugin->setParameter;
}
void VSTPlugIn::StartPlugin()
{
// Set some default properties
dispatcher(plugin, effOpen, 0, 0, NULL, 0);
dispatcher(plugin, effSetSampleRate, 0, 0, NULL, sampleRate);
dispatcher(plugin, effSetBlockSize, 0, blocksize, NULL, 0.0f);
this->ResumePlugin();
}
void VSTPlugIn::ResumePlugin()
{
dispatcher(plugin, effMainsChanged, 0, 1, NULL, 0.0f);
}
void VSTPlugIn::SuspendPlugin()
{
dispatcher(plugin, effMainsChanged, 0, 0, NULL, 0.0f);
}
void VSTPlugIn::ProcessAudio(float** inputs, float** outputs, long numFrames)
{
plugin->processReplacing(plugin, inputs, out, 128);
memcpy(outputs, out, sizeof(float) * 128);
}
EDIT: Here's the code I use to interface my sw with the VST Host
// Copying the outer buffer in the inner container
for(unsigned i = 0; i < bufferLenght; i++)
{
float f;
f = ((float) buff[i]) / (float) std::numeric_limits<int>::max()
if( f > 1 ) f = 1;
if( f < -1 ) f = -1;
samples[0][i] = f;
}
// DO JOB
for(auto it = inserts.begin(); it != inserts.end(); ++it)
{
(*it)->ProcessAudio(samples, samples, bufferLenght);
}
// Copying the result back into the buffer
for(unsigned i = 0; i < bufferLenght; i++)
{
float f = samples[0][i];
int intval;
f = f * std::numeric_limits<int>::max();
if( f > std::numeric_limits<int>::max() ) f = std::numeric_limits<int>::max();
if( f < std::numeric_limits<int>::min() ) f = std::numeric_limits<int>::min();
intval = (int) f;
buff[i] = intval;
}
where "buff" is defined as "__int32* buff"
I'm guessing that when you call f = std::numeric_limits<int>::max() (and the related min() case on the line below), this might cause overflow. Have you tried f = std::numeric_limits<int>::max() - 1?
Same goes for the code snippit above with f = ((float) buff[i]) / (float) std::numeric_limits<int>::max()... I'd also subtract one there to avoid a potential overflow later on.

Pops / clicks when stopping and starting DirectX sound synth in C++ / MFC

I have made a soft synthesizer in Visual Studio 2012 with C++, MFC and DirectX. Despite having added code to rapidly fade out the sound I am experiencing popping / clicking when stopping playback (also when starting).
I copied the DirectX code from this project: http://www.codeproject.com/Articles/7474/Sound-Generator-How-to-create-alien-sounds-using-m
I'm not sure if I'm allowed to cut and paste all the code from the Code Project. Basically I use the Player class from that project as is, the instance of this class is called m_player in my code. The Stop member function in that class calls the Stop function of LPDIRECTSOUNDBUFFER:
void Player::Stop()
{
DWORD status;
if (m_lpDSBuffer == NULL)
return;
HRESULT hres = m_lpDSBuffer->GetStatus(&status);
if (FAILED(hres))
EXCEP(DirectSoundErr::GetErrDesc(hres), "Player::Stop GetStatus");
if ((status & DSBSTATUS_PLAYING) == DSBSTATUS_PLAYING)
{
hres = m_lpDSBuffer->Stop();
if (FAILED(hres))
EXCEP(DirectSoundErr::GetErrDesc(hres), "Player::Stop Stop");
}
}
Here is the notification code (with some supporting code) in my project that fills the sound buffer. Note that the rend function always returns a double between -1 to 1, m_ev_smps = 441, m_n_evs = 3 and m_ev_sz = 882. subInit is called from OnInitDialog:
#define FD_STEP 0.0005
#define SC_NOT_PLYD 0
#define SC_PLYNG 1
#define SC_FD_OUT 2
#define SC_FD_IN 3
#define SC_STPNG 4
#define SC_STPD 5
bool CMainDlg::subInit()
// initialises various variables and the sound player
{
Player *pPlayer;
SOUNDFORMAT format;
std::vector<DWORD> events;
int t, buf_sz;
try
{
pPlayer = new Player();
pPlayer->SetHWnd(m_hWnd);
m_player = pPlayer;
m_player->Init();
format.NbBitsPerSample = 16;
format.NbChannels = 1;
format.SamplingRate = 44100;
m_ev_smps = 441;
m_n_evs = 3;
m_smps = new short[m_ev_smps];
m_smp_scale = (int)pow(2, format.NbBitsPerSample - 1);
m_max_tm = (int)((double)m_ev_smps / (double)(format.SamplingRate * 1000));
m_ev_sz = m_ev_smps * format.NbBitsPerSample/8;
buf_sz = m_ev_sz * m_n_evs;
m_player->CreateSoundBuffer(format, buf_sz, 0);
m_player->SetSoundEventListener(this);
for(t = 0; t < m_n_evs; t++)
events.push_back((int)((t + 1)*m_ev_sz - m_ev_sz * 0.95));
m_player->CreateEventReadNotification(events);
m_status = SC_NOT_PLYD;
}
catch(MATExceptions &e)
{
MessageBox(e.getAllExceptionStr().c_str(), "Error initializing the sound player");
EndDialog(IDCANCEL);
return FALSE;
}
return TRUE;
}
void CMainDlg::Stop()
// stop playing
{
m_player->Stop();
m_status = SC_STPD;
}
void CMainDlg::OnBnClickedStop()
// causes fade out
{
m_status = SC_FD_OUT;
}
void CMainDlg::OnSoundPlayerNotify(int ev_num)
// render some sound samples and check for errors
{
ScopeGuardMutex guard(&m_mutex);
int s, end, begin, elapsed;
if (m_status != SC_STPNG)
{
begin = GetTickCount();
try
{
for(s = 0; s < m_ev_smps; s++)
{
m_smps[s] = (int)(m_synth->rend() * 32768 * m_fade);
if (m_status == SC_FD_IN)
{
m_fade += FD_STEP;
if (m_fade > 1)
{
m_fade = 1;
m_status = SC_PLYNG;
}
}
else if (m_status == SC_FD_OUT)
{
m_fade -= FD_STEP;
if (m_fade < 0)
{
m_fade = 0;
m_status = SC_STPNG;
}
}
}
}
catch(MATExceptions &e)
{
OutputDebugString(e.getAllExceptionStr().c_str());
}
try
{
m_player->Write(((ev_num + 1) % m_n_evs)*m_ev_sz, (unsigned char*)m_smps, m_ev_sz);
}
catch(MATExceptions &e)
{
OutputDebugString(e.getAllExceptionStr().c_str());
}
end = GetTickCount();
elapsed = end - begin;
if(elapsed > m_max_tm)
m_warn_msg.Format(_T("Warning! compute time: %dms"), elapsed);
else
m_warn_msg.Format(_T("compute time: %dms"), elapsed);
}
if (m_status == SC_STPNG)
Stop();
}
It seems like the buffer is not always sounding out when the stop button is clicked. I don't have any specific code for waiting for the sound buffer to finish playing before the DirectX Stop is called. Other than that the sound playback is working just fine, so at least I am initialising the player correctly and notification code is working in that respect.
Try replacing 32768 with 32767. Not by any means sure this is your issue, but it could overflow the positive short int range (assuming your audio is 16-bit) and cause a "pop".
I got rid of the pops / clicks when stopping playback, by filling the buffer with zeros after the fade out. However I still get pops when re-starting playback, despite filling with zeros and then fading back in (it is frustrating).

GIF LZW decompression

I am trying to implement a simple Gif-Reader in c++.
I currently stuck with decompressing the Imagedata.
If an image includes a Clear Code my decompression algorithm fails.
After the Clear Code I rebuild the CodeTable reset the CodeSize to MinimumLzwCodeSize + 1.
Then I read the next code and add it to the indexstream. The problem is that after clearing, the next codes include values greater than the size of the current codetable.
For example the sample file from wikipedia: rotating-earth.gif has a code value of 262 but the GlobalColorTable is only 256. How do I handle this?
I implemented the lzw decompression according to gif spec..
here is the main code part of decompressing:
int prevCode = GetCode(ptr, offset, codeSize);
codeStream.push_back(prevCode);
while (true)
{
auto code = GetCode(ptr, offset, codeSize);
//
//Clear code
//
if (code == IndexClearCode)
{
//reset codesize
codeSize = blockA.LZWMinimumCodeSize + 1;
currentNodeValue = pow(2, codeSize) - 1;
//reset codeTable
codeTable.resize(colorTable.size() + 2);
//read next code
prevCode = GetCode(ptr, offset, codeSize);
codeStream.push_back(prevCode);
continue;
}
else if (code == IndexEndOfInformationCode)
break;
//exists in dictionary
if (codeTable.size() > code)
{
if (prevCode >= codeTable.size())
{
prevCode = code;
continue;
}
for (auto c : codeTable[code])
codeStream.push_back(c);
newEntry = codeTable[prevCode];
newEntry.push_back(codeTable[code][0]);
codeTable.push_back(newEntry);
prevCode = code;
if (codeTable.size() - 1 == currentNodeValue)
{
codeSize++;
currentNodeValue = pow(2, codeSize) - 1;
}
}
else
{
if (prevCode >= codeTable.size())
{
prevCode = code;
continue;
}
newEntry = codeTable[prevCode];
newEntry.push_back(codeTable[prevCode][0]);
for (auto c : newEntry)
codeStream.push_back(c);
codeTable.push_back(newEntry);
prevCode = codeTable.size() - 1;
if (codeTable.size() - 1 == currentNodeValue)
{
codeSize++;
currentNodeValue = pow(2, codeSize) - 1;
}
}
}
Found the solution.
It is called Deferred clear code. So when I check if the codeSize needs to be incremented I also need to check if the codeSize is already max(12), as it is possible to to get codes that are of the maximum Code Size. See spec-gif89a.txt.
if (codeTable.size() - 1 == currentNodeValue && codeSize < 12)
{
codeSize++;
currentNodeValue = (1 << codeSize) - 1;
}