Example #1
0
inline void Record(T& instanceToBeRecorded)
{
	typedef typename T::ReplayTag Tag;
	Tag t;

	Private::Record(buffer, instanceToBeRecorded, t);

	//Print out the buffer for easy debugging.
	buffer.Print();
	printf("\n\n");
}
PRStatus FcgiParser::formatRequest(CircularBuffer& from, CircularBuffer& to, PRUint8 streamType) {
    int toLen = 0; 
    int fromLen = 0; 
    char *toBuf = NULL;
    int available = to.requestSpace(toBuf, toLen) - sizeof(FCGI_Header);
    int dataSize = from.hasData();
    int dataToBeMoved = min(dataSize, available);
    if(dataToBeMoved > 0) {
        if(toBuf) {
            //if(makePacketHeader(streamType, maxLen, to) == PR_SUCCESS) {
            if(makePacketHeader(streamType, dataToBeMoved, to) == PR_SUCCESS) {
                if(from.move(to, dataToBeMoved) < dataToBeMoved)
                        return PR_FAILURE;
            } else
                return PR_FAILURE;
        }
    }

    return PR_SUCCESS;
}
Example #3
0
int checkForSquelch(MidiMessage& message, CircularBuffer<MidiMessage>& memory, 
      int mintime, int maxtime, int curtime) {
   int i;
   if (memory.getSize() == 0) {
      return 0;
   }

   for (i=0; i<memory.getSize(); i++) {
      if ((curtime - (int)memory[i].time) < mintime) {
         continue;
      }
      if ((curtime - (int)memory[i].time) > maxtime) {
         break;
      }
      if ((memory[i].p0() == message.p0()) && (memory[i].p1() == message.p1())) {
         return 1;
      }
   }

   return 0;
}
Example #4
0
    void processAudio(AudioBuffer &buffer) {

        float feedback, wet, _delayTime, _tone, delaySamples;

        _delayTime = getParameterValue(PARAMETER_A);
        feedback = 2*getParameterValue(PARAMETER_B)+0.01;
        _tone = getParameterValue(PARAMETER_C);
        wet = getParameterValue(PARAMETER_D);

        tone = 0.05*_tone + 0.95*tone;
        tf.setTone(tone);

        float* buf = buffer.getSamples(0);
        for (int i = 0 ; i < buffer.getSize(); i++) {
            delayTime = 0.01*_delayTime + 0.99*delayTime;
            delaySamples = delayTime * (delayBuffer.getSize()-1);
            buf[i] = dist(tf.processSample(buf[i] + (wet * delayBuffer.read(delaySamples))));
//            delayBuffer.write(dist(tf.processSample(feedback * buf[i],0)));
            delayBuffer.write(feedback * buf[i]);
        }
    }
