XBOX::VError VHTTPResponse::_CompressData() { if (fCompressionMode != COMPRESSION_NONE) return XBOX::VE_OK; XBOX::VError error = XBOX::VE_OK; bool isOK = false; if (fCanCompressBody) { // Negotiate compression Method according to the request header XBOX::VString encoding; if (GetRequestHeader().GetHeaderValue (STRING_HEADER_ACCEPT_ENCODING, encoding)) { fCompressionMode = HTTPProtocol::NegotiateEncodingMethod (encoding); if (COMPRESSION_NONE != fCompressionMode) { #if HTTP_SERVER_VERBOSE_MODE || LOG_IN_CONSOLE VDebugTimer compressionTimer; #endif error = HTTPServerTools::CompressStream (GetBody(), fCompressionMode); if (XBOX::VE_OK == error) { XBOX::VString contentEncoding; HTTPProtocol::GetEncodingMethodName (fCompressionMode, contentEncoding); /* Tell that Content-Encoding was negotiated */ GetHeaders().SetHeaderValue (STRING_HEADER_VARY, STRING_HEADER_CONTENT_ENCODING, false); GetHeaders().SetHeaderValue (STRING_HEADER_CONTENT_ENCODING, contentEncoding); /* And of course change the Content-Length */ SetContentLengthHeader (GetBody().GetSize()); isOK = true; } #if HTTP_SERVER_VERBOSE_MODE GetHeaders().SetHeaderValue (CVSTR ("X-CompressionTime"), compressionTimer.GetElapsedTime()); #endif #if LOG_IN_CONSOLE compressionTimer.DebugMsg ("* VHTTPResponse::_CompressData()"); #endif } } } if (!isOK) fCompressionMode = COMPRESSION_NONE; return error; }
bool VHTTPResponse::IsCookieSet (const VHTTPCookie& inCookie) const { XBOX::VectorOfVString cookieValues; if (GetHeaders().GetHeaderValues (HEADER_SET_COOKIE, cookieValues)) { XBOX::VString cookieName (inCookie.GetName()); cookieName.AppendUniChar (CHAR_EQUALS_SIGN); for (XBOX::VectorOfVString::const_iterator it = cookieValues.begin(); it != cookieValues.end(); ++it) { XBOX::VectorOfVString multipleCookieValues; (*it).GetSubStrings (CHAR_SEMICOLON, multipleCookieValues, false, true); XBOX::VectorOfVString::const_iterator found = std::find_if (multipleCookieValues.begin(), multipleCookieValues.end(), FindVStringFunctor (cookieName)); if (found != multipleCookieValues.end()) { VHTTPCookie cookie (*found); if (cookie == inCookie) return true; } } } return false; }
XBOX::VError VHTTPResponse::ReplyWithStatusCode (HTTPStatusCode inValue, XBOX::VString *inExplanationString) { if (HTTP_UNDEFINED == fResponseStatusCode) fResponseStatusCode = inValue; if ((HTTP_UNAUTHORIZED == inValue) || (HTTP_NOT_MODIFIED == inValue) || ((3 == (sLONG)inValue / 100))) { if (HTTP_UNAUTHORIZED == inValue) { GetVirtualHost()->GetProject()->GetAuthenticationManager()->SetAuthorizationHeader (this); } } else { if (!HTTPProtocol::IsValidStatusCode (fResponseStatusCode)) fResponseStatusCode = HTTP_INTERNAL_SERVER_ERROR; if (0 == GetBody().GetDataSize() && !HasFileToSend()) { GetHeaders().SetHeaderValue (STRING_HEADER_CONTENT_TYPE, STRING_CONTENT_TYPE_HTML); HTTPProtocol::MakeErrorResponse (inValue, GetBody(), inExplanationString); } } fCanCacheBody = false; fCanCompressBody = false; return XBOX::VE_OK; }
// ----------------------------------------------------------------------------- HTTPSTR HTTPRequest::GetRequestedURL() { if (requestedurl) return (requestedurl); const HTTPCHAR *p = GetHeaders(); int len = 0; if (p) { while ((*p) && (*p != _T(' '))) p++; p++; HTTPCHAR *q = (HTTPCHAR*)p; while (*q) { if ((*q == _T(' ')) || (*q == _T('?')) || (*q == _T('&')) || (*q == _T('\r')) || (*q == _T('\n'))) break; len++; q++; } } requestedurl = (HTTPCHAR*) malloc((len + 1)*sizeof(HTTPCHAR)); if (requestedurl) { memcpy(requestedurl, p, len*sizeof(HTTPCHAR)); requestedurl[len] = 0; } return (requestedurl); }
////////////////////////////////////////////////////////////////////////////////// // // 功能实现:将指定的RVA地址转换成相对文件的偏移 // 输入参数:Base是文件加载的基地址; // RVA是要获取文件偏移的RVA地址 // 输出参数:返回DWORD类型的相对文件的偏移量 // /////////////////////////////////////////////////////////////////////////////////// DWORD RVAToFileOffset(PCHAR Base,DWORD RVAAddress) { PIMAGE_FILE_HEADER pfh = NULL; PIMAGE_OPTIONAL_HEADER poh = NULL; PIMAGE_SECTION_HEADER psh =NULL; WORD NumOfSection=0; if(!Base) { TRACE0("[RVAToFileOffset] 基地址无效\n"); return 0x00000000; } if(!GetHeaders(Base,&pfh,&poh,&psh)) { TRACE0("[RVAToFileOffset] 获取PE头信息失败\n"); } NumOfSection=pfh->NumberOfSections; if(0==NumOfSection) { TRACE0("[RVAToFileOffset] 节个数为零\n"); } for(WORD iCount=0;iCount<NumOfSection;iCount++) { DWORD SecVA=psh[iCount].VirtualAddress; if((RVAAddress>SecVA)&&(RVAAddress<SecVA+psh[iCount].SizeOfRawData)) { return RVAAddress-SecVA+psh[iCount].PointerToRawData; } } return 0; }
NS_IMETHODIMP HTMLTableCellElement::GetHeaders(nsAString& aHeaders) { DOMString headers; GetHeaders(headers); headers.ToString(aHeaders); return NS_OK; }
MimeTypeKind VHTTPResponse::GetContentTypeKind() const { XBOX::VString contentType; GetHeaders().GetContentType (contentType, NULL); return VMimeTypeManager::GetMimeTypeKind (contentType); }
NS_IMETHODIMP HTMLTableCellElement::GetHeaders(nsAString& aHeaders) { nsString headers; GetHeaders(headers); aHeaders = headers; return NS_OK; }
XBOX::VError VHTTPResponse::_SendResponseHeader() { if (fHeaderSent) return XBOX::VE_OK; // Not sure we have to report the error _NormalizeResponseHeader(); // Write Status-Line XBOX::VString string; XBOX::VString fieldValue; HTTPProtocol::MakeStatusLine (fHTTPVersion, fResponseStatusCode, string); /* Write Server Header */ if (GetHeaders().IsHeaderSet (STRING_HEADER_SERVER)) GetHeaders().RemoveHeader (STRING_HEADER_SERVER); HTTPProtocol::MakeServerString (fieldValue, false, true); string.AppendString (fieldValue); string.AppendCString (HTTP_CRLF); /* Write Date Header */ if (!GetHeaders().IsHeaderSet (STRING_HEADER_DATE)) { HTTPProtocol::MakeRFC822GMTDateString (GMT_NOW, fieldValue, true); string.AppendString (fieldValue); string.AppendCString (HTTP_CRLF); } // Write Headers GetHeaders().ToString (string); string.AppendCString (HTTP_CRLF); XBOX::StStringConverter<char> converter (string, XBOX::VTC_UTF_8); char * buffer = (char *)converter.GetCPointer(); uLONG bufferSize = (uLONG)converter.GetSize(); XBOX::VError error = _WriteToSocket (buffer, &bufferSize); fHeaderSent = (XBOX::VE_OK == error); return error; }
// ----------------------------------------------------------------------------- HTTPCHAR *HTTPRequest::GetHTTPMethod() { if (HTTPMethod) return (HTTPMethod); if ((GetHeaders()) && (HeaderSize > 12)) { int len = 0; HTTPCHAR *p = (HTTPCHAR*)GetHeaders(); while (*p != _T(' ')) { p++; len++; } if (!len) return (NULL); HTTPMethod = (HTTPCHAR*)malloc((len + 1)*sizeof(HTTPCHAR)); if (HTTPMethod) { memcpy(HTTPMethod, GetHeaders(), len*sizeof(HTTPCHAR)); HTTPMethod[len] = _T('\0'); return (HTTPMethod); } } return (NULL); }
////////////////////////////////////////////////////////////////////////////////// // // 功能实现:获取指定PE文件中指定函数的导出地址 // 输入参数:Base为PE文件加载的基地址 // FindFunName为要查找的函数名 // NameLength为函数名长度 // 输出参数:返回指定函数名的函数首地址 // /////////////////////////////////////////////////////////////////////////////////// DWORD FindFunAddress(DWORD Base,PCHAR FindFunName,DWORD NameLength) { TRACE0("查找指定函数的地址"); PCHAR pImageBase=(PCHAR)Base; DWORD ImageBase=0x0000000; PIMAGE_FILE_HEADER pfh = NULL; PIMAGE_OPTIONAL_HEADER poh = NULL; PIMAGE_SECTION_HEADER psh =NULL; PIMAGE_EXPORT_DIRECTORY pExpDir = NULL; DWORD NumOfName=0x00000000; PDWORD pNameArray=NULL; PWORD pOrdNameArray=NULL; PDWORD pFuncArray=NULL; DWORD NumOfNativeFun=0x00000000; DWORD FunAddress=0x00000000; if(!GetHeaders(pImageBase,&pfh,&poh,&psh)) { TRACE0("[FindFunAddress] 获取PE头信息失败\n"); return 0x00000000; } ImageBase=poh->ImageBase; //获取导出表 pExpDir=(PIMAGE_EXPORT_DIRECTORY)((DWORD)pImageBase+RVAToFileOffset(pImageBase,poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress)); //获取导出函数名个数 NumOfName=pExpDir->NumberOfNames; //获取名字地址数组 pNameArray=(PDWORD)((DWORD)pImageBase+RVAToFileOffset(pImageBase,pExpDir->AddressOfNames)); //获取名字序数表 pOrdNameArray=(PWORD)((DWORD)pImageBase+RVAToFileOffset(pImageBase,pExpDir->AddressOfNameOrdinals)); //函数地址表 pFuncArray=(PDWORD)((DWORD)pImageBase+RVAToFileOffset(pImageBase,pExpDir->AddressOfFunctions)); for(DWORD iCount=0;iCount<NumOfName;iCount++) { PCSTR pName=(PCSTR)((DWORD)pImageBase+RVAToFileOffset(pImageBase,pNameArray[iCount])); if (!stricmp(pName,FindFunName)) { TRACE0("[FindFunAddress] 找到指定函数\n"); LPCVOID pFunc=(LPCVOID)((DWORD)pImageBase+RVAToFileOffset(pImageBase,pFuncArray[pOrdNameArray[iCount]])); FunAddress=(DWORD)pFunc; return FunAddress; } } TRACE0("[FindFunAddress] 没有找到指定函数\n"); return 0x00000000; }
DWORD FindKiServiceTable(HMODULE hModule,DWORD dwKSDT) { PIMAGE_FILE_HEADER pFH; PIMAGE_OPTIONAL_HEADER pOH; PIMAGE_SECTION_HEADER pSH; PIMAGE_BASE_RELOCATION pBR; PIMAGE_FIXUP_ENTRY pFE; DWORD dwFixups=0,i; DWORD dwPointerRva; DWORD dwPointsToRva; DWORD dwKiServiceTable; BOOL bFirstChunk; if( !GetHeaders((PCHAR)hModule,&pFH,&pOH,&pSH) ) return NULL; if( (pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress) && !((pFH->Characteristics)&IMAGE_FILE_RELOCS_STRIPPED) ) { pBR = (PIMAGE_BASE_RELOCATION) RVATOVA(pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress,hModule); bFirstChunk = true; while( bFirstChunk || pBR->VirtualAddress ) { bFirstChunk = false; pFE = (PIMAGE_FIXUP_ENTRY)((DWORD)pBR + sizeof(IMAGE_BASE_RELOCATION)); for( i=0; i < (pBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION))>>1; i++,pFE++ ) { if( pFE->type == IMAGE_REL_BASED_HIGHLOW ) { dwFixups++; dwPointerRva = pBR->VirtualAddress + pFE->offset; dwPointsToRva = *(PDWORD)((DWORD)hModule + dwPointerRva) - (DWORD)pOH->ImageBase; if( dwPointsToRva == dwKSDT ) { if( *(PWORD)((DWORD)hModule + dwPointerRva - 2) == 0x05c7 ) { dwKiServiceTable = *(PDWORD)((DWORD)hModule + dwPointerRva + 4) - pOH->ImageBase; return dwKiServiceTable; } } } } *(PDWORD)&pBR += pBR->SizeOfBlock; } } return NULL; }
bool InitEncoder() { x264 = x264_encoder_open(¶mData); if (!x264) { return false; } Log::writeMessage(LOG_RTSPSERV, 1, "LiveSDK_Log:------------------------------------------"); Log::writeMessage(LOG_RTSPSERV, 1, "LiveSDK_Log:%s", WcharToAnsi(GetInfoString().Array()).c_str()); Log::writeMessage(LOG_RTSPSERV, 1, "LiveSDK_Log:------------------------------------------"); DataPacket packet; GetHeaders(packet); return true; }
/* * FlushMetadata() */ bool OGRNGWDataset::FlushMetadata( char **papszMetadata ) { if( !bMetadataDerty ) { return true; } bool bResult = NGWAPI::FlushMetadata(osUrl, osResourceId, papszMetadata, GetHeaders()); if( bResult ) { bMetadataDerty = false; } return bResult; }
bool VHTTPResponse::IsCookieSet (const XBOX::VString& inName) const { XBOX::VectorOfVString cookieValues; if (GetHeaders().GetHeaderValues (HEADER_SET_COOKIE, cookieValues)) { XBOX::VString cookieName (inName); cookieName.AppendUniChar (CHAR_EQUALS_SIGN); for (XBOX::VectorOfVString::const_iterator it = cookieValues.begin(); it != cookieValues.end(); ++it) { if (HTTPServerTools::FindASCIIVString ((*it), cookieName) > 0) return true; } } return false; }
bool VHTTPResponse::AddCookie (const XBOX::VString& inName, const XBOX::VString& inValue, const XBOX::VString& inComment, const XBOX::VString& inDomain, const XBOX::VString& inPath, bool inSecure, bool inHTTPOnly, sLONG inMaxAge) { VHTTPCookie cookie; cookie.SetVersion (1); cookie.SetName (inName); cookie.SetValue (inValue); cookie.SetComment (inComment); cookie.SetDomain (inDomain); cookie.SetPath (inPath); cookie.SetSecure (inSecure); cookie.SetMaxAge (inMaxAge); cookie.SetHttpOnly (inHTTPOnly); if (cookie.IsValid() && !IsCookieSet (inName)) return GetHeaders().SetHeaderValue (HEADER_SET_COOKIE, cookie.ToString(), false); return false; }
/* * FetchPermissions() */ void OGRNGWDataset::FetchPermissions() { if( bFetchedPermissions ) { return; } if( bReadWrite ) { // Check connection and is it read only. char **papszHTTPOptions = GetHeaders(); stPermissions = NGWAPI::CheckPermissions( osUrl, osResourceId, papszHTTPOptions, bReadWrite ); CSLDestroy( papszHTTPOptions ); } else { stPermissions.bDataCanRead = true; stPermissions.bResourceCanRead = true; stPermissions.bDatastructCanRead = true; stPermissions.bMetadataCanRead = true; } bFetchedPermissions = true; }
/////////////////////////////////////////////////////////////////////////////////// // // 功能实现:获取指定文件中的指定节的指针 // 输入参数:ImagePath为要获取指定节指针的映像路径 // FindSetionName为要查找的节名 // ImageBase为返回的映像的默认加载基地址; // pFile为存放内存映像的缓冲区地址; // 输出参数:返回指向指定节数据的指针 // /////////////////////////////////////////////////////////////////////////////////// PCHAR GetSettionPoint(PCHAR ImagePath,PCHAR FindSetionName,PDWORD ImageBase,PCHAR* pFile) { TRACE0("获取指定映像指定节指针"); HANDLE h_file=NULL; CHAR Path[MAX_PATH]={0}; DWORD Filesize=0;//文件长度 PCHAR pFileBuf=NULL; PIMAGE_FILE_HEADER pfh; PIMAGE_OPTIONAL_HEADER poh; PIMAGE_SECTION_HEADER psh; //打开文件 h_file=CreateFile(ImagePath,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL); if(INVALID_HANDLE_VALUE==h_file) { TRACE0("[GetSettionPoint] 打开映像文件失败\n"); return NULL; } Filesize=GetFileSize(h_file,0); pFileBuf=(PCHAR)AllocHeapMem(Filesize); if(!pFileBuf) { TRACE0("[GetSettionPoint] 申请内存失败\n"); CloseHandle(h_file); return NULL; } DWORD Readlen; ReadFile(h_file,pFileBuf,Filesize,&Readlen,NULL); if(Readlen<=0) { TRACE0("[GetSettionPoint] 映像文件大小无效\n"); CloseHandle(h_file); FreeHeapMem(pFileBuf); return NULL; } CloseHandle(h_file); GetHeaders(pFileBuf,&pfh,&poh,&psh); if(NULL!=ImageBase) { *ImageBase=poh->ImageBase; } PIMAGE_SECTION_HEADER psec=psh; DWORD NumOfSec=pfh->NumberOfSections; DWORD iCount=0; while(iCount<NumOfSec) { if(!stricmp((char*)psec->Name,FindSetionName)) { if(psec->PointerToRawData==0) { FreeHeapMem(pFileBuf); return NULL; } break; } iCount++; psec++; } PCHAR pData=(PCHAR)(pFileBuf+psec->PointerToRawData); //保存存放win32k.sys文件数据的缓冲区指针,用于以后释放 *pFile=pFileBuf; return pData; }
bool VHTTPResponse::SetContentTypeHeader (const XBOX::VString& inValue, const XBOX::CharSet inCharSet) { return GetHeaders().SetContentType (inValue, inCharSet); }
bool VHTTPResponse::GetContentTypeHeader (XBOX::VString& outValue, XBOX::CharSet *outCharSet) const { return GetHeaders().GetContentType (outValue, outCharSet); }
X264Encoder(int fps, int width, int height, int quality, CTSTR preset, bool bUse444, ColorDescription &colorDesc, int maxBitrate, int bufferSize, bool bUseCFR) { curPreset = preset; fps_ms = 1000/fps; StringList paramList; curProfile = AppConfig->GetString(TEXT("Video Encoding"), TEXT("X264Profile"), TEXT("high")); BOOL bUseCustomParams = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCustomSettings")); if(bUseCustomParams) { String strCustomParams = AppConfig->GetString(TEXT("Video Encoding"), TEXT("CustomSettings")); strCustomParams.KillSpaces(); if(strCustomParams.IsValid()) { Log(TEXT("Using custom x264 settings: \"%s\""), strCustomParams.Array()); strCustomParams.GetTokenList(paramList, ' ', FALSE); for(UINT i=0; i<paramList.Num(); i++) { String &strParam = paramList[i]; if(!schr(strParam, '=')) continue; String strParamName = strParam.GetToken(0, '='); String strParamVal = strParam.GetTokenOffset(1, '='); if(strParamName.CompareI(TEXT("preset"))) { if(valid_x264_string(strParamVal, (const char**)x264_preset_names)) curPreset = strParamVal; else Log(TEXT("invalid preset: %s"), strParamVal.Array()); paramList.Remove(i--); } else if(strParamName.CompareI(TEXT("tune"))) { if(valid_x264_string(strParamVal, (const char**)x264_tune_names)) curTune = strParamVal; else Log(TEXT("invalid tune: %s"), strParamVal.Array()); paramList.Remove(i--); } else if(strParamName.CompareI(TEXT("profile"))) { if(valid_x264_string(strParamVal, (const char **)x264_profile_names)) curProfile = strParamVal; else Log(TEXT("invalid profile: %s"), strParamVal.Array()); paramList.Remove(i--); } } } } zero(¶mData, sizeof(paramData)); LPSTR lpPreset = curPreset.CreateUTF8String(); LPSTR lpTune = curTune.CreateUTF8String(); if (x264_param_default_preset(¶mData, lpPreset, lpTune)) Log(TEXT("Failed to set x264 defaults: %s/%s"), curPreset.Array(), curTune.Array()); Free(lpTune); Free(lpPreset); this->width = width; this->height = height; paramData.b_deterministic = false; bUseCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCBR"), 1) != 0; bPadCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("PadCBR"), 1) != 0; this->bUseCFR = bUseCFR; SetBitRateParams(maxBitrate, bufferSize); if(bUseCBR) { if(bPadCBR) paramData.i_nal_hrd = X264_NAL_HRD_CBR; paramData.rc.i_rc_method = X264_RC_ABR; paramData.rc.f_rf_constant = 0.0f; } else { paramData.rc.i_rc_method = X264_RC_CRF; paramData.rc.f_rf_constant = baseCRF+float(10-quality); } UINT keyframeInterval = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("KeyframeInterval"), 0); paramData.b_vfr_input = !bUseCFR; paramData.i_width = width; paramData.i_height = height; paramData.vui.b_fullrange = colorDesc.fullRange; paramData.vui.i_colorprim = colorDesc.primaries; paramData.vui.i_transfer = colorDesc.transfer; paramData.vui.i_colmatrix = colorDesc.matrix; if (keyframeInterval) paramData.i_keyint_max = fps*keyframeInterval; paramData.i_fps_num = fps; paramData.i_fps_den = 1; paramData.i_timebase_num = 1; paramData.i_timebase_den = 1000; paramData.pf_log = get_x264_log; paramData.i_log_level = X264_LOG_WARNING; for(UINT i=0; i<paramList.Num(); i++) { String &strParam = paramList[i]; if(!schr(strParam, '=')) continue; String strParamName = strParam.GetToken(0, '='); String strParamVal = strParam.GetTokenOffset(1, '='); if( strParamName.CompareI(TEXT("fps")) || strParamName.CompareI(TEXT("force-cfr"))) { Log(TEXT("The custom x264 command '%s' is unsupported, use the application settings instead"), strParam.Array()); continue; } else { LPSTR lpParam = strParamName.CreateUTF8String(); LPSTR lpVal = strParamVal.CreateUTF8String(); if(x264_param_parse(¶mData, lpParam, lpVal) != 0) Log(TEXT("The custom x264 command '%s' failed"), strParam.Array()); Free(lpParam); Free(lpVal); } } if(bUse444) paramData.i_csp = X264_CSP_I444; else paramData.i_csp = X264_CSP_I420; colorDesc.fullRange = paramData.vui.b_fullrange; colorDesc.primaries = paramData.vui.i_colorprim; colorDesc.transfer = paramData.vui.i_transfer; colorDesc.matrix = paramData.vui.i_colmatrix; if (curProfile) { LPSTR lpProfile = curProfile.CreateUTF8String(); if (x264_param_apply_profile (¶mData, lpProfile)) Log(TEXT("Failed to set x264 profile: %s"), curProfile.Array()); Free(lpProfile); } x264 = x264_encoder_open(¶mData); if(!x264) CrashError(TEXT("Could not initialize x264")); Log(TEXT("------------------------------------------")); Log(TEXT("%s"), GetInfoString().Array()); Log(TEXT("------------------------------------------")); DataPacket packet; GetHeaders(packet); }
// nsIStreamListener implementation NS_IMETHODIMP nsFTPDirListingConv::OnDataAvailable(nsIRequest* request, nsISupports *ctxt, nsIInputStream *inStr, uint32_t sourceOffset, uint32_t count) { NS_ASSERTION(request, "FTP dir listing stream converter needs a request"); nsresult rv; nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv); NS_ENSURE_SUCCESS(rv, rv); uint32_t read, streamLen; uint64_t streamLen64; rv = inStr->Available(&streamLen64); NS_ENSURE_SUCCESS(rv, rv); streamLen = (uint32_t)NS_MIN(streamLen64, uint64_t(PR_UINT32_MAX - 1)); nsAutoArrayPtr<char> buffer(new char[streamLen + 1]); NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY); rv = inStr->Read(buffer, streamLen, &read); NS_ENSURE_SUCCESS(rv, rv); // the dir listings are ascii text, null terminate this sucker. buffer[streamLen] = '\0'; PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("nsFTPDirListingConv::OnData(request = %x, ctxt = %x, inStr = %x, sourceOffset = %d, count = %d)\n", request, ctxt, inStr, sourceOffset, count)); if (!mBuffer.IsEmpty()) { // we have data left over from a previous OnDataAvailable() call. // combine the buffers so we don't lose any data. mBuffer.Append(buffer); buffer = new char[mBuffer.Length()+1]; NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY); strncpy(buffer, mBuffer.get(), mBuffer.Length()+1); mBuffer.Truncate(); } #ifndef DEBUG_dougt PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer.get()) ); #else printf("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer); #endif // DEBUG_dougt nsCAutoString indexFormat; if (!mSentHeading) { // build up the 300: line nsCOMPtr<nsIURI> uri; rv = channel->GetURI(getter_AddRefs(uri)); NS_ENSURE_SUCCESS(rv, rv); rv = GetHeaders(indexFormat, uri); NS_ENSURE_SUCCESS(rv, rv); mSentHeading = true; } char *line = buffer; line = DigestBufferLines(line, indexFormat); #ifndef DEBUG_dougt PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), indexFormat.get()) ); #else char *unescData = ToNewCString(indexFormat); NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY); nsUnescape(unescData); printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData); nsMemory::Free(unescData); #endif // DEBUG_dougt // if there's any data left over, buffer it. if (line && *line) { mBuffer.Append(line); PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n", PL_strlen(line), line) ); } // send the converted data out. nsCOMPtr<nsIInputStream> inputData; rv = NS_NewCStringInputStream(getter_AddRefs(inputData), indexFormat); NS_ENSURE_SUCCESS(rv, rv); rv = mFinalListener->OnDataAvailable(request, ctxt, inputData, 0, indexFormat.Length()); return rv; }
/* * Init() */ bool OGRNGWDataset::Init(int nOpenFlagsIn) { // NOTE: Skip check API version at that moment. We expected API v3. // Get resource details. CPLJSONDocument oResourceDetailsReq; char **papszHTTPOptions = GetHeaders(); bool bResult = oResourceDetailsReq.LoadUrl( NGWAPI::GetResource( osUrl, osResourceId ), papszHTTPOptions ); CPLDebug("NGW", "Get resource %s details %s", osResourceId.c_str(), bResult ? "success" : "failed"); if( bResult ) { CPLJSONObject oRoot = oResourceDetailsReq.GetRoot(); if( oRoot.IsValid() ) { std::string osResourceType = oRoot.GetString("resource/cls"); FillMetadata( oRoot ); if( osResourceType == "resource_group" ) { // Check feature paging. FillCapabilities( papszHTTPOptions ); if( oRoot.GetBool( "resource/children", false ) ) { // Get child resources. bResult = FillResources( papszHTTPOptions, nOpenFlagsIn ); } } else if( (osResourceType == "vector_layer" || osResourceType == "postgis_layer") ) { // Cehck feature paging. FillCapabilities( papszHTTPOptions ); // Add vector layer. AddLayer( oRoot, papszHTTPOptions, nOpenFlagsIn ); } else if( osResourceType == "mapserver_style" || osResourceType == "qgis_vector_style" || osResourceType == "raster_style" || osResourceType == "wmsclient_layer" ) { // GetExtent from parent. OGREnvelope stExtent; std::string osParentId = oRoot.GetString("resource/parent/id"); bool bExtentResult = NGWAPI::GetExtent(osUrl, osParentId, papszHTTPOptions, 3857, stExtent); if( !bExtentResult ) { // Set full extent for EPSG:3857. stExtent.MinX = -20037508.34; stExtent.MaxX = 20037508.34; stExtent.MinY = -20037508.34; stExtent.MaxY = 20037508.34; } CPLDebug("NGW", "Raster extent is: %f, %f, %f, %f", stExtent.MinX, stExtent.MinY, stExtent.MaxX, stExtent.MaxY); int nEPSG = 3857; // Get parent details. We can skip this as default SRS in NGW is 3857. if( osResourceType == "wmsclient_layer" ) { nEPSG = oRoot.GetInteger("wmsclient_layer/srs/id", nEPSG); } else { CPLJSONDocument oResourceReq; bResult = oResourceReq.LoadUrl( NGWAPI::GetResource( osUrl, osResourceId ), papszHTTPOptions ); if( bResult ) { CPLJSONObject oParentRoot = oResourceReq.GetRoot(); if( osResourceType == "mapserver_style" || osResourceType == "qgis_vector_style" ) { nEPSG = oParentRoot.GetInteger("vector_layer/srs/id", nEPSG); } else if( osResourceType == "raster_style") { nEPSG = oParentRoot.GetInteger("raster_layer/srs/id", nEPSG); } } } // Create raster dataset. std::string osRasterUrl = NGWAPI::GetTMS(osUrl, osResourceId); char* pszRasterUrl = CPLEscapeString(osRasterUrl.c_str(), -1, CPLES_XML); const char *pszConnStr = CPLSPrintf("<GDAL_WMS><Service name=\"TMS\">" "<ServerUrl>%s</ServerUrl></Service><DataWindow>" "<UpperLeftX>-20037508.34</UpperLeftX><UpperLeftY>20037508.34</UpperLeftY>" "<LowerRightX>20037508.34</LowerRightX><LowerRightY>-20037508.34</LowerRightY>" "<TileLevel>%d</TileLevel><TileCountX>1</TileCountX>" "<TileCountY>1</TileCountY><YOrigin>top</YOrigin></DataWindow>" "<Projection>EPSG:%d</Projection><BlockSizeX>256</BlockSizeX>" "<BlockSizeY>256</BlockSizeY><BandsCount>%d</BandsCount>" "<Cache><Type>file</Type><Expires>%d</Expires><MaxSize>%d</MaxSize>" "</Cache><ZeroBlockHttpCodes>204,404</ZeroBlockHttpCodes></GDAL_WMS>", pszRasterUrl, 22, // NOTE: We have no limit in zoom levels. nEPSG, // NOTE: Default SRS is EPSG:3857. 4, nCacheExpires, nCacheMaxSize); CPLFree( pszRasterUrl ); poRasterDS = reinterpret_cast<GDALDataset*>(GDALOpenEx(pszConnStr, GDAL_OF_READONLY | GDAL_OF_RASTER | GDAL_OF_INTERNAL, nullptr, nullptr, nullptr)); if( poRasterDS ) { bResult = true; nRasterXSize = poRasterDS->GetRasterXSize(); nRasterYSize = poRasterDS->GetRasterYSize(); for( int iBand = 1; iBand <= poRasterDS->GetRasterCount(); iBand++ ) { SetBand( iBand, new NGWWrapperRasterBand( poRasterDS->GetRasterBand( iBand )) ); } // Set pixel limits. bool bHasTransform = false; double geoTransform[6] = { 0.0 }; double invGeoTransform[6] = { 0.0 }; if(poRasterDS->GetGeoTransform(geoTransform) == CE_None) { bHasTransform = GDALInvGeoTransform(geoTransform, invGeoTransform) == TRUE; } if(bHasTransform) { GDALApplyGeoTransform(invGeoTransform, stExtent.MinX, stExtent.MinY, &stPixelExtent.MinX, &stPixelExtent.MaxY); GDALApplyGeoTransform(invGeoTransform, stExtent.MaxX, stExtent.MaxY, &stPixelExtent.MaxX, &stPixelExtent.MinY); CPLDebug("NGW", "Raster extent in px is: %f, %f, %f, %f", stPixelExtent.MinX, stPixelExtent.MinY, stPixelExtent.MaxX, stPixelExtent.MaxY); } else { stPixelExtent.MinX = 0.0; stPixelExtent.MinY = 0.0; stPixelExtent.MaxX = std::numeric_limits<double>::max(); stPixelExtent.MaxY = std::numeric_limits<double>::max(); } } else { bResult = false; } } else if( osResourceType == "raster_layer" ) //FIXME: Do we need this check? && nOpenFlagsIn & GDAL_OF_RASTER ) { AddRaster( oRoot, papszHTTPOptions ); } else { bResult = false; } // TODO: Add support for baselayers, webmap, wfsserver_service, wmsserver_service. } } CSLDestroy( papszHTTPOptions ); return bResult; }
bool VHTTPResponse::_NormalizeResponseHeader() { /* HTTP automatic fixes: (to mimic Apache's behavior for CGIs (m.c) */ XBOX::VString fieldValue; // Special CGI case: the cgi author can use the Status field to set the response code if (GetHeaders().IsHeaderSet (STRING_HEADER_STATUS)) { if (GetHeaders().GetHeaderValue (STRING_HEADER_STATUS, fieldValue)) { SetResponseStatusCode ((HTTPStatusCode)HTTPServerTools::GetLongFromString (fieldValue)); GetHeaders().RemoveHeader (STRING_HEADER_STATUS); } } // We still support some legacy, non standard special token: if (GetHeaders().IsHeaderSet (STRING_HEADER_X_STATUS)) { if (GetHeaders().GetHeaderValue (STRING_HEADER_X_STATUS, fieldValue)) { SetResponseStatusCode ((HTTPStatusCode)HTTPServerTools::GetLongFromString (fieldValue)); GetHeaders().RemoveHeader (STRING_HEADER_X_STATUS); } } if (GetHeaders().IsHeaderSet (STRING_HEADER_X_VERSION)) { if (GetHeaders().GetHeaderValue (STRING_HEADER_X_VERSION, fieldValue)) { if (HTTPServerTools::EqualASCIICString (fieldValue, "http/1.0")) SetHTTPVersion (VERSION_1_0); else SetHTTPVersion (VERSION_1_1); GetHeaders().RemoveHeader (STRING_HEADER_X_VERSION); } } // Classic Redirect trick if (GetHeaders().IsHeaderSet (STRING_HEADER_LOCATION) && (((sLONG)fResponseStatusCode / 100) != 3)) SetResponseStatusCode (HTTP_FOUND); // Best practice see: http://developer.yahoo.com/performance/rules.html#expires /* if (fCanCacheBody && fResponseStatusCode == 200 && !GetHeaders().IsHeaderSet (STRING_HEADER_EXPIRES)) { HTTPProtocol::MakeRFC822GMTDateString (GMT_FAR_FUTURE, fieldValue); GetHeaders().SetHeaderValue (STRING_HEADER_EXPIRES, fieldValue); } */ if (!GetHeaders().IsHeaderSet (STRING_HEADER_CONTENT_LENGTH) && GetBody().GetDataSize()) { fieldValue.FromLong8 (GetBody().GetDataSize()); GetHeaders().SetHeaderValue (STRING_HEADER_CONTENT_LENGTH, fieldValue); } if (!GetHeaders().IsHeaderSet (STRING_HEADER_CONTENT_TYPE) && GetBody().GetDataSize()) GetHeaders().SetHeaderValue (STRING_HEADER_CONTENT_TYPE, STRING_CONTENT_TYPE_BINARY); return true; }
XBOX::VError VHTTPResponse::SendResponse() { XBOX::VError error = XBOX::VE_OK; if (fIsChunked) { // First send buffered data that was not already sent... if (XBOX::VE_OK == (error = _SendResponseBody())) { // Then send special ending line for chunked encoding error = _WriteChunkSize (0); } } else { XBOX::VString contentType; XBOX::VString contentEncoding; GetHeaders().GetContentType (contentType); if (GetHeaders().GetHeaderValue (HEADER_CONTENT_ENCODING, contentEncoding) && !contentEncoding.IsEmpty()) { if (HTTPProtocol::NegotiateEncodingMethod (contentEncoding) != COMPRESSION_UNKNOWN) fCanCompressBody = false; } if (HTTP_UNDEFINED == fResponseStatusCode) fResponseStatusCode = HTTP_OK; VVirtualHost *virtualHost = dynamic_cast<VVirtualHost *>(GetVirtualHost()); if (NULL != virtualHost) { // Compress HTTP Message body when applicable #if HTTP_SERVER_GLOBAL_SETTINGS bool compressionEnabled = fHTTPServer->GetSettings()->GetEnableCompression(); #else bool compressionEnabled = virtualHost->GetSettings()->GetEnableCompression(); #endif if (fCanCompressBody && compressionEnabled) { sLONG size = (sLONG)GetBody().GetSize(); #if HTTP_SERVER_GLOBAL_SETTINGS sLONG minThreshold = (fMinCompressionThreshold == -1) ? fHTTPServer->GetSettings()->GetCompressionMinThreshold() : fMinCompressionThreshold; sLONG maxThreshold = (fMaxCompressionThreshold == -1) ? fHTTPServer->GetSettings()->GetCompressionMaxThreshold() : fMaxCompressionThreshold; #else sLONG minThreshold = (fMinCompressionThreshold == -1) ? virtualHost->GetSettings()->GetCompressionMinThreshold() : fMinCompressionThreshold; sLONG maxThreshold = (fMaxCompressionThreshold == -1) ? virtualHost->GetSettings()->GetCompressionMaxThreshold() : fMaxCompressionThreshold; #endif if ((size > minThreshold) && (size <= maxThreshold)) { if (!contentType.IsEmpty() && (VMimeTypeManager::IsMimeTypeCompressible (contentType))) { error = _CompressData(); } } } } // Put HTTP Message body in cache when applicable if ((NULL != virtualHost) && fCanCacheBody && (fResponseStatusCode == HTTP_OK)) { #if HTTP_SERVER_GLOBAL_CACHE VCacheManager * cacheManager = virtualHost->GetProject()->GetHTTPServer()->GetCacheManager(); #else VCacheManager * cacheManager = virtualHost->GetCacheManager(); #endif XBOX::VFilePath filePath; XBOX::VString locationPath; XBOX::VTime lastModified; XBOX::VString lastModifiedString; XBOX::VError fileError = XBOX::VE_OK; bool staticFile = false; if (XBOX::VE_OK == (fileError = virtualHost->GetFilePathFromURL (fRequest->GetURL(), locationPath))) { filePath.FromFullPath (locationPath); if (filePath.IsFile() && (XBOX::VE_OK == HTTPServerTools::GetFileInfos (filePath, &lastModified))) { staticFile = true; HTTPProtocol::MakeRFC822GMTDateString (lastModified, lastModifiedString); } } if ((XBOX::VE_OK == fileError) && (NULL != cacheManager) && cacheManager->GetEnableDataCache()) { uLONG bufferSize = (uLONG)GetBody().GetSize(); if (bufferSize <= cacheManager->GetCachedObjectMaxSize()) { void * buffer = GetBody().GetDataPtr(); XBOX::VTime lastChecked; VCachedObject * cachedObject = NULL; XBOX::VTime::Now (lastChecked); bool ok = cacheManager->AddPageToCache (fRequest->GetURL(), virtualHost->GetUUIDString(), contentType, buffer, bufferSize, filePath, lastChecked, lastModified, staticFile, fCompressionMode, &cachedObject); if (ok) { if (NULL != cachedObject) { XBOX::VTime expirationDate; sLONG maxAge = cachedObject->GetMaxAge(); if (maxAge > 0) { XBOX::VString string; string.FromCString ("max-age="); string.AppendLong (maxAge); AddResponseHeader (STRING_HEADER_CACHE_CONTROL, string); AddResponseHeader (STRING_HEADER_AGE, cachedObject->GetAge()); if (cachedObject->GetExpirationDate (expirationDate)) AddResponseHeader (STRING_HEADER_EXPIRES, expirationDate); } else if (cachedObject->GetExpirationDate (expirationDate) && IsVTimeValid (expirationDate)) { AddResponseHeader (STRING_HEADER_EXPIRES, expirationDate); } XBOX::QuickReleaseRefCountable (cachedObject); } } } } if (!lastModifiedString.IsEmpty()) AddResponseHeader (STRING_HEADER_LAST_MODIFIED, lastModifiedString); } if (HTTP_OK == fResponseStatusCode) { if (NULL != fFileToSend) { if (fFileToSend->Exists()) { sLONG8 fileSize = 0; fFileToSend->GetSize (&fileSize); this->SetContentLengthHeader (fileSize); // YT 18-Jul-2011 - ACI0072287 if (XBOX::VE_OK == (error = _SendResponseHeader())) { const sLONG CHUNK_BUFFER_SIZE = 0xFFFF; char * chunkBuffer = (char *)XBOX::vMalloc (CHUNK_BUFFER_SIZE, 0); if (testAssert (NULL != chunkBuffer)) { XBOX::VFileDesc *fileDesc = NULL; if ((XBOX::VE_OK == fFileToSend->Open (XBOX::FA_READ, &fileDesc, XBOX::FO_SequentialScan)) && (NULL != fileDesc)) { uLONG chunkSize = 0; XBOX::VSize readBytes = 0; XBOX::VError fileError = XBOX::VE_OK; sLONG8 unreadSize = 0; unreadSize = fileSize; fileDesc->SetPos (0, true); while ((XBOX::VE_OK == fileError) && (unreadSize > 0)) { chunkSize = (unreadSize > CHUNK_BUFFER_SIZE) ? CHUNK_BUFFER_SIZE : unreadSize; fileError = fileDesc->GetDataAtPos (chunkBuffer, chunkSize, 0, &readBytes); unreadSize -= (sLONG8)readBytes; if ((XBOX::VE_OK == fileError) || (XBOX::VE_STREAM_EOF == fileError)) { error = _WriteToSocket (chunkBuffer, &chunkSize); if (XBOX::VE_OK != error) break; } } delete fileDesc; fileDesc = NULL; } else { error = _SendResponseWithStatusCode (HTTP_INTERNAL_SERVER_ERROR); } XBOX::vFree (chunkBuffer); chunkBuffer = NULL; } else { error = _SendResponseWithStatusCode (HTTP_INTERNAL_SERVER_ERROR); } } } else { error = _SendResponseWithStatusCode (HTTP_NOT_FOUND); } XBOX::ReleaseRefCountable (&fFileToSend); } else if (GetBody().GetDataSize() >= 0) { if (XBOX::VE_OK == (error = _SendResponseHeader())) { if (NULL != GetBody().GetDataPtr()) error = _SendResponseBody(); } } else { error = _SendResponseWithStatusCode (HTTP_INTERNAL_SERVER_ERROR); } } else { error = _SendResponseWithStatusCode (fResponseStatusCode); } } return error; }
bool VHTTPResponse::GetCookie (const XBOX::VString& inName, XBOX::VString& outValue) const { return GetHeaders().GetCookie (inName, outValue); }
QSVEncoder(int fps_, int width, int height, int quality, CTSTR preset, bool bUse444, ColorDescription &colorDesc, int maxBitrate, int bufferSize, bool bUseCFR_) : bFirstFrameProcessed(false), width(width), height(height), max_bitrate(maxBitrate) { fps = fps_; bUseCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCBR")) != 0; bUseCFR = bUseCFR_; UINT keyframeInterval = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("KeyframeInterval"), 6); int keyint = fps*keyframeInterval; int bframes = 7; bool bHaveCustomImpl = false; impl_parameters custom = { 0 }; BOOL bUseCustomParams = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCustomSettings")) && AppConfig->GetInt(TEXT("Video Encoding"), TEXT("QSVUseVideoEncoderSettings")); if(bUseCustomParams) { StringList paramList; String strCustomParams = AppConfig->GetString(TEXT("Video Encoding"), TEXT("CustomSettings")); strCustomParams.KillSpaces(); if(strCustomParams.IsValid()) { Log(TEXT("Using custom encoder settings: \"%s\""), strCustomParams.Array()); strCustomParams.GetTokenList(paramList, ' ', FALSE); for(UINT i=0; i<paramList.Num(); i++) { String &strParam = paramList[i]; if(!schr(strParam, '=')) continue; String strParamName = strParam.GetToken(0, '='); String strParamVal = strParam.GetTokenOffset(1, '='); if(strParamName == "keyint") { int keyint_ = strParamVal.ToInt(); if(keyint_ < 0) continue; keyint = keyint_; } else if(strParamName == "bframes") { int bframes_ = strParamVal.ToInt(); if(bframes_ < 0) continue; bframes = bframes_; } else if(strParamName == "qsvimpl") { StringList bits; strParamVal.GetTokenList(bits, ',', true); if(bits.Num() < 3) continue; StringList version; bits[2].GetTokenList(version, '.', false); if(version.Num() != 2) continue; custom.type = bits[0].ToInt(); if(custom.type == 0) custom.type = MFX_IMPL_HARDWARE_ANY; auto &intf = bits[1].MakeLower(); custom.intf = intf == "d3d11" ? MFX_IMPL_VIA_D3D11 : (intf == "d3d9" ? MFX_IMPL_VIA_D3D9 : MFX_IMPL_VIA_ANY); custom.version.Major = version[0].ToInt(); custom.version.Minor = version[1].ToInt(); bHaveCustomImpl = true; } } } } if(!spawn_helper(event_prefix, qsvhelper_process, qsvhelper_thread, process_waiter)) CrashError(TEXT("Couldn't launch QSVHelper: %u"), GetLastError()); ipc_init_request request((event_prefix + INIT_REQUEST).Array()); request->mode = request->MODE_ENCODE; request->obs_process_id = GetCurrentProcessId(); request->fps = fps_; request->keyint = keyint; request->bframes = bframes; request->width = width; request->height = height; request->max_bitrate = maxBitrate; request->buffer_size = bufferSize; request->use_cbr = bUseCBR; request->full_range = colorDesc.fullRange; request->matrix = colorDesc.matrix; request->primaries = colorDesc.primaries; request->transfer = colorDesc.transfer; request->use_custom_impl = bHaveCustomImpl; request->custom_impl = custom.type; request->custom_intf = custom.intf; request->custom_version = custom.version; request.signal(); ipc_init_response response((event_prefix + INIT_RESPONSE).Array()); IPCWaiter response_waiter = process_waiter; response_waiter.push_back(response.signal_); if(response_waiter.wait_for_two(0, 1, INFINITE)) { DWORD code = 0; if(!GetExitCodeProcess(qsvhelper_process.h, &code)) CrashError(TEXT("Failed to initialize QSV session.")); switch(code) { case EXIT_INCOMPATIBLE_CONFIGURATION: CrashError(TEXT("QSVHelper.exe has exited because of an incompatible qsvimpl custom parameter (before response)")); case EXIT_NO_VALID_CONFIGURATION: if(OSGetVersion() < 8) CrashError(TEXT("QSVHelper.exe could not find a valid configuration. Make sure you have a (virtual) display connected to your iGPU")); CrashError(TEXT("QSVHelper.exe could not find a valid configuration")); default: CrashError(TEXT("QSVHelper.exe has exited with code %i (before response)"), code); } } Log(TEXT("------------------------------------------")); if(bHaveCustomImpl && !response->using_custom_impl) AppWarning(TEXT("Could not initialize QSV session using custom settings")); ver = response->version; auto intf_str = qsv_intf_str(response->requested_impl), actual_intf_str = qsv_intf_str(response->actual_impl); auto length = std::distance(std::begin(implStr), std::end(implStr)); auto impl = response->requested_impl & (MFX_IMPL_VIA_ANY - 1); if(impl > length) impl = static_cast<mfxIMPL>(length-1); Log(TEXT("QSV version %u.%u using %s%s (actual: %s%s)"), ver.Major, ver.Minor, implStr[impl], intf_str, implStr[response->actual_impl & (MFX_IMPL_VIA_ANY - 1)], actual_intf_str); target_usage = response->target_usage; encode_tasks.SetSize(response->bitstream_num); bs_buff = ipc_bitstream_buff((event_prefix + BITSTREAM_BUFF).Array(), response->bitstream_size*response->bitstream_num); if(!bs_buff) CrashError(TEXT("Failed to initialize QSV bitstream buffer (%u)"), GetLastError()); mfxU8 *bs_start = (mfxU8*)(((size_t)&bs_buff + 31)/32*32); for(unsigned i = 0; i < encode_tasks.Num(); i++) { zero(encode_tasks[i].surf); mfxBitstream &bs = encode_tasks[i].bs; zero(bs); bs.Data = bs_start + i*response->bitstream_size; bs.MaxLength = response->bitstream_size; idle_tasks << i; } frames.SetSize(response->frame_num); frame_buff = ipc_frame_buff((event_prefix + FRAME_BUFF).Array(), response->frame_size*response->frame_num); if(!frame_buff) CrashError(TEXT("Failed to initialize QSV frame buffer (%u)"), GetLastError()); mfxU8 *frame_start = (mfxU8*)(((size_t)&frame_buff + 15)/16*16); for(unsigned i = 0; i < frames.Num(); i++) { mfxFrameData& frame = frames[i]; zero(frame); frame.Y = frame_start + i * response->frame_size; frame.UV = frame_start + i * response->frame_size + response->UV_offset; frame.V = frame_start + i * response->frame_size + response->V_offset; frame.Pitch = response->frame_pitch; } Log(TEXT("Using %u bitstreams and %u frame buffers"), encode_tasks.Num(), frames.Num()); Log(TEXT("------------------------------------------")); Log(GetInfoString()); Log(TEXT("------------------------------------------")); DataPacket packet; GetHeaders(packet); frame_queue = ipc_frame_queue((event_prefix + FRAME_QUEUE).Array(), frames.Num()); if(!frame_queue) CrashError(TEXT("Failed to initialize frame queue (%u)"), GetLastError()); frame_buff_status = ipc_frame_buff_status((event_prefix + FRAME_BUFF_STATUS).Array(), frames.Num()); if(!frame_buff_status) CrashError(TEXT("Failed to initialize QSV frame buffer status (%u)"), GetLastError()); bs_info = ipc_bitstream_info((event_prefix + BITSTREAM_INFO).Array(), response->bitstream_num); if(!bs_info) CrashError(TEXT("Failed to initialize QSV bitstream info (%u)"), GetLastError()); filled_bitstream = ipc_filled_bitstream((event_prefix + FILLED_BITSTREAM).Array()); if(!filled_bitstream) CrashError(TEXT("Failed to initialize bitstream signal (%u)"), GetLastError()); stop = ipc_stop((event_prefix + STOP_REQUEST).Array()); if(!stop) CrashError(TEXT("Failed to initialize QSV stop signal (%u)"), GetLastError()); filled_bitstream_waiter = process_waiter; filled_bitstream_waiter.push_back(filled_bitstream.signal_); }
bool VHTTPResponse::SetCookie (const XBOX::VString& inName, const XBOX::VString& inValue) { return GetHeaders().SetCookie (inName, inValue); }
QSVEncoder(int fps_, int width, int height, int quality, CTSTR preset, bool bUse444, int maxBitrate, int bufferSize, bool bUseCFR_, bool bDupeFrames_) : enc(nullptr) { Log(TEXT("------------------------------------------")); for(int i = 0; i < sizeof(validImpl)/sizeof(validImpl[0]); i++) { mfxIMPL impl = validImpl[i]; ver = version; mfxStatus result = MFX_ERR_UNKNOWN; for(ver.Minor = 6; ver.Minor >= 4; ver.Minor -= 2) { result = session.Init(impl, &ver); if(result == MFX_ERR_NONE) { Log(TEXT("QSV version %u.%u using %s"), ver.Major, ver.Minor, implStr[impl]); break; } } if(result == MFX_ERR_NONE) break; } session.SetPriority(MFX_PRIORITY_HIGH); fps = fps_; bUseCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCBR")) != 0; bUseCFR = bUseCFR_; bDupeFrames = bDupeFrames_; memset(¶ms, 0, sizeof(params)); //params.AsyncDepth = 0; params.mfx.CodecId = MFX_CODEC_AVC; params.mfx.TargetUsage = MFX_TARGETUSAGE_BEST_QUALITY;//SPEED; params.mfx.TargetKbps = (mfxU16)(maxBitrate*0.9); params.mfx.MaxKbps = maxBitrate; //params.mfx.InitialDelayInKB = 1; //params.mfx.GopRefDist = 1; //params.mfx.NumRefFrame = 0; params.mfx.GopPicSize = 61; params.mfx.GopRefDist = 3; params.mfx.GopOptFlag = MFX_GOP_STRICT; params.mfx.IdrInterval = 2; params.mfx.NumSlice = 1; params.mfx.RateControlMethod = bUseCBR ? MFX_RATECONTROL_CBR : MFX_RATECONTROL_VBR; params.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY; auto& fi = params.mfx.FrameInfo; ConvertFrameRate(fps, fi.FrameRateExtN, fi.FrameRateExtD); fi.FourCC = MFX_FOURCC_NV12; fi.ChromaFormat = bUse444 ? MFX_CHROMAFORMAT_YUV444 : MFX_CHROMAFORMAT_YUV420; fi.PicStruct = MFX_PICSTRUCT_PROGRESSIVE; fi.Width = ALIGN16(width); fi.Height = ALIGN16(height); fi.CropX = 0; fi.CropY = 0; fi.CropW = width; fi.CropH = height; this->width = width; this->height = height; enc.reset(new MFXVideoENCODE(session)); enc->Close(); mfxFrameAllocRequest req; memset(&req, 0, sizeof(req)); enc->QueryIOSurf(¶ms, &req); enc->Init(¶ms); decltype(params) query; memcpy(&query, ¶ms, sizeof(params)); enc->GetVideoParam(&query); unsigned num_surf = max(6, req.NumFrameSuggested + params.AsyncDepth); encode_tasks.SetSize(num_surf); const unsigned bs_size = max(query.mfx.BufferSizeInKB*1000, bufferSize*1024/8); bs_buff.SetSize(bs_size * encode_tasks.Num() + 31); params.mfx.BufferSizeInKB = bs_size/1000; mfxU8* bs_start = (mfxU8*)(((size_t)bs_buff.Array() + 31)/32*32); for(unsigned i = 0; i < encode_tasks.Num(); i++) { encode_tasks[i].sp = nullptr; mfxFrameSurface1& surf = encode_tasks[i].surf; memset(&surf, 0, sizeof(mfxFrameSurface1)); memcpy(&surf.Info, ¶ms.mfx.FrameInfo, sizeof(params.mfx.FrameInfo)); mfxBitstream& bs = encode_tasks[i].bs; memset(&bs, 0, sizeof(mfxBitstream)); bs.Data = bs_start + i*bs_size; bs.MaxLength = bs_size; idle_tasks << i; } frames.SetSize(num_surf+3); //+NUM_OUT_BUFFERS const unsigned lum_channel_size = fi.Width*fi.Height, uv_channel_size = fi.Width*fi.Height, frame_size = lum_channel_size + uv_channel_size; frame_buff.SetSize(frame_size * frames.Num() + 15); mfxU8* frame_start = (mfxU8*)(((size_t)frame_buff.Array() + 15)/16*16); memset(frame_start, 0, frame_size * frames.Num()); for(unsigned i = 0; i < frames.Num(); i++) { mfxFrameData& frame = frames[i]; memset(&frame, 0, sizeof(mfxFrameData)); frame.Y = frame_start + i * frame_size; frame.UV = frame_start + i * frame_size + lum_channel_size; frame.V = frame.UV + 1; frame.Pitch = fi.Width; } Log(TEXT("Using %u encode tasks"), encode_tasks.Num()); Log(TEXT("Buffer size: %u configured, %u suggested by QSV; using %u"), bufferSize, query.mfx.BufferSizeInKB*1000*8/1024, params.mfx.BufferSizeInKB*1000*8/1024); Log(TEXT("------------------------------------------")); Log(TEXT("%s"), GetInfoString().Array()); Log(TEXT("------------------------------------------")); memset(&ctrl, 0, sizeof(ctrl)); ctrl.FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_REF | MFX_FRAMETYPE_IDR; deferredFrames = 0; bUsingDecodeTimestamp = false && ver.Minor >= 6; DataPacket packet; GetHeaders(packet); }
bool VHTTPResponse::DropCookie (const XBOX::VString& inName) { return GetHeaders().DropCookie (inName); }