Пример #1
0
void EngineSideChain::writeSamples(const CSAMPLE* newBuffer, int buffer_size) {
    Trace sidechain("EngineSideChain::writeSamples");
    int samples_written = m_sampleFifo.write(newBuffer, buffer_size);

    if (samples_written != buffer_size) {
        Counter("EngineSideChain::writeSamples buffer overrun").increment();
    }

    if (m_sampleFifo.writeAvailable() < SIDECHAIN_BUFFER_SIZE / 5) {
        // Signal to the sidechain that samples are available.
        Trace wakeup("EngineSideChain::writeSamples wake up");
        m_waitForSamples.wakeAll();
    }
}
Пример #2
0
void Counter(int num)
{
	if ( num > 0 )
	{
		printf ( "%d\t", num); // Behaves like queue
		//Counter ( --num); // permanent modifications to inputs matters
		Counter ( num-1); //
		printf ( "%d\t", num); // Behaves like stack
	}
	else
	{
		printf("\n");
	}
}
Пример #3
0
CounterCost * CounterCost::clone() const
{
    CounterCost * ec = NEW CounterCost(*this);
    if (tc)
        ec->tc = tc->clone();
    
    if (counter)
        ec->counter = NEW Counter(counter->target, counter->name.c_str(), counter->power, counter->toughness);

    //TODO: counter can be NULL at this point, what do we set ec->counter->nb to if it is?
    if (ec->counter != NULL)
        ec->counter->nb = counter->nb;
    
    return ec;
}
Пример #4
0
        void UpdateAI(uint32 diff)
        {
            ReduceCD(diff);
            if (IAmDead()) return;
            if (!me->GetVictim())
                Evade();
            if (clearcast && me->HasAura(CLEARCASTBUFF) && !me->IsNonMeleeSpellCasted(false))
            {
                me->ModifyPower(POWER_MANA, cost);
                me->RemoveAurasDueToSpell(CLEARCASTBUFF,me->GetGUID(),0,AURA_REMOVE_BY_EXPIRE);
                if (me->HasAura(ARCANE_POTENCY_BUFF1))
                    me->RemoveAurasDueToSpell(ARCANE_POTENCY_BUFF1,me->GetGUID(),0,AURA_REMOVE_BY_EXPIRE);
                if (me->HasAura(ARCANE_POTENCY_BUFF2))
                    me->RemoveAurasDueToSpell(ARCANE_POTENCY_BUFF2,me->GetGUID(),0,AURA_REMOVE_BY_EXPIRE);
                clearcast = false;
            }
            if (wait == 0)
                wait = GetWait();
            else
                return;
            CheckAuras();
            BreakCC(diff);
            if (CCed(me) && (!ICEBLOCK || !me->HasAura(ICEBLOCK))) return;//TODO

            CheckBlink(diff);
            CheckPoly(diff);
            CheckPots(diff);
            CureTarget(master, REMOVE_CURSE, diff);
            CureTarget(me, REMOVE_CURSE, diff);
            CureGroup(master, REMOVE_CURSE, diff);

            FocusMagic(diff);
            BuffAndHealGroup(master, diff);

            if (!me->IsInCombat())
                DoNonCombatActions(diff);
            
            if (!CheckAttackTarget(CLASS_MAGE))
                return;

            CheckPoly2();//this should go AFTER getting opponent

            Counter();
            CheckSpellSteal(diff);
            DoNormalAttack(diff);
        }
