Ejemplo n.º 1
0
int main()
{
  printf("starting test\n");
  FILE* input = fopen("screenshot.bin", "rb");
  if(input == NULL)
  {
    printf("Couldn't find file\n");
    exit(1);
  }
  
  encoder_context* context = create_context();
  init_encoder(context, 1366, 768);
  init_codec(context);
  init_image(context);
  
  struct stat stat_info;
  int result = stat("screenshot.bin", &stat_info);
  if(result)
  {
    fatal("Could not fstat");
  }
  
  char* buffer = malloc(stat_info.st_size);
  fread(buffer, stat_info.st_size, 1, input);
  
  /*
  memset(buffer, 0xF, stat_info.st_size);
  
  int a;
  for(a = 0; a < stat_info.st_size; a++)
  {
    if(a % 4 == 0)
    {
      buffer[a] = 0x0;
    }
  }*/
  
  convert_frame(context, buffer);
  FILE* output = fopen("mem.bin", "wb");
  fwrite(context->raw->planes[2], 100000, 1, output);
  fflush(output);
  printf("Size is %d\n", context->raw->stride[3]);

  int i;
  for(i = 0; i < 100; i++)
  {
  convert_frame(context, buffer);
  
  encode_next_frame(context);
  }
  encode_finish(context);
  
  printf("Finished test\n");
}
Ejemplo n.º 2
0
QString*
qstringFromZString(zval* zstring) {
	if (KCODE == 0) {
		init_codec();
	}
	if (qstrcmp(KCODE, "UTF8") == 0)
		return new QString(QString::fromUtf8(zstring->value.str.val, zstring->value.str.len));
	else if (qstrcmp(KCODE, "EUC") == 0)
		return new QString(codec->toUnicode(zstring->value.str.val));
	else if (qstrcmp(KCODE, "SJIS") == 0)
		return new QString(codec->toUnicode(zstring->value.str.val));
	else if(qstrcmp(KCODE, "Latin1") == 0)
		return new QString(QString::fromLatin1(zstring->value.str.val));

	return new QString(QString::fromLocal8Bit(zstring->value.str.val, zstring->value.str.len));
}
Ejemplo n.º 3
0
zval*
zstringFromQString(QString * s) {

	if (KCODE == 0) {
		init_codec();
	}
	zval* return_value = (zval*) emalloc(sizeof(zval));
	if (qstrcmp(KCODE, "UTF8") == 0) {
		ZVAL_STRING(return_value, (char*) s->toUtf8().constData(), /* duplicate */ 1);
	} else if (qstrcmp(KCODE, "EUC") == 0) {
		ZVAL_STRING(return_value, (char*) codec->fromUnicode(*s).constData(), /* duplicate */ 1);
	} else if (qstrcmp(KCODE, "SJIS") == 0) {
		ZVAL_STRING(return_value, (char*) codec->fromUnicode(*s).constData(), /* duplicate */ 1);
	} else if (qstrcmp(KCODE, "Latin1") == 0) {
		ZVAL_STRING(return_value, (char*) s->toLatin1().constData(), /* duplicate */ 1);
	} else {
		ZVAL_STRING(return_value, (char*) s->toUtf8().constData(), /* duplicate */ 1);
	}
	return return_value;
}
Ejemplo n.º 4
0
void main()
{

	// set up the cosine and sin matched filters for searching
	// also initialize searching buffer

	//For times within window set up the sine and cosine
		//Precalculate the cos and sin values (calculate as double, cast down to float)
	calc_filter(mfc, mfs, buf); //Initialize the searching buffer.

	// initialize clock buffer
	for (i=0;i<L;i++)
		clockbuf[i] = 0;

	// set up clock buffer to play modulated sinc centered at zero
	/////////////////////////////////////////////
	for (i=-N;i<=N;i++){
		x = i*BW;
		if (i!=0) {
			t = i*CBW;
			y = 32767.0*cos(2*PI*t)*sin(PI*x)/(PI*x); // double (Modulated sinc)
		}
		else {
			y = 32767.0;
		}
		j = i;
		if (j<0) {
			j += L; // wrap
		}
		clockbuf[j] = (short) y;
	}
///////////////////////////////////////////////

	init_codec(config, hCodec);

	while(1)						// main loop
	{
	}
}
void METH(frame)
		(t_bit_buffer	*p_bitstream,	/**< Input buffer */
		void 		*sei, 		/**< TimeStamp */
	  t_uint32 nTimeStampH, t_uint32 nTimeStampL, /**< TimeStamp */
		t_uint32 	nFlags)	/**< Openmax flags */
{
	  t_vc1_picture_type 	picture_type;
		t_hamac_param *param_in;
    ts_bitstream_buffer  decoder_bitstream;


	if( p_bitstream )
	{
     	OstTraceFiltInst1(TRACE_API,  "VC1Dec: arm_nmf: decoder: frame(): size = %d\\n", p_bitstream->end - p_bitstream->addr);
#if VERBOSE_STANDARD == 1
		NMF_LOG("NMF-ARM decoder: call to frame(), size = %d\n",p_bitstream->end - p_bitstream->addr);
#endif

	}


	if(p_bitstream == NULL)
	{
		if( nFlags & OSI_OMX_BUFFERFLAG_EOS )
		{
			// Case of end of stream.
			// all frame data have already been received - last buffer is empty and only used to send EOS flag

            OstTraceFiltInst0(TRACE_FLOW,  "Handle end of stream (empty buffer)\n");
#if VERBOSE_STANDARD == 1
      			NMF_LOG("Handle end of stream (empty buffer)\n");
#endif
      			// we post a void frame (fake frame to go through the pipe)
			// The void frame will be recognized in the output stage
			// this will indicate that all received frames have been decoded (we can bump last frame)

    			hamac_pipe_reset_frame();

    			//commented for ER 370888
			//hamac_pipe_set_void_frame_info(VOID_FRAME_EOS_WITH_FLUSH);

			// BumpFrame will choose oldest ref, so let's mark most recent ref as oldest ref
      			if(dec_static.buf.oldest_ref == 0)
         			dec_static.buf.oldest_ref = 1;
      			else
         			dec_static.buf.oldest_ref = 0;
      			// Here call it with Pic type != B in order to make it bump the oldest ref
      			BumpFrame(PICTURE_TYPE_I,&dec_static.buf);

				//+change for ER 370888
      			if (hamac_pipe_mark_eos_frame())   // this will set OMX EOS flag in last buffer, needed by proxy
      			{
					OstTraceFiltInst0(TRACE_FLOW,  "VC1Dec: arm_nmf: decoder: TRUE for hamac_pipe_mark_eos_frame()");
					hamac_pipe_set_void_frame_info(VOID_FRAME_EOS_WITH_FLUSH);
				}
				else
				{
					OstTraceFiltInst0(TRACE_FLOW,  "VC1Dec: arm_nmf: decoder: FALSE for hamac_pipe_mark_eos_frame()");
					hamac_pipe_set_void_frame_info(VOID_FRAME_EOS_WO_FLUSH);
				}
				//- change for ER 370888

			if (dec_static.sva_bypass == 1) {
				endCodec(STATUS_JOB_COMPLETE, VDC_VOID, 0);
			}
			else {
				iStartCodec.voidFrame();
			}
		}

		return;
	}

	/* wrap bitstream structure into VC1 bitstream structure */
    	decoder_bitstream.data = p_bitstream->addr;
    	decoder_bitstream.size_in_bits = 8 * (p_bitstream->end - p_bitstream->addr);
    	decoder_bitstream.pt_current_byte = p_bitstream->addr;
    	decoder_bitstream.index_current_bit = 0;

	if(seq_param_received == FALSE)
	{
		// first buffer : contains sequence parameters (no frame data)
		OMX_ERRORTYPE error = parse_sequence_header(&decoder_bitstream,&seq_params); // For ER 344032
        /* + For ER 344032 */
		if (error == OMX_ErrorFormatNotDetected)
        {
            OstTraceInt0(TRACE_ERROR,  "VC1Dec: arm_nmf: decoder: frame():Error OMX_ErrorFormatNotDetected ");
            proxy.eventHandler(OMX_EventError,error,0);
        }
		/* For ER 344032 */
        seq_param_received = TRUE;
		// We will now estimate the level from the number of MBs per frame
    		seq_params.level = find_level_from_image_size(seq_params.profile,
                                                        	picture_width,
                                                        	picture_height);

		// init input parameters
		init_codec();

		// release bitstream and request a new input buffer
		p_bitstream->next = 0;  // don't use linked lists
    		p_bitstream->inuse = 0;  // tell to input control that this buffer is not in use
    		input_control_acknowledge(p_bitstream, XON);
	}
	else
	{
		// following buffers : contain frames data

    //MeasureEventStart0(TRACE_EVENT_BUFFER_START,"decoder buffer processing");

	  // Init DPB with a dummy reference (grey pixels)
	  // -> used to decode P or B-frames after seek
	  // -> used for error concealment
	  if( !ref_frame_initialized )
	    {
	      InsertDummyRefIntoDpb(&dec_static.buf,
				    picture_width,
				    picture_height);
	      ref_frame_initialized = TRUE;
	    }

	  	// exit pause state when receive a new frame
	  	if( low_power_state == TRUE )
	  	{
	  		low_power_state = FALSE;
	  		iStartCodec.preventSleep();
	  	}

    		// We read the frame type
   	 	btpar_parse_picture_type(&decoder_bitstream,&seq_params,&picture_type);

    		// Get the position in the DPB corresponding to current frame
    		t_sint16 index = InsertFrame(picture_type,&dec_static.buf, 0, &dec_static.sva_buffers);
    		dec_static.buf.curr_info = &dec_static.buf.pics_buf[index];
    		dec_static.sva_buffers.curr_frame = dec_static.buf.curr_info->ptr[0];
    		dec_static.sva_buffers.curr_bitstream = p_bitstream;

    		// store timestamp associated to current picture into the frames table
    		// this info is not used by the decoder itself, it is just carried from input to output buffers
    		dec_static.buf.frames[dec_static.buf.curr_info->frame_pos].frameinfo.common_frameinfo.nTimeStampH = nTimeStampH;
    		dec_static.buf.frames[dec_static.buf.curr_info->frame_pos].frameinfo.common_frameinfo.nTimeStampL = nTimeStampL;

    		// store Openmax flags (end of stream, ...)
    		dec_static.buf.frames[dec_static.buf.curr_info->frame_pos].nFlags = nFlags;

		// Get the pointer on a Param_in structure , from the fifo use in front of HW decoder
    		hamac_pipe_reset_frame();
		param_in = hamac_pipe_get_write_param_in();
		HamacFillParamIn(vfm_memory_ctxt,&dec_static,0,param_in);
    		hamac_pipe_set_frame_pos(dec_static.buf.curr_info->frame_pos);

    		hamac_pipe_set_bit_buffer_addr(p_bitstream); // store bitstream addr to be able to release it after decoding
    		p_bitstream->next = 0;  // don't use linked lists
    		p_bitstream->inuse = VCL_UNDER_PROCESSING;  // tell to input control that this buffer is in use
    		input_control_acknowledge(p_bitstream, XON);      // this will make p_bitstream as pending for release
                                                 	// and will request a new input buffer if the pipe is not full

    		// Determine which picture will be output after current frame's decoding
    		BumpFrame(picture_type,&dec_static.buf);

    		// Case of end of stream. In all cases, need to output most recent ref
    		if( nFlags & OSI_OMX_BUFFERFLAG_EOS )
    		{
        OstTraceFiltInst1(TRACE_FLOW, "VC1Dec: arm_nmf: decoder: frame(): Handle end of stream - Flow line %d\n", __LINE__);
#if VERBOSE_STANDARD == 1
      			NMF_LOG("Handle end of stream\n");
#endif
      			// BumpFrame will choose oldest ref, so let's mark most recent ref as oldest ref
      			if(dec_static.buf.oldest_ref == 0)
         			dec_static.buf.oldest_ref = 1;
      			else
         			dec_static.buf.oldest_ref = 0;
      			// Here call it with Pic type != B in order to make it bump the oldest ref
      			BumpFrame(PICTURE_TYPE_I,&dec_static.buf);

      			hamac_pipe_mark_eos_frame();   // this will set OMX EOS flag in last buffer, needed by proxy
    		}

	if (dec_static.sva_bypass == 1)
  {
     // bypass DSP processing, only used for ARM load evaluation
     hamac_pipe_set_void_frame_info(VOID_FRAME_ALGO_BYPASS);
	   endCodec(STATUS_JOB_COMPLETE, VDC_VOID, 0);
  }
  else
  {

#ifdef _CACHE_OPT_
    	// Force cache clean to be sure that bitstream has been written in SDRAM
	    t_uint8 *fl_end_addr,*fl_start_addr;
	    fl_start_addr= (t_uint8*) p_bitstream->addr;
	    fl_end_addr=(t_uint8*) p_bitstream->end;
	    VFM_CacheClean(vfm_memory_ctxt, fl_start_addr,fl_end_addr-fl_start_addr+1);
	    OMX_U32 tempAddr;
	    OMX_U8 *tempPtr;

	    tempAddr = Endianess(param_in->addr_out_frame_buffer->addr_dest_buffer);
	    tempPtr = VFM_GetLogical(vfm_memory_ctxt, (t_uint8 *)tempAddr);
		VFM_CacheInvalidate(vfm_memory_ctxt, tempPtr,(picture_height*picture_width*1.5));

#endif

   		HamacToPhysicalAddresses(vfm_memory_ctxt,param_in, 0);

#if VERBOSE_STANDARD == 1
   		NMF_LOG("NMF-ARM decoder: call to startCodec\n");
#endif
   		iStartCodec.startCodec((t_uint32)param_in->addr_in_frame_buffer ,
				                  (t_uint32)param_in->addr_out_frame_buffer,
				                  (t_uint32)param_in->addr_internal_buffer,
				                  (t_uint32)param_in->addr_in_bitstream_buffer,
				                  (t_uint32)param_in->addr_out_bitstream_buffer,
				                  (t_uint32)param_in->addr_in_parameters,
				                  (t_uint32)param_in->addr_out_parameters,
                  				(t_uint32)param_in->addr_in_frame_parameters,
                  				(t_uint32)param_in->addr_out_frame_parameters);
   } // no SVA bypass

    //MeasureEventStop(TRACE_EVENT_BUFFER_STOP,"decoder buffer processing");
	}
}
Ejemplo n.º 6
0
Archivo: pktzip.c Proyecto: chemag/pktd
/*
 * uncompress_file
 *
 * Uncompresses the stream fin into foutname
 *
 * Inputs:
 *	- fin: the compressed input stream
 *	- lfout: the uncompressed output stream
 *	- co: compression parameters
 *
 * Output:
 *	- return: 0 if ok, <0 if there was any problem
 *
 */
