bool LaunchGreenShieldConfig::IsEnableLaunchNow() const
{
	assert(this->Valid());
	if(!this->Valid()) {
		return false;
	}
	if(this->GetMaxCntPerDay() == 0) {
		return false;
	}

	__time64_t nLastLaunchTime = this->GetLastPull();
	__time64_t nCurrentTime = 0;
	_time64(&nCurrentTime);

	if(this->IsNoRemind() && _abs64(nCurrentTime - nLastLaunchTime) / (3600 * 24) < this->GetNoRemindSpanDay()) {
		return false;
	}
	if(_abs64(nCurrentTime - nLastLaunchTime) / 3600 < this->GetLaunchInterval()) {
		return false;
	}
	if(this->GetCnt() >= this->GetMaxCntPerDay()) {
		const tm* curentTime = _gmtime64(&nCurrentTime);
		int cur_year = curentTime->tm_year;
		int cur_yday = curentTime->tm_yday;
		const tm* lastLaunchTime = _gmtime64(&nLastLaunchTime);
		if(cur_year == lastLaunchTime->tm_year && cur_yday == lastLaunchTime->tm_yday) {
			return false;
		}
	}
	return true;
}
/******************************************************************************
    Function Name    :  vProcessNewData
    Input(s)         :
    Output           :
    Functionality    :  Process a new Rx/Tx msg
    Member of        :  CMsgContainerLIN
    Friend of        :      -
    Author(s)        :  Anish kumar
    Date Created     :  01.04.2010
******************************************************************************/
void CMsgContainerLIN::vProcessNewData(STLINDATA& sLinData)
{

    // append : 1. Add item, get count, SetItemCount.
    // OW     : 1. Get ID, Create map index, Search if it is present in map
    //             if present change the offset and time stamp
    //          2. if not present and (get count < max count) save the Buffer index,
    //             ListCtrl index, time stamp, make offest = time stamp in disp entry
    //             and add to the map and array
    //          3. if not present and (get count = max count), do nothing
    //          4. SetItemcount

    if ( IS_A_MESSAGE(sLinData.m_ucDataType) )
    {

        // Add to append buffer
        // If its the very first entry, the time stamp must
        if (m_sLINReadDataSpl.m_lTickCount.QuadPart != 0) // be 0 and will
        {
            // retain such value.
            m_sLINReadDataSpl.m_nDeltime = _abs64(sLinData.m_lTickCount.QuadPart -
                                                  m_sLINReadDataSpl.m_lTickCount.QuadPart);
        }

        STLINDATA* pStlin = &m_sLINReadDataSpl;
        *pStlin = sLinData;
        if (!bTobeBlocked(sLinData))
        {
            m_ouAppendLinBuf.WriteIntoBuffer(&m_sLINReadDataSpl);

            if (NULL != m_pRxMsgCallBack)
            {
                m_pRxMsgCallBack((void*)&sLinData, LIN);
            }
        }
    }
    else //Add the error messages
    {
        vProcessCurrErrorEntryLin(sLinData.m_uDataInfo.m_sErrInfo);
        // Add to append buffer
        // If its the very first entry, the time stamp must
        if (m_sLINReadDataSpl.m_lTickCount.QuadPart != 0) // be 0 and will
        {
            // retain such value.
            m_sLINReadDataSpl.m_nDeltime = _abs64(sLinData.m_lTickCount.QuadPart -
                                                  m_sLINReadDataSpl.m_lTickCount.QuadPart);
        }
        STLINDATA* pStlin = &m_sLINReadDataSpl;
        *pStlin = sLinData;
        m_ouAppendLinBuf.WriteIntoBuffer(&m_sLINReadDataSpl);

        if (NULL != m_pRxMsgCallBack)
        {
            m_pRxMsgCallBack((void*)&sLinData, LIN);
        }
    }

}
/******************************************************************************
    Function Name    :  vProcessNewData
    Input(s)         :  sJ1939Msg
    Output           :
    Functionality    :  Process a new Rx/Tx msg
    Member of        :  CMsgContainerJ1939
    Friend of        :      -
    Author(s)        :  Arun kumar K
    Date Created     :  31.01.2010
******************************************************************************/
void CMsgContainerJ1939::vProcessNewData(STJ1939_MSG& sJ1939Msg)
{

    // append : 1. Add item, get count, SetItemCount.
    // OW     : 1. Get ID, Create map index, Search if it is present in map
    //             if present change the offset and time stamp
    //          2. if not present and (get count < max count) save the Buffer index,
    //             ListCtrl index, time stamp, make offest = time stamp in disp entry
    //             and add to the map and array
    //          3. if not present and (get count = max count), do nothing
    //          4. SetItemcount

    if ( !bIsErrorMsg(sJ1939Msg.m_sMsgProperties.m_eType)  )
    {

        // Add to append buffer
        // If its the very first entry, the time stamp must
        if (m_sJ1939ReadMsgSpl.m_sMsgProperties.m_un64TimeStamp != 0) // be 0 and will
        {
            // retain such value.
            m_sJ1939ReadMsgSpl.m_nDeltime = _abs64( sJ1939Msg.m_sMsgProperties.m_un64TimeStamp -
                                                    m_sJ1939ReadMsgSpl.m_sMsgProperties.m_un64TimeStamp);
        }
        static BYTE arrBuf[MAX_MSG_LEN_J1939 + sizeof(__int64)];

        if (!bTobeBlocked(sJ1939Msg))
        {
            sJ1939Msg.vGetDataStream(arrBuf);
            m_sJ1939ReadMsgSpl.vSetDataStream(arrBuf);
            m_sJ1939ReadMsgSpl.vGetDataStream(arrBuf);
            m_ouAppendJ1939Buf.WriteIntoBuffer(J1939, arrBuf/*(BYTE*)&m_sJ1939ReadMsgSpl*/, m_sJ1939ReadMsgSpl.nGetSize());

            if (nullptr != m_pRxMsgCallBack)
            {
                m_pRxMsgCallBack->onRxMsg((void*)&sJ1939Msg);
            }
        }
    }
    //else //Add the error messages
    //{
    //    vProcessCurrErrorEntry(sCanData.m_uDataInfo.m_sErrInfo);
    //    // Add to append buffer
    //    // If its the very first entry, the time stamp must
    //    if (m_sCANReadDataSpl.m_lTickCount.QuadPart != 0) // be 0 and will
    //    {                                                     // retain such value.
    //        m_sCANReadDataSpl.m_nDeltime = sCanData.m_lTickCount.QuadPart -
    //                                       m_sCANReadDataSpl.m_lTickCount.QuadPart;
    //    }
    //    STCANDATA *pStcan = &m_sCANReadDataSpl;
    //    *pStcan = sCanData;
    //    m_ouAppendCanBuf.WriteIntoBuffer(&m_sCANReadDataSpl);

    //    if (nullptr != m_pRxMsgCallBack)
    //    {
    //        m_pRxMsgCallBack((void*)&sCanData, CAN);
    //    }
    //}
}
Example #4
0
MediaOutputInfo* GetBestMediaOutput(const List<MediaOutputInfo> &outputList, UINT width, UINT height, UINT preferredType, UINT64 &frameInterval)
{
    MediaOutputInfo *bestMediaOutput = NULL;
    int bestPriority = -1;
    UINT64 closestIntervalDifference = 0xFFFFFFFFFFFFFFFFLL;
    UINT64 bestFrameInterval = 0;

    bool bUsePreferredType = preferredType != -1;

    for(UINT i=0; i<outputList.Num(); i++)
    {
        MediaOutputInfo &outputInfo = outputList[i];
        VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(outputInfo.mediaType->pbFormat);

        if( outputInfo.minCX <= width  && outputInfo.maxCX >= width &&
            outputInfo.minCY <= height && outputInfo.maxCY >= height)
        {
            int priority = inputPriority[(UINT)outputInfo.videoType];
            if(priority == -1)
                continue;

            if( (!bUsePreferredType && (priority >= bestPriority || !bestMediaOutput)) ||
                (bUsePreferredType && (UINT)outputInfo.videoType == preferredType))
            {
                UINT64 curInterval;
                if(frameInterval > outputInfo.maxFrameInterval)
                    curInterval = outputInfo.maxFrameInterval;
                else if(frameInterval < outputInfo.minFrameInterval)
                    curInterval = outputInfo.minFrameInterval;
                else
                    curInterval = frameInterval;

                UINT64 intervalDifference = (UINT64)_abs64(INT64(curInterval)-INT64(frameInterval));

                if(intervalDifference < closestIntervalDifference)
                {
                    closestIntervalDifference = intervalDifference;
                    bestFrameInterval = curInterval;
                    bestMediaOutput = &outputInfo;
                    bestPriority = priority;
                }
            }
        }
    }

    frameInterval = bestFrameInterval;
    return bestMediaOutput;
}
Example #5
0
/**
 * @brief Compare two specified files, byte-by-byte
 * @param [in] compMethod Compare method used.
 * @param [in] di Diffitem info.
 * @return DIFFCODE
 */