Пример #5
0
Clock::Clock(bool e)
{
#if defined(WIN32)
	LARGE_INTEGER	pcf;
	QueryPerformanceFrequency(&pcf);
	cout << "performance freq " << pcf.QuadPart << ", err " << GetLastError() << endl;
	performanceFrequency = pcf.QuadPart;
	usecsPerCount = 1000000.0/((double)performanceFrequency);
	timingError = MSec2Count(1);
#endif
	theEndOfTime = false;
	alarmOn = false;
	alarmTime = 0;
	theTime = 0;
	startTime = Counter();
	SetTimeSource(e);
}
Пример #6
0
int main (void)
{
	DDRD &= ~BIT(7);
	DDRA = 0xFF;
	DDRB = 0xFF;
	DDRC = 0xFF;
	initLCD();
	Counter();
	for (;;)
	{
			PORTA = TCNT2;
			PORTB = counter;
			sprintf(lcdstr,"%d",counter);
			printString(lcdstr,4);
			clearScreen();
			_delay_ms(1);
	}
}
Пример #7
0
    // Topic supplied here was converted to path name for isid mode
    void on_message_count (std::string topic,
                           const struct mosquitto_message* mosqmessage)
    {
        // Global
        messages.increment(1, mosqmessage->payloadlen);

        // Per-topic
        if (stats_topics.count(topic) == 0) {
            stats_topics[topic] = Counter(topic);
        }
        stats_topics[topic].increment(1, mosqmessage->payloadlen);

        // Check limit
        if (_limits.expired(messages.getPackets())) {
            _logger->log("Subscription " + _name + " limits expired");
            _limits_reached = true;
        }
    }
Пример #8
0
            void UpdateAI(const uint32 diff)
            {
                DoMeleeAttackIfReady();

                if (IAmDead())
                    return;

                ReduceCD(diff);

                opponent = me->getVictim();

                if (!opponent )
                {
                    ResetOrGetNextTarget();
                    DoNonCombatActions();
                    return;
                }

                me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true);
                me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true);

                if (me->GetHealth() < me->GetMaxHealth()*0.5 && isTimerReady(uiPotion_Timer))
                {
                    doCast(me, SPELL_HEALING_POTION);
                    uiPotion_Timer = 60000;
                }

                oom_spam = false;

                //buff and heal master's group
                if (master->GetGroup())
                {
                    BuffAndHealGroup(master);
                    CureGroup(master);
                }

                // Heal myself
                HealTarget (me, me->GetHealth() * 100 / me->GetMaxHealth());
                DoNormalAttack(diff);
                Counter(diff);

                ScriptedAI::UpdateAI(diff);
            }
Пример #9
0
	void			convert(const gif::Bitmap &src, const size_t max_size, gif::Palette &out) override {
		out.mColors.clear();
		if (src.empty()) return;

		// Simple utility to find all colors and eliminate based on a similarity until we're down to our max size.
		std::unordered_map<gif::ColorA8u, size_t>	ct;
		for (const auto& pix : src.mPixels) {
			const gif::ColorA8u		sc = gif::ColorA8u(pix.r, pix.g, pix.b, 255);
			ct[sc]++;
		}

		// For now, just clip based the most-used colors. CLEARLY THIS NEEDS TO CHANGE
		using Counter = std::pair<gif::ColorA8u, size_t>;
		std::vector<Counter>						vec;
		for (const auto& p : ct) vec.push_back(Counter(p.first, p.second));
		std::sort(vec.begin(), vec.end(), [](const Counter &a, const Counter &b)->bool{return a.second > b.second;});
		if (vec.size() > max_size) vec.resize(max_size);
		out.mColors.reserve(max_size);
		for (const auto& p : vec) out.mColors.push_back(p.first);
	}
