Example #1
0
void CBaseMuxerFilter::AddInput()
{
	POSITION pos = m_pInputs.GetHeadPosition();
	while(pos)
	{
		CBasePin* pPin = m_pInputs.GetNext(pos);
		if(!pPin->IsConnected()) return;
	}

	CStringW name;

	name.Format(L"Input %d", m_pInputs.GetCount()+1);

	CBaseMuxerInputPin* pInputPin = NULL;
	if(FAILED(CreateInput(name, &pInputPin)) || !pInputPin) {ASSERT(0); return;}
	CAutoPtr<CBaseMuxerInputPin> pAutoPtrInputPin(pInputPin);

	name.Format(L"~Output %d", m_pRawOutputs.GetCount()+1);

	CBaseMuxerRawOutputPin* pRawOutputPin = NULL;
	if(FAILED(CreateRawOutput(name, &pRawOutputPin)) || !pRawOutputPin) {ASSERT(0); return;}
	CAutoPtr<CBaseMuxerRawOutputPin> pAutoPtrRawOutputPin(pRawOutputPin);

	pInputPin->SetRelatedPin(pRawOutputPin);
	pRawOutputPin->SetRelatedPin(pInputPin);

	m_pInputs.AddTail(pAutoPtrInputPin);
	m_pRawOutputs.AddTail(pAutoPtrRawOutputPin);
}
Example #2
0
bool Definition::GetAsTime(Time& t, StringMapW<float>& offset, StringMapW<float>* n2n, int default_id)
{
    Definition& time = (*this)[L"time"];

    CStringW id;
    if(time[L"id"].IsValue()) id = time[L"id"];
    else id.Format(L"%d", default_id);

    float scale = time[L"scale"].IsValue() ? time[L"scale"] : 1.0f;

    if(time[L"start"].IsValue() && time[L"stop"].IsValue())
    {
        time[L"start"].GetAsNumber(t.start, n2n);
        time[L"stop"].GetAsNumber(t.stop, n2n);

        if(t.start.unit.IsEmpty()) t.start.value *= scale;
        if(t.stop.unit.IsEmpty()) t.stop.value *= scale;

        float o = 0;
        offset.Lookup(id, o);

        if(t.start.sign != 0) t.start.value = o + t.start.value;
        if(t.stop.sign != 0) t.stop.value = t.start.value + t.stop.value;

        offset[id] = t.stop.value;

        return true;
    }

    return false;
}
    void InitPathes()
    {
        GetTempPath(MAX_PATH, m_workingFolder.GetBuffer(MAX_PATH));
        m_workingFolder.ReleaseBuffer();

        SYSTEMTIME st;
        GetLocalTime(&st);

        CStringW t;
        t.Format(L"%ls_%d.%d.%d.%d_%04d%02d%02d_%02d%02d%02d",
            (LPCWSTR)m_config.Prefix,
            m_config.V[0], m_config.V[1], m_config.V[2], m_config.V[3],
            (int)st.wYear, (int)st.wMonth, (int)st.wDay, (int)st.wHour, (int)st.wMinute, (int)st.wSecond);

        m_workingFolder += t;
        m_miniDumpFile = m_workingFolder + _T("\\") + t + _T(".mini.dmp");
        m_miniDumpZipFile = m_workingFolder + _T("\\doctor_dump_mini.zip");
        m_fullDumpFile = m_workingFolder + _T("\\") + t + _T(".full.dmp");
        m_fullDumpZipFile = m_workingFolder + _T("\\doctor_dump_full.zip");
        m_infoDll = m_workingFolder + _T("\\info.dll");
        m_infoFile = m_workingFolder + _T("\\info.zip");
        m_patch = m_workingFolder + _T("\\solution.exe");

        if (!CreateDirectory(m_workingFolder, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
            throw std::runtime_error("failed to create temp directory");
    }
Example #4
0
HRESULT CStreamSwitcherFilter::CompleteConnect(PIN_DIRECTION dir, CBasePin* pPin, IPin* pReceivePin)
{
    if (dir == PINDIR_INPUT) {
        CAutoLock cAutoLock(&m_csPins);

        int nConnected = GetConnectedInputPinCount();

        if (nConnected == 1) {
            m_pInput = static_cast<CStreamSwitcherInputPin*>(pPin);
        }

        if ((size_t)nConnected == m_pInputs.GetCount()) {
            CStringW name;
            name.Format(L"Channel %d", ++m_PinVersion);

            HRESULT hr = S_OK;
            CStreamSwitcherInputPin* pPin = DEBUG_NEW CStreamSwitcherInputPin(this, &hr, name);
            if (!pPin || FAILED(hr)) {
                delete pPin;
                return E_FAIL;
            }
            m_pInputs.AddTail(pPin);
        }
    }

    return S_OK;
}
Example #5
0
LRESULT CMainDlg::OnPosChanged(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	WINDOWPOS* wp = (WINDOWPOS*)lParam;

	static BOOL bLastShow = FALSE;
	BOOL bIsShow = IsWindowVisible();
	CStringW strMessage;
	strMessage.Format(L"Carer: OnPosChanged id:%s , bLastShow:%s\n", bIsShow ? L"True" :L"False", bLastShow ? L"True":L"False" );
	OutputDebugString(strMessage);
	static HHOOK hHook = NULL;
	if(bIsShow && !bLastShow){   //show
		INT showLong = CConfig::Instance()->GetIntValue(CK_ShowLong, 30);
		BOOL bRet =::SetTimer(m_hWnd, TN_WindowHide, showLong*1000, TimerProc);
		ATLASSERT(bRet);
		OutputDebugString(L"SetTimer\n");	
		bLastShow = bIsShow;

	}
	else if(!bIsShow && bLastShow){   // hide
		BOOL bRet =::KillTimer(m_hWnd, TN_WindowHide);
		ATLASSERT(bRet);
		OutputDebugString(L"KillTimer\n");		 
		bLastShow = bIsShow;
	}	
	return 0;
}
Example #6
0
	FontWrapper* FontCache::Create(HDC hDC, const LOGFONT& lf)
	{
		CStringW key;

		key.Format(L"%s,%d,%d,%d",
				   CStringW(lf.lfFaceName), lf.lfHeight, lf.lfWeight,
				   ((lf.lfItalic&1)<<2) | ((lf.lfUnderline&1)<<1) | ((lf.lfStrikeOut&1)<<0));

		FontWrapper* pFW = NULL;

		if(m_key2obj.Lookup(key, pFW)) {
			return pFW;
		}

		HFONT hFont = CreateFontIndirect(&lf);

		if(!hFont) {
			ASSERT(0);
			return NULL;
		}

		pFW = DNew FontWrapper(hDC, hFont, key);

		Add(key, pFW, false);

		return pFW;
	}
Example #7
0
int CTWScriptEdit::IsConstant(LPCWSTR lpszSymbol)
{
	CStringW strSymbol; strSymbol.Format(L" %s ", lpszSymbol);
	if (!m_bCaseSensitive) 
		strSymbol.MakeLower();
				
	return m_strConstantsLower.Find(strSymbol);
}
Example #8
0
	void SubtitleFile::Append(InputStream& s, float start, float stop, bool fSetTime)
	{
		Reference* pRootRef = GetRootRef();

		ParseDefs(s, pRootRef);

		CAtlList<Definition*> defs;
		GetNewDefs(defs);

		POSITION pos = defs.GetHeadPosition();
		while(pos)
		{
			Definition* pDef = defs.GetNext(pos);

			if(pDef->m_parent == pRootRef && pDef->m_type == L"subtitle" && (*pDef)[L"@"].IsValue())
			{
				m_segments.Insert(start, stop, pDef);

				if(fSetTime) 
				{
					try
					{
						Definition::Time time;
						StringMapW<float> offset;
						pDef->GetAsTime(time, offset);
						if(time.start.value == start && time.stop.value == stop)
							continue;
					}
					catch(Exception&)
					{
					}

					CStringW str;
					str.Format(L"%.3f", start);
					pDef->SetChildAsNumber(L"time.start", str, L"s");
					str.Format(L"%.3f", stop);
					pDef->SetChildAsNumber(L"time.stop", str, L"s");
				}
			}
		}

		Commit();
	}
Example #9
0
// *************************************************************
//		RemoveStyle()
// *************************************************************
bool OgrStyleHelper::RemoveStyle(GDALDataset* dataset, CStringW styleTableName, CStringW layerName, CStringW styleName)
{
	USES_CONVERSION;
	CStringW sql;
	sql.Format(L"DELETE FROM %s WHERE layername = '%s' AND stylename = '%s'", styleTableName, layerName, styleName);

	CPLErrorReset();
	OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	return CPLGetLastErrorNo() == OGRERR_NONE;
}
CStringW AbstractNewDialog::GetAuthor(void)
{
  // Quote the author's name if it contains a period
  if (m_author.Find(L'.') != -1)
  {
    CStringW author;
    author.Format(L"\"%s\"",m_author);
    return author;
  }
  return m_author;
}
Example #11
0
CStringW CSySkin::A2CStringW(CString in_Str)
{
	CStringW strResult;
#ifndef _UNICODE
	CA2W a2w(in_Str);
	PWCHAR pszResult = (LPWSTR)a2w;
	strResult.Format( L"%s", pszResult);
#else
	strResult = in_Str;
#endif
	return strResult;
}
Example #12
0
// *************************************************************
//		GerStyleTableName()
// *************************************************************
CStringW OgrStyleHelper::GetStyleTableName(CStringW layerName)
{
	CStringW name;
	USES_CONVERSION;
	if (m_globalSettings.useSchemesForStyles) {
		name.Format(L"%s%s", GetDbSchemeName(layerName, true), A2W(STYLES_TABLE_NAME));
	}
	else {
		name = A2W(STYLES_TABLE_NAME);
	}

	return name;
}
Example #13
0
// *************************************************************
//		SaveStyle()
// *************************************************************
bool OgrStyleHelper::SaveStyle(GDALDataset* dataset, CStringW xml, CStringW layerName, CStringW styleName)
{
	xml.Replace(L"\n", L"");
	xml.Replace(L"'", L"''''");
	if (xml.GetLength() == 0) return false;

	CStringW sql;
	sql.Format(L"INSERT INTO %s(layername, stylename, style) VALUES ('%s', '%s', '%s')", GetStyleTableName(layerName),
		layerName, styleName, xml);

	CPLErrorReset();
	OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	return CPLGetLastErrorNo() == OGRERR_NONE;
}
Example #14
0
// *************************************************************
//		CreateStyleTable()
// *************************************************************
int OgrStyleHelper::CreateStyleTable(GDALDataset* dataset, CStringW layerName)
{
	if (OgrHelper::IsPostGisDatasource(dataset))
	{
		CPLErrorReset();
		CStringW schemaName = GetDbSchemeName(layerName, true);
		CStringW sql;
		sql.Format(L"CREATE Table %s (StyleId serial primary key, LayerName varchar(128), StyleName varchar(128), Style text, CONSTRAINT layer_style_unique UNIQUE (LayerName,StyleName));", GetStyleTableName());
		OGRLayer* lyr = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
		return CPLGetLastErrorNo() == OGRERR_NONE ? tkNO_ERROR : tkOGR_FAILED_TO_CREATE_STYLE_TABLE;
	}
	else {
		return tkOGR_NO_STYLE_TABLE_CREATION;
	}
}
Example #15
0
// *************************************************************
//		HasStyleTable()
// *************************************************************
bool OgrStyleHelper::HasStyleTable(GDALDataset* dataset, CStringW layerName)
{
	USES_CONVERSION;
	CStringW sql;
	sql.Format(L"SELECT COUNT(*) FROM %s", A2W(STYLES_TABLE_NAME));

	// we are checking the presence; it's normal to receive an error; no need to report it to user
	m_globalSettings.suppressGdalErrors = true;
	OGRLayer* lyr = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	m_globalSettings.suppressGdalErrors = false;

	bool hasTable = lyr != NULL;
	if (lyr)
		dataset->ReleaseResultSet(lyr);
	else 
		CPLErrorReset();
	return hasTable;
}
Example #16
0
VOID CALLBACK CMainDlg::TimerProc(
	_In_  HWND hwnd,
	_In_  UINT uMsg,
	_In_  UINT_PTR idEvent,
	_In_  DWORD dwTime
	)
{	
	CStringW strMessage;
	strMessage.Format(L"Carer: TimerProc id:%d\n", idEvent);
	OutputDebugString(strMessage);		 
	static UINT_PTR m_TimerID = 0;
 	if (TN_Remind == idEvent)
	{
		::SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, m_rectScreen.right, m_rectScreen.bottom, SWP_SHOWWINDOW);
		::SetActiveWindow(hwnd);		
	}
	else if(TN_WindowHide == idEvent)
	{
		::ShowWindow(hwnd, SW_HIDE);
	}
}
CStringW DebugBasicSerialize( LuaObject& obj )
{
	if ( obj.Type() == LUA_TNUMBER )
	{
		CStringW str;
		str.Format( L"%.16g", obj.GetNumber() );
		return str;
	}

	else if ( obj.Type() == LUA_TBOOLEAN )
	{
		return obj.GetBoolean() ? L"true" : L"false";
	}

	else if (obj.Type() == LUA_TSTRING)
	{
		CString str = obj.GetString();
		if ( str == "!!!NIL!!!" )
			return L"nil";
		else if ( str == "!!!FUNCTION!!!" )
			return L"{function}";
		else if ( str == "!!!CFUNCTION!!!" )
			return L"{cfunction}";
		else if ( str == "!!!USERDATA!!!" )
			return L"{userdata}";
		else if ( str == "!!!TABLE!!!" )
			return L"{table}";
		return CStringW(str);
	}
#if LUA_WIDESTRING
	else if (obj.Type() == LUA_TWSTRING)
	{
		return CStringW((wchar_t*)obj.GetWString());
	}
#endif // LUA_WIDESTRING

	else
		return _T("Unknown");
}
Example #18
0
CStringW CFormData::GetMime(LPCTSTR __szExt)
{
	HKEY   hkey;
	DWORD dwType, dwSize;
	wchar_t buffer[255];

	ZeroMemory(&buffer, sizeof(buffer));

	CStringW s;
	s.Format(L"\\.%s", __szExt);

	if(RegOpenKeyEx(HKEY_CLASSES_ROOT, s, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS)
	{
		dwType = REG_SZ;
		dwSize = sizeof(buffer);
		RegQueryValueEx(hkey, TEXT("Content Type"), 0, &dwType, (LPBYTE)&buffer, &dwSize);
        
		RegCloseKey(hkey);
	}

	return CStringW(buffer);
}
Example #19
0
void CmDxBase::OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl)
{
	switch( nControlID )
	{
	case IDC_TOGGLEFULLSCREEN:
		DXUTToggleFullScreen();
		break;
	case IDC_TOGGLEREF:
		DXUTToggleREF();
		break;
	case IDC_TOGGLEWARP:
		DXUTToggleWARP();
		break;
	case IDC_CHANGEDEVICE:
		_SettingsDlg.SetActive( !_SettingsDlg.IsActive() );
		break;
	case IDC_SLIDER:
		CStringW str;
		str.Format(L"S=%d", _SampleUI.GetSlider(IDC_SLIDER)->GetValue());
		_SampleUI.GetStatic(IDC_SLIDER_STATIC)->SetText(str);
		break;
	}
}
void CStaffManageView::OnBnClickedAddreco()
{
	// TODO: 在此添加控件通知处理程序代码
	static bool bAdd = true;
	if (bAdd)
	{
		UpdateCtrlReadOnlyState(FALSE);
		GetDlgItem(IDC_SET_PHOTO)->ShowWindow(SW_SHOW);

		m_pSet->m_strSort = "职工编号";
		m_pSet->Requery();
		m_pSet->MoveLast();
		int iID = m_pSet->m_iStaffID + 1;
		m_pSet->AddNew();

		UpdateData(FALSE);

		CStringW strText = _T("");
		strText.Format(_T("%d"),iID);
		SetDlgItemText(IDC_EDITZGBH,strText);

		bAdd = false;
		SetDlgItemText(IDC_ADDRECO,_T("保存记录"));
	}
	else
	{
		SetDlgItemText(IDC_ADDRECO,_T("增加记录"));
		GetDlgItem(IDC_SET_PHOTO)->ShowWindow(SW_HIDE);
		UpdateData(TRUE);
		m_pSet->Update();
		bAdd = true;
		AfxMessageBox(_T("增加记录成功!"));
		UpdateCtrlReadOnlyState(TRUE);
		m_pSet->MoveLast();
	}

}
Example #21
0
// *************************************************************
//		LoadStyle()
// *************************************************************
CStringW OgrStyleHelper::LoadStyle(GDALDataset* dataset, CStringW styleTableName, CStringW layerName, CStringW styleName)
{
	USES_CONVERSION;
	CStringW sql;
	sql.Format(L"SELECT style FROM %s WHERE layername = '%s' AND stylename = '%s'", styleTableName, layerName, styleName);

	CStringW xml = L"";

	bool found = false;
	CPLErrorReset();
	OGRLayer* layer = dataset->ExecuteSQL(OgrHelper::String2OgrString(sql), NULL, NULL);
	if (layer) {
		OGRFeature* ft = layer->GetNextFeature();
		if (ft) {
			const char* s = ft->GetFieldAsString(0);
			if (s) {
				xml = OgrHelper::OgrString2Unicode(s);
			}
			OGRFeature::DestroyFeature(ft);
		}
		dataset->ReleaseResultSet(layer);
	}
	return xml;
}
Example #22
0
HRESULT CSubtitleStream::FillBuffer(IMediaSample* pSample)
{
	HRESULT hr;

	{
		CAutoLock cAutoLockShared(&m_cSharedState);

		BYTE* pData = NULL;
		if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) {
			return S_FALSE;
		}

		AM_MEDIA_TYPE* pmt;
		if (SUCCEEDED(pSample->GetMediaType(&pmt)) && pmt) {
			CMediaType mt(*pmt);
			SetMediaType(&mt);
			DeleteMediaType(pmt);
		}

		int len = 0;
		REFERENCE_TIME rtStart, rtStop;

		if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) {
			rtStart = (REFERENCE_TIME)((m_nPosition*_ATPF - m_rtStart) / m_dRateSeeking);
			rtStop = (REFERENCE_TIME)(((m_nPosition+1)*_ATPF - m_rtStart) / m_dRateSeeking);
			if (m_rtStart+rtStart >= m_rtDuration) {
				return S_FALSE;
			}

			BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader;

			SubPicDesc spd;
			spd.w = _WIDTH;
			spd.h = _HEIGHT;
			spd.bpp = 32;
			spd.pitch = bmi.biWidth*4;
			spd.bits = pData;

			len = spd.h*spd.pitch;

			for (int y = 0; y < spd.h; y++) {
				memsetd((DWORD*)(pData + spd.pitch*y), 0xff000000, spd.w*4);
			}

			RECT bbox;
			m_rts.Render(spd, m_nPosition*_ATPF, 10000000.0/_ATPF, bbox);

			for (int y = 0; y < spd.h; y++) {
				DWORD* p = (DWORD*)(pData + spd.pitch*y);
				for (int x = 0; x < spd.w; x++, p++) {
					*p = (0xff000000-(*p&0xff000000))|(*p&0xffffff);
				}
			}
		} else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) {
			const STSSegment* stss = m_rts.GetSegment(m_nPosition);
			if (!stss) {
				return S_FALSE;
			}

			BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader;

			SubPicDesc spd;
			spd.w = _WIDTH;
			spd.h = _HEIGHT;
			spd.bpp = 32;
			spd.pitch = bmi.biWidth*4;
			spd.bits = pData;

			len = spd.h*spd.pitch;

			for (int y = 0; y < spd.h; y++) {
				DWORD c1 = 0xff606060, c2 = 0xffa0a0a0;
				if (y&32) {
					c1 ^= c2, c2 ^= c1, c1 ^= c2;
				}
				DWORD* p = (DWORD*)(pData + spd.pitch*y);
				for (int x = 0; x < spd.w; x+=32, p+=32) {
					memsetd(p, (x&32) ? c1 : c2, min(spd.w-x,32)*4);
				}
			}

			RECT bbox;
			m_rts.Render(spd, 10000i64*(stss->start+stss->end)/2, 10000000.0/_ATPF, bbox);

			rtStart = (REFERENCE_TIME)((10000i64*stss->start - m_rtStart) / m_dRateSeeking);
			rtStop = (REFERENCE_TIME)((10000i64*stss->end - m_rtStart) / m_dRateSeeking);
		} else {
			if ((size_t)m_nPosition >= m_rts.GetCount()) {
				return S_FALSE;
			}

			STSEntry& stse = m_rts[m_nPosition];

			if (stse.start >= m_rtStop/10000) {
				return S_FALSE;
			}

			if (m_mt.majortype == MEDIATYPE_Subtitle && m_mt.subtype == MEDIASUBTYPE_UTF8) {
				CStringA str = UTF16To8(m_rts.GetStrW(m_nPosition, false));
				memcpy((char*)pData, str, len = str.GetLength());
			} else if (m_mt.majortype == MEDIATYPE_Subtitle && (m_mt.subtype == MEDIASUBTYPE_SSA || m_mt.subtype == MEDIASUBTYPE_ASS)) {
				CStringW line;
				line.Format(L"%d,%d,%s,%s,%d,%d,%d,%s,%s",
							stse.readorder, stse.layer, CStringW(stse.style), CStringW(stse.actor),
							stse.marginRect.left, stse.marginRect.right, (stse.marginRect.top+stse.marginRect.bottom)/2,
							CStringW(stse.effect), m_rts.GetStrW(m_nPosition, true));

				CStringA str = UTF16To8(line);
				memcpy((char*)pData, str, len = str.GetLength());
			} else if (m_mt.majortype == MEDIATYPE_Text && m_mt.subtype == MEDIASUBTYPE_NULL) {
				CStringA str = m_rts.GetStrA(m_nPosition, false);
				memcpy((char*)pData, str, len = str.GetLength());
			} else {
				return S_FALSE;
			}

			rtStart = (REFERENCE_TIME)((10000i64*stse.start - m_rtStart) / m_dRateSeeking);
			rtStop = (REFERENCE_TIME)((10000i64*stse.end - m_rtStart) / m_dRateSeeking);
		}

		pSample->SetTime(&rtStart, &rtStop);
		pSample->SetActualDataLength(len);

		m_nPosition++;
	}

	pSample->SetSyncPoint(TRUE);

	if (m_bDiscontinuity) {
		pSample->SetDiscontinuity(TRUE);
		m_bDiscontinuity = FALSE;
	}

	return S_OK;
}
Example #23
0
BOOL CALLBACK UpdateProc(DWORD_PTR dwParam,CallingReason crReason,UpdateError ueCode,CDatabaseUpdater* pUpdater)
{
	switch (crReason)
	{
	case StartedDatabase:
		if (!nQuiet)
		{
			CStringW msg;
			msg.Format(IDS_UPDATEDB32UPDATINGDATABASE,pUpdater->GetCurrentDatabaseName(),pUpdater->GetCurrentDatabaseFile());
			if (pUpdater->IsIncrementUpdate())
				msg.AddString(IDS_UPDATEDB32INCREMENTALUPDATE);
			_putws(msg);
			
		}
		break;
	case RootChanged:
		if (!nQuiet)
		{
			if (pUpdater->GetCurrentRoot()!=NULL)
				wprintf(ID2W(IDS_UPDATEDB32SCANNING),(LPCWSTR)pUpdater->GetCurrentRoot()->m_Path);
			else
				wprintf(L"%s %s\n",(LPCWSTR)ID2W(IDS_UPDATEDB32WRITINGDB),pUpdater->GetCurrentDatabaseName());
		}
		break;
	case ErrorOccured:
		if (!nQuiet)
		{	
			switch (ueCode)
			{
			case ueAlloc:
				fwprintf(stderr,ID2W(IDS_UPDATEDB32ALLOCATEMEM));
				break;
			case ueOpen:
			case ueCreate:
				fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTCREATEFILE),(LPCSTR)pUpdater->GetCurrentDatabaseFile());
				break;
			case ueWrite:
				fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTWRITE),(LPCSTR)pUpdater->GetCurrentDatabaseFile());
				break;
			case ueUnknown:
				fwprintf(stderr,ID2W(IDS_UPDATEDB32ALLOCATEMEM));
				break;
			case ueFolderUnavailable:
				fwprintf(stderr,ID2W(IDS_UPDATEDB32ROOTUNAVAILABLE),
					pUpdater->GetCurrentRootPath()!=NULL?pUpdater->GetCurrentRootPath():L"(NULL)");
				break;
			case ueWrongCharset:
				{
					int ch;
					do
					{
						fwprintf(stderr,ID2W(IDS_UPDATEDB32WRONGCHARSETINDB),pUpdater->GetCurrentDatabaseFile());
						ch=getc(stdin);
					}
					while (ch!='Y' && ch!='y' && ch!='N' && ch!='n');

					if (ch!='Y' && ch!='y')
						return FALSE;
					return TRUE;
				}
			case ueCannotIncrement:
				{
					int ch;
					do
					{
						fwprintf(stderr,ID2W(IDS_UPDATEDB32CANNOTUPDATEINCREMENTALLY),pUpdater->GetCurrentDatabaseFile());
						ch=getc(stdin);
					}
					while (ch!='Y' && ch!='y' && ch!='N' && ch!='n');

					if (ch!='Y' && ch!='y')
						return FALSE;
					return TRUE;
				}
				break;
			}
		}
		if (ueCode==ueSuccess)
			return 0;
		break;
	case ClassShouldDelete:
		{
			DWORD dwRunning=0;
			if (ppUpdaters==NULL)
				return TRUE; // One thread mode

			for (int i=0;ppUpdaters[i]!=NULL;i++)
			{
				if (ppUpdaters[i]==pUpdater)
					ppUpdaters[i]=UPDATER_EXITED(ueCode);
				else if (!IS_UPDATER_EXITED(ppUpdaters[i]))
					dwRunning++;
			}
            delete pUpdater;
			
			if (dwRunning==0)
			{
				delete[] ppUpdaters;
				ppUpdaters=NULL;
			}
			break;
		}
	}
	return TRUE;
}
Example #24
0
	CStringW NodeFactory::GenName()
	{
		CStringW name;
		name.Format(L"%I64d", m_counter++);
		return name;
	}
