Ejemplo n.º 1
0
    void writeBufferToFile( int aSampleRate, int aNumChannels, bool broadcastUpdate )
    {
        // quick assertion
        if ( DiskWriter::cachedBuffer == 0 )
            return;

        aNumChannels = 1;   // TODO : currently MONO only (see appendBuffer above)

        // we improve the use of the CPU resources
        // by creating a small local thread
        // TODO: do it ? (this non-threading blocks the renderer, but nicely omits issue w/ continuous writes ;) )

        //pthread_t t1;
        //pthread_create( &t1, NULL, &print_message, NULL );

        // copy string contents for appending of filename
        std::string outputFile = std::string( DiskWriter::outputDirectory.c_str());

        int bufferSize = DiskWriter::outputBufferSize;

        // uh oh.. recorded less than maximum available in buffer ? cut silence
        if ( DiskWriter::outputWriterIndex < bufferSize )
        {
            bufferSize = DiskWriter::outputWriterIndex;

            short int* tempBuffer = new short int[ bufferSize ];

            for ( int i = 0; i < bufferSize; ++i )
                tempBuffer[ i ] = DiskWriter::cachedBuffer[ i ];

            write_wav( outputFile.append( SSTR( recordingFileName )), bufferSize, tempBuffer, aSampleRate, aNumChannels );

            delete[] tempBuffer;
        }
        else {
            write_wav( outputFile.append( SSTR( recordingFileName )), bufferSize, DiskWriter::cachedBuffer, aSampleRate, aNumChannels );
        }
        DiskWriter::flushOutput(); // free memory

        if ( broadcastUpdate )
        {
            // broadcast update via JNI, pass buffer identifier name to identify last recording
            jmethodID native_method_id = getJavaMethod( JavaAPIs::RECORDING_UPDATE );

            if ( native_method_id != 0 )
            {
                JNIEnv* env = getEnvironment();

                if ( env != 0 )
                    env->CallStaticVoidMethod( getJavaInterface(), native_method_id, recordingFileName );
            }
        }
        //void* result;
        //pthread_join( t1, &result );
    }
Ejemplo n.º 2
0
    /**
     * write the contents of the write buffer into
     * an output file, this will only write content
     * up until the point if was written to in case
     * the buffer wasn't full yet
     */
    void writeBufferToFile( int aSampleRate, int aNumChannels, bool broadcastUpdate )
    {
        // quick assertion
        if ( DiskWriter::cachedBuffer == 0 )
            return;

        // we can improve the use of the CPU resources
        // by creating a local thread
        // TODO: do it ? (this non-threading blocks the renderer, but nicely omits issue w/ continuous writes ;) )

        //pthread_t t1;
        //pthread_create( &t1, NULL, &print_message, NULL );

        // copy string contents for appending of filename
        std::string outputFile = std::string( DiskWriter::outputDirectory.c_str());

        int bufferSize = DiskWriter::outputBufferSize;

        // uh oh.. recorded less than maximum available in buffer ? cut silence
        if ( DiskWriter::outputWriterIndex < bufferSize )
        {
            bufferSize = DiskWriter::outputWriterIndex;

            short int* tempBuffer = new short int[ bufferSize ];

            for ( int i = 0; i < bufferSize; ++i )
                tempBuffer[ i ] = DiskWriter::cachedBuffer[ i ];

            write_wav( outputFile.append( SSTR( AudioEngine::recordingFileId )),
                       bufferSize, tempBuffer, aSampleRate, aNumChannels );

            delete[] tempBuffer; // free memory of temporary buffer
        }
        else {
            write_wav( outputFile.append( SSTR( AudioEngine::recordingFileId )),
                       bufferSize, DiskWriter::cachedBuffer, aSampleRate, aNumChannels );
        }

        DiskWriter::flushOutput(); // free memory

        if ( broadcastUpdate )
        {
            // broadcast update via JNI, pass buffer identifier to identify last recording
            Observer::broadcastRecordingUpdate( AudioEngine::recordingFileId );
        }
        //void* result;
        //pthread_join( t1, &result );
    }
