int sec_aes_import_key(void) { int ret = SEC_OK; uchar key[AES_KEY_SIZE] = {0}; AES_VER aes_ver = AES_VER_LEGACY; uint32 key_len = 0; /* avoid re-init aes key if re-init key again, key value will be decoded twice ..*/ if(TRUE == bAesKeyInit) { SMSG("[%s] reset aes vector\n",MOD); /* initialize internal crypto engine */ if(SEC_OK != (ret = lib_aes_init_vector (rom_info.m_SEC_CTRL.m_sec_aes_legacy?(AES_VER_LEGACY):(AES_VER_SO)))) { goto _end; } return ret; } bAesKeyInit = TRUE; if(0 != mcmp(rom_info.m_id,RI_NAME,RI_NAME_LEN)) { SMSG("[%s] error. key not found\n",MOD); ret = ERR_AES_KEY_NOT_FOUND; goto _end; } /* -------------------------- */ /* check aes type */ /* -------------------------- */ if(TRUE == rom_info.m_SEC_CTRL.m_sec_aes_legacy) { aes_ver = AES_VER_LEGACY; key_len = 32; } else { aes_ver = AES_VER_SO; key_len = 16; } /* -------------------------- */ /* get sml aes key */ /* -------------------------- */ if(FALSE == rom_info.m_SEC_CTRL.m_sml_aes_key_ac_en) { sec_decode_key( rom_info.m_SEC_KEY.sml_aes_key, sizeof(rom_info.m_SEC_KEY.sml_aes_key), rom_info.m_SEC_KEY.crypto_seed, sizeof(rom_info.m_SEC_KEY.crypto_seed)); dump_buf(rom_info.m_SEC_KEY.sml_aes_key,4); mcpy(key,rom_info.m_SEC_KEY.sml_aes_key,sizeof(key)); } else { SMSG("\n[%s] AC enabled\n",MOD); dump_buf(secroimg.m_andro.sml_aes_key,4); sec_decode_key( secroimg.m_andro.sml_aes_key, sizeof(secroimg.m_andro.sml_aes_key), (uchar*)SML_SCRAMBLE_SEED, sizeof(SML_SCRAMBLE_SEED)); dump_buf(secroimg.m_andro.sml_aes_key,4); mcpy(key,secroimg.m_andro.sml_aes_key,sizeof(key)); } /* initialize internal crypto engine */ if(SEC_OK != (ret = lib_aes_init_key (key,key_len,aes_ver))) { goto _end; } _end: return ret; }
void OBS::DrawStatusBar(DRAWITEMSTRUCT &dis) { if(!App->bRunning) return; HDC hdcTemp = CreateCompatibleDC(dis.hDC); HBITMAP hbmpTemp = CreateCompatibleBitmap(dis.hDC, dis.rcItem.right-dis.rcItem.left, dis.rcItem.bottom-dis.rcItem.top); SelectObject(hdcTemp, hbmpTemp); SelectObject(hdcTemp, GetCurrentObject(dis.hDC, OBJ_FONT)); //HBRUSH hColorBrush = CreateSolidBrush((green<<8)|red); RECT rc; mcpy(&rc, &dis.rcItem, sizeof(rc)); rc.left -= dis.rcItem.left; rc.right -= dis.rcItem.left; rc.top -= dis.rcItem.top; rc.bottom -= dis.rcItem.top; FillRect(hdcTemp, &rc, (HBRUSH)(COLOR_BTNFACE+1)); //DeleteObject(hColorBrush); //-------------------------------- if(dis.itemID == 4) { DWORD green = 0xFF, red = 0xFF; statusBarData.bytesPerSec = App->bytesPerSec; statusBarData.strain = App->curStrain; //statusBarData.strain = rand()%101; if(statusBarData.strain > 50.0) green = DWORD(((50.0-(statusBarData.strain-50.0))/50.0)*255.0); double redStrain = statusBarData.strain/50.0; if(redStrain > 1.0) redStrain = 1.0; red = DWORD(redStrain*255.0); //-------------------------------- HBRUSH hColorBrush = CreateSolidBrush((green<<8)|red); RECT rcBox = {0, 0, 20, 20}; /*rc.left += dis.rcItem.left; rc.right += dis.rcItem.left; rc.top += dis.rcItem.top; rc.bottom += dis.rcItem.top;*/ FillRect(hdcTemp, &rcBox, hColorBrush); DeleteObject(hColorBrush); //-------------------------------- SetBkMode(hdcTemp, TRANSPARENT); rc.left += 22; String strKBPS; strKBPS << IntString((statusBarData.bytesPerSec*8) / 1000) << TEXT("kb/s"); //strKBPS << IntString(rand()) << TEXT("kb/s"); DrawText(hdcTemp, strKBPS, strKBPS.Length(), &rc, DT_VCENTER|DT_SINGLELINE|DT_LEFT); } else { String strOutString; switch(dis.itemID) { case 0: strOutString << App->GetMostImportantInfo(); break; case 1: { DWORD streamTimeSecondsTotal = App->totalStreamTime/1000; DWORD streamTimeMinutesTotal = streamTimeSecondsTotal/60; DWORD streamTimeSeconds = streamTimeSecondsTotal%60; DWORD streamTimeHours = streamTimeMinutesTotal/60; DWORD streamTimeMinutes = streamTimeMinutesTotal%60; strOutString = FormattedString(TEXT("%u:%02u:%02u"), streamTimeHours, streamTimeMinutes, streamTimeSeconds); } break; case 2: { double percentageDropped = 0.0; if (OSTryEnterMutex(App->hStartupShutdownMutex)) { if(App->network) { UINT numTotalFrames = App->network->NumTotalVideoFrames(); if(numTotalFrames) percentageDropped = (double(App->network->NumDroppedFrames())/double(numTotalFrames))*100.0; } OSLeaveMutex(App->hStartupShutdownMutex); } strOutString << Str("MainWindow.DroppedFrames") << FormattedString(TEXT(" %u (%0.2f%%)"), App->curFramesDropped, percentageDropped); } break; case 3: strOutString << TEXT("FPS: ") << IntString(App->captureFPS); break; } if(strOutString.IsValid()) { SetBkMode(hdcTemp, TRANSPARENT); DrawText(hdcTemp, strOutString, strOutString.Length(), &rc, DT_VCENTER|DT_SINGLELINE|DT_LEFT); } } //-------------------------------- BitBlt(dis.hDC, dis.rcItem.left, dis.rcItem.top, dis.rcItem.right-dis.rcItem.left, dis.rcItem.bottom-dis.rcItem.top, hdcTemp, 0, 0, SRCCOPY); DeleteObject(hdcTemp); DeleteObject(hbmpTemp); }
/************************************************************************** * FUNCTIONS To Verify File **************************************************************************/ int sec_signfmt_verify_file_v4(ASF_FILE fp, SEC_IMG_HEADER *file_img_hdr_p) { uint32 ret = SEC_OK; uint32 final_hash_sig_len = 0; uchar *final_hash_sig_buf = NULL; uint32 read_sz = 0; SEC_IMG_EXTENSTION_SET ext_set; u64 ext_hdr_offset = 0; uint32 ext_hdr_len = 0; uchar *ext_hdr_buf = NULL; u64 file_size = 0; uint32 hash_size = 0; uint32 sig_size = 0; uint32 i = 0; uchar *cal_hash_buf = NULL; uint32 cal_hash_buf_len = 0; uchar *tmp_ptr = NULL; uchar *verify_data = NULL; uint32 verify_data_len = 0; uint32 real_chunk_size = 0; SEC_IMG_HEADER_V4 *file_img_hdr = (SEC_IMG_HEADER_V4*)file_img_hdr_p; u64 img_signature_offset = 0; /* ======================== */ /* init check */ /* ======================== */ #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump header ============> START\n",MOD); sec_signfmt_dump_buffer((uchar*)file_img_hdr,sizeof(SEC_IMG_HEADER_V4)); SMSG(sec_info.bMsg,"[%s] Dump header ============> END\n",MOD); #endif if (SEC_IMG_MAGIC != file_img_hdr->magic_number) { SMSG(true,"[%s] magic number is invalid '0x%x'\n",MOD,file_img_hdr->magic_number); ret = ERR_SIGN_FORMAT_MAGIC_WRONG; goto _magic_wrong_err; } if (SEC_EXTENSION_MAGIC_V4 != file_img_hdr->ext_magic) { SMSG(true,"[%s] extension magic number is invalid '0x%x'\n",MOD,file_img_hdr->ext_magic); ret = ERR_SIGN_FORMAT_MAGIC_WRONG; goto _magic_wrong_err; } /* ======================== */ /* locate final signature and hash */ /* ======================== */ final_hash_sig_len = file_img_hdr->signature_length; final_hash_sig_buf = (uchar*)ASF_MALLOC(final_hash_sig_len); if (NULL == final_hash_sig_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_hash_sig_fail; } img_signature_offset = sec_get_u64(file_img_hdr->image_length_high, file_img_hdr->image_length_low); img_signature_offset += file_img_hdr->image_offset; ASF_SEEK_SET(fp, img_signature_offset); if (final_hash_sig_len != (read_sz = ASF_READ(fp, final_hash_sig_buf, final_hash_sig_len))) { SMSG(true,"[%s] read size '%d' != '%d'\n",MOD,read_sz,final_hash_sig_len); ret = ERR_FS_READ_SIZE_FAIL; goto _read_hash_sig_fail; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump sign and hash value ============> START\n",MOD); sec_signfmt_dump_buffer(final_hash_sig_buf,final_hash_sig_len); SMSG(sec_info.bMsg,"[%s] Dump sign and hash value ============> END\n",MOD); #endif /* read file size */ ASF_SEEK_END(fp, 0); file_size = ASF_FILE_POS(fp); /* ======================== */ /* search for extension header */ /* ======================== */ memset(&ext_set, 0x00, sizeof(SEC_IMG_EXTENSTION_SET)); ext_hdr_offset = sec_get_u64(file_img_hdr->image_length_high, file_img_hdr->image_length_low) + file_img_hdr->image_offset + file_img_hdr->signature_length; ext_hdr_len = (file_size - ext_hdr_offset) & 0xFFFFFFFF; ext_hdr_buf = (uchar*)ASF_MALLOC(ext_hdr_len); if (NULL == ext_hdr_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_ext_hdr_fail; } ASF_SEEK_SET(fp, ext_hdr_offset); if (ext_hdr_len != (read_sz = ASF_READ(fp, ext_hdr_buf, ext_hdr_len))) { SMSG(true,"[%s] read size '%d' != '%d'\n",MOD,read_sz,ext_hdr_len); ret = ERR_FS_READ_SIZE_FAIL; goto _read_ext_hdr_fail; } if( SEC_OK != (ret = sec_signfmt_search_extension_v4(ext_hdr_buf, ext_hdr_len, &ext_set)) ) { SMSG(true,"[%s] Image extension header not found\n",MOD); goto _ext_hdr_search_fail; } hash_size = get_hash_size((SEC_CRYPTO_HASH_TYPE)ext_set.crypto->hash_type); sig_size = get_signature_size((SEC_CRYPTO_SIGNATURE_TYPE)ext_set.crypto->sig_type); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump ext hash value ============> START\n",MOD); for(i=0;i<ext_set.frag->frag_count;i++) { SMSG(sec_info.bMsg,"[%s] Dump EXT hash [%d]\n",MOD,i); sec_signfmt_dump_buffer(ext_set.hash_only_64[i]->hash_data,hash_size); } SMSG(sec_info.bMsg,"[%s] Dump ext hash value ============> END\n",MOD); #endif /* ======================== */ /* calculate each hash by chunk */ /* ======================== */ cal_hash_buf_len = hash_size*ext_set.frag->frag_count; cal_hash_buf = (uchar*)ASF_MALLOC(cal_hash_buf_len); if (NULL == cal_hash_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_cal_buf_fail; } memset(cal_hash_buf, 0x00, cal_hash_buf_len); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] dump reset data\n",MOD); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif tmp_ptr = cal_hash_buf; #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Total cal hash length is %d\n",MOD,cal_hash_buf_len); #endif for(i=0;i<ext_set.frag->frag_count;i++) { memset(tmp_ptr, 0x00, hash_size); if(ext_set.frag->chunk_size == 0) { real_chunk_size = ext_set.hash_only_64[i]->hash_len_64 & 0x00000000FFFFFFFFULL; } else { real_chunk_size = ext_set.frag->chunk_size; } if(sec_signfmt_gen_hash_by_chunk_64(fp, NULL, SEC_IMG_HEADER_SIZE+ext_set.hash_only_64[i]->hash_offset_64, ext_set.hash_only_64[i]->hash_len_64, tmp_ptr, ext_set.hash_only_64[i]->sub_type, real_chunk_size)!=0) { ret = ERR_SIGN_FORMAT_CAL_HASH_BY_CHUNK_FAIL; goto _gen_hash_by_chunk_fail; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump CAL hash right after: [%d], offset is 0x%x\n",MOD,i,tmp_ptr); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif tmp_ptr += hash_size; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump CAL hash right after all done, offset is 0x%x\n",MOD,tmp_ptr); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump cal hash value ============> START\n",MOD); tmp_ptr = cal_hash_buf; for(i=0;i<ext_set.frag->frag_count;i++) { SMSG(sec_info.bMsg,"[%s] Dump CAL hash [%d]\n",MOD,i); sec_signfmt_dump_buffer(tmp_ptr,hash_size); tmp_ptr += hash_size; } SMSG(sec_info.bMsg,"[%s] Dump cal hash value ============> END\n",MOD); #endif /* ======================== */ /* compose final verify buffer */ /* ======================== */ verify_data_len = SEC_IMG_HEADER_SIZE+cal_hash_buf_len+ext_hdr_len; verify_data = (uchar*)ASF_MALLOC(verify_data_len); if (NULL == cal_hash_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_verify_buf_fail; } tmp_ptr = verify_data; /* copy header */ mcpy(tmp_ptr,file_img_hdr,SEC_IMG_HEADER_SIZE); tmp_ptr += SEC_IMG_HEADER_SIZE; /* copy cal hash */ for(i=0;i<ext_set.frag->frag_count;i++) { mcpy(tmp_ptr,cal_hash_buf+i*hash_size,hash_size); tmp_ptr += hash_size; } /* copy extension header */ mcpy(tmp_ptr,ext_hdr_buf,ext_hdr_len); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump verify data (%d):\n",MOD,verify_data_len); sec_signfmt_dump_buffer(verify_data,verify_data_len); #endif #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump signature data (%d):\n",MOD,sig_size); sec_signfmt_dump_buffer(final_hash_sig_buf,sig_size); #endif osal_verify_lock(); /* ======================== */ /* verify buffer */ /* ======================== */ SMSG(sec_info.bMsg,"[%s] verify (lock)... \n",MOD); if(SEC_OK != (ret = sec_verify(verify_data, verify_data_len, final_hash_sig_buf, sig_size ))) { osal_verify_unlock(); SMSG(true,"[%s] verify fail (unlock), ret is %d\n\n",MOD,ret); goto _verify_fail; } osal_verify_unlock(); SMSG(sec_info.bMsg,"[%s] verify pass (unlock)\n\n",MOD); _verify_fail: ASF_FREE(verify_data); _malloc_verify_buf_fail: _gen_hash_by_chunk_fail: ASF_FREE(cal_hash_buf); _malloc_cal_buf_fail: _ext_hdr_search_fail: _read_ext_hdr_fail: ASF_FREE(ext_hdr_buf); _malloc_ext_hdr_fail: _read_hash_sig_fail: ASF_FREE(final_hash_sig_buf); _malloc_hash_sig_fail: _magic_wrong_err: return ret; }
BOOL WINAPI InjectLibrary(HANDLE hProcess, CTSTR lpDLL) { UPARAM procAddress; DWORD dwTemp, dwSize; LPVOID lpStr = NULL; BOOL bWorks, bRet = 0; HANDLE hThread = NULL; SIZE_T writtenSize; if (!hProcess) return 0; dwSize = ssize((TCHAR*)lpDLL); //-------------------------------------------------------- int obfSize = 12; char pWPMStr[19], pCRTStr[19], pVAEStr[15], pVFEStr[14], pLLStr[13]; mcpy(pWPMStr, "RvnrdPqmni|}Dmfegm", 19); //WriteProcessMemory with each character obfuscated mcpy(pCRTStr, "FvbgueQg`c{k]`yotp", 19); //CreateRemoteThread with each character obfuscated mcpy(pVAEStr, "WiqvpekGeddiHt", 15); //VirtualAllocEx with each character obfuscated mcpy(pVFEStr, "Wiqvpek@{mnOu", 14); //VirtualFreeEx with each character obfuscated mcpy(pLLStr, "MobfImethzr", 12); //LoadLibrary with each character obfuscated #ifdef UNICODE pLLStr[11] = 'W'; #else pLLStr[11] = 'A'; #endif pLLStr[12] = 0; obfSize += 6; for (int i = 0; i<obfSize; i++) pWPMStr[i] ^= i ^ 5; for (int i = 0; i<obfSize; i++) pCRTStr[i] ^= i ^ 5; obfSize -= 4; for (int i = 0; i<obfSize; i++) pVAEStr[i] ^= i ^ 1; obfSize -= 1; for (int i = 0; i<obfSize; i++) pVFEStr[i] ^= i ^ 1; obfSize -= 2; for (int i = 0; i<obfSize; i++) pLLStr[i] ^= i ^ 1; HMODULE hK32 = GetModuleHandle(TEXT("KERNEL32")); WPMPROC pWriteProcessMemory = (WPMPROC)GetProcAddress(hK32, pWPMStr); CRTPROC pCreateRemoteThread = (CRTPROC)GetProcAddress(hK32, pCRTStr); VAEPROC pVirtualAllocEx = (VAEPROC)GetProcAddress(hK32, pVAEStr); VFEPROC pVirtualFreeEx = (VFEPROC)GetProcAddress(hK32, pVFEStr); //-------------------------------------------------------- lpStr = (LPVOID)(*pVirtualAllocEx)(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!lpStr) goto end; bWorks = (*pWriteProcessMemory)(hProcess, lpStr, (LPVOID)lpDLL, dwSize, &writtenSize); if (!bWorks) goto end; procAddress = (UPARAM)GetProcAddress(hK32, pLLStr); if (!procAddress) goto end; hThread = (*pCreateRemoteThread)(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)procAddress, lpStr, 0, &dwTemp); if (!hThread) goto end; if (WaitForSingleObject(hThread, 2000) == WAIT_OBJECT_0) { DWORD dw; GetExitCodeThread(hThread, &dw); bRet = dw != 0; SetLastError(0); } end: DWORD lastError; if (!bRet) lastError = GetLastError(); if (hThread) CloseHandle(hThread); if (lpStr) (*pVirtualFreeEx)(hProcess, lpStr, 0, MEM_RELEASE); if (!bRet) SetLastError(lastError); return bRet; }
void GraphicsCaptureSource::Render(const Vect2 &pos, const Vect2 &size) { if(capture) { Shader *lastShader = GetCurrentPixelShader(); float fGamma = float(-(gamma-100) + 100) * 0.01f; LoadPixelShader(drawShader); HANDLE hGamma = drawShader->GetParameterByName(TEXT("gamma")); if(hGamma) drawShader->SetFloat(hGamma, fGamma); //---------------------------------------------------------- // capture mouse bMouseCaptured = false; if(bCaptureMouse) { CURSORINFO ci; zero(&ci, sizeof(ci)); ci.cbSize = sizeof(ci); if(GetCursorInfo(&ci) && (hwndCapture || bUseDWMCapture)) { mcpy(&cursorPos, &ci.ptScreenPos, sizeof(cursorPos)); if(!bUseDWMCapture) ScreenToClient(hwndCapture, &cursorPos); if(ci.flags & CURSOR_SHOWING) { if(ci.hCursor == hCurrentCursor) bMouseCaptured = true; else { HICON hIcon = CopyIcon(ci.hCursor); hCurrentCursor = ci.hCursor; delete cursorTexture; cursorTexture = NULL; if(hIcon) { ICONINFO ii; if(GetIconInfo(hIcon, &ii)) { xHotspot = int(ii.xHotspot); yHotspot = int(ii.yHotspot); UINT width, height; LPBYTE lpData = GetCursorData(hIcon, ii, width, height); if(lpData && width && height) { cursorTexture = CreateTexture(width, height, GS_BGRA, lpData, FALSE); if(cursorTexture) bMouseCaptured = true; Free(lpData); } DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DestroyIcon(hIcon); } } } } } //---------------------------------------------------------- // game texture Texture *tex = capture->LockTexture(); Vect2 texPos = Vect2(0.0f, 0.0f); Vect2 texStretch = Vect2(1.0f, 1.0f); if(tex) { Vect2 texSize = Vect2(float(tex->Width()), float(tex->Height())); Vect2 totalSize = API->GetBaseSize(); Vect2 center = totalSize*0.5f; if(!bAlphaBlend) BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO); else BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA); if(bStretch) { if(bIgnoreAspect) texStretch *= totalSize; else { float xAspect = totalSize.x / texSize.x; float yAspect = totalSize.y / texSize.y; float multiplyVal = ((texSize.y * xAspect) > totalSize.y) ? yAspect : xAspect; texStretch *= texSize*multiplyVal; texPos = center-(texStretch*0.5f); } } else { texStretch *= texSize; texPos = center-(texStretch*0.5f); } Vect2 sizeAdjust = size/totalSize; texPos *= sizeAdjust; texPos += pos; texStretch *= sizeAdjust; RoundVect2(texPos); RoundVect2(texSize); if(bFlip) DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y+texStretch.y, texPos.x+texStretch.x, texPos.y); else DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y, texPos.x+texStretch.x, texPos.y+texStretch.y); capture->UnlockTexture(); BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA); //---------------------------------------------------------- // draw mouse if (!foregroundCheckCount) { //only check for foreground window every 10 frames since this involves two syscalls if(!bUseDWMCapture) GetWindowThreadProcessId(GetForegroundWindow(), &foregroundPID); foregroundCheckCount = 10; } if(bMouseCaptured && cursorTexture && ((foregroundPID == targetProcessID) || bUseDWMCapture)) { Vect2 newCursorPos = Vect2(float(cursorPos.x-xHotspot), float(cursorPos.y-xHotspot)); Vect2 newCursorSize = Vect2(float(cursorTexture->Width()), float(cursorTexture->Height())); newCursorPos /= texSize; newCursorSize /= texSize; newCursorPos *= texStretch; newCursorPos += texPos; newCursorSize *= texStretch; bool bInvertCursor = false; if(invertShader) { if(bInvertCursor = ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0 || (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0)) LoadPixelShader(invertShader); } DrawSprite(cursorTexture, 0xFFFFFFFF, newCursorPos.x, newCursorPos.y, newCursorPos.x+newCursorSize.x, newCursorPos.y+newCursorSize.y); } foregroundCheckCount--; } if(lastShader) LoadPixelShader(lastShader); } }
void GraphicsCaptureSource::AttemptCapture() { //Log(TEXT("attempting to capture..")); if (!bUseHotkey) hwndTarget = FindWindow(strWindowClass, NULL); else { hwndTarget = hwndNextTarget; hwndNextTarget = NULL; } if (hwndTarget) { GetWindowThreadProcessId(hwndTarget, &targetProcessID); if(!targetProcessID) { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: GetWindowThreadProcessId failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; return; } } else { if (!bUseHotkey && !warningID) warningID = API->AddStreamInfo(Str("Sources.SoftwareCaptureSource.WindowNotFound"), StreamInfoPriority_High); bCapturing = false; return; } if(warningID) { API->RemoveStreamInfo(warningID); warningID = 0; } //------------------------------------------- // see if we already hooked the process. if not, inject DLL char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); HANDLE hProcess = (*pOpenProcess)(PROCESS_ALL_ACCESS, FALSE, targetProcessID); if(hProcess) { //------------------------------------------- // load keepalive event hOBSIsAlive = CreateEvent(NULL, FALSE, FALSE, String() << OBS_KEEPALIVE_EVENT << UINT(targetProcessID)); //------------------------------------------- hwndCapture = hwndTarget; hSignalRestart = OpenEvent(EVENT_ALL_ACCESS, FALSE, String() << RESTART_CAPTURE_EVENT << UINT(targetProcessID)); if(hSignalRestart) { SetEvent(hSignalRestart); bCapturing = true; captureWaitCount = 0; } else { BOOL bSameBit = TRUE; if(Is64BitWindows()) { BOOL bCurrentProcessWow64, bTargetProcessWow64; IsWow64Process(GetCurrentProcess(), &bCurrentProcessWow64); IsWow64Process(hProcess, &bTargetProcessWow64); bSameBit = (bCurrentProcessWow64 == bTargetProcessWow64); } if(bSameBit) { String strDLL; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLL.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLL); strDLL << TEXT("\\plugins\\GraphicsCapture\\GraphicsCaptureHook"); BOOL b32bit = TRUE; if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); if(!b32bit) strDLL << TEXT("64"); strDLL << TEXT(".dll"); if(InjectLibrary(hProcess, strDLL)) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Failed to inject library, GetLastError = %u"), GetLastError()); CloseHandle(hProcess); hProcess = NULL; bErrorAcquiring = true; } } else { String strDLLPath; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLLPath.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLLPath); strDLLPath << TEXT("\\plugins\\GraphicsCapture"); BOOL b32bit = TRUE; if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); String strHelper = strDLLPath; strHelper << ((b32bit) ? TEXT("\\injectHelper.exe") : TEXT("\\injectHelper64.exe")); String strCommandLine; strCommandLine << TEXT("\"") << strHelper << TEXT("\" ") << UIntString(targetProcessID); //--------------------------------------- PROCESS_INFORMATION pi; STARTUPINFO si; zero(&pi, sizeof(pi)); zero(&si, sizeof(si)); si.cb = sizeof(si); if(CreateProcess(strHelper, strCommandLine, NULL, NULL, FALSE, 0, NULL, strDLLPath, &si, &pi)) { int exitCode = 0; WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, (DWORD*)&exitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); if(exitCode == 0) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Failed to inject library, error code = %d"), exitCode); bErrorAcquiring = true; } } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Could not create inject helper, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } } CloseHandle(hProcess); hProcess = NULL; if (!bCapturing) { CloseHandle(hOBSIsAlive); hOBSIsAlive = NULL; } } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: OpenProcess failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } }
void Matrix4x4Convert(Matrix &mat, float *m4x4) { mcpy(&mat, m4x4, sizeof(Matrix)); }
bool DeviceSource::LoadFilters() { if(bCapturing || bFiltersLoaded) return false; bool bSucceeded = false; List<MediaOutputInfo> outputList; IAMStreamConfig *config = NULL; bool bAddedVideoCapture = false, bAddedAudioCapture = false, bAddedDevice = false; GUID expectedMediaType; IPin *devicePin = NULL, *audioPin = NULL; HRESULT err; String strShader; bUseThreadedConversion = API->UseMultithreadedOptimizations() && (OSGetTotalCores() > 1); //------------------------------------------------ // basic initialization vars bUseCustomResolution = data->GetInt(TEXT("customResolution")); strDevice = data->GetString(TEXT("device")); strDeviceName = data->GetString(TEXT("deviceName")); strDeviceID = data->GetString(TEXT("deviceID")); bFlipVertical = data->GetInt(TEXT("flipImage")) != 0; bFlipHorizontal = data->GetInt(TEXT("flipImageHorizontal")) != 0; opacity = data->GetInt(TEXT("opacity"), 100); float volume = data->GetFloat(TEXT("volume"), 1.0f); //------------------------------------------------ // chrom key stuff bUseChromaKey = data->GetInt(TEXT("useChromaKey")) != 0; keyColor = data->GetInt(TEXT("keyColor"), 0xFFFFFFFF); keySimilarity = data->GetInt(TEXT("keySimilarity")); keyBlend = data->GetInt(TEXT("keyBlend"), 80); keySpillReduction = data->GetInt(TEXT("keySpillReduction"), 50); if(keyBaseColor.x < keyBaseColor.y && keyBaseColor.x < keyBaseColor.z) keyBaseColor -= keyBaseColor.x; else if(keyBaseColor.y < keyBaseColor.x && keyBaseColor.y < keyBaseColor.z) keyBaseColor -= keyBaseColor.y; else if(keyBaseColor.z < keyBaseColor.x && keyBaseColor.z < keyBaseColor.y) keyBaseColor -= keyBaseColor.z; //------------------------------------------------ // get the device filter and pins if(strDeviceName.IsValid()) { deviceFilter = GetDeviceByValue(CLSID_VideoInputDeviceCategory, L"FriendlyName", strDeviceName, L"DevicePath", strDeviceID); if(!deviceFilter) { AppWarning(TEXT("DShowPlugin: Invalid device: name '%s', path '%s'"), strDeviceName.Array(), strDeviceID.Array()); goto cleanFinish; } } else { if(!strDevice.IsValid()) { AppWarning(TEXT("DShowPlugin: Invalid device specified")); goto cleanFinish; } deviceFilter = GetDeviceByValue(CLSID_VideoInputDeviceCategory, L"FriendlyName", strDevice); if(!deviceFilter) { AppWarning(TEXT("DShowPlugin: Could not create device filter")); goto cleanFinish; } } devicePin = GetOutputPin(deviceFilter, &MEDIATYPE_Video); if(!devicePin) { AppWarning(TEXT("DShowPlugin: Could not get device video pin")); goto cleanFinish; } soundOutputType = data->GetInt(TEXT("soundOutputType")); if(soundOutputType != 0) { err = capture->FindPin(deviceFilter, PINDIR_OUTPUT, &PIN_CATEGORY_CAPTURE, &MEDIATYPE_Audio, FALSE, 0, &audioPin); if(FAILED(err)) { Log(TEXT("DShowPlugin: No audio pin, result = %lX"), err); soundOutputType = 0; } } int soundTimeOffset = data->GetInt(TEXT("soundTimeOffset")); GetOutputList(devicePin, outputList); //------------------------------------------------ // initialize the basic video variables and data renderCX = renderCY = 0; frameInterval = 0; if(bUseCustomResolution) { renderCX = data->GetInt(TEXT("resolutionWidth")); renderCY = data->GetInt(TEXT("resolutionHeight")); frameInterval = data->GetInt(TEXT("frameInterval")); } else { SIZE size; if (!GetClosestResolution(outputList, size, frameInterval)) { AppWarning(TEXT("DShowPlugin: Unable to find appropriate resolution")); renderCX = renderCY = 64; goto cleanFinish; } renderCX = size.cx; renderCY = size.cy; } if(!renderCX || !renderCY || !frameInterval) { AppWarning(TEXT("DShowPlugin: Invalid size/fps specified")); goto cleanFinish; } preferredOutputType = (data->GetInt(TEXT("usePreferredType")) != 0) ? data->GetInt(TEXT("preferredType")) : -1; int numThreads = MAX(OSGetTotalCores()-2, 1); for(int i=0; i<numThreads; i++) { convertData[i].width = renderCX; convertData[i].height = renderCY; convertData[i].sample = NULL; convertData[i].hSignalConvert = CreateEvent(NULL, FALSE, FALSE, NULL); convertData[i].hSignalComplete = CreateEvent(NULL, FALSE, FALSE, NULL); if(i == 0) convertData[i].startY = 0; else convertData[i].startY = convertData[i-1].endY; if(i == (numThreads-1)) convertData[i].endY = renderCY; else convertData[i].endY = ((renderCY/numThreads)*(i+1)) & 0xFFFFFFFE; } bFirstFrame = true; //------------------------------------------------ // get the closest media output for the settings used MediaOutputInfo *bestOutput = GetBestMediaOutput(outputList, renderCX, renderCY, preferredOutputType, frameInterval); if(!bestOutput) { AppWarning(TEXT("DShowPlugin: Could not find appropriate resolution to create device image source")); goto cleanFinish; } //------------------------------------------------ // log video info { String strTest = FormattedString(TEXT(" device: %s,\r\n device id %s,\r\n chosen type: %s, usingFourCC: %s, res: %ux%u - %ux%u, frameIntervals: %llu-%llu"), strDevice.Array(), strDeviceID.Array(), EnumToName[(int)bestOutput->videoType], bestOutput->bUsingFourCC ? TEXT("true") : TEXT("false"), bestOutput->minCX, bestOutput->minCY, bestOutput->maxCX, bestOutput->maxCY, bestOutput->minFrameInterval, bestOutput->maxFrameInterval); BITMAPINFOHEADER *bmiHeader = GetVideoBMIHeader(bestOutput->mediaType); char fourcc[5]; mcpy(fourcc, &bmiHeader->biCompression, 4); fourcc[4] = 0; if(bmiHeader->biCompression > 1000) strTest << FormattedString(TEXT(", fourCC: '%S'\r\n"), fourcc); else strTest << FormattedString(TEXT(", fourCC: %08lX\r\n"), bmiHeader->biCompression); Log(TEXT("------------------------------------------")); Log(strTest.Array()); } //------------------------------------------------ // set up shaders and video output data expectedMediaType = bestOutput->mediaType->subtype; colorType = DeviceOutputType_RGB; if(bestOutput->videoType == VideoOutputType_I420) colorType = DeviceOutputType_I420; else if(bestOutput->videoType == VideoOutputType_YV12) colorType = DeviceOutputType_YV12; else if(bestOutput->videoType == VideoOutputType_YVYU) colorType = DeviceOutputType_YVYU; else if(bestOutput->videoType == VideoOutputType_YUY2) colorType = DeviceOutputType_YUY2; else if(bestOutput->videoType == VideoOutputType_UYVY) colorType = DeviceOutputType_UYVY; else if(bestOutput->videoType == VideoOutputType_HDYC) colorType = DeviceOutputType_HDYC; else { colorType = DeviceOutputType_RGB; expectedMediaType = MEDIASUBTYPE_RGB32; } strShader = ChooseShader(); if(strShader.IsValid()) colorConvertShader = CreatePixelShaderFromFile(strShader); if(colorType != DeviceOutputType_RGB && !colorConvertShader) { AppWarning(TEXT("DShowPlugin: Could not create color space conversion pixel shader")); goto cleanFinish; } if(colorType == DeviceOutputType_YV12 || colorType == DeviceOutputType_I420) { for(int i=0; i<numThreads; i++) hConvertThreads[i] = OSCreateThread((XTHREAD)PackPlanarThread, convertData+i); } //------------------------------------------------ // set chroma details keyBaseColor = Color4().MakeFromRGBA(keyColor); Matrix4x4TransformVect(keyChroma, (colorType == DeviceOutputType_HDYC) ? (float*)yuv709Mat : (float*)yuvMat, keyBaseColor); keyChroma *= 2.0f; //------------------------------------------------ // configure video pin if(FAILED(err = devicePin->QueryInterface(IID_IAMStreamConfig, (void**)&config))) { AppWarning(TEXT("DShowPlugin: Could not get IAMStreamConfig for device pin, result = %08lX"), err); goto cleanFinish; } AM_MEDIA_TYPE outputMediaType; CopyMediaType(&outputMediaType, bestOutput->mediaType); VIDEOINFOHEADER *vih = reinterpret_cast<VIDEOINFOHEADER*>(outputMediaType.pbFormat); BITMAPINFOHEADER *bmi = GetVideoBMIHeader(&outputMediaType); vih->AvgTimePerFrame = frameInterval; bmi->biWidth = renderCX; bmi->biHeight = renderCY; bmi->biSizeImage = renderCX*renderCY*(bmi->biBitCount>>3); if(FAILED(err = config->SetFormat(&outputMediaType))) { if(err != E_NOTIMPL) { AppWarning(TEXT("DShowPlugin: SetFormat on device pin failed, result = %08lX"), err); goto cleanFinish; } } FreeMediaType(outputMediaType); //------------------------------------------------ // get audio pin configuration, optionally configure audio pin to 44100 GUID expectedAudioType; if(soundOutputType == 1) { IAMStreamConfig *audioConfig; if(SUCCEEDED(audioPin->QueryInterface(IID_IAMStreamConfig, (void**)&audioConfig))) { AM_MEDIA_TYPE *audioMediaType; if(SUCCEEDED(err = audioConfig->GetFormat(&audioMediaType))) { SetAudioInfo(audioMediaType, expectedAudioType); } else if(err == E_NOTIMPL) //elgato probably { IEnumMediaTypes *audioMediaTypes; if(SUCCEEDED(err = audioPin->EnumMediaTypes(&audioMediaTypes))) { ULONG i = 0; if((err = audioMediaTypes->Next(1, &audioMediaType, &i)) == S_OK) SetAudioInfo(audioMediaType, expectedAudioType); else { AppWarning(TEXT("DShowPlugin: audioMediaTypes->Next failed, result = %08lX"), err); soundOutputType = 0; } audioMediaTypes->Release(); } else { AppWarning(TEXT("DShowPlugin: audioMediaTypes->Next failed, result = %08lX"), err); soundOutputType = 0; } } else { AppWarning(TEXT("DShowPlugin: Could not get audio format, result = %08lX"), err); soundOutputType = 0; } audioConfig->Release(); } else soundOutputType = 0; } //------------------------------------------------ // add video capture filter if any captureFilter = new CaptureFilter(this, MEDIATYPE_Video, expectedMediaType); if(FAILED(err = graph->AddFilter(captureFilter, NULL))) { AppWarning(TEXT("DShowPlugin: Failed to add video capture filter to graph, result = %08lX"), err); goto cleanFinish; } bAddedVideoCapture = true; //------------------------------------------------ // add audio capture filter if any if(soundOutputType == 1) { audioFilter = new CaptureFilter(this, MEDIATYPE_Audio, expectedAudioType); if(!audioFilter) { AppWarning(TEXT("Failed to create audio ccapture filter")); soundOutputType = 0; } } else if(soundOutputType == 2) { if(FAILED(err = CoCreateInstance(CLSID_AudioRender, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&audioFilter))) { AppWarning(TEXT("DShowPlugin: failed to create audio renderer, result = %08lX"), err); soundOutputType = 0; } IBasicAudio *basicAudio; if(SUCCEEDED(audioFilter->QueryInterface(IID_IBasicAudio, (void**)&basicAudio))) { long lVol = long((double(volume)*NEAR_SILENTf)-NEAR_SILENTf); if(lVol <= -NEAR_SILENT) lVol = -10000; basicAudio->put_Volume(lVol); basicAudio->Release(); } } if(soundOutputType != 0) { if(FAILED(err = graph->AddFilter(audioFilter, NULL))) { AppWarning(TEXT("DShowPlugin: Failed to add audio capture filter to graph, result = %08lX"), err); goto cleanFinish; } bAddedAudioCapture = true; } //------------------------------------------------ // add primary device filter if(FAILED(err = graph->AddFilter(deviceFilter, NULL))) { AppWarning(TEXT("DShowPlugin: Failed to add device filter to graph, result = %08lX"), err); goto cleanFinish; } bAddedDevice = true; //------------------------------------------------ // connect all pins and set up the whole capture thing /*if(bNoBuffering) { IMediaFilter *mediaFilter; if(SUCCEEDED(graph->QueryInterface(IID_IMediaFilter, (void**)&mediaFilter))) { if(FAILED(mediaFilter->SetSyncSource(NULL))) AppWarning(TEXT("DShowPlugin: Failed to set sync source, result = %08lX"), err); Log(TEXT("Disabling buffering (hopefully)")); mediaFilter->Release(); } }*/ //THANK THE NINE DIVINES I FINALLY GOT IT WORKING bool bConnected = SUCCEEDED(err = capture->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, deviceFilter, NULL, captureFilter)); if(!bConnected) { if(FAILED(err = graph->Connect(devicePin, captureFilter->GetCapturePin()))) { AppWarning(TEXT("DShowPlugin: Failed to connect the video device pin to the video capture pin, result = %08lX"), err); goto cleanFinish; } } if(soundOutputType != 0) { bConnected = SUCCEEDED(err = capture->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Audio, deviceFilter, NULL, audioFilter)); if(!bConnected) { AppWarning(TEXT("DShowPlugin: Failed to connect the audio device pin to the audio capture pin, result = %08lX"), err); soundOutputType = 0; } } if(FAILED(err = graph->QueryInterface(IID_IMediaControl, (void**)&control))) { AppWarning(TEXT("DShowPlugin: Failed to get IMediaControl, result = %08lX"), err); goto cleanFinish; } if(soundOutputType == 1) { audioOut = new DeviceAudioSource; audioOut->Initialize(this); API->AddAudioSource(audioOut); audioOut->SetVolume(volume); } bSucceeded = true; cleanFinish: SafeRelease(config); SafeRelease(devicePin); SafeRelease(audioPin); for(UINT i=0; i<outputList.Num(); i++) outputList[i].FreeData(); if(!bSucceeded) { bCapturing = false; if(bAddedVideoCapture) graph->RemoveFilter(captureFilter); if(bAddedAudioCapture) graph->RemoveFilter(audioFilter); if(bAddedDevice) graph->RemoveFilter(deviceFilter); SafeRelease(deviceFilter); SafeRelease(captureFilter); SafeRelease(audioFilter); SafeRelease(control); if(colorConvertShader) { delete colorConvertShader; colorConvertShader = NULL; } if(audioOut) { delete audioOut; audioOut = NULL; } if(lpImageBuffer) { Free(lpImageBuffer); lpImageBuffer = NULL; } bReadyToDraw = true; } else bReadyToDraw = false; if(!renderCX) renderCX = 32; if(!renderCY) renderCY = 32; //----------------------------------------------------- // create the texture regardless, will just show up as red to indicate failure BYTE *textureData = (BYTE*)Allocate(renderCX*renderCY*4); if(colorType == DeviceOutputType_RGB) //you may be confused, but when directshow outputs RGB, it's actually outputting BGR { msetd(textureData, 0xFFFF0000, renderCX*renderCY*4); texture = CreateTexture(renderCX, renderCY, GS_BGR, textureData, FALSE, FALSE); } else //if we're working with planar YUV, we can just use regular RGB textures instead { msetd(textureData, 0xFF0000FF, renderCX*renderCY*4); texture = CreateTexture(renderCX, renderCY, GS_RGB, textureData, FALSE, FALSE); } if(bSucceeded && bUseThreadedConversion) { if(colorType == DeviceOutputType_I420 || colorType == DeviceOutputType_YV12) { LPBYTE lpData; if(texture->Map(lpData, texturePitch)) texture->Unmap(); else texturePitch = renderCX*4; lpImageBuffer = (LPBYTE)Allocate(texturePitch*renderCY); } } Free(textureData); bFiltersLoaded = bSucceeded; return bSucceeded; }
void D3DTexture::SetImage(void *lpData) { traceInFast(D3DTexture::SetImage); assert(lpData); D3DLOCKED_RECT d3dRect; int i,j; HRESULT problemo = GetTex()->LockRect(0, &d3dRect, NULL, 0); if(!d3dRect.pBits) return; if(dwFormat <= GS_GRAYSCALE) // if dwFormat is GS_ALPHA or GS_GRAYSCALE { if(dwInternalFormat == D3DFMT_A8L8) { LPWORD lpBits = (LPWORD)d3dRect.pBits; LPBYTE lpInput = (LPBYTE)lpData; for(i=0; i<texHeight; i++) { for(j=0; j<texWidth; j++) { WORD val = ((lpInput[(i*texWidth)+j]) << 8) | 0xFF; lpBits[(i*(d3dRect.Pitch/2))+j] = val; } } } else { LPBYTE lpBits = (LPBYTE)d3dRect.pBits; LPBYTE lpInput = (LPBYTE)lpData; for(i=0; i<texHeight; i++) mcpy(lpBits+(i*(d3dRect.Pitch)), lpInput+(i*texWidth), texWidth); } } else if((dwFormat == GS_A8L8) || (dwFormat == GS_L16)) { LPWORD lpBits = (LPWORD)d3dRect.pBits; LPWORD lpInput = (LPWORD)lpData; DWORD widthX2 = texWidth*2; for(i=0; i<texHeight; i++) mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX2), widthX2); } else if(dwFormat == GS_RGB) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; //DWORD widthX3 = texWidth*3; for(i=0; i<texHeight; i++) { //mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX3), widthX3); DWORD curY = (i*texWidth*3); DWORD curD3DY = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { DWORD curX = curY+(j*3); DWORD curD3DX = curD3DY+(j*4); lpBits[curD3DX] = lpInput[curX]; lpBits[curD3DX+1] = lpInput[curX+1]; lpBits[curD3DX+2] = lpInput[curX+2]; } } } else if(dwFormat == GS_DXT1) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; DWORD tempWidth = (texWidth+3)/4; DWORD tempHeight = (texHeight+3)/4; mcpy(lpBits, lpInput, tempWidth*tempHeight*8); } else if((dwFormat == GS_DXT3) || (dwFormat == GS_DXT5)) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; DWORD tempWidth = (texWidth+3)/4; DWORD tempHeight = (texHeight+3)/4; mcpy(lpBits, lpInput, tempWidth*tempHeight*16); } else if((dwFormat == GS_RGBA) || (dwFormat == GS_RG16F)) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; DWORD widthX4 = texWidth*4; for(i=0; i<texHeight; i++) { mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX4), widthX4); /*DWORD curY = (i*texWidth*4); DWORD curD3DY = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { DWORD jx4 = (j*4); DWORD curX = curY+jx4; DWORD curD3DX = curD3DY+jx4; lpBits[curD3DX] = lpInput[curX+2]; lpBits[curD3DX+1] = lpInput[curX+1]; lpBits[curD3DX+2] = lpInput[curX]; lpBits[curD3DX+3] = lpInput[curX+3]; }*/ } } else if((dwFormat == GS_RGBA16) || (dwFormat == GS_RGBA16F) || (dwFormat == GS_RG32F)) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits; LPWORD lpInput = (LPWORD)lpData; DWORD widthX8 = texWidth*8; for(i=0; i<texHeight; i++) { mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX8), widthX8); /*DWORD yOffset = (i*(texWidth*8)); DWORD yTexOffset = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { WORD *lpColors = (WORD*)&lpBits[yTexOffset+(j*8)]; DWORD offset = yOffset+(j*8); lpColors[3] = lpInput[offset+2]; lpColors[2] = lpInput[offset+1]; lpColors[1] = lpInput[offset]; lpColors[0] = lpInput[offset+3]; }*/ } } else if(dwFormat == GS_RGBA32F) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits; LPDWORD lpInput = (LPDWORD)lpData; DWORD widthX16 = texWidth*16; for(i=0; i<texHeight; i++) { mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX16), widthX16); /*DWORD yOffset = (i*(texWidth*16)); DWORD yTexOffset = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { LPDWORD lpColors = (LPDWORD)&lpBits[yTexOffset+(j*8)]; DWORD offset = yOffset+(j*16); lpColors[3] = lpInput[offset+2]; lpColors[2] = lpInput[offset+1]; lpColors[1] = lpInput[offset]; lpColors[0] = lpInput[offset+3]; }*/ } } else { GetTex()->UnlockRect(0); ErrOut(TEXT("eep-chi, this message is required because a texture format needs Texture::SetImage implementation.")); return; } GetTex()->UnlockRect(0); if(bHasMipMaps && (dwTexType == D3DTEXTURE_STANDARD_BUFFER)) D3DXFilterTexture(GetTex(), NULL, 0, D3DX_DEFAULT); if(bDynamic && (textureData != lpData)) { Free(textureData); textureData = (LPBYTE)lpData; } traceOutFast; }
void DXInput::ProcessInput() { traceIn(DXInput::ProcessInput); DWORD dwEventStatus; HRESULT result; while(!bInputExiting && ((dwEventStatus = WaitForMultipleObjects(2, InputEvents, FALSE, 0)) != WAIT_TIMEOUT)) { if(bInputExiting) break; if(dwEventStatus == KEYBOARD_EVENT_TRIGGER) { unsigned char newkeys[256]; if((result = diKeyboard->GetDeviceState(256, newkeys)) != DI_OK) { if((result != DIERR_INPUTLOST) && (result != DIERR_OTHERAPPHASPRIO) && (result != DIERR_NOTACQUIRED)) AppWarning(TEXT("DInput: Could not get keyboard device state")); continue; } if(bIgnoreNextKeyFrame) { bIgnoreNextKeyFrame = FALSE; continue; } /*newkeys[DIK_LSHIFT] |= newkeys[DIK_RSHIFT]; newkeys[DIK_RSHIFT] = 0; newkeys[DIK_LCONTROL] |= newkeys[DIK_RCONTROL]; newkeys[DIK_RCONTROL] = 0;*/ for(int i=0; i<256; i++) { if(keys[i] != newkeys[i]) { if(!curKBHandler.Num() || !curKBHandler[0]->bCharInput) { if(curKBHandler.Num()) curKBHandler[0]->KeyboardHandler(GetDIKInputCode(i), ((newkeys[i] & 0x80) != 0)); else ControlWindow::WindowKeyboardHandler(GetDIKInputCode(i), ((newkeys[i] & 0x80) != 0), GS); } keys[i] = newkeys[i]; } } } else if(dwEventStatus == MOUSE_EVENT_TRIGGER) { DIMOUSESTATE newMouseState; //6x25 if((result = diMouse->GetDeviceState(sizeof(DIMOUSESTATE), &newMouseState)) != DI_OK) { if((result != DIERR_INPUTLOST) && (result != DIERR_OTHERAPPHASPRIO) && (result != DIERR_NOTACQUIRED)) AppWarning(TEXT("DInput: Could not get keyboard device state")); continue; } if((newMouseState.lX != 0) || (newMouseState.lY != 0)) { if(curMouseHandler.Num()) curMouseHandler[0]->MouseHandler(MOUSE_MOVE, curMouseButtonStates, MAKELPARAM(newMouseState.lX, mousestate.lY)); else ControlWindow::WindowMouseHandler(MOUSE_MOVE, curMouseButtonStates, MAKELPARAM(newMouseState.lX, mousestate.lY), GS); } if(newMouseState.lZ != 0) { if(curMouseHandler.Num()) curMouseHandler[0]->MouseHandler(MOUSE_WHEEL, curMouseButtonStates, (int)newMouseState.lZ); else ControlWindow::WindowMouseHandler(MOUSE_WHEEL, curMouseButtonStates, (int)newMouseState.lZ, GS); } if(newMouseState.rgbButtons[0] != mousestate.rgbButtons[0]) { if(newMouseState.rgbButtons[0]) curMouseButtonStates |= STATE_LBUTTONDOWN; else curMouseButtonStates &= ~STATE_LBUTTONDOWN; BOOL bDown = ((curMouseButtonStates & STATE_LBUTTONDOWN) != 0); if(curMouseHandler.Num()) curMouseHandler[0]->MouseHandler(MOUSE_LEFTBUTTON, curMouseButtonStates, (int)bDown); else ControlWindow::WindowMouseHandler(MOUSE_LEFTBUTTON, curMouseButtonStates, (int)bDown, GS); } if(newMouseState.rgbButtons[1] != mousestate.rgbButtons[1]) { if(newMouseState.rgbButtons[1]) curMouseButtonStates |= STATE_RBUTTONDOWN; else curMouseButtonStates &= ~STATE_RBUTTONDOWN; BOOL bDown = ((curMouseButtonStates & STATE_RBUTTONDOWN) != 0); if(curMouseHandler.Num()) curMouseHandler[0]->MouseHandler(MOUSE_RIGHTBUTTON, curMouseButtonStates, (int)bDown); else ControlWindow::WindowMouseHandler(MOUSE_RIGHTBUTTON, curMouseButtonStates, (int)bDown, GS); } if(newMouseState.rgbButtons[2] != mousestate.rgbButtons[2]) { if(newMouseState.rgbButtons[2]) curMouseButtonStates |= STATE_MBUTTONDOWN; else curMouseButtonStates &= ~STATE_MBUTTONDOWN; BOOL bDown = ((curMouseButtonStates & STATE_MBUTTONDOWN) != 0); if(curMouseHandler.Num()) curMouseHandler[0]->MouseHandler(MOUSE_MIDDLEBUTTON, curMouseButtonStates, (int)bDown); else ControlWindow::WindowMouseHandler(MOUSE_MIDDLEBUTTON, curMouseButtonStates, (int)bDown, GS); } mcpy(&mousestate, &newMouseState, sizeof(DIMOUSESTATE)); } } Super::ProcessInput(); //return 0; traceOut; }
void GetDisplayDevices(DeviceOutputs &deviceList) { HRESULT err; deviceList.ClearData(); #ifdef USE_DXGI1_2 REFIID iidVal = OSGetVersion() >= 8 ? __uuidof(IDXGIFactory2) : __uuidof(IDXGIFactory1); #else REFIIF iidVal = __uuidof(IDXGIFactory1); #endif IDXGIFactory1 *factory; if(SUCCEEDED(err = CreateDXGIFactory1(iidVal, (void**)&factory))) { UINT i=0; IDXGIAdapter1 *giAdapter; while(factory->EnumAdapters1(i++, &giAdapter) == S_OK) { //Log(TEXT("------------------------------------------")); DXGI_ADAPTER_DESC adapterDesc; if(SUCCEEDED(err = giAdapter->GetDesc(&adapterDesc))) { if (adapterDesc.DedicatedVideoMemory != 0) { DeviceOutputData &deviceData = *deviceList.devices.CreateNew(); deviceData.strDevice = adapterDesc.Description; UINT j=0; IDXGIOutput *giOutput; while(giAdapter->EnumOutputs(j++, &giOutput) == S_OK) { DXGI_OUTPUT_DESC outputDesc; if(SUCCEEDED(giOutput->GetDesc(&outputDesc))) { if(outputDesc.AttachedToDesktop) { deviceData.monitorNameList << outputDesc.DeviceName; MonitorInfo &monitorInfo = *deviceData.monitors.CreateNew(); monitorInfo.hMonitor = outputDesc.Monitor; mcpy(&monitorInfo.rect, &outputDesc.DesktopCoordinates, sizeof(RECT)); switch (outputDesc.Rotation) { case DXGI_MODE_ROTATION_ROTATE90: monitorInfo.rotationDegrees = 90.0f; break; case DXGI_MODE_ROTATION_ROTATE180: monitorInfo.rotationDegrees = 180.0f; break; case DXGI_MODE_ROTATION_ROTATE270: monitorInfo.rotationDegrees = 270.0f; } } } giOutput->Release(); } } } else AppWarning(TEXT("Could not query adapter %u"), i); giAdapter->Release(); } factory->Release(); } }
BOOL Material::LoadFromFile(CTSTR lpFile) { traceIn(Material::LoadFromFile); String path; ConfigFile materialFile; if(!materialFile.Open(lpFile)) { AppWarning(TEXT("Couldn't load material file '%s'"), lpFile); return FALSE; } effect = ::GetEffect(materialFile.GetString(TEXT("Material"), TEXT("Effect"))); if(!effect) { AppWarning(TEXT("Invalid effect in material file '%s'"), lpFile); return FALSE; } String soundName = materialFile.GetString(TEXT("Material"), TEXT("SoftSound")); if(soundName.IsValid()) SetSoftHitSound(soundName); soundName = materialFile.GetString(TEXT("Material"), TEXT("HardSound")); if(soundName.IsValid()) SetHardHitSound(soundName); restitution = materialFile.GetFloat(TEXT("Material"), TEXT("Restitution")); friction = materialFile.GetFloat(TEXT("Material"), TEXT("Friction"), 0.5f); DWORD curParamID = 0; HANDLE hCurParam; while(hCurParam = effect->GetParameter(curParamID++)) { EffectParameterInfo paramInfo; effect->GetEffectParameterInfo(hCurParam, paramInfo); if(paramInfo.propertyType != EffectProperty_None) { if(paramInfo.propertyType == EffectProperty_Texture) { MaterialParameter *param = Params.CreateNew(); param->type = Parameter_Texture; param->handle = hCurParam; *(BaseTexture**)param->data = GetTexture(materialFile.GetString(TEXT("Parameters"), paramInfo.name)); } else if(paramInfo.propertyType == EffectProperty_Color) { MaterialParameter *param = Params.CreateNew(); param->type = Parameter_Vector3; param->handle = hCurParam; Vect chi = materialFile.GetColor3(TEXT("Parameters"), paramInfo.name); mcpy(param->data, &chi, sizeof(Vect)); } else if(paramInfo.propertyType == EffectProperty_Float) { MaterialParameter *param = Params.CreateNew(); param->type = Parameter_Float; param->handle = hCurParam; *(float*)param->data = materialFile.GetFloat(TEXT("Parameters"), paramInfo.name)*paramInfo.fMul; } } } return TRUE; traceOut; }
virtual void AddPacket(BYTE *data, UINT size, DWORD timestamp, PacketType type) { UINT64 offset = fileOut.GetPos(); if(type == PacketType_Audio) { UINT copySize; if(bMP3) { copySize = size-1; fileOut.Serialize(data+1, copySize); } else { copySize = size-2; fileOut.Serialize(data+2, copySize); } MP4AudioFrameInfo audioFrame; audioFrame.fileOffset = offset; audioFrame.size = copySize; audioFrame.timestamp = timestamp; GetChunkInfo<MP4AudioFrameInfo>(audioFrame, audioFrames.Num(), audioChunks, audioSampleToChunk, curAudioChunkOffset, connectedAudioSampleOffset, numAudioSamples); if(audioFrames.Num()) GetAudioDecodeTime(audioFrames.Last(), false); audioFrames << audioFrame; } else { UINT totalCopied = 0; if(data[0] == 0x17 && data[1] == 0) //if SPS/PPS { LPBYTE lpData = data+11; UINT spsSize = fastHtons(*(WORD*)lpData); fileOut.OutputWord(0); fileOut.Serialize(lpData, spsSize+2); lpData += spsSize+3; UINT ppsSize = fastHtons(*(WORD*)lpData); fileOut.OutputWord(0); fileOut.Serialize(lpData, ppsSize+2); totalCopied = spsSize+ppsSize+8; } else { if (!bSentSEI) { DataPacket sei; App->GetVideoEncoder()->GetSEI(sei); fileOut.Serialize(sei.lpPacket, sei.size); totalCopied += sei.size; bSentSEI = true; } totalCopied += size-5; fileOut.Serialize(data+5, size-5); } if(!videoFrames.Num() || timestamp != lastVideoTimestamp) { INT timeOffset = 0; mcpy(((BYTE*)&timeOffset)+1, data+2, 3); if(data[2] >= 0x80) timeOffset |= 0xFF; timeOffset = (INT)fastHtonl(DWORD(timeOffset)); if(data[0] == 0x17) //i-frame IFrameIDs << fastHtonl(videoFrames.Num()+1); MP4VideoFrameInfo frameInfo; frameInfo.fileOffset = offset; frameInfo.size = totalCopied; frameInfo.timestamp = timestamp; frameInfo.compositionOffset = timeOffset; GetChunkInfo<MP4VideoFrameInfo>(frameInfo, videoFrames.Num(), videoChunks, videoSampleToChunk, curVideoChunkOffset, connectedVideoSampleOffset, numVideoSamples); if(videoFrames.Num()) GetVideoDecodeTime(frameInfo, false); videoFrames << frameInfo; } else videoFrames.Last().size += totalCopied; lastVideoTimestamp = timestamp; } }
void D3D10VertexBuffer::FlushBuffers(D3D10System *D3DSystem) { if(!bDynamic) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: Cannot flush buffers on a non-dynamic vertex buffer")); return; } HRESULT err; //--------------------------------------------------- D3D11_MAPPED_SUBRESOURCE map; if (FAILED(err = D3DSystem->GetContextInline()->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map))) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: failed to map vertex buffer, result = %08lX"), err); return; } mcpy(map.pData, data->VertList.Array(), sizeof(Vect)*numVerts); D3DSystem->GetContextInline()->Unmap(vertexBuffer, 0); //--------------------------------------------------- if(normalBuffer) { if (FAILED(err = D3DSystem->GetContextInline()->Map(normalBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map))) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: failed to map normal buffer, result = %08lX"), err); return; } mcpy(map.pData, data->NormalList.Array(), sizeof(Vect)*numVerts); D3DSystem->GetContextInline()->Unmap(normalBuffer, 0); } //--------------------------------------------------- if(colorBuffer) { if (FAILED(err = D3DSystem->GetContextInline()->Map(colorBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map))) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: failed to map color buffer, result = %08lX"), err); return; } mcpy(map.pData, data->ColorList.Array(), sizeof(Vect)*numVerts); D3DSystem->GetContextInline()->Unmap(colorBuffer, 0); } //--------------------------------------------------- if(tangentBuffer) { if (FAILED(err = D3DSystem->GetContextInline()->Map(tangentBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map))) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: failed to map tangent buffer, result = %08lX"), err); return; } mcpy(map.pData, data->TangentList.Array(), sizeof(Vect)*numVerts); D3DSystem->GetContextInline()->Unmap(tangentBuffer, 0); } //--------------------------------------------------- if(UVBuffers.Num()) { for(UINT i=0; i<UVBuffers.Num(); i++) { List<UVWCoord> &textureVerts = data->UVList[i]; ID3D11Buffer *buffer = UVBuffers[i]; if (FAILED(err = D3DSystem->GetContextInline()->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map))) { AppWarning(TEXT("D3D10VertexBuffer::FlushBuffers: failed to map texture vertex buffer %d, result = %08lX"), i, err); return; } mcpy(map.pData, textureVerts.Array(), sizeof(UVWCoord)*numVerts); D3DSystem->GetContextInline()->Unmap(buffer, 0); } } }
int pro_img_v3(char *hs_name, char *img_name,char *hdr_name) { uint32 br = 0; uchar *d_buf = NULL; uchar *d_buf_prt = NULL; uchar c_buf[SEC_IMG_HDR_SZ]; uchar *sig; uchar *hash; uint32 i = 0, ret = 0; SEC_IMG_HEADER *sec = NULL; SEC_EXTENTION_CFG *p_ext_cfg = (SEC_EXTENTION_CFG *)get_ext_cfg(); SEC_EXTENSTION_CRYPTO *crypto_ext = NULL; SEC_FRAGMENT_CFG *frag_ext = NULL; SEC_EXTENSTION_HASH_ONLY **hash_only_ext; SEC_EXTENSTION_END_MARK *end_ext = NULL; uint32 total_size = 0; uint32 real_chunk_size = 0; /* ------------------------------------- */ /* open hash and signature file */ /* ------------------------------------- */ FILE *hs_fd = fopen(hs_name,"wb"); if(hs_fd == 0) { MSG("[%s] %s not found\n",MOD,hs_name); goto _init_fail; } /* ------------------------------------- */ /* read image header */ /* ------------------------------------- */ FILE *hdr_fd = fopen(hdr_name,"r"); br = fread(c_buf,1,SEC_IMG_HDR_SZ,hdr_fd); /* read header */ sec = (SEC_IMG_HEADER *)c_buf; if(br == 0) { MSG("\n[%s] read '%s' image hdr fail, read bytes = '%d'\n",MOD,hdr_name,br); ret = -1; goto _hdr_fail; } /* ------------------------------------- */ /* initialize buffer */ /* ------------------------------------- */ sig = (uchar*) malloc(get_sigature_size(g_sig_type)); hash = (uchar*) malloc(get_hash_size(g_hash_type)); /* ------------------------------------- */ /* initialize extnesion header buffer */ /* ------------------------------------- */ crypto_ext = (SEC_EXTENSTION_CRYPTO *) allocate_ext_crypto(); frag_ext = (SEC_FRAGMENT_CFG *) allocate_ext_frag(); hash_only_ext = (SEC_EXTENSTION_HASH_ONLY **)malloc(p_ext_cfg->verify_count * sizeof(SEC_EXTENSTION_HASH_ONLY *)); for(i=0;i<p_ext_cfg->verify_count;i++) { hash_only_ext[i] = (SEC_EXTENSTION_HASH_ONLY *) allocate_ext_hash_only(g_hash_type); } end_ext = (SEC_EXTENSTION_END_MARK *) allocate_ext_end(); /* ------------------------------------- */ /* initial extenstion header */ /* ------------------------------------- */ crypto_ext->hash_type = g_hash_type; crypto_ext->sig_type = g_sig_type; crypto_ext->enc_type = SEC_CRYPTO_ENC_UNKNOWN; frag_ext->frag_count = p_ext_cfg->verify_count; frag_ext->chunk_size = p_ext_cfg->chunk_size; for(i=0;i<p_ext_cfg->verify_count;i++) { hash_only_ext[i]->hash_offset = p_ext_cfg->verify_offset[i]; hash_only_ext[i]->hash_len = p_ext_cfg->verify_length[i]; } /* ----------------------------------------- */ /* generate hash for each region by chunk size */ /* ----------------------------------------- */ FILE *img_fd = fopen(img_name,"r"); if(img_fd == 0) { MSG("[%s] %s not found\n",MOD,img_name); ret = -1; goto _img_open_fail; } for(i=0;i<p_ext_cfg->verify_count;i++) { if(frag_ext->chunk_size == 0) { real_chunk_size = hash_only_ext[i]->hash_len; } else { real_chunk_size = frag_ext->chunk_size; } if(gen_hash_by_chunk(img_fd, hash_only_ext[i]->hash_offset, hash_only_ext[i]->hash_len, hash, hash_only_ext[i]->sub_type, real_chunk_size)!=0) { ret = -1; goto _ext_hash_fail; } mcpy(hash_only_ext[i]->hash_data,hash,get_hash_size(g_hash_type)); } /* ------------------------------------- */ /* prepare buffer */ /* ------------------------------------- */ total_size = SEC_IMG_HDR_SZ + p_ext_cfg->verify_count*get_hash_size(g_hash_type)+ sizeof(*crypto_ext)+ sizeof(*frag_ext)+ p_ext_cfg->verify_count*get_ext_hash_only_struct_size(g_hash_type)+ sizeof(*end_ext); d_buf = (uchar*) malloc(total_size); d_buf_prt = d_buf; /* copy header */ mcpy(d_buf_prt,c_buf,SEC_IMG_HDR_SZ); d_buf_prt += SEC_IMG_HDR_SZ; /* copy hash */ for(i=0;i<p_ext_cfg->verify_count;i++) { mcpy(d_buf_prt,hash_only_ext[i]->hash_data,get_hash_size(g_hash_type)); d_buf_prt += get_hash_size(g_hash_type); } /* copy crypto extension */ mcpy(d_buf_prt,crypto_ext,sizeof(*crypto_ext)); d_buf_prt += sizeof(*crypto_ext); /* copy frag extension */ mcpy(d_buf_prt,frag_ext,sizeof(*frag_ext)); d_buf_prt += sizeof(*frag_ext); /* copy hash extension */ for(i=0;i<p_ext_cfg->verify_count;i++) { mcpy(d_buf_prt,hash_only_ext[i],get_ext_hash_only_struct_size(g_hash_type)); d_buf_prt += get_ext_hash_only_struct_size(g_hash_type); } /* copy end mark extension */ mcpy(d_buf_prt,end_ext,sizeof(*end_ext)); d_buf_prt += sizeof(*end_ext); /* ------------------------------------- */ /* generate hash */ /* ------------------------------------- */ if( cust_hash(d_buf,total_size,hash,get_hash_size(g_hash_type)) == -1) { MSG("[%s] Sign %s fail\n",MOD,img_name); ret = -1; goto _final_hash_fail; } /* ------------------------------------- */ /* generate signature */ /* ------------------------------------- */ if( cust_sign(d_buf,total_size,sig,get_sigature_size(g_sig_type)) == -1) { MSG("[%s] Sign %s fail\n",MOD,img_name); ret = -1; goto _final_sign_fail; } /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ #if DUMP_MORE_FOR_DEBUG { unsigned loop_count = total_size/8; unsigned remain_count = total_size%8; MSG("[%s] Total verify size is : %d\n",MOD, total_size); for(i=0; i<loop_count ; i++) { DBG("[%s] Data value [%d-%d]==> (0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x) \n",MOD, i*8, (i+1)*8-1, d_buf[0+i*8], d_buf[1+i*8], d_buf[2+i*8], d_buf[3+i*8], d_buf[4+i*8], d_buf[5+i*8], d_buf[6+i*8], d_buf[7+i*8]); } if(remain_count) { DBG("[%s] Data value [%d-%d]==> (",MOD,loop_count*8, loop_count*8+remain_count); for(i=0; i<remain_count ; i++) { DBG("0x%x,", d_buf[loop_count*8+i]); } DBG(") \n"); } } #endif MSG("[%s] Hash value : \n",MOD); for(i=0;i<get_hash_size(g_hash_type);i++) { MSG("0x%x,",hash[i]); } MSG("\n",MOD); /* ------------------------------------- */ /* write hash and signature */ /* ------------------------------------- */ fwrite (sig , 1 , get_sigature_size(g_sig_type), hs_fd); fwrite (hash , 1 , get_hash_size(g_hash_type) , hs_fd); /* ------------------------------------- */ /* write extension */ /* ------------------------------------- */ d_buf_prt = d_buf; d_buf_prt += SEC_IMG_HDR_SZ + p_ext_cfg->verify_count*get_hash_size(g_hash_type); fwrite (d_buf_prt , 1 , total_size-(SEC_IMG_HDR_SZ+p_ext_cfg->verify_count*get_hash_size(g_hash_type)), hs_fd); fclose (hs_fd); _final_sign_fail: _final_hash_fail: free(d_buf); _ext_hash_fail: _img_open_fail: _img_read_fail: free(end_ext); free(frag_ext); free(crypto_ext); free(hash_only_ext); free(hash); free(sig); _hdr_fail: fclose(hdr_fd); _init_fail: return ret; }
void* D3DTexture::GetImage(BOOL bForce, void *lpInputPtr) { if(!bForce || (bDynamic && (dwTexType != D3DTEXTURE_FRAME_BUFFER))) { if(dwTexType == D3DTEXTURE_FRAME_BUFFER) ErrOut(TEXT("Tried to query image for frame buffer")); if(!bDynamic) ErrOut(TEXT("Tried to query image for non-dynamic texture")); } else { IDirect3DSurface9 *RenderSurface=NULL, *CopySurface=NULL; BOOL bSuccess=FALSE; LPVOID lpData=NULL; D3DLOCKED_RECT d3dRect; int i,j; if(dwTexType == D3DTEXTURE_FRAME_BUFFER) { if(SUCCEEDED(GetTex()->GetSurfaceLevel(0, &RenderSurface))) { profileSegment("is it this?"); //3.14% if(SUCCEEDED(d3d->d3dDevice->CreateOffscreenPlainSurface(Width(), Height(), (D3DFORMAT)dwInternalFormat, D3DPOOL_SYSTEMMEM, &CopySurface, NULL))) { profileSegment("or is it this?"); //5.48% if(SUCCEEDED(d3d->d3dDevice->GetRenderTargetData(RenderSurface, CopySurface))) { profileSegment("or how about this?"); if(SUCCEEDED(CopySurface->LockRect(&d3dRect, NULL, 0))) bSuccess = TRUE; } } } if(RenderSurface) RenderSurface->Release(); if(!bSuccess) { if(CopySurface) CopySurface->Release(); return NULL; } } else { if(!SUCCEEDED(GetTex()->GetSurfaceLevel(0, &CopySurface))) return NULL; if(!SUCCEEDED(CopySurface->LockRect(&d3dRect, NULL, 0))) { CopySurface->Release(); return NULL; } } //------------------------------------------------------- if(dwFormat <= GS_GRAYSCALE) { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()); LPBYTE lpBits = (LPBYTE)d3dRect.pBits; LPBYTE lpInput = (LPBYTE)lpData; for(i=0; i<texHeight; i++) mcpy(lpInput+(i*texWidth), lpBits+(i*(d3dRect.Pitch)), texWidth); } else if(dwFormat == GS_A8L8) { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*2); LPWORD lpBits = (LPWORD)d3dRect.pBits; LPWORD lpInput = (LPWORD)lpData; DWORD widthX2 = texWidth*2; for(i=0; i<texHeight; i++) mcpy(lpInput+(i*widthX2), lpBits+(i*d3dRect.Pitch), widthX2); } else if(dwFormat == GS_RGB) { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*3); LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; //DWORD widthX3 = texWidth*3; for(i=0; i<texHeight; i++) { //mcpy(lpBits+(i*d3dRect.Pitch), lpInput+(i*widthX3), widthX3); DWORD curY = (i*texWidth*3); DWORD curD3DY = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { DWORD curX = curY+(j*3); DWORD curD3DX = curD3DY+(j*4); lpInput[curX] = lpBits[curD3DX]; lpInput[curX+1] = lpBits[curD3DX+1]; lpInput[curX+2] = lpBits[curD3DX+2]; } } } else if(dwFormat == GS_DXT1) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits; DWORD tempWidth = (texWidth+3)/4; DWORD tempHeight = (texHeight+3)/4; lpData = lpInputPtr ? lpInputPtr : Allocate(tempWidth*tempHeight*8); mcpy(lpData, lpBits, tempWidth*tempHeight*8); } else if((dwFormat == GS_DXT3) || (dwFormat == GS_DXT5)) { LPBYTE lpBits = (LPBYTE)d3dRect.pBits; DWORD tempWidth = (texWidth+3)/4; DWORD tempHeight = (texHeight+3)/4; lpData = lpInputPtr ? lpInputPtr : Allocate(tempWidth*tempHeight*16); mcpy(lpData, lpBits, tempWidth*tempHeight*16); } else if((dwFormat == GS_RGBA) || (dwFormat == GS_RG16F)) { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*4); LPBYTE lpBits = (LPBYTE)d3dRect.pBits, lpInput = (LPBYTE)lpData; DWORD widthX4 = texWidth*4; for(i=0; i<texHeight; i++) mcpy(lpInput+(i*widthX4), lpBits+(i*d3dRect.Pitch), widthX4); } else if((dwFormat == GS_RGBA16) || (dwFormat == GS_RG32F)) { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*2*4); LPBYTE lpBits = (LPBYTE)d3dRect.pBits; LPWORD lpInput = (LPWORD)lpData; DWORD widthX8 = texWidth*8; for(i=0; i<texHeight; i++) mcpy(lpInput+(i*widthX8), lpBits+(i*d3dRect.Pitch), widthX8); } else if(dwFormat == GS_RGBA16F) //converts to 8bit RGBA { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*sizeof(Vect4)); LPBYTE lpBits = (LPBYTE)d3dRect.pBits; Vect4* lpInput = (Vect4*)lpData; DWORD widthXVect = texWidth*sizeof(Vect4); for(i=0; i<texHeight; i++) { DWORD curY = (i*texWidth); DWORD curD3DY = (i*d3dRect.Pitch); for(j=0; j<texWidth; j++) { DWORD curX = curY+(j*4); DWORD curD3DX = curD3DY+(j*2*4); lpInput[curY+j].x = ((FLOAT)*(D3DXFLOAT16*)(lpBits+(curD3DX))); lpInput[curY+j].y = ((FLOAT)*(D3DXFLOAT16*)(lpBits+(curD3DX+2))); lpInput[curY+j].z = ((FLOAT)*(D3DXFLOAT16*)(lpBits+(curD3DX+4))); lpInput[curY+j].w = ((FLOAT)*(D3DXFLOAT16*)(lpBits+(curD3DX+6))); } } } else if(dwFormat == GS_RGBA32F) //converts to 8bit RGBA { lpData = lpInputPtr ? lpInputPtr : Allocate(Width()*Height()*sizeof(Vect4)); LPBYTE lpBits = (LPBYTE)d3dRect.pBits; Vect4* lpInput = (Vect4*)lpData; DWORD widthXVect = texWidth*sizeof(Vect4); if(widthXVect == d3dRect.Pitch) mcpy(lpInput, lpBits, widthXVect*texHeight); else { for(i=0; i<texHeight; i++) mcpy(lpInput+(i*texWidth), lpBits+(i*d3dRect.Pitch), widthXVect); } } //------------------------------------------------------- CopySurface->UnlockRect(); CopySurface->Release(); return lpData; } return textureData; }
int imp_key (char *kf, char *kp, char gen_hdr, FILE *gen_fd) { CUSTOMER_SEC_INTER cust; uchar *r0,*r1,*r2; uchar line[300]; /* ------------------------------------- */ /* import key */ /* ------------------------------------- */ FILE *key_fd = fopen(kf,"r"); if(key_fd == 0) { MSG("[%s] %s not found\n",MOD,kf); return -1; } else { while(fgets(line,300,key_fd) != NULL) { r0 = strtok(line," "); r1 = strtok(NULL, " "); r2 = strtok(NULL, " \n"); /* ------------------------------------- */ /* parse key */ /* ------------------------------------- */ if ( 0 == mcmp(r0,CUSTOM_RSA_N,strlen(CUSTOM_RSA_N))) { MSG("[%s] import CUSTOM_RSA_N\n",MOD); mcpy(cust.key_rsa_n,r2+PREFIX_SIZE,sizeof(cust.key_rsa_n)); /* ------------------------------------- */ /* write key to generated header file */ /* ------------------------------------- */ if (TRUE == gen_hdr) { fwrite ("#define ",1,strlen("#define "),gen_fd); fwrite (kp,1,strlen(kp),gen_fd); fwrite ("_",1,strlen("_"),gen_fd); fwrite (CUSTOM_RSA_N,1,strlen(CUSTOM_RSA_N),gen_fd); fwrite (" \"",1,strlen(" \""),gen_fd); fwrite (cust.key_rsa_n,1,sizeof(cust.key_rsa_n),gen_fd); fwrite ("\"\n",1,strlen("\"\n"),gen_fd); } } else if ( 0 == mcmp(r0,CUSTOM_RSA_D,strlen(CUSTOM_RSA_D))) { MSG("[%s] import CUSTOM_RSA_D\n",MOD); mcpy(cust.key_rsa_d,r2+PREFIX_SIZE,sizeof(cust.key_rsa_d)); } else if ( 0 == mcmp(r0,CUSTOM_RSA_E,strlen(CUSTOM_RSA_E))) { MSG("[%s] import CUSTOM_RSA_E\n",MOD); mcpy(cust.key_rsa_e,r2+PREFIX_SIZE,sizeof(cust.key_rsa_e)); /* ------------------------------------- */ /* write rsa key to generate header file */ /* ------------------------------------- */ if (TRUE == gen_hdr) { fwrite ("#define ",1,strlen("#define "),gen_fd); fwrite (kp,1,strlen(kp),gen_fd); fwrite ("_",1,strlen("_"),gen_fd); fwrite (CUSTOM_RSA_E,1,strlen(CUSTOM_RSA_E),gen_fd); fwrite (" \"",1,strlen(" \""),gen_fd); fwrite (cust.key_rsa_e,1,sizeof(cust.key_rsa_e),gen_fd); fwrite ("\"\n",1,strlen("\"\n"),gen_fd); } } else { MSG("[%s] %s format error\n",MOD,kf); return -1; } } } /* ------------------------------------- */ /* initialize internal crypto engine */ /* ------------------------------------- */ cust_init_key(cust.key_rsa_n, sizeof(cust.key_rsa_n), cust.key_rsa_d, sizeof(cust.key_rsa_d), cust.key_rsa_e, sizeof(cust.key_rsa_e)); /* close key file */ fclose (key_fd); return 0; }
/****************************************************************************** * RETURN SECROIMG MD PLAINTEXT DATA ******************************************************************************/ uint32 masp_secro_md_get_data (uchar *md_info, uchar* buf, uint32 offset, uint32 len) { uint32 ret = SEC_OK; uint32 cipher_len = sizeof(AND_AC_ANDRO_T) + sizeof(AND_AC_MD_T) + sizeof(AND_AC_MD2_T); AND_AC_MD_INFO_V3a_T* cur_md_info = NULL; uint32 md_info_len = 0; uint32 index = 0; osal_secro_lock(); /* ----------------- */ /* check */ /* ----------------- */ if (NULL == md_info) { ret = ERR_SECROIMG_EMPTY_MD_INFO_STR; goto _exit; } else { md_info_len = strlen(md_info); } if(FALSE == bSecroExist) { ret = ERR_SECROIMG_IS_EMPTY; goto _exit; } if(len == 0) { ret = ERR_SECROIMG_INVALID_BUF_LEN; goto _exit; } if (0 != (len % masp_hal_sp_hacc_blk_sz())) { ret = ERR_HACC_DATA_UNALIGNED; goto _exit; } /* check if it only supports secro v3 format */ if (0 == secroimg.m_header.world_phone_support) { SMSG(TRUE,"[%s]sro v3 \n",MOD); /* ------------------------ */ /* decrypt secroimg */ /* ------------------------ */ if(TRUE == sec_secro_ac()) { masp_hal_sp_hacc_dec((uchar*)&secroimg.m_andro, cipher_len, TRUE,HACC_USER1,TRUE); } /* ------------------------ */ /* check header */ /* ------------------------ */ if(AC_ANDRO_MAGIC != secroimg.m_andro.magic_number) { ret = ERR_SECROIMG_HACC_AP_DECRYPT_FAIL; goto _exit; } if(AC_MD_MAGIC != secroimg.m_md.magic_number) { ret = ERR_SECROIMG_HACC_MD_DECRYPT_FAIL; goto _exit; } if(AC_MD2_MAGIC != secroimg.m_md2.magic_number) { ret = ERR_SECROIMG_HACC_MD_DECRYPT_FAIL; goto _exit; } /* ------------------------ */ /* fill buffer */ /* ------------------------ */ /* only copy the data with user specified length */ /* check if this image's information exist */ if ('1' == md_info[0]) { mcpy(buf,secroimg.m_md.reserve+offset,len); } else if ('2' == md_info[0]) { mcpy(buf,secroimg.m_md2.reserve+offset,len); } else { SMSG(TRUE,"[%s] MD user not supported!\n",MOD); } /* ------------------------ */ /* encrypt secro image */ /* ------------------------ */ if(TRUE == sec_secro_ac()) { masp_hal_sp_hacc_enc((uchar*)&secroimg.m_andro, cipher_len, TRUE,HACC_USER1,TRUE); } } else { SMSG(TRUE,"[%s]sro v5 \n",MOD); /* ----------------------------- */ /* if it supports v5 format */ /* ----------------------------- */ /* check if this image's information exist */ for(index=0; index<MAX_V5_SUPPORT_MD_NUM; index++) { cur_md_info = &(secroimg.m_padding.md_v3a_info[index]); if(0 == strncmp(md_info,cur_md_info->md_name+strlen("SECURE_RO_"),md_info_len)) { break; } } /* md info dees not exist */ if (MAX_V5_SUPPORT_MD_NUM == index) { ret = ERR_SECROIMG_MD_INFO_NOT_EXIST; goto _exit; } /* ------------------------ */ /* read secro v5 from flash */ /* ------------------------ */ bSecroV5Exist = FALSE; bSecroV5Intergiy = FALSE; if(SEC_OK != (ret = sec_dev_read_secroimg_v5(index))) { goto _exit; } else { /* ------------------------ */ /* decrypt secroimg */ /* ------------------------ */ cipher_len = sizeof(AND_AC_MD_INFO_V5a_T) + sizeof(AND_AC_MD_V5a_T); if(TRUE == sec_secro_ac()) { masp_hal_sp_hacc_dec((uchar*)&secroimg_v5.m_md_info_v5a, cipher_len, TRUE,HACC_USER1,TRUE); } /* ------------------------ */ /* check header */ /* ------------------------ */ if(AC_MD_INFO_MAGIC != secroimg_v5.m_md_info_v5a.magic_number) { ret = ERR_SECROIMG_HACC_MD_DECRYPT_FAIL; goto _exit; } if(AC_SV5_MAGIC_MD_V5a != secroimg_v5.m_md_sro_v5a.magic_number) { ret = ERR_SECROIMG_HACC_MD_DECRYPT_FAIL; goto _exit; } /* ------------------------ */ /* fill buffer */ /* ------------------------ */ /* only copy the data with user specified length */ mcpy(buf,secroimg_v5.m_md_sro_v5a.reserve+offset,len); /* no need to encrypt since next time, we'll read it again from flash*/ } } _exit: osal_secro_unlock(); return ret; }
void Matrix4x4Convert(float *destMatrix, const Matrix &mat) { mcpy(destMatrix, &mat, sizeof(Matrix)); destMatrix[15] = 1.0f; }
void runtime·newstack(void) { int32 framesize, argsize; Stktop *top; byte *stk, *sp; G *g1; Gobuf label; bool reflectcall; uintptr free; framesize = m->moreframesize; argsize = m->moreargsize; g1 = m->curg; if(m->morebuf.sp < g1->stackguard - StackGuard) { runtime·printf("runtime: split stack overflow: %p < %p\n", m->morebuf.sp, g1->stackguard - StackGuard); runtime·throw("runtime: split stack overflow"); } if(argsize % sizeof(uintptr) != 0) { runtime·printf("runtime: stack split with misaligned argsize %d\n", argsize); runtime·throw("runtime: stack split argsize"); } reflectcall = framesize==1; if(reflectcall) framesize = 0; if(reflectcall && m->morebuf.sp - sizeof(Stktop) - argsize - 32 > g1->stackguard) { // special case: called from reflect.call (framesize==1) // to call code with an arbitrary argument size, // and we have enough space on the current stack. // the new Stktop* is necessary to unwind, but // we don't need to create a new segment. top = (Stktop*)(m->morebuf.sp - sizeof(*top)); stk = g1->stackguard - StackGuard; free = 0; } else { // allocate new segment. framesize += argsize; framesize += StackExtra; // room for more functions, Stktop. if(framesize < StackMin) framesize = StackMin; framesize += StackSystem; stk = runtime·stackalloc(framesize); top = (Stktop*)(stk+framesize-sizeof(*top)); free = framesize; } //runtime·printf("newstack framesize=%d argsize=%d morepc=%p moreargp=%p gobuf=%p, %p top=%p old=%p\n", //framesize, argsize, m->morepc, m->moreargp, m->morebuf.pc, m->morebuf.sp, top, g1->stackbase); top->stackbase = g1->stackbase; top->stackguard = g1->stackguard; top->gobuf = m->morebuf; top->argp = m->moreargp; top->argsize = argsize; top->free = free; // copy flag from panic top->panic = g1->ispanic; g1->ispanic = false; g1->stackbase = (byte*)top; g1->stackguard = stk + StackGuard; sp = (byte*)top; if(argsize > 0) { sp -= argsize; runtime·mcpy(sp, m->moreargp, argsize); } if(thechar == '5') { // caller would have saved its LR below args. sp -= sizeof(void*); *(void**)sp = nil; } // Continue as if lessstack had just called m->morepc // (the PC that decided to grow the stack). label.sp = sp; label.pc = (byte*)runtime·lessstack; label.g = m->curg; runtime·gogocall(&label, m->morepc); *(int32*)345 = 123; // never return }
void RTMPPublisher::SendPacket(BYTE *data, UINT size, DWORD timestamp, PacketType type) { if(!bConnected && !bConnecting && !bStopping) { hConnectionThread = OSCreateThread((XTHREAD)CreateConnectionThread, this); bConnecting = true; } if (bFastInitialKeyframe) { if (!bConnected) { //while not connected, keep at most one keyframe buffered if (type != PacketType_VideoHighest) return; bufferedPackets.Clear(); } if (bConnected && bFirstKeyframe) { bFirstKeyframe = false; firstTimestamp = timestamp; //send out our buffered keyframe immediately, unless this packet happens to also be a keyframe if (type != PacketType_VideoHighest && bufferedPackets.Num() == 1) { TimedPacket packet; mcpy(&packet, &bufferedPackets[0], sizeof(TimedPacket)); bufferedPackets.Remove(0); packet.timestamp = 0; SendPacketForReal(packet.data.Array(), packet.data.Num(), packet.timestamp, packet.type); } else bufferedPackets.Clear(); } } else { if (bFirstKeyframe) { if (!bConnected || type != PacketType_VideoHighest) return; firstTimestamp = timestamp; bFirstKeyframe = false; } } //OSDebugOut (TEXT("%u: SendPacket (%d bytes - %08x @ %u)\n"), OSGetTime(), size, quickHash(data,size), timestamp); if (bufferedPackets.Num() == MAX_BUFFERED_PACKETS) { if (!bBufferFull) { InitializeBuffer(); bBufferFull = true; } TimedPacket packet; mcpy(&packet, &bufferedPackets[0], sizeof(TimedPacket)); bufferedPackets.Remove(0); SendPacketForReal(packet.data.Array(), packet.data.Num(), packet.timestamp, packet.type); } timestamp -= firstTimestamp; TimedPacket *packet; if (type == PacketType_Audio) { UINT newID; timestamp -= audioTimeOffset; newID = FindClosestBufferIndex(timestamp); packet = bufferedPackets.InsertNew(newID); } else { packet = bufferedPackets.CreateNew(); } packet->data.CopyArray(data, size); packet->timestamp = timestamp; packet->type = type; /*for (UINT i=0; i<bufferedPackets.Num(); i++) { if (bufferedPackets[i].data.Array() == 0) nop(); }*/ }
void GraphicsCaptureSource::Render(const Vect2 &pos, const Vect2 &size) { if(capture) { Shader *lastShader = GetCurrentPixelShader(); float fGamma = float(-(gamma-100) + 100) * 0.01f; LoadPixelShader(drawShader); HANDLE hGamma = drawShader->GetParameterByName(TEXT("gamma")); if(hGamma) drawShader->SetFloat(hGamma, fGamma); //---------------------------------------------------------- // capture mouse bMouseCaptured = false; if(bCaptureMouse) { CURSORINFO ci; zero(&ci, sizeof(ci)); ci.cbSize = sizeof(ci); if(GetCursorInfo(&ci) && hwndCapture) { mcpy(&cursorPos, &ci.ptScreenPos, sizeof(cursorPos)); ScreenToClient(hwndCapture, &cursorPos); if(ci.flags & CURSOR_SHOWING) { if(ci.hCursor == hCurrentCursor) bMouseCaptured = true; else { HICON hIcon = CopyIcon(ci.hCursor); hCurrentCursor = ci.hCursor; delete cursorTexture; cursorTexture = NULL; if(hIcon) { ICONINFO ii; if(GetIconInfo(hIcon, &ii)) { xHotspot = int(ii.xHotspot); yHotspot = int(ii.yHotspot); UINT size; LPBYTE lpData = GetCursorData(hIcon, ii, size); if(lpData) { cursorTexture = CreateTexture(size, size, GS_BGRA, lpData, FALSE); if(cursorTexture) bMouseCaptured = true; Free(lpData); } DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DestroyIcon(hIcon); } } } } } //---------------------------------------------------------- // game texture Texture *tex = capture->LockTexture(); Vect2 texPos = Vect2(0.0f, 0.0f); Vect2 texStretch = Vect2(1.0f, 1.0f); if(tex) { Vect2 texSize = Vect2(float(tex->Width()), float(tex->Height())); Vect2 totalSize = API->GetBaseSize(); Vect2 center = totalSize*0.5f; BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO); if(bStretch) { if(bIgnoreAspect) texStretch *= totalSize; else { float xDif = fabsf(totalSize.x-texSize.x); float yDif = fabsf(totalSize.y-texSize.y); float multiplyVal = (xDif < yDif) ? (totalSize.x/texSize.x) : (totalSize.y/texSize.y); texStretch *= texSize*multiplyVal; texPos = center-(texStretch*0.5f); } } else { texStretch *= texSize; texPos = center-(texStretch*0.5f); } Vect2 sizeAdjust = size/totalSize; texPos *= sizeAdjust; texPos += pos; texStretch *= sizeAdjust; RoundVect2(texPos); RoundVect2(texSize); if(bFlip) DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y+texStretch.y, texPos.x+texStretch.x, texPos.y); else DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y, texPos.x+texStretch.x, texPos.y+texStretch.y); capture->UnlockTexture(); BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA); //---------------------------------------------------------- // draw mouse if(bMouseCaptured && cursorTexture) { Vect2 newCursorPos = Vect2(float(cursorPos.x-xHotspot), float(cursorPos.y-xHotspot)); Vect2 newCursorSize = Vect2(float(cursorTexture->Width()), float(cursorTexture->Height())); newCursorPos /= texSize; newCursorSize /= texSize; newCursorPos *= texStretch; newCursorPos += texPos; newCursorSize *= texStretch; bool bInvertCursor = false; if(invertShader) { if(bInvertCursor = ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0 || (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0)) LoadPixelShader(invertShader); } DrawSprite(cursorTexture, 0xFFFFFFFF, newCursorPos.x, newCursorPos.y+newCursorSize.y, newCursorPos.x+newCursorSize.x, newCursorPos.y); } } if(lastShader) LoadPixelShader(lastShader); } }
void GraphicsCaptureSource::AttemptCapture() { OSDebugOut(TEXT("attempting to capture..\n")); if (scmpi(strWindowClass, L"dwm") == 0) { hwndTarget = FindWindow(strWindowClass, NULL); } else { FindWindowData fwd; //FIXME: duplicated code, but we need OpenProcess here char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i = 0; i<11; i++) pOPStr[i] ^= i ^ 1; fwd.pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); fwd.classname = strWindowClass; fwd.exename = strExecutable; fwd.hwnd = nullptr; EnumWindows(GraphicsCaptureFindWindow, (LPARAM)&fwd); hwndTarget = fwd.hwnd; } // use foregroundwindow as fallback (should be NULL if not using hotkey capture) if (!hwndTarget) hwndTarget = hwndNextTarget; hwndNextTarget = nullptr; OSDebugOut(L"Window: %s: ", strWindowClass.Array()); if (hwndTarget) { OSDebugOut(L"Valid window\n"); targetThreadID = GetWindowThreadProcessId(hwndTarget, &targetProcessID); if (!targetThreadID || !targetProcessID) { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: GetWindowThreadProcessId failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; return; } } else { OSDebugOut(L"Bad window\n"); if (!bUseHotkey && !warningID) { //Log(TEXT("GraphicsCaptureSource::AttemptCapture: Window '%s' [%s] not found."), strWindowClass.Array(), strExecutable.Array()); //warningID = API->AddStreamInfo(Str("Sources.SoftwareCaptureSource.WindowNotFound"), StreamInfoPriority_High); } bCapturing = false; return; } if (injectHelperProcess && WaitForSingleObject(injectHelperProcess, 0) == WAIT_TIMEOUT) return; if(warningID) { //API->RemoveStreamInfo(warningID); warningID = 0; } //------------------------------------------- // see if we already hooked the process. if not, inject DLL char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); DWORD permission = useSafeHook ? (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) : (PROCESS_ALL_ACCESS); HANDLE hProcess = (*pOpenProcess)(permission, FALSE, targetProcessID); if(hProcess) { DWORD dwSize = MAX_PATH; wchar_t processName[MAX_PATH]; memset(processName, 0, sizeof(processName)); QueryFullProcessImageName(hProcess, 0, processName, &dwSize); if (dwSize != 0 && scmpi(processName, lastProcessName) != 0) { if (processName[0]) { wchar_t *fileName = srchr(processName, '\\'); Log(L"Trying to hook process: %s", (fileName ? fileName+1 : processName)); } scpy_n(lastProcessName, processName, MAX_PATH-1); } //------------------------------------------- // load keepalive event hOBSIsAlive = CreateEvent(NULL, FALSE, FALSE, String() << OBS_KEEPALIVE_EVENT << UINT(targetProcessID)); //------------------------------------------- hwndCapture = hwndTarget; hSignalRestart = OpenEvent(EVENT_ALL_ACCESS, FALSE, String() << RESTART_CAPTURE_EVENT << UINT(targetProcessID)); if(hSignalRestart) { OSDebugOut(L"Setting signal for process ID %u\n", targetProcessID); SetEvent(hSignalRestart); bCapturing = true; captureWaitCount = 0; } else { BOOL bSameBit = TRUE; BOOL b32bit = TRUE; if (Is64BitWindows()) { BOOL bCurrentProcessWow64, bTargetProcessWow64; IsWow64Process(GetCurrentProcess(), &bCurrentProcessWow64); IsWow64Process(hProcess, &bTargetProcessWow64); bSameBit = (bCurrentProcessWow64 == bTargetProcessWow64); } if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); //verify the hook DLL is accessible String strDLL; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLL.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLL); strDLL << TEXT("\\plugins\\GraphicsCapture\\GraphicsCaptureHook"); if (!b32bit) strDLL << TEXT("64"); strDLL << TEXT(".dll"); if (!CheckFileIntegrity(strDLL.Array())) { OSDebugOut(L"Error acquiring\n"); bErrorAcquiring = true; } else { if (bSameBit && !useSafeHook) { if (InjectLibrary(hProcess, strDLL)) { captureWaitCount = 0; OSDebugOut(L"Inject successful\n"); bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Failed to inject library, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } else { String strDLLPath; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLLPath.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLLPath); strDLLPath << TEXT("\\plugins\\GraphicsCapture"); String strHelper = strDLLPath; strHelper << ((b32bit) ? TEXT("\\injectHelper.exe") : TEXT("\\injectHelper64.exe")); if (!CheckFileIntegrity(strHelper.Array())) { bErrorAcquiring = true; } else { String strCommandLine; strCommandLine << TEXT("\"") << strHelper << TEXT("\" "); if (useSafeHook) strCommandLine << UIntString(targetThreadID) << " 1"; else strCommandLine << UIntString(targetProcessID) << " 0"; //--------------------------------------- PROCESS_INFORMATION pi; STARTUPINFO si; zero(&pi, sizeof(pi)); zero(&si, sizeof(si)); si.cb = sizeof(si); if (CreateProcess(strHelper, strCommandLine, NULL, NULL, FALSE, 0, NULL, strDLLPath, &si, &pi)) { int exitCode = 0; CloseHandle(pi.hThread); if (!useSafeHook) { WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, (DWORD*)&exitCode); CloseHandle(pi.hProcess); } else { injectHelperProcess = pi.hProcess; } if (exitCode == 0) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Failed to inject library, error code = %d"), exitCode); bErrorAcquiring = true; } } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Could not create inject helper, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } } } } //save a copy of the process handle which we injected into, this lets us check for process exit in Tick() if (!hTargetProcess) { if (!DuplicateHandle(GetCurrentProcess(), hProcess, GetCurrentProcess(), &hTargetProcess, 0, FALSE, DUPLICATE_SAME_ACCESS)) { Log(TEXT("Warning: Couldn't DuplicateHandle, %d"), GetLastError()); } } CloseHandle(hProcess); if (!bCapturing) { CloseHandle(hOBSIsAlive); hOBSIsAlive = NULL; } } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: OpenProcess failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } }
int gen_hdr (char *cfg_name, char *hdr_name, char* img_name, char *hs_name) { SEC_IMG_HEADER sec = {0}; uchar *r0,*r1,*r2; uchar line[300]; SEC_EXTENTION_CFG *p_ext_cfg = (SEC_EXTENTION_CFG *)get_ext_cfg(); bool b_ext_offset[MAX_VERITY_COUNT] = {0}; bool b_ext_length[MAX_VERITY_COUNT] = {0}; unsigned int tmp, i; p_ext_cfg->chunk_size = SEC_CHUNK_SIZE_ZERO; /* ------------------------------------- */ /* open image config file */ /* ------------------------------------- */ FILE *config_fd = fopen(cfg_name,"r"); if(config_fd == 0) { MSG("[%s] %s not found\n",MOD,cfg_name); return -1; } else { while(fgets(line,300,config_fd) != NULL) { r0 = strtok(line," "); r1 = strtok(NULL, " "); r2 = strtok(NULL, " \n"); /* ------------------------------------- */ /* parse image config */ /* ------------------------------------- */ if ( 0 == mcmp(r0,CUSTOM_NAME,strlen(CUSTOM_NAME))) { if(0 == mcmp(r2,"NULL",strlen("NULL"))) { MSG("[%s] empty customer name '%s'\n",MOD,r2); memset(sec.cust_name,0,sizeof(sec.cust_name)); } else { mcpy(sec.cust_name,r2,sizeof(sec.cust_name)); } } else if ( 0 == mcmp(r0,IMAGE_VERSION,strlen(IMAGE_VERSION))) { sec.img_ver = atoi(r2); } else if ( 0 == mcmp(r0,VERIFY_OFFSET,strlen(VERIFY_OFFSET))) { if (strlen(VERIFY_OFFSET) != strlen(r0)) { sscanf(r0, "VERIFY_OFFSET[%d]", &tmp); p_ext_cfg->verify_offset[tmp] = atoi(r2); b_ext_offset[tmp] = TRUE; MSG("[%s] VERIFY_OFFSET[%d]=%d\n",MOD, tmp, p_ext_cfg->verify_offset[tmp]); } else { sec.s_off = atoi(r2); } } else if ( 0 == mcmp(r0,VERIFY_LENGTH,strlen(VERIFY_LENGTH))) { if (strlen(VERIFY_LENGTH) != strlen(r0)) { sscanf(r0, "VERIFY_LENGTH[%d]", &tmp); p_ext_cfg->verify_length[tmp] = atoi(r2); b_ext_length[tmp] = TRUE; MSG("[%s] VERIFY_LENGTH[%d]=%d\n",MOD, tmp, p_ext_cfg->verify_length[tmp]); } else { sec.s_len = atoi(r2); } } else if ( 0 == mcmp(r0,VERIFY_COUNT,strlen(VERIFY_COUNT))) { p_ext_cfg->verify_count = atoi(r2); set_hdr_version(SEC_HDR_V3); MSG("[%s] VERIFY_COUNT=%d\n",MOD, p_ext_cfg->verify_count); } else if ( 0 == mcmp(r0,CHUNK_SIZE,strlen(CHUNK_SIZE))) { p_ext_cfg->chunk_size = atoi(r2); MSG("[%s] CHUNK_SIZE=%d\n",MOD, p_ext_cfg->chunk_size); } else if (';' == r0[0]) { } else if (NULL == r1) { } else { MSG("[%s] %s format error\n",MOD,cfg_name); return -1; } } /* check config format for v3 */ if( is_hdr_version3() ) { for(i=0 ; i<p_ext_cfg->verify_count ; i++) { if( !b_ext_offset[i] || !b_ext_length[i]) { MSG("[%s] %s config setting error\n",MOD,cfg_name); return -1; } } } } /* ------------------------------------- */ /* fill and write header */ /* ------------------------------------- */ COMPILE_ASSERT(SEC_IMG_HDR_SZ == sizeof(sec)); FILE *hdr_fd = fopen(hdr_name,"wb"); /* config common part */ FILE *img_fd = fopen(img_name,"r"); if(img_fd == 0) { MSG("[%s] %s not found\n",MOD,img_name); goto img_err; } fseek(img_fd, 0, SEEK_END); sec.img_len = ftell(img_fd); fclose(img_fd); sec.magic_num = SEC_IMG_MAGIC; sec.img_off = SEC_IMG_HDR_SZ; sec.sig_off = sec.img_off + sec.img_len; if( is_hdr_version3() ) { /* config header for v3 */ if(config_header_v3_chk(&sec)) goto check_err; } else { /* config header for v1 and v2 */ if(config_header_v1_v2_chk(&sec)) goto check_err; } /* ------------------------------------- */ /* write to image */ /* ------------------------------------- */ fwrite (&sec, 1 , sizeof(sec) , hdr_fd); /* ------------------------------------- */ /* dump information */ /* ------------------------------------- */ MSG("[%s] hdr.magic_num = 0x%x\n",MOD,sec.magic_num,sec.magic_num); MSG("[%s] hdr.cust_name = %s\n",MOD,sec.cust_name); MSG("[%s] hdr.img_ver = %d (0x%x)\n",MOD,sec.img_ver,sec.img_ver); MSG("[%s] hdr.img_off = %d (0x%x)\n",MOD,sec.img_off,sec.img_off); MSG("[%s] hdr.img_len = %d (0x%x)\n",MOD,sec.img_len,sec.img_len); MSG("[%s] hdr.sign_off = %d (0x%x)\n",MOD,sec.s_off,sec.s_off); MSG("[%s] hdr.sign_len = %d (0x%x)\n",MOD,sec.s_len,sec.s_len); MSG("[%s] hdr.hs_off = %d (0x%x)\n",MOD,sec.sig_off,sec.sig_off); MSG("[%s] hdr.hs_len = %d (0x%x)\n",MOD,sec.sig_len,sec.sig_len); img_err: check_err: /* close header file */ fclose (hdr_fd); return 0; }
void RTMPPublisher::SendPacketForReal(BYTE *data, UINT size, DWORD timestamp, PacketType type) { //OSDebugOut (TEXT("SendPacketForReal (%08x)\n"), quickHash(data,size)); //Log(TEXT("packet| timestamp: %u, type: %u, bytes: %u"), timestamp, (UINT)type, size); OSEnterMutex(hDataMutex); if(bConnected) { ProcessPackets(); bool bSend = bSentFirstKeyframe; if(!bSentFirstKeyframe) { if(type == PacketType_VideoHighest) { bSend = true; OSDebugOut(TEXT("got keyframe: %u\r\n"), OSGetTime()); } } if(bSend) { if(!bSentFirstAudio && type == PacketType_Audio) { timestamp = 0; bSentFirstAudio = true; } totalFrames++; if(type != PacketType_Audio) totalVideoFrames++; bool bAddPacket = false; if(type >= packetWaitType) { if(type != PacketType_Audio) packetWaitType = PacketType_VideoDisposable; bAddPacket = true; } if(bAddPacket) { List<BYTE> paddedData; paddedData.SetSize(size+RTMP_MAX_HEADER_SIZE); mcpy(paddedData.Array()+RTMP_MAX_HEADER_SIZE, data, size); if(!bSentFirstKeyframe) { DataPacket sei; App->GetVideoEncoder()->GetSEI(sei); paddedData.InsertArray(RTMP_MAX_HEADER_SIZE+5, sei.lpPacket, sei.size); bSentFirstKeyframe = true; } currentBufferSize += paddedData.Num(); UINT droppedFrameVal = queuedPackets.Num() ? queuedPackets.Last().distanceFromDroppedFrame+1 : 10000; UINT id = FindClosestQueueIndex(timestamp); NetworkPacket *queuedPacket = queuedPackets.InsertNew(id); queuedPacket->distanceFromDroppedFrame = droppedFrameVal; queuedPacket->data.TransferFrom(paddedData); queuedPacket->timestamp = timestamp; queuedPacket->type = type; } else { if(type < PacketType_VideoHigh) numBFramesDumped++; else numPFramesDumped++; } } } OSLeaveMutex(hDataMutex); }
int pro_img_v1_v2(char *hs_name, char *img_name,char *hdr_name) { uint32 br = 0; uchar *d_buf = NULL; uchar c_buf[SEC_IMG_HDR_SZ]; uchar *sig; uchar *hash; uint32 i = 0; SEC_IMG_HEADER *sec = NULL; /* ------------------------------------- */ /* open hash and signature file */ /* ------------------------------------- */ FILE *hs_fd = fopen(hs_name,"wb"); if(hs_fd == 0) { MSG("[%s] %s not found\n",MOD,hs_name); goto _err; } /* ------------------------------------- */ /* read image header */ /* ------------------------------------- */ FILE *hdr_fd = fopen(hdr_name,"r"); br = fread(c_buf,1,SEC_IMG_HDR_SZ,hdr_fd); /* read header */ sec = (SEC_IMG_HEADER *)c_buf; if(br == 0) { MSG("\n[%s] read '%s' image hdr fail, read bytes = '%d'\n",MOD,hdr_name,br); goto _err; } /* ------------------------------------- */ /* initialize buffer */ /* ------------------------------------- */ d_buf = (uchar*) malloc(SEC_IMG_HDR_SZ + sec->s_len*sizeof(char)); sig = (uchar*) malloc(get_sigature_size(g_sig_type)); hash = (uchar*) malloc(get_hash_size(g_hash_type)); mcpy(d_buf,c_buf,SEC_IMG_HDR_SZ); /* ------------------------------------- */ /* read image content */ /* ------------------------------------- */ FILE *img_fd = fopen(img_name,"r"); if(img_fd == 0) { MSG("[%s] %s not found\n",MOD,img_name); goto _err; } fseek(img_fd,sec->s_off*sizeof(char),SEEK_SET); br = fread(d_buf+SEC_IMG_HDR_SZ,1,sec->s_len,img_fd); if(br == 0) { MSG("\n[%s] read image content fail, read bytes = '%d'\n",MOD,br); goto _err; } /* ------------------------------------- */ /* Sign * @1 : file * @2 : file length to be signed * @3 : signature * @3 : signature length */ /* ------------------------------------- */ if( cust_sign(d_buf,SEC_IMG_HDR_SZ + sec->s_len,sig,get_sigature_size(g_sig_type)) == -1) { MSG("[%s] Sign %s fail\n",MOD,img_name); goto _err; } /* ------------------------------------- */ /* Hash * @1 : file * @2 : file length to be hashed * @3 : hash * @3 : hash length */ /* ------------------------------------- */ if( cust_hash(d_buf,SEC_IMG_HDR_SZ + sec->s_len,hash,get_hash_size(g_hash_type)) == -1) { MSG("[%s] Sign %s fail\n",MOD,img_name); goto _err; } /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ MSG("[%s] Hash value : \n",MOD); for(i=0;i<get_hash_size(g_hash_type);i++) { MSG("0x%x,",hash[i]); } MSG("\n",MOD); /* ------------------------------------- */ /* write hash and signature */ /* ------------------------------------- */ fwrite (sig , 1 , get_sigature_size(g_sig_type), hs_fd); fwrite (hash , 1 , get_hash_size(g_hash_type) , hs_fd); fclose (hs_fd); free(d_buf); return 0; _err: free(d_buf); return -1; }
/************************************************************************** * FUNCTION To Get Image Hash **************************************************************************/ int sec_signfmt_calculate_image_hash_v4(char* part_name, SECURE_IMG_INFO_V3 *img_if, char *final_hash_buf, unsigned int hash_len, char *ext_buf) { unsigned int ret = SEC_OK; SEC_IMG_HEADER_V4 *img_hdr = (SEC_IMG_HEADER_V4 *)&img_if->header.v4; SEC_IMG_EXTENSTION_SET ext_set; uint32 ext_hdr_offset = 0; uint32 ext_hdr_len = 0; uchar *ext_hdr_buf = NULL; uint32 hash_size = 0; uint32 sig_size = 0; uint32 i = 0; uchar *cal_hash_buf = NULL; uint32 cal_hash_buf_len = 0; uchar *tmp_ptr = NULL; uchar *verify_data = NULL; uint32 verify_data_len = 0; uint32 real_chunk_size = 0; /* ======================== */ /* init check */ /* ======================== */ #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump header ============> START\n",MOD); sec_signfmt_dump_buffer((uchar*)img_hdr,sizeof(SEC_IMG_HEADER_V4)); SMSG(sec_info.bMsg,"[%s] Dump header ============> END\n",MOD); #endif if (SEC_IMG_MAGIC != img_hdr->magic_number) { SMSG(true,"[%s] magic number is invalid '0x%x'\n",MOD,img_hdr->magic_number); ret = ERR_SIGN_FORMAT_MAGIC_WRONG; goto _magic_wrong_err; } if (SEC_EXTENSION_MAGIC_V4 != img_hdr->ext_magic) { SMSG(true,"[%s] extension magic number is invalid '0x%x'\n",MOD,img_hdr->ext_magic); ret = ERR_SIGN_FORMAT_MAGIC_WRONG; goto _magic_wrong_err; } /* ======================== */ /* search for extension header */ /* ======================== */ memset(&ext_set, 0x00, sizeof(SEC_IMG_EXTENSTION_SET)); ext_hdr_offset = img_if->ext_offset + img_hdr->signature_length; ext_hdr_len = img_if->ext_len - img_hdr->signature_length; ext_hdr_buf = (uchar*)(ext_buf + ext_hdr_offset); if( SEC_OK != (ret = sec_signfmt_search_extension_v4(ext_hdr_buf, ext_hdr_len, &ext_set)) ) { SMSG(true,"[%s] Image extension header not found\n",MOD); goto _ext_hdr_search_fail; } hash_size = get_hash_size((SEC_CRYPTO_HASH_TYPE)ext_set.crypto->hash_type); sig_size = get_signature_size((SEC_CRYPTO_SIGNATURE_TYPE)ext_set.crypto->sig_type); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump ext hash value ============> START\n",MOD); for(i=0;i<ext_set.frag->frag_count;i++) { SMSG(sec_info.bMsg,"[%s] Dump EXT hash [%d]\n",MOD,i); sec_signfmt_dump_buffer(ext_set.hash_only_64[i]->hash_data,hash_size); } SMSG(sec_info.bMsg,"[%s] Dump ext hash value ============> END\n",MOD); #endif /* ======================== */ /* calculate each hash by chunk */ /* ======================== */ cal_hash_buf_len = hash_size*ext_set.frag->frag_count; cal_hash_buf = (uchar*)ASF_MALLOC(cal_hash_buf_len); if (NULL == cal_hash_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_cal_buf_fail; } memset(cal_hash_buf, 0x00, cal_hash_buf_len); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] dump reset data\n",MOD); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif tmp_ptr = cal_hash_buf; #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Total cal hash length is %d\n",MOD,cal_hash_buf_len); #endif for(i=0;i<ext_set.frag->frag_count;i++) { memset(tmp_ptr, 0x00, hash_size); if(ext_set.frag->chunk_size == 0) { real_chunk_size = ext_set.hash_only_64[i]->hash_len_64 & 0x00000000FFFFFFFFULL; } else { real_chunk_size = ext_set.frag->chunk_size; } if(sec_signfmt_gen_hash_by_chunk_64(ASF_FILE_NULL, part_name, ext_set.hash_only_64[i]->hash_offset_64, ext_set.hash_only_64[i]->hash_len_64, tmp_ptr, ext_set.hash_only_64[i]->sub_type, real_chunk_size)!=0) { ret = ERR_SIGN_FORMAT_CAL_HASH_BY_CHUNK_FAIL; goto _gen_hash_by_chunk_fail; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump CAL hash right after: [%d], offset is 0x%x\n",MOD,i,tmp_ptr); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif tmp_ptr += hash_size; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump CAL hash right after all done, offset is 0x%x\n",MOD,tmp_ptr); sec_signfmt_dump_buffer(cal_hash_buf,cal_hash_buf_len); #endif #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump cal hash value ============> START\n",MOD); tmp_ptr = cal_hash_buf; for(i=0;i<ext_set.frag->frag_count;i++) { SMSG(true,"[%s] Dump CAL hash [%d]\n",MOD,i); sec_signfmt_dump_buffer(tmp_ptr,hash_size); tmp_ptr += hash_size; } SMSG(sec_info.bMsg,"[%s] Dump cal hash value ============> END\n",MOD); #endif /* ======================== */ /* copy cal hash to extension header */ /* ======================== */ tmp_ptr = cal_hash_buf; for(i=0;i<ext_set.frag->frag_count;i++) { mcpy(ext_set.hash_only_64[i]->hash_data, tmp_ptr, hash_size); tmp_ptr += hash_size; } /* ======================== */ /* compose final verify buffer */ /* ======================== */ verify_data_len = SEC_IMG_HEADER_SIZE+cal_hash_buf_len+ext_hdr_len; verify_data = (uchar*)ASF_MALLOC(verify_data_len); if (NULL == cal_hash_buf) { ret = ERR_FS_READ_BUF_ALLOCATE_FAIL; goto _malloc_verify_buf_fail; } tmp_ptr = verify_data; /* copy header */ mcpy(tmp_ptr,img_hdr,SEC_IMG_HEADER_SIZE); tmp_ptr += SEC_IMG_HEADER_SIZE; /* copy cal hash */ for(i=0;i<ext_set.frag->frag_count;i++) { mcpy(tmp_ptr,cal_hash_buf+i*hash_size,hash_size); tmp_ptr += hash_size; } /* copy extension header */ mcpy(tmp_ptr,ext_hdr_buf,ext_hdr_len); #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Dump verify data (%d):\n",MOD,verify_data_len); sec_signfmt_dump_buffer(verify_data,verify_data_len); #endif /* ======================== */ /* generate final hash */ /* ======================== */ /* hash */ SMSG(sec_info.bMsg,"[%s] generate hash ... \n",MOD); if(SEC_OK != (ret = sec_hash(verify_data, verify_data_len, (uchar*)final_hash_buf, hash_len ))) { SMSG(true,"[%s] generate hash fail\n\n",MOD); ret = ERR_SIGN_FORMAT_GENERATE_HASH_FAIL; goto _hash_fail; } /* ================== */ /* dump hash data */ /* ================== */ SMSG(sec_info.bMsg,"[%s] dump hash data\n",MOD); dump_buf((uchar*)final_hash_buf,hash_len); SMSG(sec_info.bMsg,"[%s] generate hash pass\n\n",MOD); _hash_fail: ASF_FREE(verify_data); _malloc_verify_buf_fail: _gen_hash_by_chunk_fail: ASF_FREE(cal_hash_buf); _malloc_cal_buf_fail: _ext_hdr_search_fail: _magic_wrong_err: return ret; }
int gen_hash_by_chunk(FILE *img_fd, uint32 img_hash_off, uint32 img_hash_len, uchar *final_hash_buf, SEC_CRYPTO_HASH_TYPE hash_type, uint32 chunk_size) { uint32 br = 0; uint32 i = 0, ret = 0; uchar *chunk_buf = NULL; uchar *hash_tmp; uchar *hash_comb; uint32 seek_pos = 0; uint32 hash_size = get_hash_size(hash_type); uint32 chunk_count = ((img_hash_len-1)/chunk_size)+1; uint32 read_size = 0; uint32 left_size = 0; if(!img_hash_len) { MSG("[%s] hash length is zero, no need to do hash\n",MOD); ret = -1; memset(final_hash_buf, 0x00, hash_size); goto end_error; } #if DUMP_MORE_FOR_DEBUG DBG("[%s] Hash size is %d (0x%x)\n",MOD, hash_size, hash_size); DBG("[%s] Offset is %d (0x%x)\n",MOD, img_hash_off, img_hash_off); DBG("[%s] Size is %d (0x%x)\n",MOD, img_hash_len, img_hash_len); DBG("[%s] Chunk size is %d (0x%x)\n",MOD, chunk_size, chunk_size); DBG("[%s] Chunk count is %d (0x%x)\n",MOD, chunk_count, chunk_count); #endif /* allocate hash buffer */ hash_tmp = (uchar*) malloc(hash_size); hash_comb = (uchar*) malloc(hash_size*2); memset(hash_tmp, 0x00, hash_size); memset(hash_comb, 0x00, hash_size*2); /* allocate buffer with known chunk size */ chunk_buf = (uchar*) malloc(chunk_size); /* caculate first hash */ seek_pos = img_hash_off; left_size = img_hash_len; read_size = (left_size>=chunk_size)?chunk_size:left_size; fseek(img_fd,seek_pos*sizeof(char),SEEK_SET); br = fread(chunk_buf,1,read_size,img_fd); if(br != read_size) { MSG("[%s] read image content fail, read offset = '0x%x'\n",MOD,seek_pos); ret = -2; goto end_error; } if( cust_hash(chunk_buf,read_size,hash_tmp,hash_size) == -1) { MSG("[%s] hash fail, offset is '0x%x'(A)\n",MOD,seek_pos); ret = -3; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ DBG("[%s] Data value(4 bytes) ==> (0x%x, 0x%x, 0x%x, 0x%x) \n",MOD, chunk_buf[0], chunk_buf[1], chunk_buf[2], chunk_buf[3]); DBG("[%s] Hash value(single) (0x%x): \n",MOD, seek_pos); for(i=0;i<hash_size;i++) { DBG("0x%x,",hash_tmp[i]); } DBG("\n",MOD); #endif /* copy to compose buffer (first block) */ mcpy(hash_comb,hash_tmp,hash_size); /* move next */ seek_pos += read_size; left_size -= read_size; /* loop hash */ while(left_size) { /* load data */ read_size = (left_size>=chunk_size)?chunk_size:left_size; fseek(img_fd,seek_pos*sizeof(char),SEEK_SET); br = fread(chunk_buf,1,read_size,img_fd); if(br != read_size) { MSG("[%s] read image content fail, read offset = '0x%x'\n",MOD,seek_pos); ret = -4; goto end_error; } /* caculate this hash */ if( cust_hash(chunk_buf,read_size,hash_tmp,hash_size) == -1) { MSG("[%s] hash fail, offset is '0x%x'(B)\n",MOD,seek_pos); ret = -5; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ DBG("[%s] Data value(4 bytes) ==> (0x%x, 0x%x, 0x%x, 0x%x) \n",MOD, chunk_buf[0], chunk_buf[1], chunk_buf[2], chunk_buf[3]); DBG("[%s] Hash value(single) (0x%x): \n",MOD, seek_pos); for(i=0;i<hash_size;i++) { DBG("0x%x,",hash_tmp[i]); } DBG("\n",MOD); #endif /* compose two hash to buffer (second block) */ mcpy(hash_comb+hash_size,hash_tmp,hash_size); /* caculate compose hash */ if( cust_hash(hash_comb,hash_size*2,hash_tmp,hash_size) == -1) { MSG("[%s] hash fail, offset is '0x%x'(C)\n",MOD,seek_pos); ret = -6; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ DBG("[%s] Data value(4 bytes) ==> (0x%x, 0x%x, 0x%x, 0x%x) \n",MOD, hash_comb[0], hash_comb[1], hash_comb[2], hash_comb[3]); DBG("[%s] Hash value(comp): \n",MOD); for(i=0;i<hash_size;i++) { DBG("0x%x,",hash_tmp[i]); } DBG("\n",MOD); #endif /* save this hash to compose buffer (first block) */ mcpy(hash_comb,hash_tmp,hash_size); /* move next */ seek_pos += read_size; left_size -= read_size; } /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ #if DUMP_MORE_FOR_DEBUG DBG("[%s] Hash value(final) : \n",MOD); for(i=0;i<hash_size;i++) { DBG("0x%x,",hash_tmp[i]); } DBG("\n",MOD); #endif /* copy hash */ mcpy(final_hash_buf,hash_tmp,hash_size); end_error: free(hash_comb); free(chunk_buf); free(hash_tmp); return ret; }
static int sec_signfmt_gen_hash_by_chunk_64(ASF_FILE img_fd, char* part_name, u64 img_hash_off, u64 img_hash_len, uchar *final_hash_buf, SEC_CRYPTO_HASH_TYPE hash_type, uint32 chunk_size) { uint32 br = 0; uint32 ret = 0; uchar *chunk_buf = NULL; uchar *hash_tmp = NULL; uchar *hash_comb = NULL; u64 seek_pos = 0; uint32 hash_size = get_hash_size(hash_type); #if DUMP_MORE_FOR_DEBUG u64 chunk_count = ((img_hash_len-1)/chunk_size)+1; #endif uint32 read_size = 0; u64 left_size = 0; if(!img_hash_len) { SMSG(true,"[%s] hash length is zero, no need to do hash\n",MOD); ret = -1; memset(final_hash_buf, 0x00, hash_size); goto end_error; } #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Hash size is %d (0x%x)\n",MOD, hash_size, hash_size); SMSG(sec_info.bMsg,"[%s] Offset is %d (0x%llx)\n",MOD, img_hash_off, img_hash_off); SMSG(sec_info.bMsg,"[%s] Size is %d (0x%llx)\n",MOD, img_hash_len, img_hash_len); SMSG(sec_info.bMsg,"[%s] Chunk size is %d (0x%x)\n",MOD, chunk_size, chunk_size); SMSG(sec_info.bMsg,"[%s] Chunk count is %d (0x%llx)\n",MOD, chunk_count, chunk_count); #endif /* allocate hash buffer */ hash_tmp = ASF_MALLOC(hash_size); hash_comb = ASF_MALLOC(hash_size*2); memset(hash_tmp, 0x00, hash_size); memset(hash_comb, 0x00, hash_size*2); /* allocate buffer with known chunk size */ chunk_buf = ASF_MALLOC(chunk_size); /* caculate first hash */ seek_pos = img_hash_off; left_size = img_hash_len; read_size = (left_size>=chunk_size)?chunk_size:(left_size & 0xFFFFFFFF); br = sec_signfmt_image_read_64(img_fd, part_name, seek_pos*sizeof(char), (char*)chunk_buf, read_size); if(br != read_size) { SMSG(true,"[%s] read image content fail, read offset = '0x%llx'\n",MOD,seek_pos); ret = -2; goto end_error; } if( sec_hash(chunk_buf,read_size,hash_tmp,hash_size) == -1) { SMSG(true,"[%s] hash fail, offset is '0x%llx'(A)\n",MOD,seek_pos); ret = -3; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ SMSG(sec_info.bMsg,"[%s] Data value(4 bytes) ==>\n",MOD); sec_signfmt_dump_buffer(chunk_buf, 4); SMSG(sec_info.bMsg,"[%s] Hash value(single) (0x%llx): \n",MOD, seek_pos); sec_signfmt_dump_buffer(hash_tmp, hash_size); #endif /* copy to compose buffer (first block) */ mcpy(hash_comb,hash_tmp,hash_size); /* move next */ seek_pos += read_size; left_size -= read_size; /* loop hash */ while(left_size) { /* load data */ read_size = (left_size>=chunk_size)?chunk_size:(left_size & 0xFFFFFFFF); br = sec_signfmt_image_read_64(img_fd, part_name, seek_pos*sizeof(char), (char*)chunk_buf, read_size); if(br != read_size) { SMSG(true,"[%s] read image content fail, read offset = '0x%llx'\n",MOD,seek_pos); ret = -4; goto end_error; } /* caculate this hash */ if( sec_hash(chunk_buf,read_size,hash_tmp,hash_size) == -1) { SMSG(true,"[%s] hash fail, offset is '0x%llx'(B)\n",MOD,seek_pos); ret = -5; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ SMSG(sec_info.bMsg,"[%s] Data value(4 bytes) ==>\n",MOD); sec_signfmt_dump_buffer(chunk_buf, 4); SMSG(sec_info.bMsg,"[%s] Hash value(single) (0x%llx): \n",MOD, seek_pos); sec_signfmt_dump_buffer(hash_tmp, hash_size); #endif /* compose two hash to buffer (second block) */ mcpy(hash_comb+hash_size,hash_tmp,hash_size); /* caculate compose hash */ if( sec_hash(hash_comb,hash_size*2,hash_tmp,hash_size) == -1) { SMSG(true,"[%s] hash fail, offset is '0x%llx'(C)\n",MOD,seek_pos); ret = -6; goto end_error; } #if DUMP_MORE_FOR_DEBUG /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ SMSG(sec_info.bMsg,"[%s] Data value(4 bytes) ==>\n",MOD); sec_signfmt_dump_buffer(chunk_buf, 4); SMSG(sec_info.bMsg,"[%s] Hash value(comp) (0x%llx): \n",MOD, seek_pos); sec_signfmt_dump_buffer(hash_tmp, hash_size); #endif /* save this hash to compose buffer (first block) */ mcpy(hash_comb,hash_tmp,hash_size); /* move next */ seek_pos += read_size; left_size -= read_size; } /* ------------------------------------- */ /* dump hash value for debug */ /* ------------------------------------- */ #if DUMP_MORE_FOR_DEBUG SMSG(sec_info.bMsg,"[%s] Hash value(final) (0x%llx): \n",MOD, seek_pos); sec_signfmt_dump_buffer(hash_tmp, hash_size); #endif /* copy hash */ mcpy(final_hash_buf,hash_tmp,hash_size); end_error: ASF_FREE(hash_comb); ASF_FREE(chunk_buf); ASF_FREE(hash_tmp); return ret; }
void VolumeControlData::DrawVolumeControl(HDC hDC) { HDC hdcTemp = CreateCompatibleDC(hDC); HBITMAP hbmpTemp = CreateCompatibleBitmap(hDC, cx, cy); SelectObject(hdcTemp, hbmpTemp); RECT clientRect = {0, 0, cx, cy}; FillRect(hdcTemp, &clientRect, (HBRUSH)COLOR_WINDOW); HBRUSH hGray = CreateSolidBrush(REVERSE_COLOR(Color_Gray)); HBRUSH hRed = CreateSolidBrush(0x2020bf);//0xff4040); float visualVolume = (bDisabled) ? 0.0f : curVolume; int cxAdjust = cx; if(bDrawIcon) cxAdjust -= 32; const int padding = 1; const float volSliceSize = float(cxAdjust-(padding*9))/10.0f; int volPixelPos = int(visualVolume*float(cxAdjust)); if(volSliceSize > 1.0f) { float ySliceStart, ySliceSize; if(bDrawIcon) { ySliceStart = 4.0f; ySliceSize = float((cy-ySliceStart)/10); } else { ySliceStart = 0.0f; ySliceSize = float(cy/10); } for(int i=0; i<10; i++) { int pos = int(volSliceSize*float(i)) + (padding*i); RECT sliceRect = {pos, int(ySliceStart+((9.0f-float(i))*ySliceSize)), pos+int(volSliceSize), cy}; if(sliceRect.right < volPixelPos) //full FillRect(hdcTemp, &sliceRect, hRed); else if(sliceRect.left < volPixelPos) //half { RECT leftHalf, rightHalf; mcpy(&leftHalf, &sliceRect, sizeof(sliceRect)); mcpy(&rightHalf, &sliceRect, sizeof(sliceRect)); rightHalf.left = leftHalf.right = volPixelPos; FillRect(hdcTemp, &leftHalf, hRed); FillRect(hdcTemp, &rightHalf, hGray); } else //empty FillRect(hdcTemp, &sliceRect, hGray); } if(bDrawIcon) DrawIcon(hdcTemp, cx-32, 0, (visualVolume > 0.05f) ? hiconPlay : hiconMute); } BitBlt(hDC, 0, 0, cx, cy, hdcTemp, 0, 0, SRCCOPY); DeleteObject(hdcTemp); DeleteObject(hbmpTemp); DeleteObject(hGray); DeleteObject(hRed); }