int TimeSizeCompare::CompareFiles(int compMethod, const DIFFITEM &di)
{
	UINT code = DIFFCODE::SAME;
	if ((compMethod == CMP_DATE) || (compMethod == CMP_DATE_SIZE))
	{
		// Compare by modified date
		// Check that we have both filetimes
		if (di.left.mtime != 0 && di.right.mtime != 0)
		{
			INT64 nTimeDiff =_abs64(di.left.mtime - di.right.mtime);
			if (m_ignoreSmallDiff)
			{
				// If option to ignore small timediffs (couple of seconds)
				// is set, decrease absolute difference by allowed diff
				nTimeDiff -= SmallTimeDiff;
			}
			if (nTimeDiff <= 0)
				code = DIFFCODE::SAME;
			else
				code = DIFFCODE::DIFF;
		}
		else
		{
			// Filetimes for item(s) could not be read. So we have to
			// set error status, unless we have DATE_SIZE -compare
			// when we have still hope for size compare..
			if (compMethod == CMP_DATE_SIZE)
				code = DIFFCODE::SAME;
			else
				code = DIFFCODE::CMPERR;
		}
	}
	// This is actual CMP_SIZE method..
	// If file sizes differ mark them different
	if ((compMethod == CMP_DATE_SIZE) || (compMethod == CMP_SIZE))
	{
		if (di.left.size != di.right.size)
		{
			code &= ~DIFFCODE::SAME;
			code = DIFFCODE::DIFF;
		}
	}
	return code;
}
Example #6
0
static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_abs_longlong(PY_LONG_LONG x) {
    if (unlikely(x == -PY_LLONG_MAX-1))
        return ((unsigned PY_LONG_LONG)PY_LLONG_MAX) + 1U;
#if defined (__cplusplus) && __cplusplus >= 201103L
    return (unsigned PY_LONG_LONG) std::abs(x);
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    return (unsigned PY_LONG_LONG) llabs(x);
#elif defined (_MSC_VER) && defined (_M_X64)
    // abs() is defined for long, but 64-bits type on MSVC is long long.
    // Use MS-specific _abs64 instead.
    return (unsigned PY_LONG_LONG) _abs64(x);
#elif defined (__GNUC__)
    // gcc or clang on 64 bit windows.
    return (unsigned PY_LONG_LONG) __builtin_llabs(x);
#else
    if (sizeof(PY_LONG_LONG) <= sizeof(Py_ssize_t))
        return __Pyx_sst_abs(x);
    return (x<0) ? (unsigned PY_LONG_LONG)-x : (unsigned PY_LONG_LONG)x;
#endif
}
void CVolumeFunction::SeVolume()
{
    while(m_bRun)
    {
        m_lock.Lock();
        tagVolumeConf stVolumeConf = m_stVolumeConf;
        m_lock.UnLock();
        if(stVolumeConf.vecVolume.size() <= 0)
        {
            Sleep(5*1000);
            continue;;
        }

        for (vector<tagVolumeConf::_st_Volume>::iterator iter = stVolumeConf.vecVolume.begin();
                iter != stVolumeConf.vecVolume.end();
                iter++)
        {
            string strTime = "";

            time_t tn = time(0);
            string strDateNow = CBase::time2string_date(tn);
            string strTimeNow = CBase::time2string_time(tn);

            strTime = strDateNow;
            strTime += " ";
            strTime += iter->strTime;
            strTime += ":00";

            time_t tc = CBase::string2time(strTime);

            if( _abs64(tn - tc) <= 60)
            {
                CVolumeManager::GetInstance()->SetSpeakerLevel(atoi(iter->strVolume.c_str()));
                break;
            }
        }

        Sleep(5*1000);
    }
}
Example #8
0
BOOL Utils::isFileExpired( const LPCTSTR szFile, DWORD dwMaxLiveInDays )
{
	BOOL result = TRUE;//默认是超时的
	HANDLE hFile = ::CreateFile(szFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile!=INVALID_HANDLE_VALUE)
	{
		// get time current file size
		FILETIME ftCreate, ftAccess, ftModify;
		if (::GetFileTime(hFile, &ftCreate, &ftAccess, &ftModify))
		{
			unsigned __int64 qwFileMTime = *((unsigned __int64*)&ftModify);
			unsigned __int64 ftNow;
			GetSystemTimeAsFileTime((LPFILETIME)&ftNow);
			double diff = _abs64(ftNow - qwFileMTime) /10000.0 / 1000.0 / 3600.0 / 24.0;
			if (diff<dwMaxLiveInDays) {
				result = FALSE;
			}
		}
		::CloseHandle(hFile);
	}
	return result;
}
/******************************************************************************
    Function Name    :  vProcessNewData
    Input(s)         :
    Output           :
    Functionality    :  Process a new Rx/Tx msg
    Member of        :  CMsgContainerCAN
    Friend of        :      -
    Author(s)        :  Anish kumar
    Date Created     :  01.04.2010
******************************************************************************/
void CMsgContainerCAN::vProcessNewData(STCANDATA& sCanData)
{

    // append : 1. Add item, get count, SetItemCount.
    // OW     : 1. Get ID, Create map index, Search if it is present in map
    //             if present change the offset and time stamp
    //          2. if not present and (get count < max count) save the Buffer index,
    //             ListCtrl index, time stamp, make offest = time stamp in disp entry
    //             and add to the map and array
    //          3. if not present and (get count = max count), do nothing
    //          4. SetItemcount

    if ( IS_A_MESSAGE(sCanData.m_ucDataType) )
    {

        // Add to append buffer
        // If its the very first entry, the time stamp must
        if (m_sCANReadDataSpl.m_lTickCount.QuadPart != 0) // be 0 and will
        {
            // retain such value.
            m_sCANReadDataSpl.m_nDeltime = _abs64(sCanData.m_lTickCount.QuadPart -
                                                  m_sCANReadDataSpl.m_lTickCount.QuadPart);
        }

        STCANDATA* pStcan = &m_sCANReadDataSpl;
        *pStcan = sCanData;
        if (!bTobeBlocked(sCanData))
        {
            unsigned char FDataType = m_sCANReadDataSpl.m_ucDataType;
            if(IS_RX_MESSAGE(FDataType))
            {
                HRESULT h_Evaluate = EvaluateMessage(m_sCANReadDataSpl.m_uDataInfo.m_sCANMsg);
            }

            m_ouAppendCanBuf.WriteIntoBuffer(&m_sCANReadDataSpl);
            if (nullptr != m_pRxMsgCallBack)
            {
                m_pRxMsgCallBack->onRxMsg((void*)&sCanData);
            }
        }
    }
    else //Add the error messages
    {
        vProcessCurrErrorEntry(sCanData.m_uDataInfo.m_sErrInfo);
        // Add to append buffer
        // If its the very first entry, the time stamp must
        if (m_sCANReadDataSpl.m_lTickCount.QuadPart != 0) // be 0 and will
        {
            // retain such value.
            m_sCANReadDataSpl.m_nDeltime = _abs64(sCanData.m_lTickCount.QuadPart -
                                                  m_sCANReadDataSpl.m_lTickCount.QuadPart);
        }
        STCANDATA* pStcan = &m_sCANReadDataSpl;
        *pStcan = sCanData;

        if (!bTobeBlocked(sCanData))
        {
            m_ouAppendCanBuf.WriteIntoBuffer(&m_sCANReadDataSpl);
            if (nullptr != m_pRxMsgCallBack)
            {
                m_pRxMsgCallBack->onRxMsg((void*)&sCanData);
            }
        }
    }

}
Example #10
0
		void load_database_t::load_cache(HWND wnd, ipod_device_ptr_ref_t p_ipod, bool b_CheckIfFilesChanged, threaded_process_v2_t & p_status, abort_callback & p_abort)
		{
			pfc::string8 base;
			p_ipod->get_root_path(base);

			metadb_handle_list handlestoread(m_handles);

			pfc::string8 cachePath = base;
			cachePath << "metadata_cache.fpl";

			//We want to hint from main thread to avoid annoyances
			static_api_ptr_t<main_thread_callback_manager> p_main_thread;
			p_status.update_text("Loading metadata cache");
			service_ptr_t<t_main_thread_load_cache_v2_t> p_cache_loader = new service_impl_t<t_main_thread_load_cache_v2_t>
				(base);

			p_cache_loader->callback_run();
			//p_main_thread->add_callback(p_cache_loader);
			if (!p_cache_loader->m_signal.wait_for(-1))
				throw pfc::exception("Cache read timeout!");
			if (!p_cache_loader->m_ret)
				throw pfc::exception(pfc::string8() << "Error reading metadata cache: " << p_cache_loader->m_error);

			p_status.update_text("Checking files for changes");
			//pfc::hires_timer timer2;
			//timer2.start();
			t_size n = handlestoread.get_count(), count = n;
			for (; n; n--)
			{
				if (p_ipod->mobile || !b_CheckIfFilesChanged)
				{
					if (handlestoread[n - 1]->is_info_loaded_async())
						handlestoread.remove_by_idx(n - 1);
					m_tracks[n - 1]->m_runtime_filestats.m_timestamp = filetimestamp_invalid;
					if (m_tracks[n - 1]->original_timestamp_valid)
						m_tracks[n - 1]->m_runtime_filestats.m_timestamp = m_tracks[n - 1]->original_timestamp;
					else if (m_tracks[n - 1]->lastmodifiedtime)
						m_tracks[n - 1]->m_runtime_filestats.m_timestamp = filetime_time_from_appletime(m_tracks[n - 1]->lastmodifiedtime);
					m_tracks[n - 1]->m_runtime_filestats.m_size = m_tracks[n - 1]->size;
				}
				else
				{
					if (true)
					{
						if (n % 20 == 0)
							p_abort.check();
						t_filestats stats = handlestoread[n - 1]->get_filestats();
						const char * path = handlestoread[n - 1]->get_path();
						if (!stricmp_utf8_max(path, "file://", 7))
						{
							path += 7;
							win32::handle_ptr_t p_file =
								CreateFile(pfc::stringcvt::string_os_from_utf8(path), FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
							if (p_file.is_valid())
							{
								t_filestats newstats = filestats_invalid;
								GetFileSizeEx(p_file, (PLARGE_INTEGER)&newstats.m_size);
								GetFileTime(p_file, NULL, NULL, (LPFILETIME)&newstats.m_timestamp);
								m_tracks[n - 1]->m_runtime_filestats = newstats;
								if (handlestoread[n - 1]->is_info_loaded_async())
								{
									t_uint64 hour = 60 * 60;
									hour *= 10000000;
									if (stats.m_size == newstats.m_size && (stats.m_timestamp == newstats.m_timestamp || _abs64(newstats.m_timestamp - stats.m_timestamp) == hour) && newstats.m_size != filesize_invalid && newstats.m_timestamp != filetimestamp_invalid)
										handlestoread.remove_by_idx(n - 1);
								}
							}
						}
					}
				}
				p_status.update_progress_subpart_helper(count - n + 1, count);
			}
			//console::formatter() << "info checked in: " << pfc::format_time_ex(timer2.query(),6);

			if (handlestoread.get_count())
			{
				p_status.update_text("Loading file info");
				//static_api_ptr_t<main_thread_callback_manager> p_main_thread;

				service_ptr_t<t_main_thread_scan_file_info> p_info_loader = new service_impl_t<t_main_thread_scan_file_info>
					(handlestoread, metadb_io::load_info_force, wnd);
				p_main_thread->add_callback(p_info_loader);
				if (!p_info_loader->m_signal.wait_for(-1))
					throw pfc::exception("File info reading timeout!");
				if (p_info_loader->m_ret == metadb_io::load_info_aborted)
					throw pfc::exception("File info read was aborted");
			}

			p_abort.check();

		}
HRESULT CBaseSplitterOutputPin::DeliverPacket(CAutoPtr<Packet> p)
{
	HRESULT hr;

	long nBytes = (long)p->GetCount();

	if (nBytes == 0) {
		return S_OK;
	}

	DWORD nFlag = (static_cast<CBaseSplitterFilter*>(m_pFilter))->GetFlag();

	if (p->rtStart != INVALID_TIME && (nFlag & PACKET_PTS_DISCONTINUITY)) {
		// Filter invalid PTS value (if too different from previous packet)
		if (!IsDiscontinuous() && !((nFlag & PACKET_PTS_VALIDATE_POSITIVE) && p->rtStart < 0)) {
			REFERENCE_TIME rt = p->rtStart + m_rtOffset;
			if (_abs64(rt - m_rtPrev) > MAX_PTS_SHIFT) {
				m_rtOffset += m_rtPrev - rt;
				DbgLog((LOG_TRACE, 3, L"CBaseSplitterOutputPin::DeliverPacket() : Packet discontinuity detected, adjusting offset to %I64d", m_rtOffset));
			}
		}

		p->rtStart	+= m_rtOffset;
		p->rtStop	+= m_rtOffset;

		m_rtPrev	= p->rtStart;
	}

	m_brs.nBytesSinceLastDeliverTime += nBytes;

	if (p->rtStart != INVALID_TIME) {
		if (m_brs.rtLastDeliverTime == INVALID_TIME) {
			m_brs.rtLastDeliverTime = p->rtStart;
			m_brs.nBytesSinceLastDeliverTime = 0;
		}

		if (m_brs.rtLastDeliverTime + 10000000 < p->rtStart) {
			REFERENCE_TIME rtDiff = p->rtStart - m_brs.rtLastDeliverTime;

			double secs, bits;

			secs = (double)rtDiff / 10000000;
			bits = 8.0 * m_brs.nBytesSinceLastDeliverTime;
			m_brs.nCurrentBitRate = (DWORD)(bits / secs);

			m_brs.rtTotalTimeDelivered += rtDiff;
			m_brs.nTotalBytesDelivered += m_brs.nBytesSinceLastDeliverTime;

			secs = (double)m_brs.rtTotalTimeDelivered / 10000000;
			bits = 8.0 * m_brs.nTotalBytesDelivered;
			m_brs.nAverageBitRate = (DWORD)(bits / secs);

			m_brs.rtLastDeliverTime = p->rtStart;
			m_brs.nBytesSinceLastDeliverTime = 0;
			/*
						TRACE(_T("[%d] c: %d kbps, a: %d kbps\n"),
							p->TrackNumber,
							(m_brs.nCurrentBitRate+500)/1000,
							(m_brs.nAverageBitRate+500)/1000);
			*/
		}

		double dRate = 1.0;
		if (SUCCEEDED((static_cast<CBaseSplitterFilter*>(m_pFilter))->GetRate(&dRate))) {
			p->rtStart = (REFERENCE_TIME)((double)p->rtStart / dRate);
			p->rtStop = (REFERENCE_TIME)((double)p->rtStop / dRate);
		}
	}

	do {
		CComPtr<IMediaSample> pSample;
		if (S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) {
			break;
		}

		if (nBytes > pSample->GetSize()) {
			pSample.Release();

			ALLOCATOR_PROPERTIES props, actual;
			if (S_OK != (hr = m_pAllocator->GetProperties(&props))) {
				break;
			}
			props.cbBuffer = nBytes*3/2;

			if (props.cBuffers > 1) {
				if (S_OK != (hr = __super::DeliverBeginFlush())) {
					break;
				}
				if (S_OK != (hr = __super::DeliverEndFlush())) {
					break;
				}
			}

			if (S_OK != (hr = m_pAllocator->Decommit())) {
				break;
			}
			if (S_OK != (hr = m_pAllocator->SetProperties(&props, &actual))) {
				break;
			}
			if (S_OK != (hr = m_pAllocator->Commit())) {
				break;
			}
			if (S_OK != (hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0))) {
				break;
			}
		}

		if (p->pmt) {
			pSample->SetMediaType(p->pmt);
			p->bDiscontinuity = true;

			// CAutoLock cAutoLock(m_pLock); // this can cause the lock
			m_mts.RemoveAll();
			m_mts.Add(*p->pmt);
		}

		bool fTimeValid = p->rtStart != INVALID_TIME;

#if defined(_DEBUG) && 0
		TRACE(_T("[%d]: d%d s%d p%d, b=%d, [%20I64d - %20I64d]\n"),
			  p->TrackNumber,
			  p->bDiscontinuity, p->bSyncPoint, fTimeValid && p->rtStart < 0,
			  nBytes, p->rtStart, p->rtStop);
#endif

		ASSERT(!p->bSyncPoint || fTimeValid);

		BYTE* pData = NULL;
		if (S_OK != (hr = pSample->GetPointer(&pData)) || !pData) {
			break;
		}
		memcpy(pData, p->GetData(), nBytes);
		if (S_OK != (hr = pSample->SetActualDataLength(nBytes))) {
			break;
		}
		if (S_OK != (hr = pSample->SetTime(fTimeValid ? &p->rtStart : NULL, fTimeValid ? &p->rtStop : NULL))) {
			break;
		}
		if (S_OK != (hr = pSample->SetMediaTime(NULL, NULL))) {
			break;
		}
		if (S_OK != (hr = pSample->SetDiscontinuity(p->bDiscontinuity))) {
			break;
		}
		if (S_OK != (hr = pSample->SetSyncPoint(p->bSyncPoint))) {
			break;
		}
		if (S_OK != (hr = pSample->SetPreroll(fTimeValid && p->rtStart < 0))) {
			break;
		}
		if (S_OK != (hr = Deliver(pSample))) {
			break;
		}
	} while (false);

	return hr;
}
Example #12
0
/// <summary>
/// Copy original bytes using LDASM
/// </summary>
/// <param name="pFunc">Original function ptr</param>
/// <param name="OriginalStore">Buffer to store bytes</param>
/// <param name="pSize">Lenght of copied data</param>
/// <returns>Status code</returns>
NTSTATUS PHpCopyCode( IN PVOID pFunc, OUT PUCHAR OriginalStore, OUT PULONG pSize )
{
    // Store original bytes
    PUCHAR src = pFunc;
    PUCHAR old = OriginalStore;
    ULONG all_len = 0;
    ldasm_data ld = { 0 };

    do
    {
        ULONG len = ldasm( src, &ld, TRUE );

        // Determine code end
        if (ld.flags & F_INVALID
            || (len == 1 && (src[ld.opcd_offset] == 0xCC || src[ld.opcd_offset] == 0xC3))
            || (len == 3 && src[ld.opcd_offset] == 0xC2)
            || len + all_len > 128)
        {
            break;
        }

        // move instruction 
        memcpy( old, src, len );

        // if instruction has relative offset, calculate new offset 
        if (ld.flags & F_RELATIVE)
        {
            LONG diff = 0;
            const uintptr_t ofst = (ld.disp_offset != 0 ? ld.disp_offset : ld.imm_offset);
            const uintptr_t sz = ld.disp_size != 0 ? ld.disp_size : ld.imm_size;

            memcpy( &diff, src + ofst, sz );
            // exit if jump is greater then 2GB
            if (_abs64( src + len + diff - old ) > INT_MAX)
            {
                break;
            }
            else
            {
                diff += (LONG)(src - old);
                memcpy( old + ofst, &diff, sz );
            }
        }

        src += len;
        old += len;
        all_len += len;

    } while (all_len < sizeof( JUMP_THUNK ));

    // Failed to copy old code, use backup plan
    if (all_len < sizeof( JUMP_THUNK ))
    {
        return STATUS_UNSUCCESSFUL;
    }
    else
    {
        PHpInitJumpThunk( (PJUMP_THUNK)old, (ULONG64)src );
        *pSize = all_len;
    }

    return STATUS_SUCCESS;
}
Example #13
0
NTSTATUS RemoteLocalHook::SetHook( ptr_t address, asmjit::Assembler& /*hook*/ )
{
    HookCtx ctx = { { 0 } };
    HOOK_CTX_T( ctx_t, ctx );
    UNREFERENCED_PARAMETER( ctx_t );

    // Already hooked
    if (_hooks.count( address ) != 0)
        return STATUS_ADDRESS_ALREADY_EXISTS;

    auto memBlock = _process.memory().Allocate( 0x1000 );
    if (!memBlock.valid())
        return LastNtStatus();

    auto status = _process.memory().Read( address, sizeof( ctx_t.original_code ), ctx_t.original_code );
    if (!NT_SUCCESS( status ))
        return status;

    // Copy original
    uint8_t* codePtr = ctx_t.original_code;
    ptr_t old = 0;
    uint32_t all_len = 0;
    ldasm_data ld = { 0 };

    do
    {
        uint32_t len = ldasm( codePtr, &ld, is_x64 );

        // Determine code end
        if (ld.flags & F_INVALID
             || (len == 1 && (codePtr[ld.opcd_offset] == 0xCC || codePtr[ld.opcd_offset] == 0xC3))
             || (len == 3 && codePtr[ld.opcd_offset] == 0xC2)
             || len + all_len > 128)
        {
            break;
        }

        // if instruction has relative offset, calculate new offset 
        if (ld.flags & F_RELATIVE)
        {
#ifdef USE64
            // exit if jump is greater then 2GB
            if (_abs64( (uintptr_t)(codePtr + *((int*)(old + ld.opcd_size))) - (uintptr_t)old ) > INT_MAX)
                break;
            else
                *(uint32_t*)(old + ld.opcd_size) += (uint32_t)(codePtr - old);
#else
            *(uintptr_t*)(codePtr + ld.opcd_size) += reinterpret_cast<uintptr_t>(codePtr) - static_cast<uintptr_t>(old);
#endif
        }

        codePtr += len;
        old += len;
        all_len += len;

    } while (all_len < 5);


#ifdef USE64
#else 
    *codePtr = ctx_t.jmp_code[0] = 0xE9;
    *(int32_t*)(codePtr + 1) = memBlock.ptr<int32_t>() - static_cast<int32_t>(address)- 5;
    *(int32_t*)(ctx_t.jmp_code + 1) = memBlock.ptr<int32_t>() + FIELD_OFFSET( HookCtx32, original_code ) - static_cast<int32_t>(address) - 5;
#endif

    ctx_t.codeSize = all_len;
    memset( ctx_t.original_code + ctx_t.codeSize, 0x00, sizeof( ctx_t.original_code ) - ctx_t.codeSize );

    memBlock.Write( 0, ctx_t );

    /*DWORD flOld = 0;
    _process.memory().Protect( address, all_len, PAGE_EXECUTE_READWRITE, &flOld );
    _process.memory().Write( address, ctx_t.jmp_code );
    _process.memory().Protect( address, all_len, flOld );*/

    _hooks.emplace( std::make_pair( address, ctx ) );
    memBlock.Release();

    return STATUS_SUCCESS;
}
Example #14
0
/// <summary>
/// Copy original function bytes
/// </summary>
/// <param name="Ptr">Origianl function address</param>
void DetourBase::CopyOldCode( uint8_t* ptr )
{ 
    // Store original bytes
    uint8_t* src = ptr;
    uint8_t* thunk = _origThunk, *original = _origCode;
    uint32_t all_len = 0;
    ldasm_data ld = { 0 };

    do 
    {
        uint32_t len = ldasm( src, &ld, is_x64 );

        // Determine code end
        if (ld.flags & F_INVALID
                || (len == 1 && (src[ld.opcd_offset] == 0xCC || src[ld.opcd_offset] == 0xC3))
                || (len == 3 && src[ld.opcd_offset] == 0xC2)
                || len + all_len > 128)
        {
            break;
        }

        // move instruction 
        memcpy( original, src, len );
        memcpy( thunk, src, len );

        // if instruction has relative offset, calculate new offset 
        if (ld.flags & F_RELATIVE)
        {
            int32_t diff = 0;
            const uintptr_t ofst = (ld.disp_offset != 0 ? ld.disp_offset : ld.imm_offset);
            const uintptr_t sz = ld.disp_size != 0 ? ld.disp_size : ld.imm_size;

            memcpy( &diff, src + ofst, sz );

        #ifdef USE64
            // exit if jump is greater then 2GB
            if (_abs64( src + len + diff - thunk ) > INT_MAX)
            {
                break;
            }
            else
            {
                diff += static_cast<int32_t>(src - thunk);
                memcpy( thunk + ofst, &diff, sz );
            }
        #else
            diff += src - thunk;
            memcpy( thunk + ofst, &diff, sz );
        #endif
        }

        src += len;
        thunk += len;
        original += len;
        all_len += len;
    } while (all_len < _origSize);

    // Failed to copy old code, use backup plan
    if (all_len < _origSize)
    {
        _type = HookType::InternalInline;
        memcpy( _origCode, ptr, _origSize );
    }         
    else
    {
        SET_JUMP( thunk, src );
        _callOriginal = _origThunk;
    } 
}
Example #15
0
HRESULT CAudioDecFilter::Transform(IMediaSample *pIn, IMediaSample *pOut)
{
	// 入力データポインタを取得する
	const DWORD InSize = pIn->GetActualDataLength();
	BYTE *pInData = NULL;
	HRESULT hr = pIn->GetPointer(&pInData);
	if (FAILED(hr))
		return hr;

	{
		CAutoLock Lock(&m_cPropLock);

		/*
			複数の音声フォーマットに対応する場合、この辺りでフォーマットの判定をする
		*/
		if (!m_pDecoder) {
			m_pDecoder = new CAacDecoder();
			m_pDecoder->Open();
		}

		REFERENCE_TIME rtStart, rtEnd;
		hr = pIn->GetTime(&rtStart, &rtEnd);
		if (FAILED(hr))
			rtStart = -1;
		if (pIn->IsDiscontinuity() == S_OK) {
			m_bDiscontinuity = true;
			m_bInputDiscontinuity = true;
		} else if (hr == S_OK || hr == VFW_S_NO_STOP_TIME) {
			if (!m_bJitterCorrection) {
				m_StartTime = rtStart;
			} else if (m_StartTime >= 0
					&& _abs64(rtStart - m_StartTime) > MAX_JITTER) {
				TRACE(TEXT("Resync audio stream time (%lld -> %lld [%f])\n"),
					  m_StartTime, rtStart,
					  (double)(rtStart - m_StartTime) / (double)REFERENCE_TIME_SECOND);
				m_StartTime = rtStart;
			}
		}
		if (m_StartTime < 0 || m_bDiscontinuity) {
			TRACE(TEXT("Initialize audio stream time (%lld)\n"), rtStart);
			m_StartTime = rtStart;
		}

		m_BitRateCalculator.Update(InSize);
	}

	DWORD InDataPos = 0;
	FrameSampleInfo SampleInfo;
	SampleInfo.pData = &m_OutData;

	hr = S_OK;

	while (InDataPos < InSize) {
		{
			CAutoLock Lock(&m_cPropLock);

			CAudioDecoder::DecodeFrameInfo FrameInfo;
			const DWORD DataSize = InSize - InDataPos;
			DWORD DecodeSize = DataSize;
			if (!m_pDecoder->Decode(&pInData[InDataPos], &DecodeSize, &FrameInfo)) {
				if (DecodeSize < DataSize) {
					InDataPos += DecodeSize;
					continue;
				}
				break;
			}
			InDataPos += DecodeSize;

			if (FrameInfo.bDiscontinuity)
				m_bDiscontinuity = true;

			SampleInfo.bMediaTypeChanged = false;

			hr = OnFrame(FrameInfo.pData, FrameInfo.Samples, FrameInfo.Info,
						 &SampleInfo);
		}

		if (SUCCEEDED(hr)) {
			if (SampleInfo.bMediaTypeChanged) {
				hr = ReconnectOutput(SampleInfo.MediaBufferSize, SampleInfo.MediaType);
				if (FAILED(hr))
					break;
				OutputLog(TEXT("出力メディアタイプを更新します。\r\n"));
				hr = m_pOutput->SetMediaType(&SampleInfo.MediaType);
				if (FAILED(hr)) {
					OutputLog(TEXT("出力メディアタイプを設定できません。(%08x)\r\n"), hr);
					break;
				}
				m_MediaType = SampleInfo.MediaType;
				m_bDiscontinuity = true;
				m_bInputDiscontinuity = true;
			}

			IMediaSample *pOutSample = NULL;
			hr = m_pOutput->GetDeliveryBuffer(&pOutSample, NULL, NULL, 0);
			if (FAILED(hr)) {
				OutputLog(TEXT("出力メディアサンプルを取得できません。(%08x)\r\n"), hr);
				break;
			}

			if (SampleInfo.bMediaTypeChanged)
				pOutSample->SetMediaType(&m_MediaType);

			// 出力ポインタ取得
			BYTE *pOutBuff = NULL;
			hr = pOutSample->GetPointer(&pOutBuff);
			if (FAILED(hr)) {
				OutputLog(TEXT("出力サンプルのバッファを取得できません。(%08x)\r\n"), hr);
				pOutSample->Release();
				break;
			}

			::CopyMemory(pOutBuff, m_OutData.GetData(), m_OutData.GetSize());
			pOutSample->SetActualDataLength(m_OutData.GetSize());

			if (m_StartTime >= 0) {
				REFERENCE_TIME rtDuration, rtStart, rtEnd;
				rtDuration = REFERENCE_TIME_SECOND * (LONGLONG)SampleInfo.Samples / FREQUENCY;
				rtStart = m_StartTime;
				m_StartTime += rtDuration;
				// 音ずれ補正用時間シフト
				if (m_DelayAdjustment > 0) {
					// 最大2倍まで時間を遅らせる
					if (rtDuration >= m_DelayAdjustment) {
						rtDuration += m_DelayAdjustment;
						m_DelayAdjustment = 0;
					} else {
						m_DelayAdjustment -= rtDuration;
						rtDuration *= 2;
					}
				} else if (m_DelayAdjustment < 0) {
					// 最短1/2まで時間を早める
					if (rtDuration >= -m_DelayAdjustment * 2) {
						rtDuration += m_DelayAdjustment;
						m_DelayAdjustment = 0;
					} else {
						m_DelayAdjustment += rtDuration;
						rtDuration /= 2;
					}
				} else {
					rtStart += m_Delay;
				}
				rtEnd = rtStart + rtDuration;
				pOutSample->SetTime(&rtStart, &rtEnd);
			}
			pOutSample->SetMediaTime(NULL, NULL);
			pOutSample->SetPreroll(FALSE);
#if 0
			// Discontinuityを設定すると倍速再生がおかしくなる模様
			pOutSample->SetDiscontinuity(m_bDiscontinuity);
#else
			pOutSample->SetDiscontinuity(m_bInputDiscontinuity);
#endif
			m_bDiscontinuity = false;
			m_bInputDiscontinuity = false;
			pOutSample->SetSyncPoint(TRUE);

			hr = m_pOutput->Deliver(pOutSample);
#ifdef _DEBUG
			if (FAILED(hr)) {
				OutputLog(TEXT("サンプルを送信できません。(%08x)\r\n"), hr);
				if (m_bPassthrough && !m_bPassthroughError) {
					m_bPassthroughError = true;
					if (m_pEventHandler)
						m_pEventHandler->OnSpdifPassthroughError(hr);
				}
			}
#endif
			pOutSample->Release();
			if (FAILED(hr))
				break;
		}
	}

	return hr;
}
bool ImplicitList::compute()
{
    if (m_bComputed == true)
    {
        return true;
    }

    m_iSize = -1;
    if (isComputable() == true)
    {
        m_iSize = 0;
        if (m_eOutType == ScilabDouble)
        {
            m_pDblStart = m_poStart->getAs<Double>();
            double dblStart	= m_pDblStart->get(0);

            m_pDblStep = m_poStep->getAs<Double>();
            double dblStep	= m_pDblStep->get(0);

            m_pDblEnd = m_poEnd->getAs<Double>();
            double dblEnd	= m_pDblEnd->get(0);
            // othe way to compute

            // nan value
            if (ISNAN(dblStart) || ISNAN(dblStep) || ISNAN(dblEnd))
            {
                m_iSize = -1;
                m_bComputed = true;
                return true;
            }

            // no finite values
            if ( finite(dblStart) == 0 || finite(dblStep) == 0 || finite(dblEnd) == 0)
            {
                if ((dblStep > 0 && dblStart < dblEnd) ||
                        (dblStep < 0 && dblStart > dblEnd))
                {
                    // return nan
                    m_iSize = -1;
                }
                // else return []

                m_bComputed = true;
                return true;
            }

            // step null
            if (dblStep == 0) // return []
            {
                m_bComputed = true;
                return true;
            }

            double dblVal = dblStart; // temp value
            double dblEps = NumericConstants::eps;
            double dblPrec = 2 * std::max(fabs(dblStart), fabs(dblEnd)) * dblEps;

            while (dblStep * (dblVal - dblEnd) <= 0)
            {
                m_iSize++;
                dblVal = dblStart + m_iSize * dblStep;
            }

            if (fabs(dblVal - dblEnd) < dblPrec)
            {
                m_iSize++;
            }
        }
        else //m_eOutType == ScilabInt
        {
            if (m_eOutType == ScilabInt8 ||
                    m_eOutType == ScilabInt16 ||
                    m_eOutType == ScilabInt32 ||
                    m_eOutType == ScilabInt64)
            {
                //signed
                long long llStart   = convert_input(m_poStart);
                long long llStep    = convert_input(m_poStep);
                long long llEnd     = convert_input(m_poEnd);

#ifdef _MSC_VER
                m_iSize = static_cast<int>(floor( static_cast<double>(_abs64(llEnd - llStart) / _abs64(llStep)) )) + 1;
#else
                m_iSize = static_cast<int>(floor( static_cast<double>(llabs(llEnd - llStart) / llabs(llStep)) )) + 1;
#endif
            }
            else
            {
                //unsigned
                unsigned long long ullStart = convert_unsigned_input(m_poStart);
                unsigned long long ullStep	= convert_unsigned_input(m_poStep);
                unsigned long long ullEnd   = convert_unsigned_input(m_poEnd);

#ifdef _MSC_VER
                m_iSize = static_cast<int>(floor(static_cast<double>(_abs64(ullEnd - ullStart) / _abs64(ullStep)) )) + 1;
#else
                m_iSize = static_cast<int>(floor(static_cast<double>(llabs(ullEnd - ullStart) / llabs(ullStep)) )) + 1;
#endif
            }
        }
        m_bComputed = true;
        return true;
    }
    else
    {
        return false;
    }
}