Пример #10
0
void simnet()
{
  Signal Strobe (1);   // Counter strobe input
  Signal ResetA (1);   // Counter reset signal (before complemented)
  Signal ResetB (1);   // Counter reset signal (after complemented)
  Signal Output (4);   // Counter output

  // A pulser is used to generate a temporary value of "One" on a specified
  // signal line (signal value:  Zero ==> One ==> Zero)

  Pulser ((SD("1a"), "r -- Reset counter"),  ResetA, 'r', 10000);
  Pulser ((SD("2a"), "s -- Strobe counter"), Strobe, 's', 10000);

  // Complement the reset signal (counter reset is active low)

  Not (SD("1b"), ResetA, ResetB);

  Counter ((SD("1c-2c"), "4-bit counter"), (ResetB, Strobe), Output);

  Probe ((SD("1d-2d"), "Output"), Output);
}
Пример #11
0
//延时器函数 放慢动画的模仿速度
void GameObject::DelayerCount()
{
	AddCounter();
	if (Counter() >= Delayer()) {
		AddIndexColumn();
		if (IndexColumn() == Ima()->Column())
		{
			IndexColumn(0);
			AddIndexRow();
		}
		if (IndexRow() == Ima()->Row())
		{
			if (Loop()) {
				IndexRow(0);
				IndexColumn(0);
			}
			else Killed();
		}
		ClearCounter();
	}
}
Пример #12
0
int main( void )
{
  
  WDTCTL = WDTPW + WDTHOLD;          // Stop watchdog timer
 
  BCSCTL1 = CALBC1_1MHZ;             // Set range  (1 Mhz)
  DCOCTL = CALDCO_1MHZ;              // Set DCO step + modulation */ 
  
  SPI_Master_Init();
  
  num=0;
  
  P2OUT &= ~(0x1F);            // Set P2.0 to P2.4 to 0 (when output)
  P2DIR |= (0x1F);             // Set P2.0 and P2.4 to output direction 
  
  timerInterruptFlag=CLEAR;

  ConfigTimer0();                    //Configure Timer0 Module
                                     //for 10 ms interrupt 
  
  _EINT();                           // enable (general) interrupts
                                     //eint <-----> bis #8,sr
  
  //example of a timed loop:
  
  for(;;){                                // loop forever 

    while(timerInterruptFlag != SET);     // loop forever while Flag not SET
    timerInterruptFlag=CLEAR;             // Clear timer flag
    
    Display(num);

    Counter();
           

  }

  return 0;
}
Пример #13
0
CNum::Counter &CNum::Counter::operator*=(const Counter &rhs) {
    assert(isNormalized());
    assert(rhs.isNormalized());

    Counter sol = 0;
    Unit shift1 = 0;
    for (Index rpos = 0; rpos < rhs.value.size(); ++rpos) {
        Unit shift2 = 0;
        Unit carry = 0;
        for (Index lpos = 0; carry || lpos < value.size(); ++lpos) {
            Unit l = lpos < value.size() ? value[lpos] : 0;
            CNum::mul(l, rhs.value[rpos], carry);
            sol += (Counter(l) << (shift1 + shift2));
            shift2 += UNIT_BIT_SIZE;
        }
        shift1 += UNIT_BIT_SIZE;
    }
    assert(sol.isNormalized());
    *this = sol;
    assert(isNormalized());
    return *this;
}
Пример #14
0
int Counters::addCounter(const char * _name, int _power, int _toughness, bool _noevent)
{
    /*420.5n If a permanent has both a +1/+1 counter and a -1/-1 counter on it, N +1/+1 and N -1/-1 counters are removed from it, where N is the smaller of the number of +1/+1 and -1/-1 counters on it.*/
    GameObserver *g = target->getObserver();
    WEvent * e = NEW WEventCounters(this,_name,_power,_toughness);
    dynamic_cast<WEventCounters*>(e)->targetCard = this->target;
    if (e == g->replacementEffects->replace(e))
    {
        for (int i = 0; i < mCount; i++)
        {
            if (counters[i]->sameAs(_name, _power, _toughness))
            {
                counters[i]->added();
                counters[i]->nb++;
                WEvent * j = NEW WEventCounters(this,_name,_power,_toughness,true,false);
                dynamic_cast<WEventCounters*>(j)->targetCard = this->target;
                g->receiveEvent(j);
                delete(e);
                return mCount;
            }
        }
        Counter * counter = NEW Counter(target, _name, _power, _toughness);
        counters.push_back(counter);
        counter->added();
        if (!_noevent)
        {
            WEvent * w = NEW WEventCounters(this,_name,_power,_toughness,true,false);
            dynamic_cast<WEventCounters*>(w)->targetCard = this->target;
            g->receiveEvent(w);
        }
        mCount++;
        /*the damage test should be handled on game state based effect i think*/
        //this->target->doDamageTest = 1;
        //this->target->afterDamage();
    }
    delete(e);
    return mCount;
}
Пример #15
0
void task1(void *pvParameters)
{
    Counter local_counter = Counter(12);
    Counter *new_counter = new Counter(24);
    while(1) {
        Counter *counter = NULL;
        switch(rand() % 3) {
        case 0:
            counter = &local_counter;
            break;
        case 1:
            counter = &static_counter;
            break;
        default:
            counter = new_counter;
            break;
        }
        counter->Increment();
        printf("local counter %d static counter %d newly allocated counter %d\r\n", local_counter.getCount(),
               static_counter.getCount(), new_counter->getCount());
        vTaskDelay(100);
    }
}
Пример #16
0
void
Clock::Set(float time_to)
{
	startTime = Counter() - bigtime_t(time_to*performanceFrequency);
}
Пример #17
0
T FibCounter_t<T>::FindGreaterOrEqual(T Value_)
{
  for (Reset(); Value_ > Counter(); Increment());
  return _Count;
}
Пример #18
0
TEST(Connection, Timeout)
{
    Timer::GetInstance().UseVirtualTime();

    SignalCounter sc_new;
    SignalCounter sc_close;

    const BufferAddress addr0(1000);
    QSharedPointer<EdgeListener> be0(EdgeListenerFactory::GetInstance().CreateEdgeListener(addr0));
    QSharedPointer<RpcHandler> rpc0(new RpcHandler());
    Id id0;
    ConnectionManager cm0(id0, rpc0);
    QObject::connect(&cm0, SIGNAL(NewConnection(const QSharedPointer<Connection> &)),
                     &sc_new, SLOT(Counter()));
    cm0.AddEdgeListener(be0);
    be0->Start();
    cm0.Start();

    const BufferAddress addr1(10001);
    QSharedPointer<EdgeListener> be1(EdgeListenerFactory::GetInstance().CreateEdgeListener(addr1));
    QSharedPointer<RpcHandler> rpc1(new RpcHandler());
    Id id1;
    ConnectionManager cm1(id1, rpc1);
    QObject::connect(&cm1, SIGNAL(NewConnection(const QSharedPointer<Connection> &)),
                     &sc_new, SLOT(Counter()));
    cm1.AddEdgeListener(QSharedPointer<EdgeListener>(be1));
    be1->Start();
    cm1.Start();

    ASSERT_FALSE(cm0.GetConnectionTable().GetConnection(id1));
    ASSERT_FALSE(cm1.GetConnectionTable().GetConnection(id0));
    cm1.ConnectTo(addr0);

    RunUntil(sc_new, 2);

    ASSERT_TRUE(cm0.GetConnectionTable().GetConnection(id1));
    ASSERT_TRUE(cm1.GetConnectionTable().GetConnection(id0));

    QObject::connect(cm0.GetConnectionTable().GetConnection(id1)->GetEdge().data(),
                     SIGNAL(StoppedSignal()), &sc_close, SLOT(Counter()));
    QObject::connect(cm1.GetConnectionTable().GetConnection(id0)->GetEdge().data(),
                     SIGNAL(StoppedSignal()), &sc_close, SLOT(Counter()));

    cm0.GetConnectionTable().GetConnection(id1)->GetEdge()->Stop("For fun");

    RunUntil(sc_close, 1);

    ASSERT_FALSE(cm0.GetConnectionTable().GetConnection(id1));
    ASSERT_TRUE(cm1.GetConnectionTable().GetConnection(id0));

    RunUntil(sc_close, 2);

    ASSERT_FALSE(cm0.GetConnectionTable().GetConnection(id1));
    ASSERT_FALSE(cm1.GetConnectionTable().GetConnection(id0));

    cm1.Stop();
    cm0.Stop();

    qint64 next = Timer::GetInstance().VirtualRun();
    while(next != -1) {
        Time::GetInstance().IncrementVirtualClock(next);
        next = Timer::GetInstance().VirtualRun();
    }
}
Пример #19
0
// Performs the calibration according to calibration method chosen.
// Compares different calibration results in order to achieve optimal results.
void CalibrateInternalRc(void)
{
	uint16_t count;

#ifdef CALIBRATION_METHOD_SIMPLE			// Simple search method
	uint8_t cycles = 0x80;

	do {
		count = Counter();
		if (count > countVal)
			OSCCAL--;						// If count is more than count value corresponding to the given frequency:
		NOP();								// - decrease speed
		if (count < countVal)
			OSCCAL++;
		NOP();								// If count is less: - increase speed
		if (count == countVal)
			cycles = 1;			
	} while (--cycles);						// Calibrate using 128(0x80) calibration cycles

#else										// Binary search with or without neighbor search
	uint8_t countDiff;
	uint8_t neighborSearchStatus = FINISHED;

	while (calibration == RUNNING)
	{
		count = Counter();					// Counter returns the count value after external ticks on XTAL
		if (calStep != 0)
		{
			BinarySearch(count);			// Do binary search until stepsize is zero
		}
		else
		{
			if (neighborSearchStatus == RUNNING)
			{
				countDiff = ABS((int16_t)count-(int16_t)countVal);
				if (countDiff < bestCountDiff)		// Store OSCCAL if higher accuracy is achieved
				{
					bestCountDiff = countDiff;
					bestOSCCAL = OSCCAL;
				}
				NeighborSearch();					// Do neighbor search
			}
			else									// Prepare and start neighbor search
			{
#ifdef CALIBRATION_METHOD_BINARY_WITHOUT_NEIGHBOR	// No neighbor search if deselected
				calibration = FINISHED;
				countDiff = ABS((int16_t)count - (int16_t)countVal);
				bestCountDiff = countDiff;
				bestOSCCAL = OSCCAL;
#else
				neighborSearchStatus = RUNNING;		// Do neighbor search by default
				neighborsSearched = 0;
				countDiff = ABS((int16_t)count - (int16_t)countVal);
				bestCountDiff = countDiff;
				bestOSCCAL = OSCCAL;
#endif
			}
		}
	}
#endif
}
Пример #20
0
  void RoundTest_MultiRound(CreateSessionCallback callback, CreateGroupGenerator cgg)
  {
    Timer::GetInstance().UseVirtualTime();

    int count = Random::GetInstance().GetInt(TEST_RANGE_MIN, TEST_RANGE_MAX);
    int leader = Random::GetInstance().GetInt(0, count);
    int sender0 = Random::GetInstance().GetInt(0, count);
    int sender1 = Random::GetInstance().GetInt(0, count);
    while(sender0 != sender1) {
      sender1 = Random::GetInstance().GetInt(0, count);
    }

    QVector<TestNode *> nodes;
    Group *group;
    ConstructOverlay(count, nodes, group);

    Id leader_id = nodes[leader]->cm.GetId();
    Id session_id;

    CreateSessions(nodes, *group, leader_id, session_id, callback, cgg);

    Library *lib = CryptoFactory::GetInstance().GetLibrary();
    QScopedPointer<Dissent::Utils::Random> rand(lib->GetRandomNumberGenerator());

    QByteArray msg(512, 0);
    rand->GenerateBlock(msg);
    nodes[sender0]->session->Send(msg);

    SignalCounter sc;
    for(int idx = 0; idx < count; idx++) {
      QObject::connect(&nodes[idx]->sink, SIGNAL(DataReceived()), &sc, SLOT(Counter()));
      nodes[idx]->session->Start();
    }

    TestNode::calledback = 0;
    qint64 next = Timer::GetInstance().VirtualRun();
    while(next != -1 && sc.GetCount() < count && TestNode::calledback < count) {
      Time::GetInstance().IncrementVirtualClock(next);
      next = Timer::GetInstance().VirtualRun();
    }

    sc.Reset();

    for(int idx = 0; idx < count; idx++) {
      EXPECT_EQ(msg, nodes[idx]->sink.Last().first);
    }

    rand->GenerateBlock(msg);
    nodes[sender1]->session->Send(msg);

    TestNode::calledback = 0;
    next = Timer::GetInstance().VirtualRun();
    while(next != -1 && sc.GetCount() < count && TestNode::calledback < count * 2) {
      Time::GetInstance().IncrementVirtualClock(next);
      next = Timer::GetInstance().VirtualRun();
    }

    for(int idx = 0; idx < count; idx++) {
      EXPECT_EQ(msg, nodes[idx]->sink.Last().first);
    }

    CleanUp(nodes);
    delete group;
  }