Example #25
0
BOOL
SetupWizard::OnInitDialog () 
{
  BOOL ret = CPropertySheet::OnInitDialog();
  try
    {
      SetIcon (AfxGetApp()->LoadIcon(IDR_MAINFRAME), TRUE);
      CStringW title;
      if (theApp.isMiKTeXDirect)
	{
	  title.Format (T_(_T("MiKTeX %s Setup (%d-bit)")),
			static_cast<LPCTSTR>(UW_(MIKTEX_FULL_VERSION_STR)),
			static_cast<int>(sizeof(void*)) * 8);
	}
      else if (theApp.pSetupService->GetOptions().IsPrefabricated)
	{
	  PathName configFile (theApp.GetLocalPackageRepository());
	  configFile += "pr.ini";
	  SmartPointer<Cfg> pConfig (Cfg::Create());
	  pConfig->Read (configFile);
	  CString prefix;
	  CString version (MIKTEXTEXT(MIKTEX_SERIES_STR));
	  version += MIKTEXTEXT('.');
	  version += UT_(pConfig->GetValue("repository", "version").c_str());
	  switch (theApp.GetPackageLevel().Get())
	    {
	    case PackageLevel::Essential:
	      prefix = T_("Essential ");
	      break;
	    case PackageLevel::Basic:
	      prefix = T_("Basic ");
	      break;
	    case PackageLevel::Complete:
	      prefix = "";
	      break;
	    default:
	      MIKTEX_ASSERT (false);
	      __assume (false);
	      break;
	    }
	  title.Format (T_(_T("%sMiKTeX %s Installer (%d-bit)")),
			static_cast<LPCTSTR>(prefix),
			static_cast<LPCTSTR>(version),
			static_cast<int>(sizeof(void*)) * 8);
	}
      else
	{
	  title.Format (T_(_T("MiKTeX %s Net Installer (%d-bit)")),
			static_cast<LPCTSTR>(UW_(MIKTEX_VERSION_STR)),
			static_cast<int>(sizeof(void*)) * 8);
	}
      SetTitle (title);
      SetActivePage (&m_License);
    }
  catch (const MiKTeXException & e)
    {
      ReportError (e);
    }
  catch (const exception & e)
    {
      ReportError (e);
    }
  return (ret);
}
Example #26
0
void TabDoc::DecodeHTML(const char* filename, int scheme)
{
  // Open the file
  CFile htmlFile;
  if (htmlFile.Open(filename,CFile::modeRead) == 0)
    return;

  // Read it into memory
  CString htmlText;
  int len = (int)htmlFile.GetLength();
  htmlFile.Read(htmlText.GetBuffer(len),len);
  htmlText.ReleaseBuffer(len);

  // Convert from UTF-8 to Unicode
  CStringW html = TextFormat::UTF8ToUnicode(htmlText);

  // Get the body text
  int body1 = html.Find(L"<body");
  if (body1 == -1)
    return;
  body1 = html.Find(L">",body1);
  if (body1 == -1)
    return;
  int body2 = html.Find(L"</body>");
  if (body2 <= body1)
    return;
  CStringW bodyHtml = html.Mid(body1+1,body2-body1-1);

  // Create a DocText instance for this file
  DocText* mainDocText = new DocText();
  mainDocText->file = filename;
  mainDocText->colourScheme = scheme;
  m_docTexts.Add(mainDocText);

  // Reserve space for the main text
  len = bodyHtml.GetLength();
  mainDocText->body.Preallocate(len);

  // Scan the text, removing markup
  DocText* docText = mainDocText;
  bool ignore = false;
  bool white = false;
  const wchar_t* p1 = bodyHtml;
  const wchar_t* p2 = p1+len;
  while (p1 < p2)
  {
    // Look for a markup element
    if ((*p1 == L'<') && (iswalpha(*(p1+1)) || (*(p1+1) == L'/')))
    {
      // Check for a closing markup element
      bool closing = false;
      if (*(p1+1) == L'/')
      {
        closing = true;
        p1++;
      }

      // Scan for a known markup element
      bool found = false;
      int i = 0;
      while (!found && (i < sizeof tags / sizeof tags[0]))
      {
        if (wcsncmp(p1+1,tags[i].name,tags[i].len) == 0)
          found = true;
        if (!found)
          i++;
      }
      ASSERT(found);

      // Remove the markup
      if (found && tags[i].remove)
      {
        ASSERT(!closing);

        // Remove everything until the closing element
        CStringW search;
        search.Format(L"</%s>",tags[i].name);
        p1 = wcsstr(p1,search);
        if (p1 != NULL)
          p1 += search.GetLength()-1;
        else
          p1 = p2;
      }
      else
      {
        // Remove just the element
        while ((p1 < p2) && (*p1 != L'>'))
          p1++;
      }
      ASSERT(*p1 == L'>');

      // Add a carriage return for appropriate markup
      if (found && !closing && tags[i].cr && !ignore)
        docText->AddToBody(L'\n');
      white = false;
    }
    else if ((*p1 == L'<') && (*(p1+1) == L'!'))
    {
      // Extract metadata from comments
      wchar_t meta1[256], meta2[256];
      if (swscanf(p1,L"<!-- SEARCH TITLE \"%[^\"]",meta1) == 1)
        docText->title = meta1;
      else if (swscanf(p1,L"<!-- SEARCH SECTION \"%[^\"]",meta1) == 1)
        docText->section = meta1;
      else if (swscanf(p1,L"<!-- SEARCH SORT \"%[^\"]",meta1) == 1)
        docText->sort = meta1;
      else if (swscanf(p1,L"<!-- START EXAMPLE \"%[^\"]\" \"%[^\"]",meta1,meta2) == 2)
      {
        docText = new DocText();
        docText->file = mainDocText->file + "#" + CStringA(meta2);
        docText->colourScheme = mainDocText->colourScheme;
        docText->title = "Example " + CStringA(meta1);
        docText->section = mainDocText->section;
        docText->sort = mainDocText->sort;
        docText->body.Preallocate(len/2);
        m_docTexts.Add(docText);
      }
      else if (wcsncmp(p1,L"<!-- END EXAMPLE -->",20) == 0)
        docText = mainDocText;
      else if (wcsncmp(p1,L"<!-- START IGNORE ",18) == 0)
        ignore = true;
      else if (wcsncmp(p1,L"<!-- END IGNORE -->",19) == 0)
        ignore = false;

      p1 = wcsstr(p1,L"-->");
      if (p1 != NULL)
        p1 += 2;
      else
        p1 = p2;
    }
    else if (*p1 == L'&')
    {
      // Scan for a known literal
      bool found = false;
      int i = 0;
      while (!found && (i < sizeof literals / sizeof literals[0]))
      {
        if (wcsncmp(p1+1,literals[i].name,literals[i].len) == 0)
          found = true;
        if (!found)
          i++;
      }

      // Replace the literal
      if (found)
      {
        if (!ignore)
          docText->AddToBody(literals[i].replace);
        p1 += literals[i].len;
      }
      else
      {
        ASSERT(FALSE);
        if (!ignore)
          docText->AddToBody(*p1);
      }
      white = false;
    }
    else if (iswspace(*p1))
    {
      if (!white && !ignore)
        docText->AddToBody(L' ');
      white = true;
    }
    else
    {
      if (!ignore)
        docText->AddToBody(*p1);
      white = false;
    }
    p1++;
  }

/*
  CString bodyA(docText->body);
  AfxMessageBox(bodyA);
*/
}
Example #27
0
ULONG CFormData::ProcessForm()
{
	CStringA startPart = "--" + CStringA(m_sBoundary) + "\r\n";
	Append(startPart);

	BOOL bHasFields = FALSE;

	//STLOG_WRITE("%s(%d): Ponto de apoio", __FUNCTION__, __LINE__);

	// Varrer os fields primeiro
	POSITION p1 = m_items.GetStartPosition();
	while(p1)
	{
		CStringW key1;
		CFormItem *pAttr;
		m_items.GetNextAssoc(p1, key1, pAttr);
		if(!pAttr->m_bFile)
		{
			bHasFields = TRUE;
			CStringW s;
			s.Format(FIELD_BOUND, pAttr->m_name, pAttr->m_value);
			Append(CStringA(s));
		}

		if(p1 != NULL)
		{
			startPart = "--" + CStringA(m_sBoundary) + "\r\n";
			Append(startPart);
		}
	}

	//STLOG_WRITE("%s(%d): Ponto de apoio", __FUNCTION__, __LINE__);

	BOOL bFirst = TRUE;
	// Varrer os files
	p1 = m_items.GetStartPosition();
	while(p1)
	{
		CStringW key1;
		CFormItem *pAttr;
		m_items.GetNextAssoc(p1, key1, pAttr);
		if(pAttr->m_bFile)
		{
			if(bFirst && bHasFields)
			{
				startPart = "--" + CStringA(m_sBoundary) + "\r\n";
				Append(startPart);
				bFirst = FALSE;
			}

			CStringW sFileName = pAttr->m_value;
			if(sFileName.Find('\\') >= 0 || sFileName.Find('/') >= 0)
			{
				int pos = sFileName.ReverseFind('\\');
				if(pos < 0)
					pos = sFileName.ReverseFind('/');

				sFileName = sFileName.Mid(pos+1);
			}

			CStringW s;
			s.Format(FILE_BOUND, pAttr->m_name, sFileName, pAttr->m_mime);
			Append(CStringA(s));

			Append("\r\n");

			AppendFile(pAttr->m_value);

			Append("\r\n");

			if(p1 != NULL)
			{
				startPart = "--" + CStringA(m_sBoundary) + "\r\n";
				Append(startPart);
			}
		}
	}

	startPart = "--" + CStringA(m_sBoundary) + "--\r\n";
	Append(startPart);

	//STLOG_WRITE("%s(%d): Ponto de apoio", __FUNCTION__, __LINE__);
	//STLOG_WRITE("%s(%d): Buffer: %s", __FUNCTION__, __LINE__, m_buffer.GetData());

	return m_buffer.GetCount();
}
Example #28
0
void LogViewRE::Log(LogFacility logType, LPCWSTR aName, SAFEARRAY* pVals, LPDISPATCH pOptions)
{
  LogIntro(logType, aName);

  ATLASSERT(0 == pVals->rgsabound[0].lLbound);
  VARIANT* pVariants = (VARIANT*)pVals->pvData;

  // see if we can do a printf
  ULONG valueCount = pVals->rgsabound[0].cElements;
  ULONG currentValueIndex = 0;

  if ((valueCount > 1) && (VT_BSTR == pVariants[0].vt)) {
    ++currentValueIndex;
    CStringW sIn(pVariants[0].bstrVal), sOut;
    int pos = sIn.Find(L'%');
    int posLast = 0;
    int sInLength = sIn.GetLength();
    while((-1 != pos) && (pos < sInLength-1) && (currentValueIndex < valueCount)) {
      // add everything before
      sOut += sIn.Mid(posLast, (pos - posLast));
      ++pos;
      wchar_t format = sIn[pos];
      CComVariant vt(pVariants[currentValueIndex]);
      HRESULT hr = E_FAIL;
      switch(format) {
        case L's':
          // a string: change to string type and log as it is
          hr = vt.ChangeType(VT_BSTR);
          if (SUCCEEDED(hr)) {
            sOut += vt.bstrVal;
          }
          ++currentValueIndex;
          ++pos;
          break;
        case L'd':
        case L'i':
          // an integer number
          // check for type, set "undefined" if empty, "NaN" if can't be converted to a number
          {
            CStringW s;
            switch (vt.vt) {
              case VT_I1:
              case VT_I2:
              case VT_I4:
              case VT_INT:
                s.Format(L"%i", vt.lVal);
                break;
              case VT_UI1:
              case VT_UI2:
              case VT_UI4:
              case VT_UINT:
                s.Format(L"%u", vt.ulVal);
                break;
              case VT_EMPTY:
                s = L"-undefined-";
                break;
              default:
                if (SUCCEEDED(vt.ChangeType(VT_UI4))) {
                  s.Format(L"%u", vt.ulVal);
                }
                else if (SUCCEEDED(vt.ChangeType(VT_I4))) {
                  s.Format(L"%u", vt.lVal);
                }
                else {
                  s = L"NaN";
                }
                break;
            }
            ++currentValueIndex;
            sOut += s;
          }
          ++pos;
          break;
        case L'f':
          // a float number
          // check for type, set "undefined" if empty, "NaN" if can't be converted to a number
          {
            CStringW s;
            switch (vt.vt) {
              case VT_R4:
                s.Format(L"%f", vt.fltVal);
                break;
              case VT_R8:
                s.Format(L"%f", vt.dblVal);
                break;
              case VT_EMPTY:
                s = L"-undefined-";
                break;
              default:
                if (SUCCEEDED(vt.ChangeType(VT_R8))) {
                  s.Format(L"%f", vt.dblVal);
                }
                else {
                  s = L"NaN";
                }
                break;
            }
            ++currentValueIndex;
            sOut += s;
          }
          ++pos;
          break;
        case L'o':
          // an object
          // check for type, set "undefined" if empty, "NaO" if can't be converted to string representation
          if (VT_DISPATCH == vt.vt) {
            CStringW s, s2;
            s2.Format(L"[Object at 0x%%0%ix]", sizeof(vt.pdispVal) * 2);
            s.Format(s2, (IUnknown*)(vt.pdispVal));
            sOut += s;
          }
          else if (VT_EMPTY == vt.vt) {
            sOut += L"-undefined-";
          }
          else if (SUCCEEDED(vt.ChangeType(VT_BSTR))) {
            sOut += vt.bstrVal;
          }
          else {
            sOut += L"NaO";
          }
          ++currentValueIndex;
          ++pos;
          break;
        default:
          // all other cases: not a format spec, take it as it is
          sOut += L'%';
          sOut += format;
          ++pos;
          break;
      }
      posLast = pos;
      pos = sIn.Find(L'%', pos);
    }
    // append the rest
    sOut += sIn.Mid(posLast);
    LogVariant(CComVariant(sOut));
    AppendText(_T(" "));
  }

  // log all the rest
  for(ULONG n = currentValueIndex; n < pVals->rgsabound[0].cElements; n++)
  {
    LogVariant(pVariants[n]);
    AppendText(_T(" "));
  }

  LogExtro();
}
Example #29
0
HRESULT CMatroskaSplitterFilter::CreateOutputs(IAsyncReader* pAsyncReader)
{
	CheckPointer(pAsyncReader, E_POINTER);

	HRESULT hr = E_FAIL;

	m_pFile.Free();
	m_pTrackEntryMap.RemoveAll();
	m_pOrderedTrackArray.RemoveAll();

	CAtlArray<CMatroskaSplitterOutputPin*> pinOut;
	CAtlArray<TrackEntry*> pinOutTE;

	m_pFile.Attach(DNew CMatroskaFile(pAsyncReader, hr));
	if(!m_pFile) return E_OUTOFMEMORY;
	if(FAILED(hr)) {m_pFile.Free(); return hr;}

	m_rtNewStart = m_rtCurrent = 0;
	m_rtNewStop = m_rtStop = m_rtDuration = 0;

	int iVideo = 1, iAudio = 1, iSubtitle = 1;

	POSITION pos = m_pFile->m_segment.Tracks.GetHeadPosition();
	while(pos)
	{
		Track* pT = m_pFile->m_segment.Tracks.GetNext(pos);

		POSITION pos2 = pT->TrackEntries.GetHeadPosition();
		while(pos2)
		{
			TrackEntry* pTE = pT->TrackEntries.GetNext(pos2);

			bool isSub = false;

			if(!pTE->Expand(pTE->CodecPrivate, ContentEncoding::TracksPrivateData))
				continue;

			CStringA CodecID = pTE->CodecID.ToString();

			CStringW Name;
			Name.Format(L"Output %I64d", (UINT64)pTE->TrackNumber);

			CMediaType mt;
			CAtlArray<CMediaType> mts;

			mt.SetSampleSize(1);

			if(pTE->TrackType == TrackEntry::TypeVideo)
			{
				Name.Format(L"Video %d", iVideo++);

				mt.majortype = MEDIATYPE_Video;

				if(CodecID == "V_MS/VFW/FOURCC")
				{
					mt.formattype = FORMAT_VideoInfo;
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount() - sizeof(BITMAPINFOHEADER));
					memset(mt.Format(), 0, mt.FormatLength());
					memcpy(&pvih->bmiHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					mt.subtype = FOURCCMap(pvih->bmiHeader.biCompression);
					switch(pvih->bmiHeader.biCompression)
					{
					case BI_RGB: case BI_BITFIELDS: mt.subtype = 
						pvih->bmiHeader.biBitCount == 1 ? MEDIASUBTYPE_RGB1 :
						pvih->bmiHeader.biBitCount == 4 ? MEDIASUBTYPE_RGB4 :
						pvih->bmiHeader.biBitCount == 8 ? MEDIASUBTYPE_RGB8 :
						pvih->bmiHeader.biBitCount == 16 ? MEDIASUBTYPE_RGB565 :
						pvih->bmiHeader.biBitCount == 24 ? MEDIASUBTYPE_RGB24 :
						pvih->bmiHeader.biBitCount == 32 ? MEDIASUBTYPE_ARGB32 :
						MEDIASUBTYPE_NULL;
						break;
//					case BI_RLE8: mt.subtype = MEDIASUBTYPE_RGB8; break;
//					case BI_RLE4: mt.subtype = MEDIASUBTYPE_RGB4; break;
					}
					mts.Add(mt);
				}
				else if(CodecID == "V_UNCOMPRESSED")
				{
				}
				else if(CodecID.Find("V_MPEG4/ISO/AVC") == 0 && pTE->CodecPrivate.GetCount() >= 6)
				{
					BYTE sps = pTE->CodecPrivate[5] & 0x1f;

	std::vector<BYTE> avcC;
	for(int i = 0, j = pTE->CodecPrivate.GetCount(); i < j; i++)
		avcC.push_back(pTE->CodecPrivate[i]);

	std::vector<BYTE> sh;

	unsigned jj = 6;

	while (sps--) {
	  if (jj + 2 > avcC.size())
	    goto avcfail;
	  unsigned spslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
	  if (jj + 2 + spslen > avcC.size())
	    goto avcfail;
	  unsigned cur = sh.size();
	  sh.resize(cur + spslen + 2, 0);
	  std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + spslen,sh.begin() + cur);
	  jj += 2 + spslen;
	}

	if (jj + 1 > avcC.size())
	  continue;

	unsigned pps = avcC[jj++];

	while (pps--) {
	  if (jj + 2 > avcC.size())
	    goto avcfail;
	  unsigned ppslen = ((unsigned)avcC[jj] << 8) | avcC[jj+1];
	  if (jj + 2 + ppslen > avcC.size())
	    goto avcfail;
	  unsigned cur = sh.size();
	  sh.resize(cur + ppslen + 2, 0);
	  std::copy(avcC.begin() + jj, avcC.begin() + jj + 2 + ppslen, sh.begin() + cur);
	  jj += 2 + ppslen;
	}

	goto avcsuccess;
avcfail:
	continue;
avcsuccess:

					CAtlArray<BYTE> data;
					data.SetCount(sh.size());
					std::copy(sh.begin(), sh.end(), data.GetData());

					mt.subtype = FOURCCMap('1CVA');
					mt.formattype = FORMAT_MPEG2Video;
					MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + data.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
					pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pm2vi->hdr.bmiHeader.biCompression = '1CVA';
					pm2vi->hdr.bmiHeader.biPlanes = 1;
					pm2vi->hdr.bmiHeader.biBitCount = 24;
					pm2vi->dwProfile = pTE->CodecPrivate[1];
					pm2vi->dwLevel = pTE->CodecPrivate[3];
					pm2vi->dwFlags = (pTE->CodecPrivate[4] & 3) + 1;
					BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
					memcpy(pSequenceHeader, data.GetData(), data.GetCount());
					pm2vi->cbSequenceHeader = data.GetCount();
					mts.Add(mt);
				}
				else if(CodecID.Find("V_MPEG4/") == 0)
				{
					mt.subtype = FOURCCMap('V4PM');
					mt.formattype = FORMAT_MPEG2Video;
					MPEG2VIDEOINFO* pm2vi = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					pm2vi->hdr.bmiHeader.biSize = sizeof(pm2vi->hdr.bmiHeader);
					pm2vi->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pm2vi->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pm2vi->hdr.bmiHeader.biCompression = 'V4PM';
					pm2vi->hdr.bmiHeader.biPlanes = 1;
					pm2vi->hdr.bmiHeader.biBitCount = 24;
					BYTE* pSequenceHeader = (BYTE*)pm2vi->dwSequenceHeader;
					memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					pm2vi->cbSequenceHeader = pTE->CodecPrivate.GetCount();
					mts.Add(mt);
				}
				else if(CodecID.Find("V_REAL/RV") == 0)
				{
					mt.subtype = FOURCCMap('00VR' + ((CodecID[9]-0x30)<<16));
					mt.formattype = FORMAT_VideoInfo;
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader);
					pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					pvih->bmiHeader.biCompression = mt.subtype.Data1;
					mts.Add(mt);
				}
				else if(CodecID == "V_DIRAC")
				{
					mt.subtype = MEDIASUBTYPE_DiracVideo;
					mt.formattype = FORMAT_DiracVideoInfo;
					DIRACINFOHEADER* dvih = (DIRACINFOHEADER*)mt.AllocFormatBuffer(FIELD_OFFSET(DIRACINFOHEADER, dwSequenceHeader) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					dvih->hdr.bmiHeader.biSize = sizeof(dvih->hdr.bmiHeader);
					dvih->hdr.bmiHeader.biWidth = (LONG)pTE->v.PixelWidth;
					dvih->hdr.bmiHeader.biHeight = (LONG)pTE->v.PixelHeight;
					dvih->hdr.dwPictAspectRatioX = dvih->hdr.bmiHeader.biWidth;
					dvih->hdr.dwPictAspectRatioY = dvih->hdr.bmiHeader.biHeight;

					BYTE* pSequenceHeader = (BYTE*)dvih->dwSequenceHeader;
					memcpy(pSequenceHeader, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					dvih->cbSequenceHeader = pTE->CodecPrivate.GetCount();

					mts.Add(mt);
				}
				else if(CodecID == "V_MPEG2")
				{
					BYTE* seqhdr = pTE->CodecPrivate.GetData();
					DWORD len = pTE->CodecPrivate.GetCount();
					int w = pTE->v.PixelWidth;
					int h = pTE->v.PixelHeight;

					if(MakeMPEG2MediaType(mt, seqhdr, len, w, h))
						mts.Add(mt);
				}
				else if(CodecID == "V_THEORA")
				{
					BYTE* thdr = pTE->CodecPrivate.GetData() + 3;

					mt.majortype		= MEDIATYPE_Video;
					mt.subtype			= FOURCCMap('OEHT');
					mt.formattype		= FORMAT_MPEG2_VIDEO;
					MPEG2VIDEOINFO* vih = (MPEG2VIDEOINFO*)mt.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO) + pTE->CodecPrivate.GetCount());
					memset(mt.Format(), 0, mt.FormatLength());
					vih->hdr.bmiHeader.biSize		 = sizeof(vih->hdr.bmiHeader);
					vih->hdr.bmiHeader.biWidth		 = *(WORD*)&thdr[10] >> 4;
					vih->hdr.bmiHeader.biHeight		 = *(WORD*)&thdr[12] >> 4;
					vih->hdr.bmiHeader.biCompression = 'OEHT';
					vih->hdr.bmiHeader.biPlanes		 = 1;
					vih->hdr.bmiHeader.biBitCount	 = 24;
					int nFpsNum	= (thdr[22]<<24)|(thdr[23]<<16)|(thdr[24]<<8)|thdr[25];
					int nFpsDenum	= (thdr[26]<<24)|(thdr[27]<<16)|(thdr[28]<<8)|thdr[29];
					if(nFpsNum) vih->hdr.AvgTimePerFrame = (REFERENCE_TIME)(10000000.0 * nFpsDenum / nFpsNum);
					vih->hdr.dwPictAspectRatioX = (thdr[14]<<16)|(thdr[15]<<8)|thdr[16];
					vih->hdr.dwPictAspectRatioY = (thdr[17]<<16)|(thdr[18]<<8)|thdr[19];
					mt.bFixedSizeSamples = 0;

					vih->cbSequenceHeader = pTE->CodecPrivate.GetCount();
					memcpy (&vih->dwSequenceHeader, pTE->CodecPrivate.GetData(), vih->cbSequenceHeader);

					mts.Add(mt);
				}
				else if(CodecID.Find("V_VP8") == 0) 
				{ 
					mt.subtype = FOURCCMap('08PV'); 
					mt.formattype = FORMAT_VideoInfo; 
					VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)mt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER) + pTE->CodecPrivate.GetCount()); 
					memset(mt.Format(), 0, mt.FormatLength()); 
					memcpy(mt.Format() + sizeof(VIDEOINFOHEADER), pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount()); 
					pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); 
					pvih->bmiHeader.biWidth = (LONG)pTE->v.PixelWidth; 
					pvih->bmiHeader.biHeight = (LONG)pTE->v.PixelHeight; 
					pvih->bmiHeader.biCompression = mt.subtype.Data1; 
					mts.Add(mt); 
				} 