Example #5
0
void Plot::timerEvent( QTimerEvent * )
{
    CircularBuffer *buffer = ( CircularBuffer * )d_curve->data();
    buffer->setReferenceTime( d_clock.elapsed() / 1000.0 );

    switch( d_settings.updateType )
    {
        case Settings::RepaintCanvas:
        {
            // the axes in this example doesn't change. So all we need to do
            // is to repaint the canvas.

            canvas()->replot();
            break;
        }
        default:
        {
            replot();
        }
    }
}
Example #6
0
void mainloopalgorithms(void) { 
   if (synth.getNoteCount() > 0) {
      nextActionTime = t_time;
      message = synth.extractNote();
      if (message.p2() == 0) {   // note off
         keyCount--;
         if (keyCount < 0) {
            keyCount = 0;
         }
         switch (message.p1()) {
            case C3:   lastOffTime[1]  = t_time;   break;
            case D3:   lastOffTime[2]  = t_time;   break;
            case E3:   lastOffTime[3]  = t_time;   break;
            case F3:   lastOffTime[4]  = t_time;   break;
            case G3:   lastOffTime[5]  = t_time;   break;
            case C4:   lastOffTime[6]  = t_time;   break;
            case D4:   lastOffTime[7]  = t_time;   break;
            case E4:   lastOffTime[8]  = t_time;   break;
            case F4:   lastOffTime[9]  = t_time;   break;
            case G4:   lastOffTime[10] = t_time;   break;
         }
      } else {                   // note on
         keyCount++;
         keysOn.insert(message.p1());
         onKey2 = onKey1;
         switch (message.p1()) {
            case C3:   lastOnTime[1]  = t_time;  onKey1 = 1;   break;
            case D3:   lastOnTime[2]  = t_time;  onKey1 = 2;   break;
            case E3:   lastOnTime[3]  = t_time;  onKey1 = 3;   break;
            case F3:   lastOnTime[4]  = t_time;  onKey1 = 4;   break;
            case G3:   lastOnTime[5]  = t_time;  onKey1 = 5;   break;
            case C4:   lastOnTime[6]  = t_time;  onKey1 = 6;   break;
            case D4:   lastOnTime[7]  = t_time;  onKey1 = 7;   break;
            case E4:   lastOnTime[8]  = t_time;  onKey1 = 8;   break;
            case F4:   lastOnTime[9]  = t_time;  onKey1 = 9;   break;
            case G4:   lastOnTime[10] = t_time;  onKey1 = 10;  break;
         }
      }
   }

   if (nextActionTime + repeatRate <= t_time) {
      nextActionTime = t_time;
   }    

   event = makeEventDecision();
   if (event > 0) {
      if (shift) {
         event = toupper(event);
      }
      cout << (char)event << flush;
   }

}
TEST(CircularBuffer, SimplePushBackPop)
{
    CircularBuffer<int, 5> cb;

    cb.pushBack(123);
    
    ASSERT_FALSE(cb.empty());
    ASSERT_EQ(cb.size(), 1);
    ASSERT_EQ(cb.popFront(), 123);
    ASSERT_TRUE(cb.empty());
    ASSERT_EQ(cb.size(), 0);    
}
// Pops the next command from the thread queue, if any is available.
bool ThreadCommandQueueImpl::PopCommand(ThreadCommand::PopBuffer* popBuffer)
{    
    Lock::Locker lock(&QueueLock);

    UByte* buffer = CommandBuffer.ReadBegin();
    if (!buffer)
    {
        // Notify thread while in lock scope, enabling initialization of wait.
        pQueue->OnPopEmpty_Locked();
        return false;
    }

    popBuffer->InitFromBuffer(buffer);
    CommandBuffer.ReadEnd(popBuffer->GetSize());

    if (!BlockedProducers.IsEmpty())
    {
        ThreadCommand::NotifyEvent* queueAvailableEvent = BlockedProducers.GetFirst();
        queueAvailableEvent->RemoveNode();
        queueAvailableEvent->PulseEvent();
        // Event is freed later by waiter.
    }    
    return true;
}
Example #9
0
bool PNGTrans::AppendToRowBuffer( void )
{
    uint8	buffer[1024];

    // Free space in rowbuffer
    uint32	nSize = m_nRowSize - m_nRowPos;
    // Adjust to available amount of data (so we don't get a deadlock)
    nSize = nSize > (uint32)m_cInBuffer.Size() ? m_cInBuffer.Size() : nSize;
    // Longword alignment, 24 bpp => 32 bpp size conversion
    nSize = ((int)( nSize / 3 )) * 4;
    // Adjust to available buffer size
    nSize = nSize > sizeof( buffer ) ? sizeof(buffer) : nSize;

//	dbprintf("pos: %ld, size: %ld\n", m_nRowPos, m_nRowSize);


    // Read and convert RGB32 => RGB24
//	dbprintf("m_cInBuffer.Read( %p, %ld )...", buffer, nSize);
    m_cInBuffer.Read( buffer, nSize );
//	dbprintf("Done!\n");
    int i, j;
    for( i = 0, j = 0; i < nSize; i+=4, j+=3 ) {
        m_pRowBuffer[ m_nRowPos + j     ] = buffer[ i     ];
        m_pRowBuffer[ m_nRowPos + j + 1 ] = buffer[ i + 1 ];
        m_pRowBuffer[ m_nRowPos + j + 2 ] = buffer[ i + 2 ];
    }

    m_nRowPos += (nSize/4)*3;
    if( m_nRowPos >= m_nRowSize ) {
//		dbprintf("New row\n");
        m_nRowPos = 0;
        return true;
    } else {
        return false;
    }
}
  void processAudio(AudioBuffer &buffer)
  {
    float delayTime, feedback, wetDry,drive;
    delayTime = getParameterValue(PARAMETER_A);
    feedback  = getParameterValue(PARAMETER_B);
    drive     = getParameterValue(PARAMETER_C);
    wetDry    = getParameterValue(PARAMETER_D);
     
     
       drive += 0.03;
        drive *= 40;

      
    int newDelay;
    newDelay = delayTime * (delayBuffer.getSize()-1);
      
    float* x = buffer.getSamples(0);
    float y = 0;
      
    int size = buffer.getSize();
    for (int n = 0; n < size; n++)     {
        y = (delayBuffer.read(delay)*(size-1-n) + delayBuffer.read(newDelay)*n)/size + x[n];
   
        y = nonLinear(y * 1.5);
        
        delayBuffer.write(feedback * y);
        
        y = (nonLinear(y * drive)) * 0.25;
      
        
        x[n] = (y *  (1 - wetDry)) +  (x[n] * wetDry);

      
    }
    delay=newDelay;
  }
