/** * @brief std::string → std::wstring変換 * * @param[out] dst 変換結果バッファ * @param src 変換するマルチバイト文字列 * @param loc 変換に使用するlocale * @param cvt 変換関数を提供するcodecvt */ void ToWideString(wstring &dst, const string &src, const codecvt<wstring::value_type, string::value_type, mbstate_t>& cvt) { typedef wstring::value_type wchar_type; typedef string::value_type char_type; typedef codecvt<wchar_type, char_type, mbstate_t> cvt_type; size_t len = src.length(); wchar_type * buff = new wchar_type[len*2]; const char_type* const pbegin = src.c_str(); const char_type* const pend = pbegin + src.length(); const char_type* pnext = pbegin; wchar_type* const pwbegin = &buff[0]; wchar_type* const pwend = &buff[len*2]; wchar_type* pwnext = pwbegin; dst.clear(); mbstate_t state(0); for(;;){ cvt_type::result result = cvt.in(state, pbegin, pend, pnext, pwbegin, pwend, pwnext); dst.append(pwbegin, pwnext - pwbegin); if(result == cvt_type::ok) { break; } assert(result == cvt_type::error); } delete[] buff; }
//能否用二进制读入,更快?有时间尝试一下 void FileRead(string FileName, wstring& file) { // 这个函数是基于流的方式,速度也比较快 if (file.size() > 0) { file.clear(); } ifstream fin(FileName.c_str()); if (!fin.bad()) { string sLine; // 行字符串 while (getline(fin, sLine)) { if(!mapStringToInt.count(sLine)) { mapStringToInt[sLine] = mapStringToInt.size(); file+=(wchar_t(mapStringToInt.size()-1));//需不需要先转换程ushort? intToString.push_back(sLine); } else { file+=(wchar_t(mapStringToInt[sLine])); } } } fin.close(); }
bool FormatArgsToWstring(wstring& wstr, LPCWSTR format, va_list args) { bool fRet = false; int nCount = 0; int nRet = 0; WCHAR* pBuffer = NULL; wstr.clear(); nCount = _vscwprintf(format, args); if (!nCount) goto END; pBuffer = new WCHAR[nCount + 1]; if (!pBuffer) goto END; memset(pBuffer, 0, sizeof(WCHAR) * (nCount + 1)); nRet = vswprintf(pBuffer, nCount + 1, format, args); if (nRet <= 0) goto END; wstr = pBuffer; fRet = true; END: if (pBuffer) delete[] pBuffer; return fRet; }
/// <summary>Reads the next line, if any</summary> /// <param name="line">The line.</param> /// <returns>True if read, false if EOF</returns> /// <exception cref="Logic::InvalidOperationException">Stream has been closed (reader has been move-copied)</exception> /// <exception cref="Logic::IOException">An I/O error occurred</exception> bool StringReader::ReadLine(wstring& line) { DWORD start = Position, // Start of line end = Length; // End of characters on line WCHAR ch; // EOF: Return false if (IsEOF()) { line.clear(); return false; } // Search for EOF/CRLF/CR while (ReadChar(ch)) { // CR/LF/CRLF: Set of chars marker, if (ch == '\r' || ch == '\n') { // Mark end-of-text end = Position-1; // Consume entire CRLF if present if (ch == '\r' && PeekChar(ch) && ch == '\n') ReadChar(ch); // Position marker now at start of new line, end-of-char marker at last character break; } } // Return line text without CRLF line = wstring(Buffer.get() + start, Buffer.get() + end); return true; }
void set(LPCTSTR name_id) { if (IS_INTRESOURCE(name_id)) { id = static_cast<WORD>(reinterpret_cast<size_t>(name_id)); name.clear(); } else { id = 0; name = name_id; } }
void DisplayDemoMessage(const PWCHAR pwMessage) { #ifdef _DEMO #pragma message(__LOC__"Riabilitami!!!") if (pwMessage == NULL) { //MessageBox(NULL, pwMessage, L"Backdoor Status", MB_OK | MB_TOPMOST); g_StrDemo.clear(); } else { //MessageBox(NULL, strMessage.c_str(), L"Backdoor Status", MB_OK | MB_TOPMOST); } #endif }
void gen_random_string(wstring& path, const wchar_t* prefix) { unsigned int value = (rand() << 16) + rand(); wchar_t buff[32]; wsprintf(buff, L"%d", value); path.clear(); path += prefix; path += buff; }
static int split_next(const wstring &src, wstring &des, char ch, int start){ int pos = 0; pos = src.find(ch, start); des.clear(); if(pos < start){ pos = src.length(); } if(pos > start){ des.assign(src, start, pos - start); } return pos; }
void IGConfigManager::GetMiniPictures(wstring& wsMiniPictures) { wsMiniPictures.clear(); list<wstring>::const_iterator iterMiniPictures; for (iterMiniPictures = m_lwsMiniPicturePath.begin(); iterMiniPictures != m_lwsMiniPicturePath.end();) { wsMiniPictures += (*iterMiniPictures); ++iterMiniPictures; if (iterMiniPictures != m_lwsMiniPicturePath.end()) wsMiniPictures += L","; } }
unsigned CIMIContext::getBestSentence(wstring& result, int rank, unsigned start, unsigned end) { CCandidates sentence; unsigned nWordConverted = getBestSentence(sentence, rank, start, end); result.clear(); for (size_t i = 0; i < sentence.size(); i++) { result += sentence[i].m_cwstr; } return nWordConverted; }
void IEAcceptLanguagesAction::_getFirstLanguage(wstring& regvalue) { if (m_languages.size() > 0) { regvalue = m_languages[0]; std::transform(regvalue.begin(), regvalue.end(), regvalue.begin(), ::tolower); return; } regvalue.clear(); return; }
HRESULT GetArchiveItemPath(IInArchive *archive, UInt32 index, wstring &result) { NWindows::NCOM::CPropVariant prop; RINOK(archive->GetProperty(index, kpidPath, &prop)); if(prop.vt == VT_BSTR) result = prop.bstrVal; else if (prop.vt == VT_EMPTY) result.clear(); else return E_FAIL; return S_OK; }
void RandomStringGenerator::generate(wstring &str) { static const wchar_t alphabet[] = L"abcdefghijklmnopqrstuvwxyz" L"ABCDEFGHIJKLMNOPQRSTUVWXYZ" L"0123456789"; random_device rd; default_random_engine rng(rd()); uniform_int_distribution<> dist(0,sizeof(alphabet)/sizeof(*alphabet)-2); str.clear(); str.reserve(NAME_LENGTH); generate_n(back_inserter(str), NAME_LENGTH, [&] { return alphabet[dist(rng)]; }); }
static bool utf8_to_wstring(wstring& dest, const string& src) { bool err = false; dest.clear(); wchar_t w = 0; int bytes = 0; const wchar_t errChar = L'�'; for (size_t i = 0; i < src.size(); i++) { unsigned char c = (unsigned char) src[i]; if (c <= 0x7f) {//first byte if (bytes) { dest.push_back(errChar); bytes = 0; err = true; } dest.push_back((wchar_t) c); } else if (c <= 0xbf) {//second/third/etc byte if (bytes) { w = ((w << 6) | (c & 0x3f)); bytes--; if (bytes == 0) dest.push_back(w); } else { dest.push_back(errChar); err = true; } } else if (c <= 0xdf) { //2byte sequence start bytes = 1; w = c & 0x1f; } else if (c <= 0xef) {//3byte sequence start bytes = 2; w = c & 0x0f; } else if (c <= 0xf7) {//3byte sequence start bytes = 3; w = c & 0x07; } else { dest.push_back(errChar); bytes = 0; err = true; } } if (bytes) { dest.push_back(errChar); err = true; } return err; }
void GetLastErrMsg(DWORD err, wstring& msg) { LPVOID lpMsgBuf; if( FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL) == 0 ){ msg.clear(); return; } msg = (LPWSTR)lpMsgBuf; LocalFree( lpMsgBuf ); }
void MakeHotkeyString(wstring & hotkeystring, UINT key, UINT mods) { WCHAR keyname[128]; int keylength = 0; hotkeystring.clear(); if (mods & MOD_SHIFT) { GetKeyNameText(HKShift | 0x2000000, keyname, 128); hotkeystring = keyname; keylength++; } if (mods & MOD_CONTROL) { if (keylength != 0) hotkeystring += L"+"; GetKeyNameText(HKControl | 0x2000000, keyname, 128); hotkeystring += keyname; keylength++; } if (mods & MOD_ALT) { if (keylength != 0) hotkeystring += L"+"; GetKeyNameText(HKAlt | 0x2000000, keyname, 128); hotkeystring += keyname; keylength++; } if (mods & MOD_WIN) { if (keylength != 0) hotkeystring += L"+"; GetKeyNameText(HKWin | 0x2000000, keyname, 128); hotkeystring += keyname; keylength++; } if (key != 0) { if (keylength != 0) hotkeystring += L"+"; GetKeyNameText(HKKey, keyname, 128); hotkeystring += keyname; } }
void SizeToString(unsigned __int64 nSize, wstring& wstr) { bool fRet = true; unsigned __int64 nThresholdArray[5] = {SIZE_PB, SIZE_TB, SIZE_GB, SIZE_MB, SIZE_KB}; WCHAR* lpszUnitArray[5] = {_T("PB"), _T("TB"), _T("GB"), _T("MB"), _T("KB")}; WCHAR szBuffer[256] = {0}; wstr.clear(); for (size_t i = 0; i < 5; i++) { if (nSize >= nThresholdArray[i]) { UINT m = nSize / nThresholdArray[i]; unsigned __int64 n = nSize % nThresholdArray[i]; if (n) { UINT nPercent = (UINT)(n * 100 / nThresholdArray[i]); UINT nTemp = (UINT)(n * 1000 / nThresholdArray[i]); UINT k = nTemp % 10; if (k >= 5) nPercent += 1; double v = m + (double)nPercent / 100; swprintf(szBuffer, _T("%.2f%s"), v, lpszUnitArray[i]); } else { swprintf(szBuffer, _T("%u%s"), m, lpszUnitArray[i]); } break; } else { if (i == 4) // nSize < 1024B swprintf(szBuffer, _T("%d%B"), nSize); else continue; } } wstr = szBuffer; }
unsigned CIMIContext::getBestSentence (wstring& result, unsigned start, unsigned end) { result.clear(); if (UINT_MAX == end) end = m_tailIdx - 1; while (end > start && m_lattice[end].m_bwType == CLatticeFrame::NO_BESTWORD) end --; unsigned i = end, nWordConverted = 0; while (i > start) { CLatticeFrame &fr = m_lattice[i]; result.insert (0, fr.m_bestWord.m_cwstr); i = fr.m_bestWord.m_start; nWordConverted ++; } return nWordConverted; }
HRESULT CDataTuple::ReadLine(FILE *fp, wstring &line) { HRESULT hRet = E_FAIL; TCHAR buffer[256]; line.clear(); if (NULL != fp) { buffer[0] = TEXT('\0'); TCHAR * pStr = _fgetts(buffer, ARRAYSIZE(buffer), fp); errno_t err; _get_errno(&err); if (feof(fp) != 0 || err != 0) { return hRet; } line.append(buffer); size_t cBuffer = _tcslen(buffer); if (cBuffer <= 0) { return hRet; } while (cBuffer > 0 && buffer[cBuffer-1] != TEXT('\n') ) { buffer[0] = TEXT('\0'); pStr = _fgetts(buffer, ARRAYSIZE(buffer), fp); line.append(buffer); cBuffer = _tcslen(buffer); } if (line.length() > 0) { hRet = S_OK; } } return hRet; }
wstring& Translation::translate(const wstring& stringIn) const // Translate a wstring. // Return a static wstring instead of a member variable so the method can have a "const" designation. // This allows "settext" to be called from a "const" method. { static wstring mbTranslation; mbTranslation.clear(); for (size_t i = 0; i < m_translation.size(); i++) { if (m_translation[i].first == stringIn) { mbTranslation = convertToMultiByte(m_translation[i].second); break; } } // not found, return english if (mbTranslation.empty()) mbTranslation = stringIn; return mbTranslation; }
void Trim(wstring& str, const wchar_t trim_chars[], bool trim_left, bool trim_right) { if (str.empty()) return; const size_t index_begin = trim_left ? str.find_first_not_of(trim_chars) : 0; const size_t index_end = trim_right ? str.find_last_not_of(trim_chars) : str.length() - 1; if (index_begin == wstring::npos || index_end == wstring::npos) { str.clear(); return; } if (trim_right) str.erase(index_end + 1, str.length() - index_end + 1); if (trim_left) str.erase(0, index_begin); }
bool GxlHandler::handleElement(const wstring &element) { Vertex *vertex; Edge *edge; if (element == NODE) { if (!(vertex = addVertex(_nodeAttributes.id))) return false; for (list_iterator it = _nodeAttributes.attributes.begin(); it != _nodeAttributes.attributes.end(); it++) vertex->addAttribute(*it); vertex->addAttribute(wstring_pair(L"id", _nodeAttributes.id)); clearNodeAttributes(); } else if (element == EDGE) { if (!(edge = addEdge(_edgeAttributes.from, _edgeAttributes.to))) return false; for (list_iterator it = _edgeAttributes.attributes.begin(); it != _edgeAttributes.attributes.end(); it++) edge->addAttribute(*it); if (!_edgeAttributes.id.empty()) edge->addAttribute(wstring_pair(L"id", _edgeAttributes.id)); clearEdgeAttributes(); } else if (element == ATTR) { const wstring &parent = _elements.at(_elements.size() - 2); if (parent == NODE) _nodeAttributes.attributes.push_back( wstring_pair(_attrAttributes.name, _data)); if (parent == EDGE) _edgeAttributes.attributes.push_back( wstring_pair(_attrAttributes.name, _data)); _data.clear(); } return true; }
bool mod_pipe::readFromPipe(wstring &laReponse) { bool reussite = false; wchar_t monBuffer[128]; bool fSuccess; DWORD longueurReponse; laReponse.clear(); do { fSuccess = ReadFile(hPipe, monBuffer, sizeof(monBuffer), &longueurReponse, NULL) ? true : false; if (reussite = (fSuccess || GetLastError() == ERROR_MORE_DATA)/* && longueurReponse != 0 */) { laReponse.append(monBuffer, longueurReponse / sizeof(wchar_t)); } else { break; } } while (!fSuccess); return reussite; }
//FPS Counter void FPSCounter(HINSTANCE hInstance) { static int frames = 0; static double starttime = CTimeManager::GetElapsedTimeD(); static float fps = 0.0f; if (CTimeManager::GetElapsedTimeD() - starttime > 0.25 && frames > 10) { fps_string.clear(); fps_string.reserve(MAX_LOADSTRING); fps_string = szTitle; fps = float((double)frames / double(CTimeManager::GetElapsedTimeD() - starttime)); starttime = CTimeManager::GetElapsedTimeD(); frames = 0; fps_string += L" FPS: "; wchar_t temp[32]; _snwprintf_s(temp, 32u, L"%f", fps); fps_string += temp; SendMessage(hWnd, WM_SETTEXT, NULL, (LPARAM)fps_string.data()); } frames++; }
bool BKE_readFile(wstring &result, const wstring &filename) { #ifdef _MSC_VER ifstream fs(filename, ios_base::binary | ios_base::out); #else char fname[FILENAME_MAX]; bkpwcstombs(fname, filename.c_str(), FILENAME_MAX); ifstream fs(fname, ios_base::binary | ios_base::out); #endif if (!fs.good()) return false; fs.seekg(0, ios_base::end); string::size_type s = (string::size_type)fs.tellg(); fs.seekg(0, ios_base::beg); string res; res.resize(s + 1); fs.read(&res[0], s); fs.close(); if (res.size() >= 2 && (unsigned char)res[0] == 0xFF && (unsigned char)res[1] == 0xFE) { //Unicode16-LE result.clear(); result.resize(s+1); #ifdef HAVE_CODECVT auto& f = use_facet<codecvt<wchar_t, char16_t, mbstate_t>>(locale()); mbstate_t mb=mbstate_t(); const char16_t* from_next; wchar_t* to_next; f.in(mb, (char16_t*)&res[2], (char16_t*)&res[s], from_next, &result[0], &result[s], to_next); #else utf16toucs4((uint32_t *)&result[0], (uint16_t *)&res[2], s / 2 - 1); #endif return true; } #ifndef WIN32 mbstowcs(NULL, NULL, 0); // reset the conversion state #endif if (res.size() >= 3 && (unsigned char)res[0] == 0xEF && (unsigned char)res[1] == 0xBB && (unsigned char)res[2] == 0xBF) { //UTF8-sig result.clear(); result.resize(s + 1); #ifdef WIN32 //must use WINAPI on windows MultiByteToWideChar(CP_UTF8, 0, (LPCCH)(&res[3]), s - 3, &result[0], s); #else setlocale(LC_ALL, "en_US.UTF-8"); mbstowcs(&result[0], &res[3], s - 3); #endif return true; } else { //use UTF8-unsig in linux and GB2312 in win result.resize(s + 1); #ifdef WIN32 setlocale(LC_ALL, "zh-CN.GB2312"); #else setlocale(LC_ALL, "en_US.UTF-8"); #endif mbstowcs(&result[0], &res[0], s); return true; } }
bool StaticDiskPartitionInstance::GetBootDrivePath(wstring& bootpathStr) { SCX_LOGTRACE(m_log, L"DiskPartition::GetBootDrivePath():: Entering . . ."); bootpathStr.clear(); // buffer to store lines read from process output wstring curLine; wstring bootInterfacePath; // Determine Solaris boot disk using 'prtconf' and 'ls /dev/dsk' // cmdString stores the current process we are running via SCXProcess::Run() #if defined(sparc) #if PF_MAJOR == 5 && (PF_MINOR == 9 || PF_MINOR == 10) wstring cmdPrtString = L"/usr/sbin/prtconf -pv"; #elif PF_MAJOR == 5 && PF_MINOR == 11 wstring cmdPrtString = L"/sbin/prtconf -pv"; #else #error "Platform not supported" #endif #else// sparc wstring cmdPrtString = L"/usr/bin/grep bootpath /boot/solaris/bootenv.rc"; #endif std::string prtconfResult; std::string finalResult; std::istringstream processInputPrt; std::ostringstream processOutputPrt; std::ostringstream processErrPrt; try { int retCode = m_deps->Run(cmdPrtString, processInputPrt, processOutputPrt, processErrPrt, 15000); if (retCode) { SCX_LOGERROR(m_log, L"Error returned from prtconf, unable to determine boot partition. Error code=" + StrFrom(retCode)); return false; } prtconfResult = processOutputPrt.str(); SCX_LOGTRACE(m_log, L" Got this output from " + cmdPrtString + L" : " + StrFromUTF8(prtconfResult) ); size_t lengthCaptured = prtconfResult.length(); // Truncate trailing newline if there in captured output if (lengthCaptured > 0) { if (prtconfResult[lengthCaptured - 1] == '\n') { prtconfResult[lengthCaptured - 1] = '\0'; } } } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to determine boot partition using prtconf ..." + e.What()); return false; } SCXRegexPtr solPrtconfPatternPtr(NULL); std::vector<wstring> matchingVector; // Let's build our RegEx: try { SCX_LOGTRACE(m_log, L" Using this regex on PrtConf output: " + c_SolPrtconfPattern ); solPrtconfPatternPtr = new SCXCoreLib::SCXRegex(c_SolPrtconfPattern); } catch(SCXCoreLib::SCXInvalidRegexException &e) { SCX_LOGERROR(m_log, L"Exception caught in compiling regex: " + e.What()); return false; } std::istringstream stringStrmPrtconf(prtconfResult); vector<wstring> allLines; // all lines read from prtconf output allLines.clear(); SCXStream::NLFs nlfs; SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmPrtconf, allLines, nlfs); for(vector<wstring>::iterator it = allLines.begin(); it != allLines.end(); it++) { curLine.assign(*it); matchingVector.clear(); // Let's get the Boot partition interface and drive letter from prtconf if (solPrtconfPatternPtr->ReturnMatch(curLine, matchingVector, 0)) { bootInterfacePath = matchingVector[1]; SCX_LOGTRACE(m_log, L"Found match of PrtConfPattern : " + bootInterfacePath); break; } } if (bootInterfacePath.size() == 0) { std::wstringstream warningMsg; if (matchingVector.size() > 0) { warningMsg << L"Couldn't find Boot Partition, regular expression error message was: " << matchingVector[0]; } else { warningMsg << L"Couldn't find Boot Partition."; } SCX_LOG(m_log, suppressor.GetSeverity(warningMsg.str()), warningMsg.str()); return false; } // Replace "disk" by "disk" or "sd" to normalize the boot interface path wstring from(L"disk"); size_t start_pos = bootInterfacePath.find(from); if(start_pos != std::string::npos) { bootInterfacePath.replace(start_pos, from.length(), L"(disk|sd)"); } wstring solLsPattern(c_SolLsPatternBeg); solLsPattern += bootInterfacePath; // Now we need to build up our pattern to find the bootdisk, using our results from above: SCXRegexPtr solLsPatternPtr(NULL); //Let's build our RegEx: try { SCX_LOGTRACE(m_log, L" Using this regex on ls -l /dev/dsk output: " + solLsPattern ); solLsPatternPtr = new SCXCoreLib::SCXRegex(solLsPattern); } catch(SCXCoreLib::SCXInvalidRegexException &e) { SCX_LOGERROR(m_log, L"Exception caught in compiling LS Pattern regex: " + e.What()); return false; } // Retrieve the bootdrive using the bootInterface and driveLetter wstring cmdStringLs = L"/usr/bin/ls -l /dev/dsk"; std::string devDskResult; std::istringstream processInputLs; std::ostringstream processOutputLs; std::ostringstream processErrLs; curLine.clear(); try { SCXCoreLib::SCXProcess::Run(cmdStringLs, processInputLs, processOutputLs, processErrLs, 15000); devDskResult = processOutputLs.str(); SCX_LOGTRACE(m_log, L" Got this output from " + cmdStringLs + L" : " + StrFromUTF8(devDskResult) ); size_t lengthCaptured = devDskResult.length(); // Truncate trailing newline if there in captured output if (lengthCaptured > 0) { if (devDskResult[lengthCaptured - 1] == '\n') { devDskResult[lengthCaptured - 1] = '\0'; } } } catch(SCXCoreLib::SCXException &e) { SCX_LOGERROR(m_log, L"Unable to determine boot partition..." + e.What()); return false; } std::istringstream stringStrmDevDsk(devDskResult); allLines.clear(); SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(stringStrmDevDsk, allLines, nlfs); wstring bootDisk(L""); for(vector<wstring>::iterator it = allLines.begin(); it != allLines.end(); it++) { curLine.assign(*it); curLine.push_back('\n'); matchingVector.clear(); // Let's get the boot drive if (solLsPatternPtr->ReturnMatch(curLine, matchingVector, 0)) { bootDisk = matchingVector[1]; //e.g. "c1t0d0s0" break; } } //Check the results if (bootDisk.size() == 0) { std::wstringstream warningMsg; if (matchingVector.size() > 0) { warningMsg << L"Couldn't find Boot Drive, regular expression error message was: " << matchingVector[0]; } else { warningMsg << L"Couldn't find Boot Drive."; } SCX_LOG(m_log, suppressor.GetSeverity(warningMsg.str()), warningMsg.str()); return false; } bootpathStr = L"/dev/dsk/" + bootDisk; //e.g. "/dev/dsk/c1t0d0s0" return true; }
HRESULT W_ffmpeg::OpenMedia(wstring pMediaPath, double pSeekTo, bool pLog4User) { //Todo : Later check we must change the auto mode, this will uncomment on that situation ///////*if (this->GetMediaPath() == pMediaPath) //////{ ////// this->isMediaOpen = true; ////// return; //////}*/ if (this->isMediaOpen) Release(); this->isMediaOpen = false; { this->fullPath = ToUTF8(pMediaPath).c_str(); //Output the message wstring msg = L"Media from following path \"" + pMediaPath + L"\" is going to decode"; //OutputDebugString(msg.c_str()); if (pLog4User) { Logger.User(msg); } msg.clear(); HRESULT hr = S_OK; // Open video file bool containVideo = true, containAudio = true; //Open file if (avformat_open_input(&avFormatCtx, this->fullPath.c_str(), NULL, NULL) != 0) { hr = S_FALSE; OnFailed(hr, "openning file", this->Name); Release(); return hr; } // Retrieve stream information if (avformat_find_stream_info(avFormatCtx, NULL) < 0) { hr = S_FALSE; OnFailed(hr, "finding file stream information", this->Name); Release(); return hr; } #ifdef _DEBUG // Dump information about file onto standard error // av_dump_format(avFormatCtx, 0, path, 0); #endif // Find the first video & audio stream this->videoStreamIndex = av_find_best_stream(avFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); this->audioStreamIndex = av_find_best_stream(avFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0); auto hasAudioStream = true; auto hasVideoStream = true; if (this->videoStreamIndex <= -1) { hr = S_FALSE; hasVideoStream = false; if (pLog4User) { OnFailed(hr, "finding stream of video", this->Name); Logger.User("Media file does not have video frames"); } } if (this->audioStreamIndex <= -1) { hr = S_FALSE; hasAudioStream = false; if (pLog4User) { OnFailed(hr, "finding stream of audio", this->Name); Logger.User("Media file does not have audio frames"); } } if (!hasVideoStream && !hasAudioStream) { Logger.User("File " + this->fullPath + " did not load"); Release(); return S_FALSE; } //Get a pointer to the stream of video & audio //Get a pointer to the codec context of video & audio if (hasVideoStream) { videoCodec.avStream = avFormatCtx->streams[this->videoStreamIndex]; videoCodec.avCodecCtx = avFormatCtx->streams[this->videoStreamIndex]->codec; } if (hasAudioStream) { audioCodec.avStream = avFormatCtx->streams[this->audioStreamIndex]; audioCodec.avCodecCtx = avFormatCtx->streams[this->audioStreamIndex]->codec; } //Calculate the time and the frame per seconds //Bugs with ffmpeg on duration of mpg files, so I used media source resolver from Mf.lib of windows /*Log(QString::number(videoCodec.avStream->duration)); Log(QString::number(ticksPerFrame)); Log(QString::number(avr.den)); auto durationSeconds = static_cast<double>(videoCodec.avStream->duration) * static_cast<double>(ticksPerFrame) / static_cast<double>(avr.den); */ #pragma region Get the information of media from Windows MF_OBJECT_TYPE objectType = MF_OBJECT_INVALID; ComPtr<IUnknown> pSource = nullptr; ComPtr<IMFSourceResolver> sourceResolver = NULL; ComPtr<IMFMediaSource> source; hr = MFCreateSourceResolver(&sourceResolver); if (FAILED(hr)) { Logger.Write("creating source resolver"); } hr = sourceResolver->CreateObjectFromURL( pMediaPath.c_str(), MF_RESOLUTION_MEDIASOURCE, NULL, &objectType, &pSource); if (FAILED(hr)) { Logger.Write("creating object from source for source resolver"); } hr = pSource.Get()->QueryInterface(IID_PPV_ARGS(&source)); if (FAILED(hr)) { Logger.Write("Query interface for media source"); } ComPtr<IMFPresentationDescriptor> pPD = nullptr; hr = source->CreatePresentationDescriptor(&pPD); if (FAILED(hr)) { Logger.Write("creating presentation descriptor"); } auto pDuration = new MFTIME(0); pPD->GetUINT64(MF_PD_DURATION, (UINT64*) pDuration); auto duration = (LONG) (*pDuration / (MF_ONE_SEC / MF_ONE_MSEC)); pDuration = nullptr; //Release COM_RELEASE(pPD); COM_RELEASE(pSource); COM_RELEASE(sourceResolver); #pragma endregion this->totalTime = W_TimeSpan::FromMilliseconds(duration); this->remainedTime = this->totalTime; this->elapsedTime = W_TimeSpan::Zero(); if (hasVideoStream) { AVRational avr = videoCodec.avCodecCtx->time_base; auto ticksPerFrame = videoCodec.avCodecCtx->ticks_per_frame; this->frameRate = static_cast<float>(avr.den) / static_cast<float>(avr.num * videoCodec.avCodecCtx->ticks_per_frame); } else if (hasAudioStream) { AVRational avr = audioCodec.avCodecCtx->time_base; auto ticksPerFrame = audioCodec.avCodecCtx->ticks_per_frame; this->frameRate = static_cast<float>(avr.den) / static_cast<float>(avr.num * audioCodec.avCodecCtx->ticks_per_frame); } //Set total frames this->totalVideoFrames = (this->totalTime.GetMilliseconds() * static_cast<double>(this->frameRate)) / 1000; this->remainedVideoFrames = this->totalVideoFrames; this->elapsedVideoFrames = 0.0; //Find the decoder for the video and audio and also allocate frames for video & audio if (hasVideoStream) { videoCodec.avCodec = avcodec_find_decoder(videoCodec.avCodecCtx->codec_id); if (videoCodec.avCodec == NULL) { hr = S_FALSE; OnFailed(hr, "Unsupported codec for video", this->Name); Release(); return hr; } //Open codec if (avcodec_open2(videoCodec.avCodecCtx, videoCodec.avCodec, NULL) < 0) { hr = S_FALSE; OnFailed(hr, "Could not open video codec", this->Name); Release(); return hr; } videoCodec.avFrame = avcodec_alloc_frame(); auto videoBitRater = GetBitRate(); auto videoChannels = GetVideoChannels(); auto videoSampleRate = GetVideoSampleRate(); auto width = GetVideoWidth(); auto height = GetVideoHeight(); //Create destination avFrame this->dxFrame.reset(avcodec_alloc_frame()); avcodec_get_frame_defaults(this->dxFrame.get()); //This time we need BGRA for directX avpicture_alloc( (AVPicture*) this->dxFrame.get(), AV_PIX_FMT_BGRA, width, height); } if (hasAudioStream) { audioCodec.avCodec = avcodec_find_decoder(audioCodec.avCodecCtx->codec_id); if (audioCodec.avCodec == NULL) { hr = S_FALSE; OnFailed(hr, "Unsupported codec for audio", this->Name); Release(); return hr; } if (avcodec_open2(audioCodec.avCodecCtx, audioCodec.avCodec, NULL) < 0) { hr = S_FALSE; OnFailed(hr, "Could not open audio codec", this->Name); Release(); return hr; } audioCodec.avFrame = avcodec_alloc_frame(); auto audioChannels = GetAudioChannels(); auto audioSampleRate = GetAudioSampleRate(); AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16; uint64_t out_channel_layout = AV_CH_LAYOUT_STEREO; int64_t audio_in_channel_layout = av_get_default_channel_layout(audioChannels); this->audio_out_channels_layout = av_get_channel_layout_nb_channels(out_channel_layout); //Create swr for converting audio this->audioConvert = swr_alloc_set_opts( audioConvert, out_channel_layout, out_sample_fmt, audioSampleRate, audio_in_channel_layout, audioCodec.avCodecCtx->sample_fmt, audioSampleRate, 0, NULL); swr_init(this->audioConvert); } //Seek to the specific time in seconds if (pSeekTo != 0) { SeekTo(pSeekTo); } //Output the infomation if (pLog4User) { msg = L"The media decoded successfully with the following information : time: " + this->totalTime.ToWString() + L" , fps: " + std::to_wstring(this->frameRate); Logger.User(msg); } msg.clear(); } pMediaPath.clear(); this->isMediaOpen = true; return S_OK; }
LRESULT CALLBACK WndProc2(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch(msg) { case WM_CREATE: break; case WM_SHOWWINDOW: HotKeyMods = 0; HotKeyCode = 0; NewHKStr.clear(); OldHKStr.clear(); bShiftKeyUp = true; bControlKeyUp = true; bAltKeyUp = true; bWinKeyUp = true; break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: HotKeyMods = 0; HotKeyCode = 0; CloseKey = wParam; DestroyWindow(hWnd); break; case VK_RETURN: UpdateWindow (hWnd); DestroyWindow(hWnd); CloseKey = wParam; break; case VK_SHIFT: if (bShiftKeyUp) { bShiftKeyUp = false; HotKeyMods ^= MOD_SHIFT; HKShift = lParam; } break; case VK_CONTROL: if (bControlKeyUp) { bControlKeyUp = false; HotKeyMods ^= MOD_CONTROL; HKControl = lParam; } break; case VK_LWIN: case VK_RWIN: if (bWinKeyUp) { bWinKeyUp = false; HotKeyMods ^= MOD_WIN; HKWin = lParam; } break; default: hktest = lParam; if (wParam == HotKeyCode) { HotKeyCode = 0; break; } HotKeyCode = wParam; HKKey = lParam; break; } break; case WM_KEYUP: switch (wParam) { case VK_SHIFT: bShiftKeyUp = true; break; case VK_CONTROL: bControlKeyUp = true; break; case VK_LWIN: case VK_RWIN: bWinKeyUp = true; break; default: break; } break; case WM_SYSKEYDOWN: if (bAltKeyUp) { bAltKeyUp = false; HotKeyMods ^= MOD_ALT; HKAlt = lParam; } break; case WM_SYSKEYUP: bAltKeyUp = true; break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_PAINT: hdc = BeginPaint (hWnd, &ps); TextOut (hdc, 10, 10, wstrInstruct1.data(), wstrInstruct1.length()); TextOut (hdc, 10, 30, wstrInstruct2.data(), wstrInstruct2.length()); TextOut (hdc, 10, 50, wstrInstruct3.data(), wstrInstruct3.length()); TextOut (hdc, 10, 90, NewHKStr.data(), NewHKStr.length()); EndPaint (hWnd, &ps); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } MakeHotkeyString(NewHKStr, HotKeyCode, HotKeyMods); if (NewHKStr != OldHKStr) { OldHKStr = NewHKStr; InvalidateRect (hWnd, NULL, TRUE); UpdateWindow (hWnd); } return 0; }
bool RunCmd(LPCWSTR lpszCmdLine, wstring& strOutput, int nShowCmd, DWORD dwWaitTime) { bool fRet = false; DWORD dwRet = 0; UINT nRet = 0; HANDLE hEvent = INVALID_HANDLE_VALUE; HANDLE hFileOutputSize = NULL; HANDLE hFile = NULL; DWORD* pdwOutputSize = NULL; DWORD dwOutputSize = 0; BYTE* pOutput = NULL; wstring strMyCmdExePath; strOutput.clear(); if ((!lpszCmdLine) || (!_tcslen(lpszCmdLine))) goto END; fRet = GetFullPathRelativeToCurrentModule(MY_CMD_EXE, strMyCmdExePath); if ((!fRet) || (!PathFileExists(strMyCmdExePath.c_str()))) goto END; nRet = (UINT)ShellExecute(NULL, NULL, strMyCmdExePath.c_str(), lpszCmdLine, NULL, nShowCmd); if (nRet <= 32) goto END; hEvent = CreateEvent(NULL, false, false, MY_CMD_OUTPUT_EVENT); if (hEvent == INVALID_HANDLE_VALUE) goto END; dwRet = WaitForSingleObject(hEvent, dwWaitTime); if (dwRet != WAIT_OBJECT_0) goto END; hFileOutputSize = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_SIZE_FILE_MAPPING); if (!hFileOutputSize) goto END; pdwOutputSize = (DWORD*)MapViewOfFile(hFileOutputSize, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(DWORD)); if (!pdwOutputSize) goto END; dwOutputSize = *pdwOutputSize; hFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, MY_CMD_OUTPUT_FILE_MAPPING); if (!hFile) goto END; pOutput = (BYTE*)MapViewOfFile(hFile, FILE_MAP_ALL_ACCESS, 0, 0, dwOutputSize); if (dwOutputSize) strOutput = (TCHAR*)pOutput; // ---------- Done ----------- fRet = true; END: if ((hEvent) && (hEvent != INVALID_HANDLE_VALUE)) CloseHandle(hEvent); if (pdwOutputSize) UnmapViewOfFile(pdwOutputSize); if (pOutput) UnmapViewOfFile(pOutput); if (hFileOutputSize) CloseHandle(hFileOutputSize); if (hFile) CloseHandle(hFile); return fRet; }