Пример #21
0
Counter CSSPrimitiveValue::getCounterValue(  )
{
    if(!impl) return Counter();
    return ((CSSPrimitiveValueImpl *)impl)->getCounterValue(  );
}
Пример #22
0
void
UdpReceiver::operator()()
{
    ssize_t no_of_bytes;

    /* create the socket */
    _sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (_sock < 0) {
        _logger->log("Opening socket error on port " +
                     std::to_string(_server.sin_port));
        exit(1);
    }
    
    /* bind port to the IP */
    if(bind(_sock, (struct sockaddr *)&_server, sizeof(_server))<0) {
        _logger->log("Bind socket error on port " +
                     std::to_string(_server.sin_port));
        exit(1);
    }

    char server_ip[20];
    inet_ntop(AF_INET, &(_server.sin_addr), &server_ip[0], INET_ADDRSTRLEN);
    std::string server_ip_str(server_ip);
    _logger->log("UDP Receiver ready. Listening on IP=" + server_ip_str +
                 ", Port=" + std::to_string(_server.sin_port));

    /* continuously listen on the specified port */
    while (true) {
        no_of_bytes = recvfrom(_sock, _request->buf, PACKET_SIZE, 0,
                     (struct sockaddr *)&_request->from, &_request->fromlen);
        if(no_of_bytes < 0) {
            _recvfrom_error++;
            // TODO ABBAS --- supress this later
            _logger->log("Error: recvfrom no_of_bytes < 0");
        }
        else {
            // Increment valid pkts counter
            _total_pkts_received++;
            _messages.increment(1, no_of_bytes);

            // TODO ABBAS --- supress this later
            if (_total_pkts_received % 1000 == 0) {
                _logger->log("Count = " + std::to_string(_total_pkts_received));
            }

            // Extract the subscription id
            // first four bytes is subscription id
            id_idx_t *pIntid = (id_idx_t *)_request->buf;
            id_idx_t int_id = ntohl(*pIntid);

            // Per int_id counter
            if (_stats_topics.count(int_id) == 0) {
                _stats_topics[int_id] = Counter(std::to_string(int_id));
            }
            _stats_topics[int_id].increment(1, no_of_bytes-sizeof(id_idx_t));

            // std::cout << "Int id = " << int_id << std::endl;
            std::lock_guard<std::mutex> guard(_udpreceiver_mutex);

            // Find the external id vector list
            Int_Ext_List_DB::iterator itr = _int_to_ext_list_store.find(int_id);
            std::vector<int> *v;

            // Did we find it ?
            if (itr != _int_to_ext_list_store.end()) {
                v = itr->second;
            } else {
                // std::cout << "Error ... missing internal id mapping to "
                //           << "external id mapping: " << n << std::endl;
                _int_to_ext_list_not_found++;
                continue;
            }

            // Iterate through the external id vector list
            for (auto &ext_id : *v) {
                Ext_id_Worker_DB::iterator itr = _ext_id_worker_store.find(ext_id);
                AgentSubscriptionUdpWorker *wp;
                // Did we find it ?
                if (itr != _ext_id_worker_store.end()) {
                    wp = itr->second;
                } else {
                    // std::cout << "Error cannot find worker for "
                    //           << ext_id << std::endl;
                    _worker_not_found++;
                    continue;
                }
                {
                    std::unique_lock<std::mutex> l(wp->_m);
                    std::vector<unsigned char> vec(_request->buf+sizeof(id_idx_t),
                                                   _request->buf+no_of_bytes);
                    wp->_q.push(vec);
                    l.unlock();
                    wp->_c.notify_one();
                }
            }
        }
    
    }
}
Пример #23
0
void
Clock::Set(bigtime_t time_to)
{
	startTime = Counter() - time_to;
}
Пример #24
0
bigtime_t
Clock::CounterTime()
{
    return Counter() - startTime;
}
Пример #25
0
		///\return seconds 
		static double S(void) { return Counter() * (1.0 / Freq()); }