void AccelMaths::tick( void )
{
  //********Update to the Buffers********//
  //Start by filling a circular buffer
  upDataBuffer.write(readFloatAccelY());
  rightDataBuffer.write(readFloatAccelZ());
  //outDataBuffer.write(readFloatAccelX());
  
  //Now average the circular buffer into another
  float floatTemp = 0;
  for( int i = 0; i < 30; i++)
  {
    floatTemp += upDataBuffer.read(i);
  }
  upAverageBuffer.write(floatTemp / 30);
  
  floatTemp = 0;
  for( int i = 0; i < 30; i++)
  {
    floatTemp += rightDataBuffer.read(i);
  }
  rightAverageBuffer.write(floatTemp / 30);
  
  // floatTemp = 0;
  // for( int i = 0; i < 30; i++)
  // {
    // floatTemp += outDataBuffer.read(i);
  // }
  // outAverageBuffer.write(floatTemp / 30);
  
  //********Do Buffer Specific Calculation********//
  //Newer minus older
    // Serial.print("\n");
	// Serial.print(upAverageBuffer.read(0), 4);
	// Serial.print(",");
	// Serial.print(upAverageBuffer.read(1), 4);
  verticalDerivativeBuffer.write( (upAverageBuffer.read(0) - upAverageBuffer.read(1) ) * 1000);
  
}
Example #12
0
void dummy_function(void)
#endif
{
#if (USE_AUDIO_INPUT==true)
	adc_count = 0;
	startSecondAudioADC();
#endif

		// read about dual pwm at http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/
		// sketches at http://wiki.openmusiclabs.com/wiki/PWMDAC,  http://wiki.openmusiclabs.com/wiki/MiniArDSP
		//if (!output_buffer.isEmpty()){
		unsigned int out = output_buffer.read();
		// 14 bit, 7 bits on each pin
		AUDIO_CHANNEL_1_HIGHUINT8_T_REGISTER = out >> 7; // B11111110000000 becomes B1111111
		AUDIO_CHANNEL_1_lowByte_REGISTER = out & 127; // B01111111
		//}
}
        // the main method
        virtual void run() {

            // update the output
            new_value = buffer->pop();

            if (c < new_value.x) {

                //update the output
                output.x = a*log(b*new_value.x + 1);

            } else if (-c > new_value.x) {

                // update the output
                output.x = -a*log(b*(-new_value.x) + 1);

            } else {

                // update the output
                output.x = 0.0;

            }

            // update the vertical
            if (c < new_value.y) {

                // update the output
                output.y = a*log(b*new_value.y + 1);

            } else if (-c > new_value.y) {

                // update the output
                output.y = -a*log(b*(-new_value.y) + 1);

            } else {

                // update the output
                output.y = 0.0;

            }

            // send the output value to external devices
            DeviceOutput<cv::Point2f>::send(output);

        }
