//===============================================================================================
// FUNCTION: ReadEpochs
// PURPOSE:  Reads the epochs from the data file.
//
BOOL CABF2ProtocolReader::ReadEpochs()
{
   MEMBERASSERT();

   BOOL bOK = TRUE;

   // Analog Epochs ... one set for each DAC in use.
   if( m_FileInfo.EpochPerDACSection.uBlockIndex )
   {
      ABF_EpochInfoPerDAC Epoch;
      ASSERT( m_FileInfo.EpochPerDACSection.uBytes == sizeof( Epoch ) );
      ASSERT( m_FileInfo.EpochPerDACSection.llNumEntries );
      bOK &= m_pFI->Seek( LONGLONG(m_FileInfo.EpochPerDACSection.uBlockIndex) * ABF_BLOCKSIZE, FILE_BEGIN );
      if( !bOK )
         return FALSE;

      for( long i=0; i<m_FileInfo.EpochPerDACSection.llNumEntries; i++ )
      {
         bOK &= m_pFI->Read( &Epoch, sizeof( Epoch ) );
         ASSERT( Epoch.nEpochType != ABF_EPOCHDISABLED );
         short e = Epoch.nEpochNum;         
         short d = Epoch.nDACNum; 

         m_pFH->nEpochType[d][e]         = Epoch.nEpochType;          
         m_pFH->fEpochInitLevel[d][e]    = Epoch.fEpochInitLevel;     
         m_pFH->fEpochLevelInc[d][e]     = Epoch.fEpochLevelInc;      
         m_pFH->lEpochInitDuration[d][e] = Epoch.lEpochInitDuration;
         m_pFH->lEpochDurationInc[d][e]  = Epoch.lEpochDurationInc;   
         m_pFH->lEpochPulsePeriod[d][e]  = Epoch.lEpochPulsePeriod;   
         m_pFH->lEpochPulseWidth[d][e]   = Epoch.lEpochPulseWidth;    
      }
   }

   // Digital Epochs ... one set only.
   if( m_FileInfo.EpochSection.uBlockIndex )
   {
      ABF_EpochInfo Epoch;
      ASSERT( m_FileInfo.EpochSection.uBytes == sizeof( Epoch ) );
      ASSERT( m_FileInfo.EpochSection.llNumEntries );
      bOK &= m_pFI->Seek( LONGLONG(m_FileInfo.EpochSection.uBlockIndex) * ABF_BLOCKSIZE, FILE_BEGIN );
      if( !bOK )
         return FALSE;

      for( long i=0; i<m_FileInfo.EpochSection.llNumEntries; i++ )
      {
         bOK &= m_pFI->Read( &Epoch, sizeof( Epoch ) );
         short e = Epoch.nEpochNum;         

         m_pFH->nDigitalValue[e]               = Epoch.nDigitalValue;          
         m_pFH->nDigitalTrainValue[e]          = Epoch.nDigitalTrainValue;      
         m_pFH->nAlternateDigitalValue[e]      = Epoch.nAlternateDigitalValue;
         m_pFH->nAlternateDigitalTrainValue[e] = Epoch.nAlternateDigitalTrainValue;   
         m_pFH->bEpochCompression[e]           = Epoch.bEpochCompression;    
      }
   }
   return bOK;
}
STDMETHODIMP_(SIZE) CSubPicAllocatorPresenterImpl::GetVideoSize(bool fCorrectAR)
{
	CSize VideoSize(GetVisibleVideoSize());

	if(fCorrectAR && m_AspectRatio.cx > 0 && m_AspectRatio.cy > 0) {
		VideoSize.cx = (LONGLONG(VideoSize.cy)*LONGLONG(m_AspectRatio.cx))/LONGLONG(m_AspectRatio.cy);
	}

	return(VideoSize);
}
Пример #3
0
double LimitDecimalPlace(double val, size_t decimalPlace)
{
	double factor = pow(10.0, (double)decimalPlace);
	LONGLONG integralPart = LONGLONG(LONGLONG(val) * factor);
	LONGLONG allPart = LONGLONG(val * factor);
	LONGLONG fractionalPart = allPart - integralPart;

	double integral = double(LONGLONG(val));
	double fractional = (fractionalPart / factor);
	return integral + fractional;
}
/****************************************************************************
@function   INSERT_testPhases
@class		C_roboticManipulator
@brief      add some phases for testing the servos 
@return     DWORD error_sum
************/
DWORD C_roboticManipulator::INSERT_testPhases(void)
{
	// add some phases
	LONGLONG addVal = 0;
	LONGLONG phaseInterval = 800 * NS100_1MS;
	int i_phase_max = 11;
	int i_serv_min = 5;
	C_spatialConfiguration new_phase;

	new_phase.phaseInterval.QuadPart = phaseInterval;	
	// set initial phase servos position
	
	//____________________________________________________
	// go 0-180°
	for(int i_phase = 0; i_phase < i_phase_max ; i_phase++)
	{ // phases
		for(int i_serv=i_serv_min; i_serv<SUM_SERVOMOTORS; i_serv++)
		{
			new_phase.serv_fixedPositioning[i_serv] = false;
			new_phase.serv_intervalOne_changed[i_serv] = true;

			addVal = serv[i_serv].intervalOne_max.QuadPart 
				- serv[i_serv].intervalOne_min.QuadPart;
			addVal = LONGLONG( double(addVal) / double(i_phase_max) );

			new_phase.serv_intervalOne[i_serv].QuadPart = 
				serv[i_serv].intervalOne_min.QuadPart 
				+ LONGLONG(i_phase) * addVal;
		}
		PUSHBACK_newPhase(&new_phase); 
	}
	//____________________________________________________
	// and back	(180-0°)
	for(int i_phase = 0; i_phase < i_phase_max ; i_phase++)
	{ // phases
		for(int i_serv=i_serv_min; i_serv<SUM_SERVOMOTORS; i_serv++)
		{
			new_phase.serv_fixedPositioning[i_serv] = false;
			addVal = serv[i_serv].intervalOne_max.QuadPart 
				- serv[i_serv].intervalOne_min.QuadPart;
			addVal = LONGLONG( double(addVal) / double(i_phase_max) );
			new_phase.serv_intervalOne[i_serv].QuadPart = 
				serv[i_serv].intervalOne_max.QuadPart 
				- LONGLONG(i_phase) * addVal;
		}
		PUSHBACK_newPhase(&new_phase); 
	}
	return(FLAWLESS_EXECUTION);
}
static void
InitThresholds()
{
  DWORD timeAdjustment = 0, timeIncrement = 0;
  BOOL timeAdjustmentDisabled;
  GetSystemTimeAdjustment(&timeAdjustment,
                          &timeIncrement,
                          &timeAdjustmentDisabled);

  LOG(("TimeStamp: timeIncrement=%d [100ns]", timeIncrement));

  if (!timeIncrement)
    timeIncrement = kDefaultTimeIncrement;

  // Ceiling to a millisecond
  // Example values: 156001, 210000
  DWORD timeIncrementCeil = timeIncrement;
  // Don't want to round up if already rounded, values will be: 156000, 209999
  timeIncrementCeil -= 1;
  // Convert to ms, values will be: 15, 20
  timeIncrementCeil /= 10000;
  // Round up, values will be: 16, 21
  timeIncrementCeil += 1;
  // Convert back to 100ns, values will be: 160000, 210000
  timeIncrementCeil *= 10000;

  // How many milli-ticks has the interval
  LONGLONG ticksPerGetTickCountResolution =
    (int64_t(timeIncrement) * sFrequencyPerSec) / 10000LL;

  // How many milli-ticks has the interval rounded up
  LONGLONG ticksPerGetTickCountResolutionCeiling =
    (int64_t(timeIncrementCeil) * sFrequencyPerSec) / 10000LL;

  // I observed differences about 2 times of the GTC resolution.  GTC may
  // jump by 32 ms in two steps, therefor use the ceiling value.
  // Having 64 (15.6 or 16 * 4 exactly) is used to avoid false negatives
  // for very short times where QPC and GTC may jitter even more.
  sUnderrunThreshold =
    LONGLONG((-4) * ticksPerGetTickCountResolutionCeiling);

  // QPC should go no further than 2 * GTC resolution.
  sOverrunThreshold =
    LONGLONG((+4) * ticksPerGetTickCountResolution);

  sQPCHardFailureDetectionInterval =
    LONGLONG(kQPCHardFailureDetectionInterval) * sFrequencyPerSec;
}
Пример #6
0
GLB_FORCEINLINE void Timer::getCorrectPerformanceValue (int64& nPerfCountElapsed) const
{
  uint32 uiTicksElapsed;
  uint32 uiPerfCountElapsedMilli;
  int32  nLeapTest;

  // get performance counter value
  this->getPerformanceCount(nPerfCountElapsed, uiTicksElapsed);

  // prepare a workaround to compensate a potential performance counter leap
  nPerfCountElapsed       -= m_nStart;
  uiPerfCountElapsedMilli  = uint32(nPerfCountElapsed * 1000 / m_nFrequency);

  GLB_ASSERT((nPerfCountElapsed * 1000 / m_nFrequency) <= (LONGLONG)std::numeric_limits<uint32>::max());
  GLB_ASSERT(uiPerfCountElapsedMilli <= (uint32)std::numeric_limits<int32>::max());
  GLB_ASSERT(uiTicksElapsed          <= (uint32)std::numeric_limits<int32>::max());

  // if too great leap is detected, adjust start time and update state
  // accordingly before return
  nLeapTest = (int32)uiPerfCountElapsedMilli - (int32)uiTicksElapsed;
  if ((nLeapTest < -c_nMaxLeapThreshold) || (nLeapTest > c_nMaxLeapThreshold))
  {
    LONGLONG nUpdate = std::min<LONGLONG>(LONGLONG(nLeapTest * m_nFrequency / 1000), (nPerfCountElapsed - m_nLastPerfCountElapsed));

#ifdef GLB_DEBUG
    //GLB_LOGWARN("Performance Counter leap detected (%d ms) !", nLeapTest);
#endif

    m_nStart          += nUpdate;
    nPerfCountElapsed -= nUpdate;
  }

  // update state
  m_nLastPerfCountElapsed = nPerfCountElapsed;
}
Пример #7
0
// Append to the signal buffer and compute resulting times
void XTime::Signal()
{
	// make room for the new signal
	memmove_s(localStack.signals+1u, sizeof(LARGE_INTEGER) * 255, localStack.signals, sizeof(LARGE_INTEGER) * localStack.numSamples); 
	// append to the front of signals and up the count (no more than the last index tho)
	QueryPerformanceCounter( localStack.signals );
	localStack.signalCount = min( localStack.signalCount+1, 255 );
	// with our signal buffer updated, we can now compute our timing values
	localStack.totalTime = double((*localStack.signals).QuadPart - localStack.start.QuadPart) / double(localStack.frequency.QuadPart);
	localStack.deltaTime = double(localStack.signals[0].QuadPart - localStack.signals[1].QuadPart) / double(localStack.frequency.QuadPart);
	// with our signal buffer updated we can compute our weighted average for a smoother delta curve.
	double totalWeight = 0, runningWeight = 1;
	LONGLONG totalValue = 0, sampleDelta;
	// loop up to num samples or as many as we have available
	for(unsigned char i = 0; i < min(localStack.numSamples, localStack.signalCount-1); ++i)
	{
		// determine each delta as we go
		sampleDelta = localStack.signals[i].QuadPart - localStack.signals[i+1].QuadPart;
		totalValue += LONGLONG(sampleDelta * runningWeight); // this cast is expensive, need to look into optimizing
		totalWeight += runningWeight; // tally all the weights used
		runningWeight *= localStack.blendWeight; // adjust the weight of next delta
	}
	// with our totals calculated, determine the weighted average.
	localStack.smoothDelta = (totalValue / totalWeight) / double(localStack.frequency.QuadPart);
	// done calculating deltas
}
Пример #8
0
/*****************************Private*Routine******************************\
* SeekToPosition
*
\**************************************************************************/
BOOL
CMovie::SeekToPosition(
					   REFTIME rt,
					   BOOL bFlushData
					   )
{
	HRESULT hr;
	LONGLONG llTime = LONGLONG(m_TimeFormat == TIME_FORMAT_MEDIA_TIME ? rt * double(UNITS) : rt );

	if(m_Ms != NULL)
	{
		FILTER_STATE fs;
		hr = m_Mc->GetState(100, (OAFilterState *)&fs);

		hr = m_Ms->SetPositions(&llTime, AM_SEEKING_AbsolutePositioning, NULL, 0);

		// This gets new data through to the renderers
		if(fs == State_Stopped && bFlushData)
		{
			hr = m_Mc->Pause();
			hr = m_Mc->GetState(INFINITE, (OAFilterState *)&fs);
			hr = m_Mc->Stop();
		}

		if(SUCCEEDED(hr))
		{
			return TRUE;
		}
	}

	return FALSE;
}
void DirectShowPlayerService::doSeek(QMutexLocker *locker)
{
    if (IMediaSeeking *seeking = com_cast<IMediaSeeking>(m_graph, IID_IMediaSeeking)) {
        LONGLONG seekPosition = LONGLONG(m_position) * qt_directShowTimeScale;

        // Cache current values as we can't query IMediaSeeking during a seek due to the
        // possibility of a deadlock when flushing the VideoSurfaceFilter.
        LONGLONG currentPosition = 0;
        seeking->GetCurrentPosition(&currentPosition);
        m_position = currentPosition / qt_directShowTimeScale;

        LONGLONG minimum = 0;
        LONGLONG maximum = 0;
        m_playbackRange = SUCCEEDED(seeking->GetAvailable(&minimum, &maximum))
                ? QMediaTimeRange(
                        minimum / qt_directShowTimeScale, maximum / qt_directShowTimeScale)
                : QMediaTimeRange();

        locker->unlock();
        seeking->SetPositions(
                &seekPosition, AM_SEEKING_AbsolutePositioning, 0, AM_SEEKING_NoPositioning);
        locker->relock();

        seeking->GetCurrentPosition(&currentPosition);
        m_position = currentPosition / qt_directShowTimeScale;

        seeking->Release();
    } else {
        m_position = 0;
    }

    QCoreApplication::postEvent(this, new QEvent(QEvent::Type(PositionChange)));
}
Пример #10
0
dLong dNewton::GetTimeInMicrosenconds() const 
{
	#ifdef _MSC_VER
		LARGE_INTEGER count;
		QueryPerformanceCounter (&count);
		count.QuadPart -= m_baseCount;
		dLong ticks = count.QuadPart * LONGLONG (1000000) / m_frequency;
		return ticks;
	#endif
/*
	#if (defined (_POSIX_VER) || defined (_POSIX_VER_64))
		timespec ts;
		clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
		//return unsigned64 (ts.tv_nsec / 1000) - baseCount;
		
		return unsigned64 (ts.tv_sec) * 1000000 + ts.tv_nsec / 1000 - baseCount;
	#endif


	#ifdef _MACOSX_VER
		timeval tp;
		gettimeofday(&tp, NULL);
		unsigned64 microsecunds =  unsigned64 (tp.tv_sec) * 1000000 + tp.tv_usec;
		return microsecunds - baseCount;
	#endif
*/
}
// Accurate sleeping
void DFUEngineBase::AccurateSleep(uint32 milliseconds)
{
	LARGE_INTEGER frequency;

	// Check if a high performance timer is available
	if (QueryPerformanceFrequency(&frequency))
	{
		// Calculate the required end time
		LARGE_INTEGER end;
		QueryPerformanceCounter(&end);
		end.QuadPart += LONGLONG((float) frequency.QuadPart * ((float) milliseconds / 1000.0));

		// Use the simple sleep for the bulk of long delays
		if (accurateMilliseconds < milliseconds)
		{
			Sleep(milliseconds - accurateMilliseconds);
		}

		// Sleep until the time has elapsed
		LARGE_INTEGER now;
		while (QueryPerformanceCounter(&now) && ((now.QuadPart - end.QuadPart) < 0))
		{
			Sleep(0);
		}
	}
	else
	{
		// Use a simple sleep otherwise
		Sleep(milliseconds);
	}
}
//===============================================================================================
// FUNCTION: ReadUserList
// PURPOSE:  Reads the user list from the data file.
//
BOOL CABF2ProtocolReader::ReadUserList()
{
   MEMBERASSERT();

   BOOL bOK = TRUE;
   if( m_FileInfo.UserListSection.uBlockIndex )
   {
      ABF_UserListInfo UserList;
      ASSERT( m_FileInfo.UserListSection.uBytes == sizeof( UserList ) );
      ASSERT( m_FileInfo.UserListSection.llNumEntries );
      bOK &= m_pFI->Seek( LONGLONG(m_FileInfo.UserListSection.uBlockIndex) * ABF_BLOCKSIZE, FILE_BEGIN );
      if( !bOK )
         return FALSE;

      for( long i=0; i<m_FileInfo.UserListSection.llNumEntries; i++ )
      {
         bOK &= m_pFI->Read( &UserList, sizeof( UserList ) );
         short u = UserList.nListNum;         

         m_pFH->nULEnable[u]      = 1;    
         m_pFH->nULParamToVary[u] = UserList.nULParamToVary;           
         m_pFH->nULRepeat[u]      = UserList.nULRepeat; 

         bOK &= GetString( UserList.lULParamValueListIndex, m_pFH->sULParamValueList[u], ABF_USERLISTLEN );
      }
   }
   return bOK;
}
// If the duration is less then one second, perform check of QPC stability
// by comparing both 'epoch' and 'now' skew (=GTC - QPC) values.
bool
TimeStampValue::CheckQPC(int64_t aDuration, const TimeStampValue &aOther) const
{
  if (!mHasQPC || !aOther.mHasQPC) // Not both holding QPC
    return false;

  if (sHasStableTSC) // For stable TSC there is no need to check
    return true;

  if (!sUseQPC) // QPC globally disabled
    return false;

  // Treat absolutely for calibration purposes
  aDuration = Abs(aDuration);

  // Check QPC is sane before using it.

  LONGLONG skew1 = mGTC - mQPC;
  LONGLONG skew2 = aOther.mGTC - aOther.mQPC;

  LONGLONG diff = skew1 - skew2;
  LONGLONG overflow;

  if (diff < sUnderrunThreshold)
    overflow = sUnderrunThreshold - diff;
  else if (diff > sOverrunThreshold)
    overflow = diff - sOverrunThreshold;
  else
    return true;

  ULONGLONG trend;
  if (aDuration)
    trend = LONGLONG(overflow * (double(sQPCHardFailureDetectionInterval) / aDuration));
  else
    trend = overflow;

  LOG(("TimeStamp: QPC check after %llums with overflow %1.4fms"
       ", adjusted trend per interval is %1.4fms",
       mt2ms(aDuration),
       mt2ms_f(overflow),
       mt2ms_f(trend)));

  if (trend <= ms2mt(kOverflowLimit)) {
    // We are in the limit, let go.
    return true;
  }

  // QPC deviates, don't use it.
  LOG(("TimeStamp: QPC found highly jittering"));

  if (aDuration < sQPCHardFailureDetectionInterval) {
    // Interval between the two time stamps is very short, consider
    // QPC as unstable and disable it completely.
    sUseQPC = false;
    LOG(("TimeStamp: QPC disabled"));
  }

  return false;
}
//===============================================================================================
// FUNCTION: ReadStats
// PURPOSE:  Reads the Stats regions from the data file.
//
BOOL CABF2ProtocolReader::ReadStats()
{
   MEMBERASSERT();

   BOOL bOK = TRUE;
   if( m_FileInfo.StatsRegionSection.uBlockIndex )
   {
      ABF_StatsRegionInfo Stats;
      ASSERT( m_FileInfo.StatsRegionSection.uBytes == sizeof( Stats ) );
      ASSERT( m_FileInfo.StatsRegionSection.llNumEntries );
      bOK &= m_pFI->Seek( LONGLONG(m_FileInfo.StatsRegionSection.uBlockIndex) * ABF_BLOCKSIZE, FILE_BEGIN );
      if( !bOK )
         return FALSE;

      for( long i=0; i<m_FileInfo.StatsRegionSection.llNumEntries; i++ )
      {
         Stats = ABF_StatsRegionInfo();
         bOK &= m_pFI->Read( &Stats, sizeof( Stats ) );

         short r = Stats.nRegionNum;         
         UINT uBitMask = 0x01 << r;
         m_pFH->nStatsSearchRegionFlags |= uBitMask;

         m_pFH->lStatsMeasurements[r]     = Stats.lStatsMeasurements;    
         m_pFH->lStatsStart[r]            = Stats.lStatsStart;           
         m_pFH->lStatsEnd[r]              = Stats.lStatsEnd;             
         m_pFH->nRiseTopPercentile[r]     = Stats.nRiseTopPercentile;    
         m_pFH->nRiseBottomPercentile[r]  = Stats.nRiseBottomPercentile; 
         m_pFH->nDecayBottomPercentile[r] = Stats.nDecayBottomPercentile;
         m_pFH->nDecayTopPercentile[r]    = Stats.nDecayTopPercentile;   
         m_pFH->nStatsSearchMode[r]       = Stats.nStatsSearchMode; 
         m_pFH->nStatsSearchDAC[r]        = Stats.nStatsSearchDAC; 

         m_pFH->nStatsActiveChannels      = Stats.nStatsActiveChannels;
         m_pFH->nStatsSearchRegionFlags   = Stats.nStatsSearchRegionFlags;
         m_pFH->nStatsSmoothing           = Stats.nStatsSmoothing;
         m_pFH->nStatsSmoothingEnable     = Stats.nStatsSmoothingEnable;
         m_pFH->nStatsBaseline            = Stats.nStatsBaseline;
         m_pFH->nStatsBaselineDAC         = Stats.nStatsBaselineDAC;
         m_pFH->lStatsBaselineStart       = Stats.lStatsBaselineStart;
         m_pFH->lStatsBaselineEnd         = Stats.lStatsBaselineEnd;

         // Some early ABF 2 protocols did not use the "DAC" field, so coerce these.
         if( Stats.nStatsSearchMode >= ABF_EPOCHCOUNT )
         {
            m_pFH->nStatsSearchMode[r] = Stats.nStatsSearchMode % ABF_EPOCHCOUNT;
            m_pFH->nStatsSearchDAC[r]  = Stats.nStatsSearchMode / ABF_EPOCHCOUNT;
         }

         if( Stats.nStatsBaseline >= ABF_EPOCHCOUNT )
         {
            m_pFH->nStatsBaseline    = Stats.nStatsBaseline % ABF_EPOCHCOUNT;
            m_pFH->nStatsBaselineDAC = Stats.nStatsBaseline / ABF_EPOCHCOUNT;
         }
      }
   }
   return bOK;
}
Пример #15
0
REFERENCE_TIME CSyncClock::GetTicks100ns()
{
    LONGLONG i64Ticks100ns;
    if (m_llPerfFrequency != 0) {
        QueryPerformanceCounter((LARGE_INTEGER*)&i64Ticks100ns);
        i64Ticks100ns = LONGLONG((double(i64Ticks100ns) * 10000000) / double(m_llPerfFrequency) + 0.5);
        return (REFERENCE_TIME)i64Ticks100ns;
    }
    return 0;
}
Пример #16
0
static void
InitThresholds()
{
  DWORD timeAdjustment = 0, timeIncrement = 0;
  BOOL timeAdjustmentDisabled;
  GetSystemTimeAdjustment(&timeAdjustment,
                          &timeIncrement,
                          &timeAdjustmentDisabled);

  if (!timeIncrement)
    timeIncrement = kDefaultTimeIncrement;

  // Ceiling to a millisecond
  // Example values: 156001, 210000
  DWORD timeIncrementCeil = timeIncrement;
  // Don't want to round up if already rounded, values will be: 156000, 209999
  timeIncrementCeil -= 1;
  // Convert to ms, values will be: 15, 20
  timeIncrementCeil /= 10000;
  // Round up, values will be: 16, 21
  timeIncrementCeil += 1;
  // Convert back to 100ns, values will be: 160000, 210000
  timeIncrementCeil *= 10000;

  // How many milli-ticks has the interval
  LONGLONG ticksPerGetTickCountResolution =
    (PRInt64(timeIncrement) * sFrequencyPerSec) / 10000LL;

  // How many milli-ticks has the interval rounded up
  LONGLONG ticksPerGetTickCountResolutionCeiling =
    (PRInt64(timeIncrementCeil) * sFrequencyPerSec) / 10000LL;


  // I observed differences about 2 times of the GTC resolution.  GTC may
  // jump by 32 ms in two steps, therefor use the ceiling value.
  sUnderrunThreshold =
    LONGLONG((-2) * ticksPerGetTickCountResolutionCeiling);

  // QPC should go no further then 2 * GTC resolution
  sOverrunThreshold =
    LONGLONG((+2) * ticksPerGetTickCountResolution);
}
/****************************************************************************
@function   IS_reallyTimeToWriteOne
@class		C_roboticManipulator
@brief      
@param[in]	int a_i_serv | on which servo from the array serv we count
@return     bool 
			| if fixedPositioning - always [true]
			| if not fixedPositioning = ramp
				| if the number of tics is greater 
				than counted tic treshold [true]
			| else [false]

************/
bool C_roboticManipulator::IS_reallyTimeToWriteOne(int i_serv)
{
	//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// not ramp - square position change
	if(phase_act->serv_fixedPositioning[i_serv] == true)
	{ 
		return(true);
	}
	//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// ramp - linear position change
	else
	{ 
		
		LONGLONG intervalOne_thisPeriodDiff = 0;
		// the previous phase has different intervalOne value
		if( serv[i_serv].intervalOne_difference.QuadPart != 0)
		{
			//____________________________________________________
			// evaluate new value of intOne
			intervalOne_thisPeriodDiff = LONGLONG(
					(double)PWMperiod_sum 
					* (double)(serv[i_serv].intervalOne_difference.QuadPart)  
					/ (double)PWMperiod_sum_max
					);
			// (add || subtract) thisPeriodDiff to the previous period intOne
			serv[i_serv].intervalOne_actual.QuadPart = phase_prev->serv_intervalOne[i_serv].QuadPart;

			// intOne is growing -> intOne = previous + thisPeriodDiff
			if( serv[i_serv].intervalOne_growing )
			{						
				serv[i_serv].intervalOne_actual.QuadPart += intervalOne_thisPeriodDiff;
			}
			// intOne is not growing -> intOne = previous - thisPeriodDiff
			else
			{
				serv[i_serv].intervalOne_actual.QuadPart -= intervalOne_thisPeriodDiff;
			}
				
			//____________________________________________________
			// the time for writing 1 has really come - with linear positioning
			if(PWMtic_sum >= (PWMperiod_interval.QuadPart - serv[i_serv].intervalOne_actual.QuadPart))
			{
				// write one to this servo bit
				return(true);
			}
#ifdef DEBUG // debuging breakpoint 
			if( PWMperiod_sum != PWMperiod_sum_last)
			{PWMperiod_sum_last = PWMperiod_sum;}
#endif
		}// end - for all the servos
	} // ramp - linear position change
	// it is not the time
	return(false);
}
int WriteClast1P(DWORD nClast, BYTE *buff)                   //Запись кластера
{
   DWORD nb;
   if(MaxClast < nClast) MaxClast = nClast;                  //Номер самого старшего кластера использованного для записи
   DWORD nSector = Start_SecDir1 + (nClast - 1) * sClSec;    //Номер сектора по номеру кластера
   LONGLONG Poz = LONGLONG(sSecB) * nSector;
   if(SetInFilePointer(Poz) < 0) return -1;                  //Изменение позиции указателя на диске
   if(WriteFile(hDrive, buff, sCl_B, &nb, NULL) == FALSE || nb != sCl_B)
     return ErrorSys1((Lan+175)->msg);                       //"Ошибка при записи кластера."
   return 0;
}
int Save_FAT1(void)                                          //Сохранение обновленной FAT первого раздела
{
   //Возможно лучше менять не всю FAT, а только изменившиеся сектора или один изменившийся кусок FAT (несколько секторов)
   //Контрольное чтение FAT и сравнение с памятью, повторная запись в случае обнаружения несоответсвия
   DWORD nb;
   LONGLONG Poz = LONGLONG(sSecB) * Start_SecFAT1;
   if(SetInFilePointer(Poz) < 0) return -1;                  //Изменение позиции указателя в файле

   if(WriteFile(hDrive, c_FAT1, Size_FAT1, &nb, NULL) == FALSE || nb != Size_FAT1)
      return ErrorSys1((Lan+176)->msg);                      //"Ошибка при записи FAT."
   CopyMemory(FAT1, c_FAT1, Size_FAT1);                      //Скопировали содержимое FAT1
   return 0;
Пример #20
0
LONGLONG CFormProgress::getImageSize( CString strPath )
{
	HANDLE hFile;
	hFile = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

	if( INVALID_HANDLE_VALUE == hFile )
		return FALSE;

	LONGLONG dwFileSize = LONGLONG( GetFileSize( hFile, NULL ) );
	CloseHandle( hFile );
	
	return dwFileSize;
}
Пример #21
0
LONGLONG CRenderersData::GetPerfCounter() const
{
    LARGE_INTEGER i64Ticks100ns;
    LARGE_INTEGER llPerfFrequency;

    QueryPerformanceFrequency(&llPerfFrequency);
    if (llPerfFrequency.QuadPart != 0) {
        QueryPerformanceCounter(&i64Ticks100ns);
        return llMulDiv(i64Ticks100ns.QuadPart, 10000000, llPerfFrequency.QuadPart, 0);
    } else {
        // ms to 100ns units
        return LONGLONG(timeGetTime()) * 10000;
    }
}
Пример #22
0
void CPtrList::Dump(CDumpContext& dc) const
{
	CObject::Dump(dc);

	dc << "with " << LONGLONG(m_nCount) << " elements";
	if (dc.GetDepth() > 0)
	{
		POSITION pos = GetHeadPosition();
		while (pos != NULL)
			dc << "\n\t" << GetNext(pos);
	}

	dc << "\n";
}
Пример #23
0
AsyncPeriodicUpdateThread::AsyncPeriodicUpdateThread( String name,
                                                      AsyncUpdateList* updateList,
                                                      U32 intervalMS )
   : Parent( name, updateList )
{
   mUpdateTimer = CreateWaitableTimer( NULL, FALSE, NULL );

   // This is a bit contrived.  The 'dueTime' is in 100 nanosecond intervals
   // and relative if it is negative.  The period is in milliseconds.

   LARGE_INTEGER deltaTime;
   deltaTime.QuadPart = - LONGLONG( intervalMS * 10 /* micro */ * 1000 /* milli */ );

   SetWaitableTimer( ( HANDLE ) mUpdateTimer, &deltaTime, intervalMS, NULL, NULL, FALSE );
}
Пример #24
0
void VideoCompressor::AddFrame(const Bitmap &Bmp, double TimeInSeconds)
{
    if(_Clock != NULL)
    {
        TimeInSeconds = _Clock->Elapsed();
    }
    _Sample->SetSampleTime( LONGLONG( TimeInSeconds * 10000000.0 ) );
        
    BYTE *BufferData;
    HRESULT hr = _Buffer->Lock(&BufferData, NULL, NULL);
    PersistentAssert(SUCCEEDED(hr), "_Buffer->Lock failed");

    memcpy( BufferData, &(Bmp[0][0]), Bmp.Width() * Bmp.Height() * sizeof(RGBColor) );
    _Buffer->Unlock();

    hr = _Writer->WriteSample(0, _Sample);
    PersistentAssert(SUCCEEDED(hr), "WriteSample failed");
}
Пример #25
0
// Check the current skew is in bounderies and occasionally recalculate it.
// Return true if QPC is OK to use, return false to use GTC only.
//
// Arguments:
// overflow - the calculated overflow out of the bounderies for skew difference
// qpc - current value of QueryPerformanceCounter
// gtc - current value of GetTickCount, more actual according possible system
//       sleep between read of QPC and GTC
static inline bool
CheckCalibration(LONGLONG overflow, ULONGLONG qpc, ULONGLONG gtc)
{
  if (sFallBackToGTC) {
    // We are forbidden to use QPC
    return false;
  }

  ULONGLONG sinceLastCalibration = gtc - sLastCalibrated;

  if (overflow && !sForceRecalibrate) {
    // Calculate trend of the overflow to correspond to the calibration
    // interval, we may get here long after the last calibration because we
    // either didn't read the hi-res function or the system was suspended.
    ULONGLONG trend = LONGLONG(overflow *
      (double(kCalibrationInterval) / sinceLastCalibration));

    LOG(("TimeStamp: calibration after %llus with overflow %1.4fms"
         ", adjusted trend per calibration interval is %1.4fms",
         sinceLastCalibration / 1000,
         mt2ms_d(overflow),
         mt2ms_d(trend)));

    if (trend > ms2mt(kOverflowLimit)) {
      // This sets sFallBackToGTC, we have detected
      // an unreliability of QPC, stop using it.
      RecordFlaw();
      return false;
    }
  }

  if (sinceLastCalibration > kCalibrationInterval || sForceRecalibrate) {
    // Recalculate the skew now
    sSkew = qpc - ms2mt(gtc);
    sLastCalibrated = gtc;
    LOG(("TimeStamp: new skew is %1.2fms (force:%d)",
      mt2ms_d(sSkew), sForceRecalibrate));

    sForceRecalibrate = false;
  }

  return true;
}
Пример #26
0
void CMapWordToPtr::Dump(CDumpContext& dc) const
{
	CObject::Dump(dc);

	dc << "with " << LONGLONG(m_nCount) << " elements";
	if (dc.GetDepth() > 0)
	{
		// Dump in format "[key] -> value"
		WORD key;
		void* val;

		POSITION pos = GetStartPosition();
		while (pos != NULL)
		{
			GetNextAssoc(pos, key, val);
			dc << "\n\t[" << key << "] = " << val;
		}
	}

	dc << "\n";
}
Пример #27
0
static void
InitThresholds()
{
  DWORD timeAdjustment = 0, timeIncrement = 0;
  BOOL timeAdjustmentDisabled;
  GetSystemTimeAdjustment(&timeAdjustment,
                          &timeIncrement,
                          &timeAdjustmentDisabled);

  LOG(("TimeStamp: timeIncrement=%d [100ns]", timeIncrement));

  if (!timeIncrement) {
    timeIncrement = kDefaultTimeIncrement;
  }

  // Ceiling to a millisecond
  // Example values: 156001, 210000
  DWORD timeIncrementCeil = timeIncrement;
  // Don't want to round up if already rounded, values will be: 156000, 209999
  timeIncrementCeil -= 1;
  // Convert to ms, values will be: 15, 20
  timeIncrementCeil /= 10000;
  // Round up, values will be: 16, 21
  timeIncrementCeil += 1;
  // Convert back to 100ns, values will be: 160000, 210000
  timeIncrementCeil *= 10000;

  // How many milli-ticks has the interval rounded up
  LONGLONG ticksPerGetTickCountResolutionCeiling =
    (int64_t(timeIncrementCeil) * sFrequencyPerSec) / 10000LL;

  // GTC may jump by 32 (2*16) ms in two steps, therefor use the ceiling value.
  sGTCResolutionThreshold =
    LONGLONG(kGTCTickLeapTolerance * ticksPerGetTickCountResolutionCeiling);

  sHardFailureLimit = ms2mt(kHardFailureLimit);
  sFailureFreeInterval = ms2mt(kFailureFreeInterval);
  sFailureThreshold = ms2mt(kFailureThreshold);
}
//===============================================================================================
// FUNCTION: ReadMathInfo
// PURPOSE:  Read the math channel info to the data file.
// NOTES:    We currently only support one math channel, but the file can support any number.
//
BOOL CABF2ProtocolReader::ReadMathInfo()
{
   MEMBERASSERT();

   BOOL bOK = TRUE;
   if( m_FileInfo.MathSection.uBlockIndex )
   {
      ABF_MathInfo Math;
      ASSERT( m_FileInfo.MathSection.uBytes == sizeof( ABF_MathInfo ) );
      ASSERT( m_FileInfo.MathSection.llNumEntries );
      bOK &= m_pFI->Seek( LONGLONG(m_FileInfo.MathSection.uBlockIndex) * ABF_BLOCKSIZE, FILE_BEGIN );
      if( !bOK )
         return FALSE;

      bOK &= m_pFI->Read( &Math, sizeof( Math ) );

      m_pFH->nArithmeticEnable     = Math.nMathEnable;
      m_pFH->nArithmeticExpression = Math.nMathExpression;   
      m_pFH->fArithmeticUpperLimit = Math.fMathUpperLimit;   
      m_pFH->fArithmeticLowerLimit = Math.fMathLowerLimit; 

      m_pFH->nArithmeticADCNumA    = Math.nMathADCNum[0];   
      m_pFH->nArithmeticADCNumB    = Math.nMathADCNum[1];   

      m_pFH->fArithmeticK1         = Math.fMathK[0];     
      m_pFH->fArithmeticK2         = Math.fMathK[1];     
      m_pFH->fArithmeticK3         = Math.fMathK[2];     
      m_pFH->fArithmeticK4         = Math.fMathK[3];     
      m_pFH->fArithmeticK5         = Math.fMathK[4];     
      m_pFH->fArithmeticK6         = Math.fMathK[5];    

      GetString( Math.uMathOperatorIndex, m_pFH->sArithmeticOperator, sizeof( m_pFH->sArithmeticOperator ) );
      GetString( Math.uMathUnitsIndex, m_pFH->sArithmeticUnits, sizeof( m_pFH->sArithmeticUnits ) );
   }

   return bOK;
}
Пример #29
0
void Context::NotifyVideoFrame(
    StreamVideo* pVideo,
    StreamVideo::VideoFrame* pFrame)
{
    pVideo;
    assert(pVideo);
    assert(pVideo == m_pVideo);
    assert(pFrame);
    assert(m_file.GetStream());  //TODO

    StreamVideo::frames_t& vframes = pVideo->GetFrames();
    assert(!vframes.empty());
    assert(vframes.back() == pFrame);

    const ULONG vt = pFrame->GetTimecode();

    StreamVideo::frames_t& rframes = m_pVideo->GetKeyFrames();

    if (rframes.empty())
    {
        rframes.push_back(pFrame);
        return;
    }

    if (pFrame->IsKey())
        rframes.push_back(pFrame);
    else
    {
        const StreamVideo::VideoFrame* const pvf0 = rframes.back();
        assert(pvf0);

        const ULONG vt0 = pvf0->GetTimecode();
        assert(vt >= vt0);

        const LONGLONG dt = LONGLONG(vt) - LONGLONG(vt0);
        assert(dt >= 0);

        const LONGLONG scale = GetTimecodeScale();
        assert(scale >= 1);

        const LONGLONG ns = scale * dt;

        //TODO: allow this to be parameterized
        if (ns <= 1000000000)  //1 sec
            return;

        rframes.push_back(pFrame);
    }

    //At this point, we have at least 2 rframes, which means
    //at least one cluster is potentially available to be written
    //to the file.  (Here the constraints that the video stream
    //needs to satisfy have been satisified.  We might still have
    //to wait for the audio stream to satisfy its constraints.)

    if ((m_pAudio == 0) || m_bEOSAudio)
    {
        CreateNewCluster(pFrame);
        return;
    }

    const StreamAudio::frames_t& aframes = m_pAudio->GetFrames();

    if (aframes.empty())
        return;

    const StreamAudio::AudioFrame* const paf = aframes.back();
    assert(paf);

    const ULONG at = paf->GetTimecode();

    if (at < vt)
        return;

    CreateNewCluster(pFrame);
}
Пример #30
0
DWORD addFileToListView (HWND hDlg, WIN32_FIND_DATA* findData, UINT itemId, LVITEM* lvI)
{
	SYSTEMTIME stUTC; 
	SYSTEMTIME stLocal;
	TCHAR str1 [MAX_PATH];
	TCHAR* tmpStr1;
	
	if (lstrcmp(findData->cFileName, L".") == 0)
	{
		return FM_AFTLV_NO;
	}

	// Занести данные из findData
	lvI->lParam = (LPARAM) fmLocalAlloc (sizeof(WIN32_FIND_DATA));
	CopyMemory ((VOID*)lvI->lParam, (const VOID*) findData, sizeof (WIN32_FIND_DATA));
	
	// Создать новую строку
	lvI->iSubItem = 0;
	lvI->pszText[0] = L'\0';
	lvI->mask = LVIF_PARAM;
	SendDlgItemMessage (hDlg, itemId, LVM_INSERTITEM, (WPARAM)0, (LPARAM)lvI);
	
	
	lvI->mask = LVIF_TEXT;
	// Файл или папка
	if (findData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{	
		// если папка
		lvI->iSubItem = FM_COLUMN_NAME;
		lstrcpy (lvI->pszText, findData->cFileName);
		SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
		
		lvI->iSubItem = FM_COLUMN_TYPE;
		lstrcpy (lvI->pszText, FM_DIRTYPE_STUB);
		SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
	}
	else 
	{	
		// Если файл, то тип файла
		lvI->iSubItem = FM_COLUMN_TYPE;
		tmpStr1 = lstrrchr (findData->cFileName, L'.');
		if (tmpStr1 != NULL)
		{
			++ tmpStr1;
			lstrcpy (lvI->pszText, tmpStr1);
			SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
		}
		
		// имя файла
		lvI->iSubItem = FM_COLUMN_NAME;
		lstrcpy (lvI->pszText, findData->cFileName);
		lcutrchr (lvI->pszText, L'.');
		SendDlgItemMessage(hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);

		// размер файла
		UINT64 fs = findData->nFileSizeLow | (UINT64(findData->nFileSizeHigh) << 32);
		StrFormatByteSize (LONGLONG(fs), str1, sizeof (str1) / sizeof (str1[0]));
		lvI->iSubItem = FM_COLUMN_SIZE;
		lstrcpy (lvI->pszText, str1);
		SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)lvI->iItem, (LPARAM)lvI);
	}

	// Дата файла или папки
	lvI->iSubItem = FM_COLUMN_DATE;
	FileTimeToSystemTime(&findData->ftLastWriteTime, &stUTC);
	SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
	wsprintf(str1, L"%02u-%02u-%02u %02u:%02u", stLocal.wYear, stLocal.wMonth,
		stLocal.wDay, stLocal.wHour, stLocal.wMinute);
	lstrcpy (lvI->pszText, str1);
	SendDlgItemMessage (hDlg, itemId, LVM_SETITEM, (WPARAM)0, (LPARAM)lvI);
	
	return FM_AFTLV_OK;
}