Пример #26
0
int main(void)
{
	Counter(10);
	return 0;
}
Пример #27
0
int CFTFace::GetCounter()
{
    return Counter();
}
Пример #28
0
int CachingReader::read(int sample, int num_samples, CSAMPLE* buffer) {
    // Check for bad inputs
    if (sample % 2 != 0 || num_samples < 0 || !buffer) {
        QString temp = QString("Sample = %1").arg(sample);
        qDebug() << "CachingReader::read() invalid arguments sample:" << sample
                 << "num_samples:" << num_samples << "buffer:" << buffer;
        return 0;
    }

    // If asked to read 0 samples, don't do anything. (this is a perfectly
    // reasonable request that happens sometimes. If no track is loaded, don't
    // do anything.
    if (num_samples == 0 || m_readerStatus != TRACK_LOADED) {
        return 0;
    }

    // Process messages from the reader thread.
    process();

    // TODO: is it possible to move this code out of caching reader
    // and into enginebuffer?  It doesn't quite make sense here, although
    // it makes preroll completely transparent to the rest of the code

    //if we're in preroll...
    int zerosWritten = 0;
    if (sample < 0) {
        if (sample + num_samples <= 0) {
            //everything is zeros, easy
            memset(buffer, 0, sizeof(*buffer) * num_samples);
            return num_samples;
        } else {
            //some of the buffer is zeros, some is from the file
            memset(buffer, 0, sizeof(*buffer) * (0 - sample));
            buffer += (0 - sample);
            num_samples = sample + num_samples;
            zerosWritten = (0 - sample);
            sample = 0;
            //continue processing the rest of the chunks normally
        }
    }

    int start_sample = math_min(m_iTrackNumSamplesCallbackSafe,
                                sample);
    int start_chunk = chunkForSample(start_sample);
    int end_sample = math_min(m_iTrackNumSamplesCallbackSafe,
                              sample + num_samples - 1);
    int end_chunk = chunkForSample(end_sample);

    int samples_remaining = num_samples;
    int current_sample = sample;

    // Sanity checks
    if (start_chunk > end_chunk) {
        qDebug() << "CachingReader::read() bad chunk range to read ["
                 << start_chunk << end_chunk << "]";
        return 0;
    }

    for (int chunk_num = start_chunk; chunk_num <= end_chunk; chunk_num++) {
        Chunk* current = lookupChunk(chunk_num);

        // If the chunk is not in cache, then we must return an error.
        if (current == NULL) {
            // qDebug() << "Couldn't get chunk " << chunk_num
            //          << " in read() of [" << sample << "," << sample + num_samples
            //          << "] chunks " << start_chunk << "-" << end_chunk;

            // Something is wrong. Break out of the loop, that should fill the
            // samples requested with zeroes.
            Counter("CachingReader::read cache miss")++;
            break;
        }

        int chunk_start_sample = CachingReaderWorker::sampleForChunk(chunk_num);
        int chunk_offset = current_sample - chunk_start_sample;
        int chunk_remaining_samples = current->length - chunk_offset;

        // More sanity checks
        if (current_sample < chunk_start_sample || current_sample % 2 != 0) {
            qDebug() << "CachingReader::read() bad chunk parameters"
                     << "chunk_start_sample" << chunk_start_sample
                     << "current_sample" << current_sample;
            break;
        }

        // If we're past the start_chunk then current_sample should be
        // chunk_start_sample.
        if (start_chunk != chunk_num && chunk_start_sample != current_sample) {
            qDebug() << "CachingReader::read() bad chunk parameters"
                     << "chunk_num" << chunk_num
                     << "start_chunk" << start_chunk
                     << "chunk_start_sample" << chunk_start_sample
                     << "current_sample" << current_sample;
            break;
        }

        if (samples_remaining < 0) {
            qDebug() << "CachingReader::read() bad samples remaining"
                     << samples_remaining;
            break;
        }

        // It is completely possible that chunk_remaining_samples is less than
        // zero. If the caller is trying to read from beyond the end of the
        // file, then this can happen. We should tolerate it.
        int samples_to_read = math_max(0, math_min(samples_remaining,
                                       chunk_remaining_samples));

        // If we did not decide to read any samples from this chunk then that
        // means we have exhausted all the samples in the song.
        if (samples_to_read == 0) {
            break;
        }

        // samples_to_read should be non-negative and even
        if (samples_to_read < 0 || samples_to_read % 2 != 0) {
            qDebug() << "CachingReader::read() samples_to_read invalid"
                     << samples_to_read;
            break;
        }

        // TODO(rryan) do a test and see if using memcpy is faster than gcc
        // optimizing the for loop
        CSAMPLE *data = current->data + chunk_offset;
        memcpy(buffer, data, sizeof(*buffer) * samples_to_read);
        // for (int i=0; i < samples_to_read; i++) {
        //     buffer[i] = data[i];
        // }

        buffer += samples_to_read;
        current_sample += samples_to_read;
        samples_remaining -= samples_to_read;
    }

    // If we didn't supply all the samples requested, that probably means we're
    // at the end of the file, or something is wrong. Provide zeroes and pretend
    // all is well. The caller can't be bothered to check how long the file is.
    // TODO(XXX) memset
    for (int i=0; i<samples_remaining; i++) {
        buffer[i] = 0.0f;
    }
    samples_remaining = 0;

    if (samples_remaining != 0) {
        qDebug() << "CachingReader::read() did read all requested samples.";
    }
    return zerosWritten + num_samples - samples_remaining;
}
Пример #29
0
		///\return nanoseconds (10^-9)
		static double Ns(void) { return Counter() * (1000000000.0 / Freq()); }