Example #14
0
status_t PNGTrans::AddData( const void* pData, size_t nLen, bool bFinal )
{
    if( !m_bWriteMode ) {
        //	dbprintf("PNG-Read: AddData()\n");
        if ( setjmp( m_psPNGStruct->jmpbuf ) ) {
            png_destroy_read_struct( &m_psPNGStruct, &m_psPNGInfo, (png_infopp)NULL );
            return -1;
        }

        png_process_data( m_psPNGStruct, m_psPNGInfo, (png_bytep)pData, nLen );
        return 0;
    } else {
        m_cInBuffer.Write( pData, nLen );
        //	dbprintf("PNG-Write: Data added!\n");
        if( m_eState == STATE_INIT && m_cInBuffer.Size() > (ssize_t)sizeof( BitmapHeader ) ) {
            m_cInBuffer.Read( &m_sBitmapHeader, sizeof( m_sBitmapHeader ) );
            m_eState = STATE_FRAMEHDR;
        }

        if( m_eState == STATE_FRAMEHDR && m_cInBuffer.Size() > (ssize_t)sizeof( BitmapFrameHeader ) ) {
            m_cInBuffer.Read( &m_sCurrentFrame, sizeof( m_sCurrentFrame ) );
            // TODO: Verify depth, convert if not RGB32
            png_set_IHDR( m_psPNGStruct, m_psPNGInfo,
                          m_sCurrentFrame.bf_frame.right - m_sCurrentFrame.bf_frame.left + 1,
                          m_sCurrentFrame.bf_frame.bottom - m_sCurrentFrame.bf_frame.top + 1,
                          8, PNG_COLOR_TYPE_RGB, //_ALPHA,
                          PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE );
            //	png_set_filler( m_psPNGStruct, 0xff, PNG_FILLER_AFTER);
            png_set_bgr( m_psPNGStruct );
            png_write_info( m_psPNGStruct, m_psPNGInfo );
            AllocRowBuffer( m_sCurrentFrame.bf_frame.right - m_sCurrentFrame.bf_frame.left + 1 );
            m_eState = STATE_READING;
        }

        while( m_eState == STATE_READING && m_cInBuffer.Size() ) {
            if( AppendToRowBuffer() ) {
                // Overflow = one row is ready
                //	dbprintf("PNG-Write: Found Row\n");
                png_write_rows( m_psPNGStruct, &m_pRowBuffer, 1);
            }
        }

        if( bFinal ) {
            png_write_end( m_psPNGStruct, m_psPNGInfo);
        }

        return 0;
    }
}
Example #15
0
void Plot::setSettings( const Settings &s )
{
    if ( d_timerId >= 0 )
        killTimer( d_timerId );

    d_timerId = startTimer( s.updateInterval );

    d_grid->setPen( s.grid.pen );
    d_grid->setVisible( s.grid.pen.style() != Qt::NoPen );

    CircularBuffer *buffer = ( CircularBuffer * )d_curve->data();
    if ( s.curve.numPoints != buffer->size() ||
            s.curve.functionType != d_settings.curve.functionType )
    {
        switch( s.curve.functionType )
        {
            case Settings::Wave:
                buffer->setFunction( wave );
                break;
            case Settings::Noise:
                buffer->setFunction( noise );
                break;
            default:
                buffer->setFunction( NULL );
        }

        buffer->fill( d_interval, s.curve.numPoints );
    }

    d_curve->setPen( s.curve.pen );
    d_curve->setBrush( s.curve.brush );

    d_curve->setPaintAttribute( QwtPlotCurve::ClipPolygons,
        s.curve.paintAttributes & QwtPlotCurve::ClipPolygons );
    d_curve->setRenderHint( QwtPlotCurve::RenderAntialiased,
        s.curve.renderHint & QwtPlotCurve::RenderAntialiased );

    canvas()->setAttribute( Qt::WA_PaintOnScreen, s.canvas.paintOnScreen );

    canvas()->setPaintAttribute(
        QwtPlotCanvas::BackingStore, s.canvas.useBackingStore );
    canvas()->setPaintAttribute(
        QwtPlotCanvas::ImmediatePaint, s.canvas.immediatePaint );

    QwtPainter::setPolylineSplitting( s.curve.lineSplitting );

    d_settings = s;
}
Example #16
0
void dummy_function(void)
#endif
{
#if (USE_AUDIO_INPUT==true)
	adc_count = 0;
	startSecondAudioADC();
#endif

		// read about dual pwm at http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/
		// sketches at http://wiki.openmusiclabs.com/wiki/PWMDAC,  http://wiki.openmusiclabs.com/wiki/MiniArDSP
		//if (!output_buffer.isEmpty()){
		unsigned int out = output_buffer.read();
		// 14 bit, 7 bits on each pin
		//AUDIO_CHANNEL_1_highByte_REGISTER = out >> 7; // B00111111 10000000 becomes B1111111
		// try to avoid looping over 7 shifts - need to check timing or disassemble to see what really happens
		unsigned int out_high = out<<1; // B00111111 10000000 becomes B01111111 00000000
		AUDIO_CHANNEL_1_highByte_REGISTER = out_high >> 8; // B01111111 00000000 produces B01111111
		//
		AUDIO_CHANNEL_1_lowByte_REGISTER = out & 127; 
		//}
}
TEST(CircularBuffer, Insert)
{
    CircularBuffer<int, 5> cb;

    cb.pushBack(0);
    cb.pushBack(1);
    cb.pushBack(3);

    auto it(cb.begin());

    ++it;
    ++it;

    cb.insert(it, 2);

    std::vector<int> values({ 0, 1, 2, 3 });

    ASSERT_TRUE(std::equal(cb.begin(), cb.end(),
                           values.begin()));
}
        // overriding the main method
        virtual void run() {

            output = buffer->pop();

            if (saturation < output.x) {
                output.x = saturation;
            } else if (-saturation > output.x) {
                output.x = -saturation;
            }


            if (saturation < output.y) {
                output.y = saturation;
            } else if (-saturation > output.y) {
                output.y = -saturation;
            }

            // send the output to external devics
            DeviceOutput<cv::Point2f>::send(output);


        }