Ejemplo n.º 3
0
int main(int argc, char **argv) {
	struct mockery m;

	
	if(prepare_mockery(&m, STEP_LENGTH, "envelope")) {
		printf("Failed to initiate mockery of module.\n");
		exit(1);
	}

	if(create_mock_output_signal(
		   &m, "Mono",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   output_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	memset(output_signal, 0, sizeof(output_signal));

	make_a_mockery(&m, MAX_STEPS);

	write_wav(output_signal, output_signal, TEST_LENGTH, "/tmp/mocking.wav");

	printf("\n\n");
	printf("output: %p\n", output_signal);

	(void) plot_wave("/tmp/mocking.wav", (int)(0.0f * 44100.0f), (int)(0.1f * 44100.0f));
	
	return 0;
}
Ejemplo n.º 4
0
static void extract_track(gchar *trk, GtkProgressBar *prog) {
	int fd;
	unsigned int fs;
	char path[80];

	// Open output file
	sprintf(path, "%s.wav", trk);
	_DBG(_DBG_PRJ, "opening output file: %s\n", path);
#ifdef WIN32
	fd = _sopen(path, _O_RDWR | _O_BINARY | _O_CREAT, _SH_DENYNO, 0666);
#else
	fd = open(path, O_RDWR | O_CREAT | O_LARGEFILE, 0666);
#endif
	if (fd<0) {
		about_box("Unable to open track file");
		return;
	}
	// Write WAV header
	_DBG(_DBG_PRJ, "writing output file\n");
	write_wav(fd, &g_proj, 0);
	// Write samples
	lseek64(g_fd, g_poff, SEEK_SET);
	fs = akaiosproject_extract(&g_proj, trk, g_fd, fd, update_prog, prog);
	// Check for empty file
	if (!fs) {
		close(fd);
		remove(path);
		_DBG(_DBG_PRJ, "removed empty file: %s\n", path);
	} else {
		// Re-write WAV header with correct file size
		lseek64(fd, (off64_t)0, SEEK_SET);
		write_wav(fd, &g_proj, fs);
		close(fd);
		_DBG(_DBG_PRJ, "file done\n");
	}
}
Ejemplo n.º 5
0
// Mic thread
void threadMic(){
	while(1) {
		svcWaitSynchronization(threadRequest, U64_MAX);
		svcClearEvent(threadRequest);		

		if(threadExit) svcExitThread();
		
		touchPosition touch;
		hidTouchRead(&touch);
		u32 kDown = hidKeysDown();

		if((touchInCircle(touch, 85, 120, 35) || kDown & KEY_A) && recording == 0)
		{
			audiobuf_pos = 0;
			MIC_SetRecording(1);
			recording = 1;
		}

		if((recording == 1) && (audiobuf_pos < audiobuf_size))
		{
			audiobuf_pos+= MIC_ReadAudioData(&audiobuf[audiobuf_pos], audiobuf_size-audiobuf_pos, 0);
			if(audiobuf_pos > audiobuf_size)audiobuf_pos = audiobuf_size;
			if(audiobuf_pos >= 32704 && print == 0){
				print = 1;
			}
		}

		if((touchInCircle(touch, 165, 120, 35) || kDown & KEY_B) && recording == 1)
		{
			print = 0;
			MIC_SetRecording(0);
			recording = 2;

			//Prevent first mute second to be allocated in wav struct
			if(audiobuf_pos >= 32704){
				nomute_audiobuf =  (u8*)linearAlloc(audiobuf_pos - 32704);
				memcpy(nomute_audiobuf,&audiobuf[32704],audiobuf_pos - 32704);
				buf_size = (audiobuf_pos - 32704) / 2;
				write_wav("audio.wav", buf_size, (short int *)nomute_audiobuf, S_RATE);
			}

			GSPGPU_FlushDataCache(NULL, nomute_audiobuf, audiobuf_pos);
			recording = 0;
		}
	}
}
Ejemplo n.º 6
0
Archivo: waver.c Proyecto: cruel2/devel
int main(int argc, char ** argv)
{
    int i;
    float t;
    float amplitude = 16000;
    float freq_Hz = 440;
    float phase1 = 0.0;
    float phase2 = 0.0;
    float phase3 = 0.0;
    
    // initialization for global variables
    noNotes = 0;
    VOLUME = 0.0;
    
    init();
    
    if (readConfig("config.ini") != 1)
    {
      fprintf(stderr, "Couldn't read config file!\n");
      return -1;
    }
    
    if (readTab("test.tab") != 1)
    {
      fprintf(stderr, "Couldn't read tab file!\n");
      return -1;
    }
    
    printf("length: %f\n", getTabLength());
    
    // TODO : miert kell ide a 2-es szorzo?
    bufferSize = 2*(int)ceil(S_RATE * getTabLength());
    buffer = (int*)calloc(sizeof(int), bufferSize);
    
    processTab();
 
    write_wav("test.wav", bufferSize, buffer, S_RATE);
    
    free(buffer);
    
    destroy();
 
    return 0;
}
Ejemplo n.º 7
0
int main(int argc, char * argv)
{
    int i;
    float t;
    float amplitude = 32000;
    float freq_Hz = 440;
    float phase=0;

    float freq_radians_per_sample = freq_Hz*2*M_PI/S_RATE;

    /* fill buffer with a sine wave */
    for (i=0; i<BUF_SIZE; i++)
    {
        phase += freq_radians_per_sample;
    buffer[i] = (int)(amplitude * sin(phase));
    }

    write_wav("test.wav", BUF_SIZE, buffer, S_RATE);

    return 0;
}
Ejemplo n.º 8
0
/*
-----------------------------------------------------------------------------
 Function: CA_SaveAudioChunk() -Decode and save audio data.
 
 Parameters: chunk -[in] Chunk number to cache.
			 filename -[in] Save as filename.
			 BuffChunk -[in] Sound data to decode.
			 BuffWav -[in] Allocated memory block to hold decoded data.
 
 Returns: Nothing.
 
 Notes: 
-----------------------------------------------------------------------------
*/
PRIVATE void CA_SaveAudioChunk( W32 chunk, const char *filename,
				  W8 *BuffChunk, W8 *BuffWav )
{     
	W32 length;

	if( ! filename || ! *filename )
	{
	   return;	
	}

	if( ! CA_CacheAudioChunk( chunk, BuffChunk ) )
	{
		return;
	}

	if( ADLIB_DecodeSound( (AdLibSound *)BuffChunk, BuffWav, &length ) == 0 )
	{
	   return;
    }	

	write_wav( filename, BuffWav, length, 1, 22050, 2  );
}
Ejemplo n.º 9
0
int main(int argc, char * argv)
{
    int i;
    float t;
    float amplitude = 32000;
    float freq_Hz = 440;
    float phase=0;

    //float freq_radians_per_sample = freq_Hz*2*M_PI/S_RATE; //comentado por el numero ya calculado
    //hasta arreglar el parseo de los asteriscos
    float freq_radians_per_sample = 1073741824;
    //printf("%d",freq_radians_per_sample);

    //* fill buffer with a sine wave */
    for (i=0; i<BUF_SIZE; i++)
    {
        phase += freq_radians_per_sample;
    buffer[i] = (int)(amplitude * sin(phase));
    }

    write_wav(BUF_SIZE, buffer, S_RATE); //saque "test.wav" xq no lo reconocia

    return 0;
}
Ejemplo n.º 10
0
	void output_wav(std::basic_ostream<Elem, Traits>& os, sprout::compost::sources::info_type const& info, InputRange const& data) {
		std::ostreambuf_iterator<Elem> it(os);
		write_wav(it, info, data);
	}
Ejemplo n.º 11
0
int main(int argc, char **argv) {
	struct mockery m;

	
	if(prepare_mockery(&m, TEST_LENGTH, "drumsampler")) {
		printf("Failed to initiate mockery of module.\n");
		exit(1);
	}

	if(create_mock_input_signal(
		   &m, "midi",
		   _MIDI,
		   1,
		   _PTR,
		   44100,
		   TEST_LENGTH,
		   input_signal
		   )) {
		printf("Failed to create mock input signal.\n");
		exit(2);
	}

	if(create_mock_output_signal(
		   &m, "Mono",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   output_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	if(create_mock_intermediate_signal(
		   &m, "A",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   a_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	if(create_mock_intermediate_signal(
		   &m, "B",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   b_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	memset(input_signal, 0, sizeof(input_signal));
	memset(output_signal, 0, sizeof(output_signal));

	uint8_t on_event[8], off_event[8];
	MidiEvent *on = (MidiEvent *)on_event;
	MidiEvent *off = (MidiEvent *)off_event;
	on->length = 4; off->length = 4;

	on->data[0] = MIDI_NOTE_ON | 0;
	on->data[1] = 38;
	on->data[2] = 127;
	
	off->data[0] = MIDI_NOTE_OFF | 0;
	off->data[1] = 38;
	off->data[2] = 127;

	input_signal[10] = on;
	input_signal[10000] = off;
	
	make_a_mockery(&m);

//	write_wav(a_signal, b_signal, TEST_LENGTH, "/tmp/mocking.wav");
//	write_wav(a_signal, output_signal, TEST_LENGTH, "/tmp/mocking.wav");
	write_wav(output_signal, output_signal, TEST_LENGTH, "/tmp/mocking.wav");

	printf("\n\n");
	printf("output: %p\n", output_signal);

	return 0;
}
Ejemplo n.º 12
0
int main(int argc, char **argv) {
	struct mockery m;

	if(prepare_mockery(&m, STEP_LENGTH, "chorus")) {
		printf("Failed to initiate mockery of module chorus.\n");
		exit(1);
	}

	if(create_mock_input_signal(
		   &m, "Mono",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   BENCH_FREQUENCY,
		   TEST_LENGTH,
		   input_signal
		   )) {
		printf("Failed to create mock input signal.\n");
		exit(2);
	}
	if(create_mock_output_signal(
		   &m, "Mono",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   BENCH_FREQUENCY,
		   TEST_LENGTH,
		   output_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	memset(input_signal, 0, sizeof(input_signal));
	memset(output_signal, 0, sizeof(output_signal));
/*
	{
		int k;
		for(k = 0; k < 1; k++) {
			input_signal[k] = ftoFTYPE(0.5f);
		}
	}
*/
	{
		int rd;
		int16_t riffdata[TEST_LENGTH * 2];
		
		RIFF_WAVE_FILE_t rwf;
		
		RIFF_open_file(&rwf, "katy_sings.wav");

		rd = RIFF_read_data(&rwf, riffdata, TEST_LENGTH);

		convert_pcm_to_mock_signal(
			input_signal, 1, TEST_LENGTH,

			riffdata,
			rwf.channels, rwf.samples);

		RIFF_close_file(&rwf);
		printf("   read: %d\n", rd);
		printf("data[0] = %d\n", riffdata[0]);
		printf("data[1] = %d\n", riffdata[1]);
		printf("data[2] = %d\n", riffdata[2]);
		printf("data[3] = %d\n", riffdata[3]);
	}

	make_a_mockery(&m, MAX_STEPS);

	write_wav(output_signal, input_signal, TEST_LENGTH, "/tmp/mocking.wav");

	printf("\n\n");
	printf("input: %p\n", input_signal);
	printf("output: %p\n", output_signal);
}
Ejemplo n.º 13
0
PRIVATE void CA_SaveMusicChunk( W32 chunk, const char *filename )
{
	W8 *data, *BuffWav;
	W32 pos, length, uncompr_length;
	W32 len;


	pos = audiostarts[ chunk ];
	length = audiostarts[ chunk+1 ] - pos;

	data = MM_MALLOC( length );
	if( data == NULL )
	{
		return;
	}

	if( fseek( audiohandle, pos, SEEK_SET ) != 0 )
	{
		printf( "[CA_SaveMusicChunk]: Could not seek!\n" );
		
		MM_FREE( data );

		return;
	}

	if( fread( data, 1, length, audiohandle ) != length )
	{
		printf( "[CA_SaveMusicChunk]: Read error!\n" );

		MM_FREE( data );

		return;	
	}


	uncompr_length = ADLIB_getLength( data );
	if( uncompr_length == 1 )
	{
		MM_FREE( data );

		return;	
	}
	

	ADLIB_LoadMusic( data );

	BuffWav = MM_MALLOC( uncompr_length * 64 * 2 );
	if( BuffWav == NULL )
	{
		MM_FREE( data );

		return;
	}

	len = ADLIB_UpdateMusic( uncompr_length, BuffWav );


#if 1

	vorbis_encode( filename, BuffWav, len, 1, 16, 44100, 0, 0, 0 );

#else

	write_wav( filename, BuffWav, len, 1, 44100, 2  );

#endif

	MM_FREE( BuffWav );
	MM_FREE( data );
}
Ejemplo n.º 14
0
Archivo: am.c Proyecto: flyhorsegit/am
int main(int argc, char **argv) {
    modulation mod = AM;
    int genwav = 0;
    int test = 0;
    int chat = 0;
    static struct option long_options[] = {
        {"modulation",  required_argument, 0, 'm'},
        {"genwav",  no_argument,       0, 'g'},
        {"test",  no_argument,       0, 't'},
        {"chat",  no_argument,       0, 'c'},
        {0, 0, 0, 0}
    };
    int c;
    int option_index = 0;
    do {
        c = getopt_long (argc, argv, "m:gt",
                         long_options, &option_index);
        switch (c) {
        case 0:
            break;
        case 'm':
            if (strcmp(optarg, "AM") == 0) {
                mod = AM;
                break;
            }
            if (strcmp(optarg, "FM") == 0) {
                mod = FM;
                break;
            }
            fprintf(stderr, "Error: Invalid modulation\n");
            return 1;
        case 't':
            test = 1;
            break;
        case 'g':
            genwav = 1;
            break;
        case 'c':
            chat = 1;
            break;
        case -1:
            break;
        default:
            return 1;
            break;
        }
    } while (c != -1);
    if (!(test || chat || genwav)) {
        fprintf(stderr, "Error: You must suply an action\n");
        return 1;
    }


    int *vbuf;
    frame *msg;
    int i;

    if (genwav || test) {
        vbuf = get_fdata(PING_STR, strlen(PING_STR), mod);
        if (chk_wav_data(vbuf, &msg, mod))
            printf("Info: PCM data is ok.\n");
        else {
            fprintf(stderr, "Error: PCM data can not be read\n");
            for (i = 0; i < FRAME_SIZE; i++)
                fprintf(stderr, "%hhx", ((char *) msg)[i]);
            fprintf(stderr, "\n");
        }
    }
    if (genwav) {
        FILE *am = fopen("am.wav", "w");
        if (am == NULL) {
            printf("could not open files\n");
            exit(1);
        }
        write_wav(am, FRAME_BUFFER, vbuf);
        printf("Info: WAV ready\n");
    }

    if (!chat) return 0;

    char *mg  = (char *) malloc(65536);
    int j;
    pa_simple *ch = get_ch();
    pa_simple *pl = get_pl();
    int err = 0;
    int *buf = (int *) malloc(sizeof(int) * SAMPLE_BUFFER);
    sbf = (int *) calloc(sizeof(int), FRAME_BUFFER);
    int *pbf;
    fd_set set;
    int rv;
    struct timeval tv;

    printf("Info: Starting soundwave chat.\n");
    while (1) {
        if (pa_simple_read(ch, buf, sizeof(int) * SAMPLE_BUFFER, &err))
            fprintf(stderr, "Error: %s\n", pa_strerror(err));
        //filter_frq(buf, SAMPLE_BUFFER);
        mmpush(sbf, FRAME_BUFFER * sizeof(int), buf, SAMPLE_BUFFER * sizeof(int));
        msg = get_msg(sbf, mod);
        if (chk_frm(msg)) {
            printf("M: %.*s", 61, msg->data);
            flushfb();
        }
        free(msg);
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        tv.tv_sec = 0;
        tv.tv_usec = 0;
        rv = select(STDIN_FILENO + 1, &set, NULL, NULL, &tv);
        if ((rv != 0) && (rv != -1)) {
            rv = read(STDIN_FILENO, mg, 65536);
            for (i = 0; i < rv; i += 61) {
                j = ((i + 61) <= rv) ? 61 : (rv - i);
                pbf = get_fdata(mg + i, j, mod);
                if (pa_simple_write(pl, pbf, FRAME_BUFFER * sizeof(int), &err))
                    printf("error: %s\n", pa_strerror(err));
                free(pbf);
            }
        }
        fflush(stdin);
        fflush(stdout);
        fflush(stderr);
    }
    printf("\n");
    pa_simple_free(ch);
    pa_simple_free(pl);
    return 0;
}
Ejemplo n.º 15
0
int main(int argc, char **argv) {
	struct mockery m;

	
	if(prepare_mockery(&m, TEST_LENGTH, "subastard")) {
		printf("Failed to initiate mockery of module.\n");
		exit(1);
	}

	if(create_mock_input_signal(
		   &m, "midi",
		   _MIDI,
		   1,
		   _PTR,
		   44100,
		   TEST_LENGTH,
		   input_signal
		   )) {
		printf("Failed to create mock input signal.\n");
		exit(2);
	}

	if(create_mock_output_signal(
		   &m, "Mono",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   output_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	if(create_mock_intermediate_signal(
		   &m, "A",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   a_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	if(create_mock_intermediate_signal(
		   &m, "B",
		   _0D,
		   1,
		   FTYPE_RESOLUTION,
		   44100,
		   TEST_LENGTH,
		   b_signal
		   )) {
		printf("Failed to create mock output signal.\n");
		exit(3);
	}

	memset(input_signal, 0, sizeof(input_signal));
	memset(output_signal, 0, sizeof(output_signal));

	uint8_t on_event[8], off_event[8];
	MidiEvent *on = (MidiEvent *)on_event;
	MidiEvent *off = (MidiEvent *)off_event;
	on->length = 4; off->length = 4;

	on->data[0] = MIDI_NOTE_ON | 0;
	on->data[1] = 69;
	on->data[2] = 127;
	
	off->data[0] = MIDI_NOTE_OFF | 0;
	off->data[1] = 69;
	off->data[2] = 127;

	input_signal[10] = on;
	input_signal[42000] = off;
	
	FTYPE *begin_1 = get_controller(&m, "Begin", "VCO-1");
	*begin_1 = ftoFTYPE(1);
	int *saw_1 = get_controller(&m, "Saw", "VCO-1");
	*saw_1 = 1;
	int *sin_1 = get_controller(&m, "Sin", "VCO-1");
	*sin_1 = 0;
	
	FTYPE *begin_2 = get_controller(&m, "Begin", "VCO-2");
	*begin_2 = ftoFTYPE(1);
	FTYPE *slide_2 = get_controller(&m, "Slide", "VCO-2");
	*slide_2 = ftoFTYPE(0.13);
	int *saw_2 = get_controller(&m, "Pulse", "VCO-2");
	*saw_2 = 1;
	int *sin_2 = get_controller(&m, "Sin", "VCO-2");
	*sin_2 = 0;

	make_a_mockery(&m);

	write_wav(a_signal, b_signal, TEST_LENGTH, "/tmp/mocking.wav");

	printf("\n\n");
	printf("output: %p\n", output_signal);

	return 0;
}
Ejemplo n.º 16
0
int main()
{
    int i = 0;
    int main_choice;
    struct sin_coeff sin_coe1;
    struct sin_coeff sin_coe2;
    struct sin_coeff sin_coe3;
    struct sin_coeff sin_coe4;
    
    char * infile_name;
    FILE * fp;

    char * buffer = malloc(sizeof(char)* 1024 * 2 * 8);


    printf("***Welcome to eeg data testing system!!!***\n");
    printf("1. read a wav file.\n") ;
    printf("2. check the data of loaded wav file.\n");
    printf("3. set a sin wav.\n");
    printf("4. write the new file\n");   
    printf("******************************************\n");
    
    
    scanf("%d", &main_choice);    
    safe_flush(stdin);

    printf("your choice: %d!\n", main_choice);
    printf("\n");

    if (main_choice == 1) {
    infile_name = "4cmotion.wav"; 
 
    if(( fp = fopen(infile_name, "rb")) == NULL){
	fprintf(stderr, "ERROR: cannot open file: %s!\n", infile_name);
	return 1;
	}

	if( fread(buffer, 1, 44, fp) != 44 ||
	    memcmp(buffer, "RIFF", 4) ||
	    memcmp(buffer + 8, "WAVEfmt ", 8) ||
	    memcmp(buffer + 36, "data", 4)
	){  
	    fprintf(stderr, "This file is not wav file file! Check the header\n");
	    fclose(fp);
	    return 1;
	}
//	unsigned bps = 16;


//read chunk size

/*
	unsigned * pos = (unsigned *) malloc (4);
	fseek(fp, 4, SEEK_SET);
	fread(pos, 1, 4, fp);
	unsigned chunksize = array2data(pos, 4);
	printf("chunksize is %u\n",chunksize);
	fflush(stdout);
	fflush(stdin);
	safe_flush(stdout);
	safe_flush(stdin);
*/

//read channel number

	unsigned * pos =(unsigned *) malloc(4);
	fseek(fp, 22, SEEK_SET);
	fread(pos, 2, 1, fp);
	unsigned channel = array2data(pos,2);
        printf("channel number: %u\n", channel);
	

//read sample rate number

	fseek(fp, 24, SEEK_SET);
	fread(pos, 4, 1, fp);
	unsigned sample_rate = array2data( pos, 4);
	printf("sample rate is %u\n", sample_rate); 

//read total samples
	
	fseek(fp, 40, SEEK_SET);
	fread(pos, 1, 4, fp);
	unsigned total_samples = array2data(pos, 4) / 2;
	printf("total samples is %u\n", total_samples);
	free(pos);

	//sleep(1);

//data store section
	
	short * data_store = (short *)malloc(total_samples * 4);
	fseek(fp, 44, SEEK_SET);
        if ( fread(data_store, 2, total_samples, fp) == 0)
	{   
	    printf("I can't read any data from wav file!\n");
	}
	fclose(fp);
	fflush(fp);

/*	for( i = 0; i < total_samples; i++)
	{
	    printf("The data_store[%u] is %hd\n", i, data_store[i]);
	}*/
	unsigned sub_samples = total_samples / 4;
	
	
	short * channel1_data = (short *)malloc(total_samples);
	short * channel2_data = (short *)malloc(total_samples);
	short * channel3_data = (short *)malloc(total_samples);
	short * channel4_data = (short *)malloc(total_samples);
	
	short * channel_bakup = (short *)malloc(total_samples*2);
	
	for( i = 0; i < total_samples; i++)
	{
	    if(i < sub_samples)
	    {
	    channel1_data[i] = data_store[i*4];
	    channel2_data[i] = data_store[i*4+1];
	    channel3_data[i] = data_store[i*4+2];
	    channel4_data[i] = data_store[i*4+3];  
	    }
	    channel_bakup[i] = data_store[i];
	}

//write and generate full(contains 4 channels) wav file
	char * outfile_full = "4cfull.wav";
	write_wav(outfile_full, sub_samples, channel_bakup, sample_rate, channel);


//find max and min value in subchannels
	
	unsigned channel1_diff = array_diff( channel1_data, sub_samples);
	unsigned channel2_diff = array_diff( channel2_data, sub_samples);
	unsigned channel3_diff = array_diff( channel3_data, sub_samples);
	unsigned channel4_diff = array_diff( channel4_data, sub_samples) ;	
    
	printf("The channel1_diff is %u, channel2 %u, channel3 %u, channel4 %u\n", channel1_diff,channel2_diff, channel3_diff, channel4_diff);

	//sleep(3);	

	//generate sine wave
	//short * sine_data = (short *) malloc (total_samples);

	
	sin_coe1 = find_best_coeff(channel1_data, channel1_diff, sub_samples, sample_rate);
	sin_coe2 = find_best_coeff(channel2_data, channel2_diff, sub_samples, sample_rate);
	sin_coe3 = find_best_coeff(channel3_data, channel3_diff, sub_samples, sample_rate);
	sin_coe4 = find_best_coeff(channel4_data, channel4_diff, sub_samples, sample_rate);

	printf("LOOK at main values:\n");
	printf("minA1 is %d, minO1 is %d\n", sin_coe1.A, sin_coe1.omega);
	printf("minA2 is %d, minO2 is %d\n", sin_coe2.A, sin_coe2.omega);
	printf("minA3 is %d, minO3 is %d\n", sin_coe3.A, sin_coe3.omega);
	printf("minA4 is %d, minO4 is %d\n", sin_coe4.A, sin_coe4.omega);

	//short * sine_wave = (short *) malloc (total_samples);
	short * final_data = (short *) malloc (total_samples);

	int mark = 0;
	for ( i = 0; i < sub_samples; i++)
	{
	    mark = i;
	    final_data[mark] = channel1_data[i] - (0.05 * sin_coe1.A * channel1_diff) * sin( 2 * PI * sample_rate * i * sin_coe1.omega);
	    final_data[mark+1] = channel2_data[i] - (0.05 * sin_coe2.A * channel2_diff) * sin( 2 * PI * sample_rate * i * sin_coe2.omega);
	    final_data[mark+2] = channel3_data[i] - (0.05 * sin_coe3.A * channel3_diff) * sin( 2 * PI * sample_rate * i * sin_coe3.omega);
	    final_data[mark+3] = channel4_data[i] - (0.05 * sin_coe4.A * channel4_diff) * sin( 2 * PI * sample_rate * i * sin_coe4.omega);
	}
	printf("mark is %d",mark);


	char * newfile = "4cnew.wav";
	write_wav(newfile, sub_samples, final_data, sample_rate, channel);

/*
	for(i = 0; i < sub_samples; i++)
	{
	    error_data[i] = channel1_data[i] - sine_data[i];
	    printf("error data[%u] is %hu\n", i, error_data[i]);
	}
*/
	//int error_diff = array_diff( error_data, sub_samples);
	//printf("error diff is %u, channel1_diff is %u\n", error_diff, channel1_diff);
	
}
	return 1;
}