Пример #30
0
int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutInitWindowPosition(100,100);
	glutCreateWindow("OGLplus+GLUT+GLEW");

	if(glewInit() == GLEW_OK) try
	{
		glGetError();
		namespace se = oglplus::smart_enums;
		oglplus::Context gl;
		oglplus::AMD_performance_monitor apm;

		const char* f1[2] = {"  +--", "  `--"};
		const char* f2[2] = {"  |", "   "};
		const char* f3[2] = {"  +--", "  `--"};
		const char* f4[2] = {"  |", ""};

		auto groups = apm.GetGroups();
		auto gi=groups.begin(), ge=groups.end();

		std::cout << "--+-{Performance monitor groups}" << std::endl;
		if(gi != ge) std::cout << "  |" << std::endl;

		while(gi != ge)
		{
			auto group = *gi;
			++gi;
			const int fgi = (gi == ge)?1:0;

			std::cout << f1[fgi] << "+-[";
			std::cout << group.GetString();
			std::cout << "]" << std::endl;
			std::cout << f2[fgi] << f4[0] << std::endl;

			GLint max;
			auto counters = group.GetCounters(max);
			auto ci=counters.begin(), ce=counters.end();

			while(ci != ce)
			{
				auto counter = *ci;
				++ci;
				const int fci = (ci == ce)?1:0;
				std::cout << f2[fgi] << f3[fci] << "(";
				std::cout << counter.GetString();
				std::cout << ") [";
				std::cout << EnumValueName(counter.Type());
				std::cout << "]" << std::endl;
				std::cout << f2[fgi] << f4[fci] << std::endl;
			}
			if(fgi != 0)
			{
				oglplus::PerfMonitorAMD mon;
				mon.SelectCounters(true, counters);
				mon.Begin();
				// Imagine some heavy duty rendering here
				gl.Clear().ColorBuffer();
				mon.End();

				if(mon.ResultAvailable())
				{
					std::vector<oglplus::PerfMonitorAMDResult>
						values;
					mon.Result(values);

					auto ri=values.begin(), re=values.end();
					while(ri != re)
					{
						auto counter = ri->Counter();
						auto type = counter.Type();

						std::cout << counter.GetString();
						std::cout << " [";
						std::cout << EnumValueName(type);
						std::cout << "] = ";
						if(type == se::UnsignedInt())
							std::cout << ri->Low();
						else if(type == se::Float())
							std::cout << ri->Float();
						else if(type == se::Percentage())
							std::cout << ri->Float() << "%";
						else if(type == se::UnsignedInt64())
							std::cout << "too big";
						std::cout << std::endl;
						++ri;
					}
				}
			}
		}
		return 0;
	}
	catch(oglplus::Error& err)
	{
		std::cerr
			<< "Error (in "
			<< err.GLFunc()
			<< "'): "
			<< err.what()
			<< " ["
			<< err.SourceFile()
			<< ":"
			<< err.SourceLine()
			<< "] "
			<< std::endl;
	}
	return 1;
}