Example #19
0
ISR(TIMER1_OVF_vect, ISR_BLOCK)
{

#if (AUDIO_MODE == STANDARD_PLUS) && (AUDIO_RATE == 16384) // only update every second ISR, if lower audio rate
	static boolean alternate;
	alternate = !alternate;
	if(alternate)
	{
#endif

#if (USE_AUDIO_INPUT==true)
		adc_count = 0;
		startSecondAudioADC();
#endif

//if (!output_buffer.isEmpty()) {
/*
output =  output_buffer.read();
AUDIO_CHANNEL_1_OUTPUT_REGISTER = output;
AUDIO_CHANNEL_2_OUTPUT_REGISTER = 0;
*/
	AUDIO_CHANNEL_1_OUTPUT_REGISTER = output_buffer.read();
//}

	// flip signal polarity - instead of signal going to 0 (both pins 0), it goes to pseudo-negative of its current value.
	// this would set non-inverted when setting sample value, and then inverted when top is reached (in an interrupt)
	// non-invert
	//TCCR1A |= _BV(COM1A1);
	// invert
	//TCCR1A |= ~_BV(COM1A1)
	
	
#if (AUDIO_MODE == STANDARD_PLUS) && (AUDIO_RATE==16384) // all this conditional compilation is so clutsy!
	}
#endif

}
Example #20
0
void processKeyboard(void) {
   MidiMessage message;
   int key;
   int vel;
   int command;
   
   while (synth.getNoteCount() > 0) {
      message = synth.extractNote();
      command = message.p0();
      key = message.p1();
      vel = message.p2();
 
      if (vel == 0 || (command & 0xf0 == 0x80)) {
         // note-off command section
         long duration = t_time - performerNotes[key];
         durations.insert(duration);
         durtimes.insert(t_time);

         performerNotes[key] = 0;
         performerPC[key%12]--;
         if (performerPC[key%12] < 0) {
            performerPC[key%12] = 0;
         }
      
      } else {   // note-on command
         performerNotes[key] = t_time;
         performerPC[key%12]++;
         performerPCHistory[key%12]++;
         keys.insert(key);
         keytimes.insert(t_time);
         volumes.insert(vel);
         voltimes.insert(t_time);

      } // end of the note-on command section

   }  // end of the while loop for processing notes from the performer

   // update the time that the performer last play a note on/off:
   lastPerformerTime = t_time;

   updatePerformRegions();
   updateDuration();
   updateVolume();
}
Example #21
0
ISR(TIMER1_OVF_vect, ISR_BLOCK)
{

#if (AUDIO_MODE == STANDARD_PLUS) && (AUDIO_RATE == 16384) // only update every second ISR, if lower audio rate
	static boolean alternate;
	alternate = !alternate;
	if(alternate)
	{
#endif

#if (USE_AUDIO_INPUT==true)
		adc_count = 0;
		startSecondAudioADC();
#endif

//if (!output_buffer.isEmpty()) {
	AUDIO_CHANNEL_1_OUTPUT_REGISTER = output_buffer.read();
//}

#if (AUDIO_MODE == STANDARD_PLUS) && (AUDIO_RATE==16384) // all this conditional compilation is so clutsy!
	}
#endif

}
Example #22
0
void audioHook() // 2us excluding updateAudio()
{
//setPin13High();
#if (USE_AUDIO_INPUT==true)
		if (!input_buffer.isEmpty()) 
			audio_input = input_buffer.read();
#endif

	if (!output_buffer.isFull()) {
		#if (STEREO_HACK == true)
		updateAudio(); // in hacked version, this returns void
		output_buffer.write((unsigned int) (audio_out_1 + AUDIO_BIAS));
		output_buffer2.write((unsigned int) (audio_out_2 + AUDIO_BIAS));
		#else
		output_buffer.write((unsigned int) (updateAudio() + AUDIO_BIAS));
		#endif

	}
//setPin13Low();
}
int main (int argc, const char * argv[])
{
	//Create a new circular buffer for unsigned integers
	CircularBuffer< UINT > buffer;

	//Resize the buffer
	buffer.resize( 10 );
	
	//Add some values to the buffer so we fill it
	for(UINT i=0; i<buffer.getSize(); i++){
		cout << "Adding " << i << " to buffer\n";
		buffer.push_back( i );
		
		//Print the values in the buffer
		cout << "Values: \t\t";
		for(UINT j=0; j<buffer.getSize(); j++){
			cout << buffer[j] << "\t";
		}cout << endl;
		
		//Print the raw values in the buffer
		cout << "RawValues: \t\t";
		for(UINT j=0; j<buffer.getSize(); j++){
			cout << buffer(j) << "\t";
		}cout << endl;
	}
	
	//Get all the data in the buffer as a vector
	vector<UINT> data = buffer.getDataAsVector();
	cout << "Data: \t\t\t";
	for(UINT j=0; j<data.size(); j++){
		cout << data[j] << "\t";
	}
	cout << endl;
	
    return EXIT_SUCCESS;
}
Example #24
0
void initialization(void) { 
   batonTimer.setPeriod(50);           // time to get new state of baton
   offTimer.setPeriod(200);            // time to check buffer for forgetting
   controlDisplayTimer.setPeriod(200); // time to check buffer for forgetting

   // set the voice channels all to be 0 for the disklavier and so
   // the channels do not have to be specified when playing the note.
   for (int i=0; i<MAXVOICES; i++) {
      voice[i].setChannel(0);
   }
   computer.setChannel(0);
   computerMessage.time = t_time;
   computerMessage.p0() = 0x90;
   computerMessage.p1() = 0;
   computerMessage.p2() = 0;

   keys.setSize(1000);        // store keys for memory of previous notes
   keytimes.setSize(1000);    // note times for keys buffer
   volumes.setSize(1000);     // duration of notes being held by performer
   voltimes.setSize(1000);    // duration of notes being held by performer
   durations.setSize(1000);   // duration of notes being held by performer
   durtimes.setSize(1000);    // duration of notes being held by performer
}
Example #25
0
ssize_t PNGTrans::AvailableDataSize()
{
    return( m_cOutBuffer.Size() );
}
Example #26
0
status_t GIFTrans::AddData( const void* pData, size_t nLen, bool bFinal )
{
    m_bEOF = bFinal;
    m_cInBuffer.Write( pData, nLen );
    return( 0 );
}
Example #27
0
int main()
{
    {
        // Test default constructor
        CircularBuffer buf;
        std::cout << buf.size() << "\n";
    }

    {
        // Test constructor taking 1 arg: size of buffer
        CircularBuffer buf(32);
        std::cout << buf.size() << "\n";
    }

    {
        // Test constructor taking std::vector
        std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        CircularBuffer buf(v);
        std::cout << buf.size() << "\n";
    }

    {
        // Test copy constructor
        std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        CircularBuffer buf(v);
        CircularBuffer buf2(buf);
        std::cout << buf.size() << ", " << buf2.size() << "\n";
    }

    {
        // Test move constructor
        std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        CircularBuffer buf(v);
        CircularBuffer buf2(std::move(buf));
        std::cout << buf.size() << ", " << buf2.size() << "\n";
    }

    {
        // Test copy assignment
        std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        CircularBuffer buf(v);
        CircularBuffer buf2(3);
        std::cout << buf.size() << ", " << buf2.size() << " -> ";
        buf2 = buf;
        std::cout << buf.size() << ", " << buf2.size() << "\n";
    }

    {
        // Test move assignment
        std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        CircularBuffer buf(v);
        CircularBuffer buf2(3);
        std::cout << buf.size() << ", " << buf2.size() << " -> ";
        buf2 = std::move(buf);
        std::cout << buf.size() << ", " << buf2.size() << "\n";
    }

    {
        // Test indexing
        CircularBuffer buf(10);
        buf[0] = buf[2] = buf[4] = buf[6] = buf[8] = 1;
        buf[1] = buf[3] = buf[5] = buf[7] = buf[9] = 2;
        std::cout << buf.at(1) << " " << buf[6] << "\n";
        std::cout << buf.at(32) << " " << buf[127] << "\n";
    }

    {
        // Test indexing const object
        const CircularBuffer buf({1, 2, 3, 4, 5});
        std::cout << buf.at(1) << " " << buf[8] << "\n";
    }

    {
        // Test size (already used above)
        CircularBuffer buf(3);
        if (buf.size() != 3)
            std::cout << "Incorrect size!\n";
        else
            std::cout << "Correct size!\n";
    }

    {
        // Test clear
        CircularBuffer buf(5);
        std::cout << buf.size() << " -> ";
        buf.clear();
        std::cout << buf.size() << "\n";
    }

    {
        // Test swap
        CircularBuffer buf({1, 2, 3, 4, 5});
        CircularBuffer buf2({6, 7, 8, 9, 0});
        std::cout << buf[0] << " " << buf[4] << " : " << buf2[0] << " "
                  << buf2[4] << " -> ";
        buf.swap(buf2);
        std::cout << buf[0] << " " << buf[4] << " : " << buf2[0] << " "
                  << buf2[4] << "\n";
    }

    {
        // Test insert
        CircularBuffer buf;
        buf.insert(0, 1);
        buf.insert(0, 2);
        buf.insert(0, 3);
        std::cout << buf.size() << " " << buf[2] << "\n";
        buf.insert(200, 4);
        std::cout << buf.size() << " " << buf[2] << "\n";
    }

    {
        // Test move-insert
        CircularBuffer buf;
        int x = 3;
        buf.insert(0, std::move(x));
        int y = 2;
        buf.insert(0, std::move(y));
        std::cout << buf[0] << " " << buf[1] << " " << buf[2] << "\n";
    }

    {
        // Test erase
        CircularBuffer buf({1, 2, 3, 4});
        std::cout << buf[0] << " " << buf.size() << " -> ";
        buf.erase(0);
        std::cout << buf[0] << " " << buf.size() << "\n";
    }

    return 0;
}
Example #28
0
int main ( int argc, char ** argv )
{
    char      optChar;
    char    * target;
    int       optindx  = 0;
    int       interval = 0;
    int       count    = -1;
    int       timeout  = ICMP_TIMEOUT_SECS;
    bool      debug    = false;
    size_t    size     = 0;

    timeval   tvin, tvsnt, tvo;

    static struct option l_opts[] = { {"count", required_argument, 0, 'c'},
                                      {"debug", no_argument, 0, 'd'},
                                      {"interval", required_argument, 0, 'i'},
                                      {"help", no_argument, 0, 'h'},
                                      {"size", required_argument, 0, 's'},
                                      {"version", no_argument, 0, 'v'},
                                      {0,0,0,0}
                                    };

    if ( argc < 2 )
        usage();

    while ( (optChar = getopt_long(argc, argv, "c:di:hs:v", l_opts, &optindx)) != EOF )
    {
        switch ( optChar ) {
            case 'c':
                count = StringUtils::FromString<int>(optarg);
                break;
            case 'd':
                debug = true;
                break;
            case 'i':
                interval = StringUtils::FromString<int>(optarg);
                break;
            case 'h':
                usage();
                break;
            case 's':
                size = StringUtils::FromString<size_t>(optarg);
                break;
            case 'v':
                version();
                break;
            default:
                usage();
                break;
        }
    }

    target = strdup(argv[argc-1]);
    ::memset(&tvsnt, 0, sizeof(tvsnt));
    ::memset(&tvin, 0, sizeof(tvin));
    ::memset(&tvo, 0, sizeof(tvo));

    if ( interval == 0 )
        interval = 1000;

    std::string host = target;
    ::free(target);

    Pid  = ::getpid() & 0xFFFF;
    ::signal(SIGPIPE, SIG_IGN);
    ::signal(SIGINT,  &sigHandler);

    ipv4addr_t dstaddr = AddrInfo::GetHostAddr(host);

    if ( dstaddr == 0 ) {
        std::cout << "Invalid target host: " << host << std::endl;
        exit(-1);
    }

    Socket * icmps  = new Socket(dstaddr, SOCKET_ICMP, SOCKTYPE_RAW, SOCKET_ICMP);
    icmps->init(false);

    dropPriv();

    neticmp_h  * req     = NULL;
    icmp_ts    * its     = NULL;
    char       * wptr    = NULL;
    char       * wbuff   = NULL;
    char       * data    = NULL;
    const char * dt      = NULL;
    bool         sendReq = true;

    sockaddr_t   csock;
    sockaddr_in* sa;
    ipv4addr_t   addr;
    size_t       sz, buflen, idsz;
    ssize_t      wt, rd;
    int          cnt, sent, rcvd;
    float        mstot, avg;

    cnt    = 1;
    sent   = 0;
    rcvd   = 0;
    mstot  = 0.0;
    avg    = 0.0;
    buflen = 2048;
    idsz   = sizeof(neticmp_h) + sizeof(icmp_ts);

    CircularBuffer * rbuff = new CircularBuffer(buflen);

    wbuff       = (char*) ::malloc(buflen);
    req         = (neticmp_h*) wbuff;
    its         = (icmp_ts*) wbuff + sizeof(neticmp_h);
    data        = wbuff + idsz;

    req->type   = ICMP_ECHO;
    req->code   = 0;
    req->chksum = 0;
    req->id     = Pid;
    req->seq    = 0;

    if ( count > 0 )
        cnt = count;

    if ( size > (buflen - idsz) )
        size = buflen - idsz - 4;

    size  += Serializer::PadLen(size);
    InitDataBlock(size);

    dt = RandData.substr(0, size).data();
    ::memcpy(data, dt, size);
    its->size = size;

    std::cout << "Sending ";
    if ( count > 0 )
        std::cout << "(" << count << ") " ;
    std::cout << "ICMP echo requests to " << IpAddr::ntop(dstaddr) 
              << " (" << host << ")" << std::endl;
    std::cout << "ICMP data size is " << size << std::endl;

    while ( ! Alarm )
    {
        rbuff->reset();

        if ( ! getTimeOfDay(tvin) )
            errorOut("error in gettime");

        float lastsnt = timeDiff(tvin, tvsnt);

        if ( lastsnt >= interval )
            sendReq = true;

        if ( sendReq && cnt > 0 ) {
            sz           = idsz + size; // account for added data size
            tvsnt        = tvin;
            its->secs    = tvin.tv_sec;
            its->usecs   = tvin.tv_usec;
            req->chksum  = 0;
            req->seq++;
            req->chksum  = Socket::IpChkSum((uint16_t*)req, sz);

            wt  = icmps->write(wbuff, sz);
            if ( wt < 0 )
                errorOut("Error in write " + icmps->getErrorString());
            
            sent++;
            sendReq = false;
            if ( count > 0 )
                cnt--;

            if ( debug )
                std::cout << "Request <" << sent << "> sent" << std::endl;
        }

        sz   = rbuff->writePtrAvailable();
        wptr = rbuff->getWritePtr(&sz);
        if ( wptr == NULL )
            errorOut("Error in writing to rbuff");

        rd   = icmps->readFrom(wptr, sz, csock);
        if ( rd < 0 )
            errorOut("Error in readFrom " + icmps->getErrorString());
        
        sa   = (sockaddr_in*) &csock;
        addr = sa->sin_addr.s_addr;

        rbuff->setWritePtr(rd);

        if ( rd > 0 && addr == dstaddr )
        {
            IcmpResponse   response;
            
            if ( ! getTimeOfDay(tvin) )
                errorOut("error in gettime");

            rd = readIcmpHeader(rbuff, response);

            if ( rd > 0 && response.icmph.id == Pid ) {
                sz      = rbuff->readAvailable();
                rcvd++;

                if ( sz == sizeof(icmp_ts) ) {
                    timeval   tv;
                    char    * idf = rbuff->getReadPtr(&sz);
                    icmp_ts * ist = (icmp_ts*) idf;
                    tv.tv_sec     = ist->secs;
                    tv.tv_usec    = ist->usecs;

                    if ( debug ) 
                        std::cout << " Received data field in echo response" << std::endl;

                    rbuff->setReadPtr(sz);
                }

                float ms = timeDiff(tvin, tvsnt);

                std::cout << (rd+sz) << " bytes from " << IpAddr::ntop(addr)
                    << ": seq=" << response.icmph.seq << " time=" << ms << " ms" 
                    << std::endl;

                mstot += ms;
                avg    = (float) mstot / rcvd;

                if ( debug )
                    std::cout << " mstot=" << mstot << " rcvd = " << rcvd << std::endl;
            }
        } 
        
        if ( cnt == 0 ) {
            if ( rcvd == cnt )
                break;
            if ( tvo.tv_sec == 0 )
                tvo.tv_sec = tvin.tv_sec;
            else if ( (tvin.tv_sec - tvo.tv_sec) > timeout )
                break;
        }

        ::usleep(1000);
    }

    float loss;
    if ( rcvd == sent )
        loss = 0.0;
    else
        loss = (  100.0 - ( ((float) rcvd / (float) sent) * 100.0) );

    std::cout << std::endl << "Results:" << std::endl;
    std::cout << "  Sent " << sent << " requests, received " << rcvd 
        << ": Loss=" << loss << "% : Avg Time= " << avg << " ms " 
        << std::endl;

    return 0;

}
void* GlassesVideo::runThread(void*) 
{

	VideoCapture gl_capture(3); 

	gl_capture.set(CV_CAP_PROP_FRAME_WIDTH , 640);
	gl_capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

	if(!gl_capture.isOpened())
	{
		cout << "Cannot open glasses video !" << endl;
	}

	Mat gl_img, gl_img_OR;

	Mat curMat, preMat;

	//glassesOR glOR(&gl_img_OR);
	//glOR.stopRunning();
	ObjectRecognition gl_or("g20111105_4.yml.gz");
	Mat gl_img_bk;
	Mat glres_image;				//display result image

	int gl_result=255;



	RobotSearch robotsearch;
	//robotsearch.create();
	robotsearch.stopRunning();

	
	//namedWindow("Glasses Video");
	//moveWindow("Glasses Video", 645, 0);
	namedWindow("Video Live");
	moveWindow("Video Live", 645, 0);
	namedWindow("Glasses_result",CV_WINDOW_NORMAL);
	moveWindow("Glasses_result",1000,600);
	//G_glassesMode = glassesOR;
	while(1)
	{

		gl_capture >> gl_img;
		cvtColor(gl_img,gl_img_bk,CV_RGB2GRAY);
		imshow("Video Live",gl_img_bk);
		waitKey(1);

		//----------------------------glasses Motion ------------------------
		preMat = gl_img.clone();
		//imshow("preMat", preMat);
		gl_capture >> curMat;
		//imshow ("cur", curMat);
		modeSwitch(preMat, curMat);
		//-------------------------------------------------------------------

		if(G_glassesMode == glassesOR) //OR MODE
		{

			//Open Glasses Objct Recognition
			//glOR.runAsync();

			gl_result=255;
			gl_result = gl_or.find(gl_img_bk, 'G');

			//if(gl_result !=255)
			//{
			//	gl_capture >> gl_img;
			//	cvtColor(gl_img,gl_img_bk,CV_RGB2GRAY);
			//	imshow("Video Live",gl_img);
			//	waitKey(1);
			//	gl_result=255;
			//	gl_result = gl_or.find(gl_img_bk, 'G');
			//	/*if(gl_result !=255)
			//	{
			//		gl_capture >> gl_img;
			//		cvtColor(gl_img,gl_img_bk,CV_RGB2GRAY);
			//		imshow("Video Live",gl_img);
			//		waitKey(1);
			//		gl_result=255;
			//		gl_result = gl_or.find(gl_img_bk, 'G');
			//	}
			//	else gl_result=255;*/

			//}
			//gl_result=4;

			if(gl_result !=255)
			{

				//-------------------------Display the result ------------------------
				robotSpeak(gl_result, "name");
				stringstream ret_src1;  //result src
				ObjectRecognition::loadImage(ret_src1, gl_result, 'G', 1);
				glres_image = imread(ret_src1.str());
				imshow("Glasses_result", glres_image);
				waitKey(1);
				
				//--------------------glasses goes to roobt search mode------------------
				GlassesModeMutex.lock();
				CB.clear();
				G_glassesMode = robotSearch;
				G_Search_Step = 0;
				isDoneRobot = true;
				G_Target= gl_result/5;
				gl_result = 255;
				HelpStartTime = time(NULL);
				//RobotCommand(CameraMotion); //cameraMotion
				GlassesModeMutex.unlock();

				////-------------------------Open robot search thread ------------------------

				if(!robotsearch.getRunning())
					robotsearch.runAsync();
				
			}

		}



	}
	//return 0;

}
Example #30
0
unsigned long audioTicks()
{
	return output_buffer.count();
}