int uncompress_file (FILE *fin, lFILE *lfout, co_t *co)
{
	codec_t *codec;
	int size;
	u_char compressed_buffer[MAX_COMPRESSED_LENGTH];
	u_char buffer[MAXDATABUFFER];
	struct pcap_pkthdr pkthdr;
	int result;


	/* create and initialize codec */
	codec = create_codec();


	/* write the new header */
	if (pktd_write_header (lfileno(lfout), 40, DLT_RAW) < 0) {
		fprintf (stderr, "Error: cannot write header in file %s\n", foutname);
		return -1;
	}


/*
 * every time you seek the rm_offset, you *must* initialize the codec
	(void)fseek (fin, co->rm_offset, SEEK_CUR);
	init_codec (codec);
 */

	/* parse traces */
	while (1) {
		/* read the trace length */
		size = TCPDUMP_PACKET_HEADER_LENGTH_COMPRESSED;
		result = fread (compressed_buffer, 1, size, fin);
		if (result != size) {
			if ((result == 0) && (feof (fin))) {
				break;
			}
			fprintf (stderr, "Error: fread'ing file %s\n", finname);
			return -1;
		}
		size = (u_int8_t)(compressed_buffer[0]);


		/* look for escaped packets */
		if (size == COMPRESSION_INIT_CODEC) {
			/* codec initialization requested */
			init_codec (codec); 
			continue;
      
		} else if (size == COMPRESSION_PADDING) {
			/* padding (empty) trace */
			continue;
		}


		/* get the rest of the compressed packet */
		result = fread (compressed_buffer+TCPDUMP_PACKET_HEADER_LENGTH_COMPRESSED, 
				1, size-TCPDUMP_PACKET_HEADER_LENGTH_COMPRESSED, fin);
		if (result != (size-TCPDUMP_PACKET_HEADER_LENGTH_COMPRESSED)) {
			if ((size == 0) && (feof (fin))) {
				break;
			}
			fprintf (stderr, "Error: freading file %s (%i)\n", finname, size);
			return -1;
		}


		/* decode the packet */
		size = decode_trace (codec, compressed_buffer, &pkthdr, buffer);
		if (size < 0) {
			fprintf (stderr, "Error: decoding trace\n");
			return -1;
		}


		/* write the uncompressed packet */
		/*
		result = fwrite(buffer, 1, size, fout);
		*/
		result = lfwrite(lfout, buffer, size);
		if (result != size) {
			fprintf (stderr, "Error: fwriting file %s\n", foutname);
			return -1;
		}
	}


	return 0;
}
Ejemplo n.º 7
0
////////////////////////////////////////////////////////////////////////////////
/// @brief	Application main function.
////////////////////////////////////////////////////////////////////////////////
void main(void) {

  // Initializations
  SET_MAIN_CLOCK_SOURCE(CRYSTAL);
  SET_MAIN_CLOCK_SPEED(MHZ_26);
  CLKCON = (CLKCON & 0xC7);

  init_peripherals();
  
  P0 &= ~0x40;                            // Pulse the Codec Reset line (high to low, low to high)
  P0 |= 0x40;
  
  init_codec();                           // Initilize the Codec
  
  INT_SETFLAG(INUM_DMA, INT_CLR);         // clear the DMA interrupt flag
  I2SCFG0 |= 0x01;                        // Enable the I2S interface

  DMA_SET_ADDR_DESC0(&DmaDesc0);          // Set up DMA configuration table for channel 0
  DMA_SET_ADDR_DESC1234(&DmaDesc1_4[0]);  // Set up DMA configuration table for channels 1 - 4
  dmaMemtoMem(AF_BUF_SIZE);               // Set up DMA Channel 0 for memmory to memory data transfers
  initRf();                               // Set radio base frequency and reserve DMA channels 1 and 2 for RX/TX buffers
  dmaAudio();                             // Set up DMA channels 3 and 4 for the Audio In/Out buffers
  DMAIRQ = 0;
  DMA_ARM_CHANNEL(4);                     // Arm DMA channel 4

  macTimer3Init();

  INT_ENABLE(INUM_T1, INT_ON);            // Enable Timer 1 interrupts
  INT_ENABLE(INUM_DMA, INT_ON);           // Enable DMA interrupts
  INT_GLOBAL_ENABLE(INT_ON);              // Enable Global interrupts

  MAStxData.macPayloadLen = TX_PAYLOAD_LEN;
  MAStxData.macField = MAC_ADDR;

  while (1)  {        // main program loop
    setChannel(channel[band][ActiveChIdx]);             // SetChannel will set the MARCSTATE to IDLE
    ActiveChIdx = (ActiveChIdx + 1) & 0x03;
    
    SCAL();           // Start PLL calibration at new channel

    if ((P1 & 0x08) != aux_option_status) {             // if the 'SEL AUX IN' option bit has changed state
      if ((P1 & 0x08) == 0) {                           // SEL AUX IN has changed state to true
        I2Cwrite(MIC1LP_LEFTADC, 0xFC);                 // Disconnect MIC1LP/M from the Left ADC, Leave Left DAC enabled
        I2Cwrite(MIC2L_MIC2R_LEFTADC, 0x2F);            // Connect AUX In (MIC2L) to Left ADC
        I2Cwrite(LEFT_ADC_PGA_GAIN, 0x00);              // Set PGA gain to 0 dB
        aux_option_status &= ~0x08;
      }
      else {                                            // SEL AUX IN has changed state to false
        I2Cwrite(MIC2L_MIC2R_LEFTADC, 0xFF);            // Disconnect AUX In (MIC2L) from Left ADC
        I2Cwrite(MIC1LP_LEFTADC, 0x84);                 // Connect the internal microphone to the Left ADC using differential inputs (gain = 0 dB); Power Up the Left ADC
        I2Cwrite(LEFT_ADC_PGA_GAIN, 0x3C);              // Enable PGA and set gain to 30 dB
        aux_option_status |= 0x08;
      }
    }
     
    if ((P1 & 0x04) != agc_option_status) {             // if the 'ENA AGC' option bit has changed state
      if ((P1 & 0x04) == 0) {                           // ENA AGC has changed state to true
        I2Cwrite(LEFT_AGC_CNTRL_A, 0x90);               // Left AGC Control Register A - Enable, set target level to -8 dB
        I2Cwrite(LEFT_AGC_CNTRL_B, 0xC8);               // Left AGC Control Register B - Set maximum gain to  to 50 dB
        I2Cwrite(LEFT_AGC_CNTRL_C, 0x00);               // Left AGC Control Register C - Disable Silence Detection
        agc_option_status &= ~0x04;
      }
      else {                                            // SEL AUX IN has changed state to false
        I2Cwrite(LEFT_AGC_CNTRL_A, 0x10);               // Left AGC Control Register A - Disable
        agc_option_status |= 0x04;
      }    
    }
    
// Check the band selection bits

    band = 2;                             // if the switch is not in position 1 or 2, in must be in position 3
    
    if ((P1 & 0x10) == 0)                 // check if switch is in position 1
      band = 0;
    
    else if ((P0 & 0x04) == 0)            // check if switch is in position 2
      band = 1;
    
// Now wait for the "audio frame ready" signal

    while (audioFrameReady == FALSE);     // Wait until an audioframe is ready to be transmitted
    
    audioFrameReady = FALSE;              // Reset the flag

// Move data from the CODEC (audioOut) buffer to the TX buffer using DMA Channel 0

    SET_WORD(DmaDesc0.SRCADDRH, DmaDesc0.SRCADDRL, audioOut[activeOut]);
    SET_WORD(DmaDesc0.DESTADDRH, DmaDesc0.DESTADDRL, MAStxData.payload);
    DmaDesc0.SRCINC = SRCINC_1;           // Increment Source address 
    DMAARM |= DMA_CHANNEL_0;
    DMAREQ |= DMA_CHANNEL_0;              // Enable memory-to-memory transfer using DMA channel 0
    while ((DMAARM & DMA_CHANNEL_0) > 0); // Wait for transfer to complete

    while (MARCSTATE != 0x01);            // Wait for calibration to complete
   
    P2 |= 0x08;                   // Debug - Set P2_3 (TP2)
    rfSendPacket(MASTER_TX_TIMEOUT_WO_CALIB);
    P2 &= ~0x08;                  // Debug - Reset P2_3 (TP2)
  
  }   // end of 'while (1)' loop
}
Ejemplo n.º 8
0
/***************************************************************************
Declaration : int main(void)

Function :    Main Loop
***************************************************************************/
int main(void)
{
	init_mcu();
	init_rf();
	init_buffer();
	init_protocol();
	init_freq();
	
	#ifdef TEST_TX_CW
		test_rf_transmitter(78);
	#endif
	#ifdef TEST_TX_MOD
		test_rf_modulator(81);
	#endif
	#ifdef TEST_RX
		test_rf_receiver(78);
	#endif
		
	/* Main Background loop */
	call_state = CALL_IDLE;
	
	while(1)
	{
		/* Call States */	
		switch (call_state)
		{
			case CALL_IDLE:
				#ifdef DONGLE
					sleep(WDT_TIMEOUT_60MS,STANDBY_MODE);
					call_status = CALL_NO_ACTIVITY;
					#ifdef USB
						SET_VOLUME_DOWN;
						SET_VOLUME_UP;
						SET_MUTE_PLAY;
						SET_MUTE_REC;
						if(CALL_ACTIVITY_PIN)
							call_status = CALL_ACTIVITY;
					#else
						if(!CALL_SETUP_KEY)
							call_status = CALL_ACTIVITY;
					#endif
					if(call_status == CALL_ACTIVITY)
						call_state = CALL_SETUP;
				#endif
				
				#ifdef HEADSET
					sleep(WDT_TIMEOUT_1S,POWER_DOWN_MODE);
					call_state = CALL_SETUP;
				#endif
				
			break;
			
			case CALL_SETUP:
				#ifdef DONGLE
					LED_ON;
					call_status = call_setup(&setup_freq[0],N_FREQ_SETUP);
					LED_OFF;
					if(call_status != CALL_SETUP_FAILURE)
					{
						init_buffer();
						init_rf();
						init_protocol();
						init_codec();
						start_codec();
						#ifdef USB
							// Enable watchdog to handle USB Suspend Mode
							wdt_enable(WDT_TIMEOUT_15MS);
						#else
							start_timer1(0,FRAME_PERIOD, DIV1);
						#endif
						call_state = CALL_CONNECTED;
					}	
					else
						call_state = CALL_IDLE;
				#endif
								
				#ifdef HEADSET
					LED_ON;
					call_status = call_detect(&setup_freq[0],N_FREQ_SETUP,N_REP_SETUP);
					LED_OFF;
					if(call_status != CALL_SETUP_FAILURE)
					{
						init_buffer();
						init_rf();
						init_protocol();
						init_codec();
						call_status &= ~MASTER_SYNC;
						start_timer1(0,FRAME_PERIOD, DIV1);
						call_state = CALL_CONNECTED;
					}
					else
						call_state = CALL_IDLE;
				#endif
			break;
			
			case CALL_CONNECTED:
				#ifdef DONGLE
					while(1)
					{
						// USB Dongle clears watchdog handling USB Suspend Mode
						#ifdef USB
							wdt_reset();
						#endif
						
						// Send and receive audio packet
						audio_transfer();
						
						// Handle key code from HEADSET
						key_code = (signal_in[1] & 0x1F);
						if(key_code != 0)
							LED_ON;
						else
							LED_OFF;
							
						#ifdef USB
							if(key_code & VOLUME_DOWN)
								CLEAR_VOLUME_DOWN;
							else
								SET_VOLUME_DOWN;
								
							if(key_code & VOLUME_UP)
								CLEAR_VOLUME_UP;
							else
								SET_VOLUME_UP;
								
							if(key_code & MUTE_PLAY)
								CLEAR_MUTE_PLAY;
							else
								SET_MUTE_PLAY;
								
							if(key_code & MUTE_REC)
								CLEAR_MUTE_REC;
							else
								SET_MUTE_REC;
						#endif
						
						// Check if call is to be cleared	
						#ifdef USB
							if(!CALL_ACTIVITY_PIN)
							{
								call_activity_timer += 1;
								if(call_activity_timer >= TIMEOUT_CALL_ACTIVITY)
									call_status = CALL_CLEAR;
							}
							else
								call_activity_timer = 0;
						
						#else
							if(!CALL_CLEAR_KEY)
								call_status = CALL_CLEAR;
						#endif
						
						
							
						// Call clearing by HEADSET or DONGLE
						if((key_code == CALL_CLEARING) || (call_status == CALL_CLEAR))
						{
							signal_out[0] |= SIGNAL_CALL_CLEAR;
							call_timer += 1;
							if(call_timer >= TIMEOUT_CALL_CLEAR_MASTER)
							{
								call_state = CALL_IDLE;
								stop_codec();
								init_buffer();
								init_rf();
								init_protocol();
								init_codec();
								eeprom_write(freq[0],EEPROM_ADR_FREQ0);
								eeprom_write(freq[1],EEPROM_ADR_FREQ1);
								LED_OFF;
								#ifdef USB
									// Disable watchdog used to handle USB Suspend Mode
									wdt_disable();
								#endif
								break;
							}
						}
						else
							signal_out[0] &= ~SIGNAL_CALL_CLEAR;
	
						// Call clearing due to Frame Loss
						if(frame_loss >= TIMEOUT_FRAME_LOSS)
						{
							#ifdef USB
								call_state = CALL_RECONNECT;
								init_rf();
								init_protocol();
								// Disable watchdog used to handle USB Suspend Mode
								wdt_disable();
							#else
								call_state = CALL_RECONNECT;
								stop_codec();
								init_buffer();
								init_rf();
								init_protocol();
								init_codec();
							#endif
							break;
						}
					}
				#endif
				
				#ifdef HEADSET
					while(1)
					{
						if(call_status & MASTER_SYNC)
						{
							audio_transfer();
						}
						else
						{
							call_status = get_sync();
							if(call_status & MASTER_SYNC)
								start_codec();
							else
								frame_loss += 10;
						}
						
						// Read and handle keys
						key_code = read_key();
						signal_out[1] &= 0xE0;
						signal_out[1] |= key_code;
						
						
						// Call cleared by DONGLE
						if(signal_in[0] & SIGNAL_CALL_CLEAR)
						{
							call_timer += 1;
							if(call_timer >= TIMEOUT_CALL_CLEAR_SLAVE)
							{
								call_state = CALL_IDLE;
								stop_codec();
								init_buffer();
								init_rf();
								init_protocol();
								init_codec();
								break;
							}
						}
						else
							call_timer = 0;
						
						// Call clearing due to Frame Loss
						if(frame_loss >= TIMEOUT_FRAME_LOSS)
						{
							call_state = CALL_RECONNECT;
							stop_codec();
							init_buffer();
							init_rf();
							init_protocol();
							init_codec();
							break;
						}
					}
				#endif
			break;

			case CALL_RECONNECT:
				#ifdef DONGLE
					LED_ON;
					call_status = call_setup(&setup_freq[0],N_FREQ_SETUP);
					LED_OFF;
					if(call_status != CALL_SETUP_FAILURE)
					{
						#ifdef USB
							init_rf();
							init_protocol();
							reset_codec();
							call_state = CALL_CONNECTED;
						#else
							init_buffer();
							init_rf();
							init_protocol();
							init_codec();
							start_codec();
							start_timer1(0,FRAME_PERIOD, DIV1);
							call_state = CALL_CONNECTED;
						#endif
					}	
					else
					{
						stop_codec();
						init_buffer();
						init_rf();
						init_protocol();
						init_codec();
						call_state = CALL_IDLE;
					}
				#endif
				
				#ifdef HEADSET
					LED_ON;
					call_status = call_detect(&setup_freq[0],N_FREQ_SETUP,N_REP_RECONNECT);
					LED_OFF;
					if(call_status != CALL_SETUP_FAILURE)
					{
						init_buffer();
						init_rf();
						init_protocol();
						init_codec();
						call_status &= ~MASTER_SYNC;
						start_timer1(0,FRAME_PERIOD, DIV1);
						call_state = CALL_CONNECTED;
					}
					else
						call_state = CALL_IDLE;

				#endif
			break;

			default:
			break;
		}
	}
}