/*
				else if(CodecID == "V_DSHOW/MPEG1VIDEO") // V_MPEG1
				{
					mt.majortype = MEDIATYPE_Video;
					mt.subtype = MEDIASUBTYPE_MPEG1Payload;
					mt.formattype = FORMAT_MPEGVideo;
					MPEG1VIDEOINFO* pm1vi = (MPEG1VIDEOINFO*)mt.AllocFormatBuffer(pTE->CodecPrivate.GetCount());
					memcpy(pm1vi, pTE->CodecPrivate.GetData(), pTE->CodecPrivate.GetCount());
					mt.SetSampleSize(pm1vi->hdr.bmiHeader.biWidth*pm1vi->hdr.bmiHeader.biHeight*4);
					mts.Add(mt);
				}
*/
				REFERENCE_TIME AvgTimePerFrame = 0;

                if(pTE->v.FramePerSec > 0)
					AvgTimePerFrame = (REFERENCE_TIME)(10000000i64 / pTE->v.FramePerSec);
				else if(pTE->DefaultDuration > 0)
					AvgTimePerFrame = (REFERENCE_TIME)pTE->DefaultDuration / 100;

				if(AvgTimePerFrame)
				{
					for(int i = 0; i < mts.GetCount(); i++)
					{
						if(mts[i].formattype == FORMAT_VideoInfo
						|| mts[i].formattype == FORMAT_VideoInfo2
						|| mts[i].formattype == FORMAT_MPEG2Video)
						{
							((VIDEOINFOHEADER*)mts[i].Format())->AvgTimePerFrame = AvgTimePerFrame;
						}
					}
				}

				if(pTE->v.DisplayWidth != 0 && pTE->v.DisplayHeight != 0)
				{
					for(int i = 0; i < mts.GetCount(); i++)
					{
						if(mts[i].formattype == FORMAT_VideoInfo)
						{
							DWORD vih1 = FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
							DWORD vih2 = FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader);
							DWORD bmi = mts[i].FormatLength() - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader);
							mt.formattype = FORMAT_VideoInfo2;
							mt.AllocFormatBuffer(vih2 + bmi);
							memcpy(mt.Format(), mts[i].Format(), vih1);
							memset(mt.Format() + vih1, 0, vih2 - vih1);
							memcpy(mt.Format() + vih2, mts[i].Format() + vih1, bmi);
							((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
							((VIDEOINFOHEADER2*)mt.Format())->dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
							mts.InsertAt(i++, mt);
						}
						else if(mts[i].formattype == FORMAT_MPEG2Video)
						{
							((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioX = (DWORD)pTE->v.DisplayWidth;
							((MPEG2VIDEOINFO*)mts[i].Format())->hdr.dwPictAspectRatioY = (DWORD)pTE->v.DisplayHeight;
						}
					}
				}
			}
HBITMAP CDpiHelper::CreateDeviceFromLogicalImage(HBITMAP _In_ hImage, ImageScalingMode scalingMode, Color clrBackground)
{
    IfNullAssertRetNull(hImage, "No image given to convert");

    // Instead of doing HBITMAP resizing with StretchBlt from one memory DC into other memory DC and HALFTONE StretchBltMode
    // which uses nearest neighbor resize algorithm (fast but results in pixelation), we'll use a GdiPlus image to do the resize, 
    // which allows specifying the interpolation mode for the resize resulting in smoother result.
    VsUI::GdiplusImage gdiplusImage;

    // Attaching the bitmap uses Bitmap.FromHBITMAP which does not take ownership of the HBITMAP passed as argument.
    // DeleteObject still needs to be used on the hImage but that should happen after the Bitmap object is deleted or goes out of scope.
    // The caller will have to DeleteObject both the HBITMAP they passed in this function and the new HBITMAP we'll be returning when we detach the GDI+ Bitmap
    gdiplusImage.Attach(hImage);

#ifdef DEBUG
    static bool fDebugDPIHelperScaling = false;
    WCHAR rgTempFolder[MAX_PATH];
    static int imgIndex = 1;
    CStringW strFileName;
    CPath pathTempFile;

    if (fDebugDPIHelperScaling)
    {
        if (!GetTempPath(_countof(rgTempFolder), rgTempFolder))
            *rgTempFolder = '\0';
    
        strFileName.Format(_T("DPIHelper_%05d_Before.png"), imgIndex);

        pathTempFile.Combine(rgTempFolder, strFileName);
        gdiplusImage.Save(pathTempFile);
    }
#endif

    Bitmap* pBitmap = gdiplusImage.GetBitmap();
    PixelFormat format = pBitmap->GetPixelFormat();
    const Color *pclrActualBackground = &clrBackground; 
    InterpolationMode interpolationMode = GetInterpolationMode(scalingMode);
    ImageScalingMode actualScalingMode = GetActualScalingMode(scalingMode);

    if (actualScalingMode != ImageScalingMode::NearestNeighbor)
    {
        // Modify the image. If the image is 24bpp or lower, convert to 32bpp so we can use alpha values
        if (format != PixelFormat32bppARGB)
        {
            pBitmap->ConvertFormat(PixelFormat32bppARGB, DitherTypeNone, PaletteTypeCustom, nullptr/*ColorPalette*/, 0 /*alphaThresholdPercent - all opaque*/);
        }

        // Now that we have 32bpp image, let's play with the pixels
        // Detect magenta or near-green in the image and use that as background
        VsUI::GdiplusImage::ProcessBitmapBits(pBitmap, [&](ARGB * pPixelData) 
        {
            if (clrBackground.GetValue() != TransparentColor.GetValue())
            {
                if (*pPixelData == clrBackground.GetValue())
                {
                    *pPixelData = TransparentHaloColor.GetValue();
                    pclrActualBackground = &clrBackground;
                }
            }
            else
            {
                if (*pPixelData == MagentaColor.GetValue())
                {
                    *pPixelData = TransparentHaloColor.GetValue();
                    pclrActualBackground = &MagentaColor;
                }
                else if (*pPixelData == NearGreenColor.GetValue())
                {
                    *pPixelData = TransparentHaloColor.GetValue();
                    pclrActualBackground = &MagentaColor;
                }
            }
        });
    }

    // Convert the GdiPlus image if necessary
    LogicalToDeviceUnits(&gdiplusImage, scalingMode, TransparentHaloColor);

    // Get again the bitmap, after the resize
    pBitmap = gdiplusImage.GetBitmap();

    if (actualScalingMode != ImageScalingMode::NearestNeighbor)
    {
        // Now that the bitmap is scaled up, convert back the pixels. 
        // Anything that is not fully opaque, make it clrActualBackground
        VsUI::GdiplusImage::ProcessBitmapBits(pBitmap, [&](ARGB * pPixelData) 
        {
            if ((*pPixelData & ALPHA_MASK) != 0xFF000000)
            {
                *pPixelData = pclrActualBackground->GetValue();
            }
        });

        // Convert back to original format
        if (format != PixelFormat32bppARGB)
        {
            pBitmap->ConvertFormat(format, DitherTypeNone, PaletteTypeCustom, nullptr/*ColorPalette*/, 0 /*alphaThresholdPercent - all opaque*/);
        }
    }

#ifdef DEBUG
    if (fDebugDPIHelperScaling)
    {
        strFileName.Format(_T("DPIHelper_%05d_After.png"), imgIndex++);
        pathTempFile.Combine(rgTempFolder, strFileName);
        gdiplusImage.Save(pathTempFile);
    }
#endif
  
    // Get the converted image handle - this returns a new HBITMAP that will need to be deleted when no longer needed
    // Detach using TransparentColor (transparent-black). If the result bitmap is to be used with AlphaBlend, that function 
    // keeps the background if the transparent pixels are black
    HBITMAP hBmpResult = gdiplusImage.Detach( TransparentColor );

    // When the image has 32bpp RGB format, when we call GDI+ to return an HBITMAP for the image, the result is actually
    // an ARGB bitmap (with alpha bytes==0xFF instead of reserved=0x00). Many GDI functions work with it fine, but 
    // adding it to an imagelist with ImageList_AddMasked will produce the wrong result, because the clrTransparent color 
    // won't match any background pixels due to the alpha byte value. So we need to zero-out out those bytes... 
    // If the bitmap was scaled with a bicubic/bilinear interpolation, the colors are interpolated with the clrBackground 
    // which may be transparent, so the resultant image will have alpha channel of interest, and we'll return the image as is.
    if (format == PixelFormat32bppRGB)
    {
        BITMAP bmp = {0};
        if (GetObject(hBmpResult, sizeof(bmp), &bmp) == sizeof(bmp) && bmp.bmBits != nullptr)
        {
            RGBQUAD* pPixels = reinterpret_cast<RGBQUAD*>(bmp.bmBits);

            for (int i=0; i< bmp.bmWidth * bmp.bmHeight; i++)
            {
                pPixels[i].rgbReserved = 0;
            }
        }
    }

    // Return the created image
    return hBmpResult;
}