コード例 #1
0
ファイル: Dump.cpp プロジェクト: Ziriax/BugSlayer
void ValidatorOne ( const void * pData , const void * pContext )
{
    // Validate the string data here.
    _RPT2 ( _CRT_WARN ,
            " Validator called with : %s : 0x%08X\n" ,
            pData , pContext ) ;
}
コード例 #2
0
ファイル: EED.cpp プロジェクト: Stretto/mago
    HRESULT ParseText( const wchar_t* text, ITypeEnv* typeEnv, NameTable* strTable, IEEDParsedExpr*& expr )
    {
        if ( (text == NULL) || (typeEnv == NULL) || (strTable == NULL) )
            return E_INVALIDARG;

        Scanner scanner( text, wcslen( text ), strTable );
        Parser  parser( &scanner, typeEnv );
        RefPtr<Expression>  e;

        try
        {
            scanner.NextToken();
            e = parser.ParseExpression();

            if ( scanner.GetToken().Code != TOKeof )
                return E_MAGOEE_SYNTAX_ERROR;
        }
        catch ( int errCode )
        {
            UNREFERENCED_PARAMETER( errCode );
            _RPT2( _CRT_WARN, "Failed to parse, error %d. Text=\"%ls\".\n", errCode, text );
            return E_MAGOEE_SYNTAX_ERROR;
        }

        expr = new EEDParsedExpr( e, strTable, typeEnv );
        if ( expr == NULL )
            return E_OUTOFMEMORY;

        expr->AddRef();

        return S_OK;
    }
コード例 #3
0
ファイル: mmutils.cpp プロジェクト: shamamuga/shortcut
bool isRenderer(IBaseFilter* filt)
{
	if (!filt) return false;

	IEnumPins*	pinList;
	int nrOutput = 0;
	int nrInput = 0;
	IPin*		pin = NULL;

	if (FAILED(filt->EnumPins(&pinList))) return false;
	pinList->Reset();
	while (pinList->Next(1, &pin, NULL) == S_OK)
	{
		if (getPinInfo(pin).dir == PINDIR_OUTPUT) nrOutput++;
		else nrInput++;
		pin->Release();
	}
	pinList->Release();

	#ifdef _DEBUG
		FILTER_INFO info;
		filt->QueryFilterInfo(&info);
		char str[100];
		WideCharToMultiByte( CP_ACP, 0, info.achName, -1, str, 100, NULL, NULL );
		_RPT0(_CRT_WARN,str);
		_RPT2(_CRT_WARN," %d %d\n", nrOutput, nrInput);
	#endif

	return nrOutput == 0 && nrInput == 1;  // the only filters that have no outputs are renderers
}
コード例 #4
0
ファイル: TCPClient.cpp プロジェクト: Dias19/avisynth64
void __stdcall TCPClient::GetAudio(void* buf, __int64 start, __int64 count, IScriptEnvironment* env) {
  if (!vi.HasAudio())
    return ;

  ClientRequestAudio a;
  memset(&a, 0 , sizeof(ClientRequestAudio));
  a.start = start;
  a.count = count;
  a.bytes = (int)vi.BytesFromAudioSamples(count);

  client->SendRequest(CLIENT_REQUEST_AUDIO, &a, sizeof(ClientRequestAudio));
  client->GetReply();
  if (client->reply->last_reply_type != SERVER_SENDING_AUDIO) {
    if (client->reply->last_reply_type == INTERNAL_DISCONNECTED)
      env->ThrowError("TCPClient: Disconnected from server");

    env->ThrowError("TCPClient: Did not recieve expected packet (SERVER_SENDING_AUDIO)");
    return ;
  }

  ServerAudioInfo* ai = (ServerAudioInfo *)client->reply->last_reply;
  switch (ai->compression) {
    case ServerAudioInfo::COMPRESSION_NONE:
      break;
    default:
      env->ThrowError("TCPClient: Unknown compression.");
  }

  _RPT2(0, "TCPClient: Got %d of %d bytes of audio (GetAudio)\n", ai->data_size, a.bytes);
  memcpy(buf, client->reply->last_reply + sizeof(ServerAudioInfo), ai->data_size);
}
コード例 #5
0
HRESULT	audioSource::FillBuffer(IMediaSample *pMediaSample)
{	
	_RPT2(_CRT_WARN,"FillBuffer %d %d\n",currentFrame,nr);

	long lDataLen = pMediaSample->GetSize();;
	{
		CAutoLock cAutoLockShared(&m_cSharedState);
		
		if (currentFrame >= nr || times[currentFrame]*10000000 > m_rtStop)
		{
			_RPT0(_CRT_WARN,"a stopping\n");
			done=1;
			
			if (stopGraph) return S_FALSE;
			else {
				pMediaSample->SetActualDataLength(0);
				REFERENCE_TIME rtStart,	rtStop;
				
				rtStart	= times[currentFrame-1]*10000000;
				rtStop = m_rtStop;
				pMediaSample->SetTime(&rtStart,	&rtStop);
			
				_RPT0(_CRT_WARN,"a Sleeping \n");
				Sleep(1000);
				return NOERROR;
			}
		}
		
		double* dData = (double*)frames[currentFrame];

		if (subtype == MEDIASUBTYPE_PCM)
		{
			short *pData;
			pMediaSample->GetPointer((BYTE**)&pData);
			
			for (int i=lens[currentFrame]*nrChannels-1;i>=0;i--) pData[i] = min((1<<15)-1,dData[i]*(1<<15));
		} else { // FLOAT format
			float *pData;
			pMediaSample->GetPointer((BYTE**)&pData);

			for (int i=lens[currentFrame]*nrChannels-1;i>=0;i--) pData[i] = dData[i];
		}

		REFERENCE_TIME rtStart,	rtStop;
		
		rtStart	= times[currentFrame]*10000000;
		rtStop	= rtStart + lens[currentFrame]/(rate*10000000.0);

		pMediaSample->SetActualDataLength(lens[currentFrame]*wordSize);
		_RPT4(_CRT_WARN,"a SetTime %d %d   %d %d\n",(int)(rtStart>>32),(int)rtStart,(int)(rtStop>>32),(int)rtStop);
		pMediaSample->SetTime(&rtStart,	&rtStop);
	
		currentFrame++;
	}

	pMediaSample->SetSyncPoint(TRUE);

	return NOERROR;
}
コード例 #6
0
ファイル: plugin.c プロジェクト: kichik/nsis-1
void watchGlobal()
{
    for (int i = 0; i < blocksnum; i++)
        if (blocks[i] != NULL)
        {
            _RPT2(_CRT_WARN, "Memory leak %d at %8X\n", i, blocks[i]);
        }
}
コード例 #7
0
ファイル: Dump.cpp プロジェクト: Ziriax/BugSlayer
// The dumper and validator for the structure allocations
void DumperTwo ( const void * pData )
{
    _RPT2 ( _CRT_WARN                       ,
             " Data is Name : %s\n"
             "         Rank : %s\n"         ,
             ((SimpleStruct*)pData)->szName   ,
             ((SimpleStruct*)pData)->szRank    ) ;
}
コード例 #8
0
ファイル: vncdesktop.cpp プロジェクト: lizard007/msf3
// Copy data from the memory bitmap into a buffer
void
vncDesktop::CopyToBuffer(const rfb::Rect &rect, BYTE *destbuff, UINT destbuffsize)
{
	// Finish drawing anything in this thread 
	// Wish we could do this for the whole system - maybe we should
	// do something with LockWindowUpdate here.
	GdiFlush();

	// Are we being asked to blit from the DIBsection to itself?
	if (destbuff == m_DIBbits) {
		// Yes.  Ignore the request!
		return;
	}

	int y_inv;
	BYTE * destbuffpos;

	// Calculate the scanline-ordered y position to copy from
	y_inv = m_scrinfo.framebufferHeight-rect.tl.y-(rect.br.y-rect.tl.y);

	// Calculate where in the output buffer to put the data
	destbuffpos = destbuff + (m_bytesPerRow * rect.tl.y);

	// Set the number of bytes for GetDIBits to actually write
	// NOTE : GetDIBits pads the destination buffer if biSizeImage < no. of bytes required
	m_bminfo.bmi.bmiHeader.biSizeImage = (rect.br.y-rect.tl.y) * m_bytesPerRow;

	// Get the actual bits from the bitmap into the bit buffer
	// If fast (DIBsection) blits are disabled then use the old GetDIBits technique
	if (m_DIBbits == NULL) {
		if (GetDIBits(m_hmemdc, m_membitmap, y_inv,
					(rect.br.y-rect.tl.y), destbuffpos,
					&m_bminfo.bmi, DIB_RGB_COLORS) == 0)
		{
			_RPT1(_CRT_WARN, "vncDesktop : [1] GetDIBits failed! %d\n", GetLastError());
			_RPT3(_CRT_WARN, "vncDesktop : thread = %d, DC = %d, bitmap = %d\n", omni_thread::self(), m_hmemdc, m_membitmap);
			_RPT2(_CRT_WARN, "vncDesktop : y = %d, height = %d\n", y_inv, (rect.br.y-rect.tl.y));
		}
	} else {
		// Fast blits are enabled.  [I have a sneaking suspicion this will never get used, unless
		// something weird goes wrong in the code.  It's here to keep the function general, though!]

		int bytesPerPixel = m_scrinfo.format.bitsPerPixel / 8;
		BYTE *srcbuffpos = (BYTE*)m_DIBbits;

		srcbuffpos += (m_bytesPerRow * rect.tl.y) + (bytesPerPixel * rect.tl.x);
		destbuffpos += bytesPerPixel * rect.tl.x;

		int widthBytes = (rect.br.x-rect.tl.x) * bytesPerPixel;

		for(int y = rect.tl.y; y < rect.br.y; y++)
		{
			memcpy(destbuffpos, srcbuffpos, widthBytes);
			srcbuffpos += m_bytesPerRow;
			destbuffpos += m_bytesPerRow;
		}
	}
}
コード例 #9
0
ファイル: Dump.cpp プロジェクト: Ziriax/BugSlayer
void ValidatorTwo ( const void * pData , const void * pContext )
{
    // Validate any structures here.
    _RPT2 ( _CRT_WARN                       ,
             "  Validator called with :\n"
             "    Data is Name : %s\n"
             "            Rank : %s\n"        ,
             ((SimpleStruct*)pData)->szName   ,
             ((SimpleStruct*)pData)->szRank    ) ;
}
コード例 #10
0
ファイル: MT.cpp プロジェクト: XhmikosR/avisynth-mt
DWORD Distributor::getframes(LPVOID param){
	Thread* current_thread=(Thread*)param;
	Distributor* _this=current_thread->distributor;
	IScriptEnvironment** penv=&_this->_env;
	TlsSetValue(TlsIndex,new ScriptEnvironmentTLS());
	while(true)
	{
		WaitForSingleObject(current_thread->begin,INFINITE);
		_RPT2(0,"Thread %d generating frame %d\n",GetCurrentThreadId(),current_thread->n);
		if(current_thread->endthread)
			break;

		current_thread->result=_this->child->GetFrame(current_thread->n,*penv);

		_RPT2(0,"Thread %d finished generating frame %d\n",GetCurrentThreadId(),current_thread->n);
		current_thread->status=Distributor::Thread::idle;
		SetEvent(current_thread->done);
	}
	delete((ScriptEnvironmentTLS*) TlsGetValue(TlsIndex));
	ExitThread(0);
  return 0;
}
コード例 #11
0
ファイル: VNCHooks.cpp プロジェクト: catataw/uvncrepeater
HKEY OpenKey(HKEY basekey, const char* path[], bool writable, bool create) {
	HKEY key = basekey;
	DWORD flags = KEY_READ;
	if (writable) flags |= KEY_WRITE;
	if (create) flags |= KEY_CREATE_SUB_KEY;
	unsigned int i = 0;
	while (path[i]) {
		HKEY newkey;
		DWORD result, dw;
		if (create) {
#ifdef _MSC_VER 
			_RPT2(_CRT_WARN, "vncHooks : creating %s from %x\n", path[i], key);
#endif
			result = RegCreateKeyEx(key, path[i], 0, REG_NONE,
				REG_OPTION_NON_VOLATILE, flags, NULL,
				&newkey, &dw);
		} else {
#ifdef _MSC_VER 
			_RPT2(_CRT_WARN, "vncHooks : opening %s from %x\n", path[i], key);
#endif
			result = RegOpenKeyEx(key, path[i], 0, flags, &newkey);
		}
		if (key && (key != basekey)) RegCloseKey(key);
		key = newkey;
		if (result != ERROR_SUCCESS) {
#ifdef _MSC_VER 
			_RPT2(_CRT_WARN, "vncHooks : failed to open %s(%lu)\n", path[i], result);
#endif
			return NULL;
		} else {
#ifdef _MSC_VER 
			_RPT2(_CRT_WARN, "vncHooks : opened %s (%x)\n", path[i], key);
#endif
		}
		i++;
	}
	return key;
}
コード例 #12
0
ファイル: file.cpp プロジェクト: ruifig/nutcracker
// handle fopen(string path, string mode)
// Open file
// 'mode' may be either one of modes used by fopen() function in libc or one of these values:
//    READ_ONLY  - open for reading only (the file must exist);
//    WRITE_ONLY - open for writing only;
//    READ_WRITE - open for both reading and writing (the file must exist);
//    APPEND     - open for appending (writing data at the end of the file).
static SQInteger FOpen (HSQUIRRELVM)
{
	if (numFiles == MAX_OPENED_FILES)
	{
		PrintError("ERROR: Too many opened files.\n");
		sq_pushnull(sqvm);
		return 1;
	}

	// Find first unopened file
	unsigned i;
	for (i = 0; i < MAX_OPENED_FILES; ++i)
	{
		if (!files[i])
			break;
	}

	const SQChar *path, *mode;
	sq_getstring(sqvm, 2, &path);
	sq_getstring(sqvm, 3, &mode);

	// Binary file I/O isn't provided to scripts
	// FIXME: Wouldn't binary file I/O be useful?
	SQChar* c = (SQChar*)strchr(mode, 'b');
	if (c)
		*c = 0;

#if defined(_MSC_VER) && (_MSC_VER >= 1400)
	if (fopen_s(&files[i], ConvPath(path, SQTrue), mode))
		files[i] = NULL;
#else
	files[i] = fopen(ConvPath(path, SQTrue), mode);
#endif

	FILE* res = files[i];
	if (res)
	{
		sq_pushuserpointer(sqvm, res);
		++numFiles;
		_RPT2(_CRT_WARN, "--- Opened file #%d. %d file(s) are opened.\n", i, numFiles);
	}
	else
		sq_pushnull(sqvm);
	return 1;
}
コード例 #13
0
ファイル: exerb.cpp プロジェクト: snaury/exerb-mingw
static FARPROC WINAPI
exerb_hook_get_proc_address(HMODULE module, LPCTSTR procname)
{
    _RPT2(_CRT_WARN, "exerb_hook_get_proc_address(0x%08X, '%s')\n", module, procname);

    static HMODULE kernel32 = ::GetModuleHandle("kernel32.dll");

    // FIXME: 序数によるインポートに対応する

    if ( module == kernel32 ) {
        if      ( ::strcmp(procname, "LoadLibraryA")     == 0 ) return (FARPROC)::exerb_hook_load_library;
        else if ( ::strcmp(procname, "LoadLibraryExA")   == 0 ) return (FARPROC)::exerb_hook_load_library_ex;
        else if ( ::strcmp(procname, "GetModuleHandleA") == 0 ) return (FARPROC)::exerb_hook_get_module_handle;
        else if ( ::strcmp(procname, "GetProcAddress")   == 0 ) return (FARPROC)::exerb_hook_get_proc_address;
    }

    return ::GetProcAddress(module, procname);
}
コード例 #14
0
void memblockinfo_output_memleak()
{
	if(!Cmdline_show_mem_usage)	return;

	if(TotalRam == 0) 
		return;

	if(TotalRam < 0) {
		 _RPT1(_CRT_WARN, "TotalRam bad value!",TotalRam);
		return;
	}

	_RPT1(_CRT_WARN, "malloc memory leak of %d\n",TotalRam);

// Now if system is compiled register it with the fuller system
#ifdef _REPORT_MEM_LEAKS

	int total = 0;
	// Find empty slot
	for(int f = 0; f < MAX_MEM_POINTERS; f++)
	{
		if(mem_ptr_list[f].ptr)
		{
		 	_RPT3(_CRT_WARN, "Memory leaks: (%s line %d) of %d bytes\n", mem_ptr_list[f].filename, mem_ptr_list[f].line, mem_ptr_list[f].size);
			total += mem_ptr_list[f].size;
		}
	}

	Assert(TotalRam == total);

#else

	for(int i = 0; i < MAX_MEM_MODULES; i++)
	{
		// Found the first empty entry, fill it
	  	if(mem_block_list[i].size > 0)
		{
			// Oh... bad code... making assumsions...
		 	_RPT2(_CRT_WARN, "Possible memory leaks: %s %d\n", mem_block_list[i].filename, mem_block_list[i].size);
		}
	}
#endif
}
コード例 #15
0
HRESULT	audioSource::SetMediaType(const CMediaType *pMediaType)
{
	_RPT0(_CRT_WARN,"SetMediaType\n");
	CAutoLock cAutoLock(m_pFilter->pStateLock());

	if (!pMediaType) return E_INVALIDARG;

	subtype=*pMediaType->Subtype();

	_RPT1(_CRT_WARN,"SetMediaType %s\n",(subtype == MEDIASUBTYPE_PCM)?"PCM":"FLOAT");
	
	WAVEFORMATEX *fmt = (WAVEFORMATEX*) pMediaType->Format();
	wordSize = fmt->nBlockAlign;
	
	HRESULT hr = CSourceStream::SetMediaType(pMediaType);

	_RPT2(_CRT_WARN,"SetMediaType hr %d %d\n",hr,FAILED(hr));
	
	return hr;
}
コード例 #16
0
ファイル: file.cpp プロジェクト: ruifig/nutcracker
// fclose(handle file)
// Close file
static SQInteger FClose (HSQUIRRELVM)
{
	FILE* file;
	sq_getuserpointer(sqvm, 2, (SQUserPointer*)&file);
	if (file)
	{
		for (unsigned i = 0; i < MAX_OPENED_FILES; ++i)
		{
			if (file != files[i])
				continue;

			fclose(file);
			files[i] = NULL;
			--numFiles;
			_RPT2(_CRT_WARN, "--- Closed file #%d. %d file(s) are still opened.\n", i, numFiles);
			break;
		}
	}
	return 0;
}
コード例 #17
0
ファイル: MT.cpp プロジェクト: XhmikosR/avisynth-mt
PVideoFrame Distributor::GetFrameX(int n, int last, IScriptEnvironment* env)
{
	PVideoFrame result=0;
	int in=-1;//thread number processing the current frame
	int inb=-1, inf=-1;
	int nmax=n, nmin=n;//Current highest frame number being processed
	unsigned int i;
	for(i=0;i<nthreads;i++)
	{
		if(thread[i].n>nmax && abs(thread[i].n - n) < 32)//find highest frame number being processed
			nmax=thread[i].n;
		if(thread[i].n<nmin && abs(thread[i].n - n) < 32)//find lowest  frame number being processed
			nmin=thread[i].n;
		if (thread[i].n==n-1)
			inb=i;
		if (thread[i].n==n+1)
			inf=i;
		if(thread[i].n==n)//if the requested frame is being processed by thread i
			if(thread[i].status==Thread::idle){//and it is ready to be used
				result=thread[i].result;//assign it to result 
			}
			else						//else assign in to the thread number
				in=i;
	}
	_RPT2(0,"Distributor status loop1: result:%x, in:%d,\n",result,in);
	if(result==0&&in==-1)//if no current thread is working on the requested frame set in to -2
		in=-2;
	int diff=last<=n?1:-1;
	do
	{
		int nextframe=(diff<0?nmin:nmax)+diff;
		int inneighbour=diff<0?inb:inf;

		for(i=0;i<nthreads;++i==in?i++:0)//run though the active threads and skip the thread that works on the requested frame.
		{
			if(thread[i].status==Thread::idle&&(diff<0?thread[i].n>=n||n-thread[i].n>20:thread[i].n<=n||thread[i].n-n>20)){//if the thread is done processing a frame that lies before the current frame 
				WaitForSingleObject(thread[i].done,INFINITE);  //wait for it to be ready to process the next frame 
															   //(as the thread might stale between setting the idle status and setting the 
															   //done event resulting in the thread signaling done even before beginning working on the frame
				thread[i].status=Thread::running;			   
				if(in!=-2)									   //if a thread is assigned to the requested frame
					if(inneighbour==-1)
					{
						inneighbour=i;
						thread[i].n=n+diff;
						if(nextframe==n+diff)
							nextframe+=diff;
					}
					else
					{
						thread[i].n=nextframe;				   //assign it to the next frame
						nextframe+=diff;
					}
				else{										
					thread[i].n=n;							   //else assign it to the requested frame
					in=i;
				}
				_RPT2(0,"Distributor loop2 Thread %d recruted to generate frame %d\n",i,thread[i].n);
				SetEvent(thread[i].begin);}					   //let the thread begin
			//NOTE: threads that are done working on a frame that is after the current requested frame is not
			//assigned a new frame as the frame will be requested soon. This could be changed as the frame is saved in the cache so it would return quickly.
		}
		diff=-diff;
	}
	while(in==-2);
	_RPT1(0,"Distributor status loop2: in:%d\n",in);
	if(in!=-1)//if the thread creating the requested frame isn't done 
	{
		WaitForSingleObject(thread[in].done,INFINITE); //wait for it to complete processing
		SetEvent(thread[in].done);					   //and signal the thread is done to avoid a deadlock in the loop above
		result=thread[in].result;					   
	}
	_RPT1(0,"Distributor end status: result:%x\n",result);
	return result;
}
コード例 #18
0
ファイル: ClientSockMsg.cpp プロジェクト: aaja/my-webgame
void ProcReceiveBuffer(char *pszPacket, int nRecv)
{
	int				nLen = nRecv;
	int				nNext = 0;
	char			szBuff[DATA_BUFSIZE];
	char			*pszData = &szBuff[0];
	_LPTMSGHEADER	lpMsgHeader;

	if (g_nRemainBuffLen > 0)
		memmove(szBuff, g_szRemainBuff, g_nRemainBuffLen);

	memmove(&szBuff[g_nRemainBuffLen], pszPacket, nLen + 1);

	nLen += g_nRemainBuffLen;

	while (nLen >= sizeof(_TMSGHEADER))
	{
		lpMsgHeader = (_LPTMSGHEADER)pszData;

		if (nLen < (int)(sizeof(_TMSGHEADER) + lpMsgHeader->nLength)) break;

		if (lpMsgHeader->nCode == 0xAA55AA55)
		{
			switch (lpMsgHeader->wIdent)
			{
				case GM_CHECKSERVER:
					SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(2, 0), (LPARAM)_TEXT("Activation"));	// Received keep alive check code from game server 
					break;
				case GM_SERVERUSERINDEX:
				{
					CSessionInfo* pSessionInfo = g_UserInfoArray.GetData(lpMsgHeader->wUserGateIndex);

					if (pSessionInfo)
						pSessionInfo->nServerUserIndex = lpMsgHeader->wUserListIndex;

					break;
				}
				case GM_RECEIVE_OK:
					SendSocketMsgS(GM_RECEIVE_OK, 0, 0, 0, 0, NULL);
					break;
				case GM_DATA:
					ProcMakeSocketStr(pszData);
					break;
				case GM_TEST:
					break;
			}

			pszData += sizeof(_TMSGHEADER) + abs(lpMsgHeader->nLength);
			nLen -= sizeof(_TMSGHEADER) + abs(lpMsgHeader->nLength);
		}
		else
		{
			pszData++;
			nLen--;
		}
	} // while

	if (nLen > 0)
	{
		memmove(g_szRemainBuff, pszData, nLen);
		g_nRemainBuffLen = nLen;
#ifdef _DEBUG
	_RPT2(_CRT_WARN, "REMAIN:%d, %s\n", g_nRemainBuffLen, pszData);
#endif
	}
	else
	{
		g_nRemainBuffLen = 0;
	}
}
コード例 #19
0
ファイル: ServerCommSockMsg.cpp プロジェクト: KaSt/mir2ei
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{
	DWORD				dwBytesTransferred;

	CServerInfo*		pServerInfo;

	LPOVERLAPPED		lpOverlapped;

	DWORD				dwFlags;
	DWORD				dwRecvBytes;

	char				szBuff[DATA_BUFSIZE];
	int					nBuffLen;
	char				*pszFirst, *pszEnd, *pszDivide;

	LONG				lValid;
	WORD				w1, w2;
	char				szCC[32];
	int					nPos;

	while (TRUE)
	{
		GetQueuedCompletionStatus((HANDLE)CompletionPortID, &dwBytesTransferred, (LPDWORD)&pServerInfo, (LPOVERLAPPED *)&lpOverlapped, INFINITE);
		
		if (g_fTerminated) return 0L;

		if (dwBytesTransferred == 0)
		{
			closesocket(pServerInfo->m_sock);
			if (pServerInfo) GlobalFree(pServerInfo);

			UpdateStatusBarSession(FALSE);
			
			continue;
		}

		if (pServerInfo->nOvFlag == OVERLAPPED_RECV)
		{
			if (pServerInfo->nRemainBuffLen)
			{
				memmove(szBuff, pServerInfo->RemainBuff, pServerInfo->nRemainBuffLen); // Copy previous remain data in szBuff
				memmove(&szBuff[pServerInfo->nRemainBuffLen], pServerInfo->Buffer, dwBytesTransferred + 1); // Append new received data in szBuff

				nBuffLen = pServerInfo->nRemainBuffLen + dwBytesTransferred;

				pszEnd = &szBuff[0];
			}
			else
			{
				pszEnd		= &pServerInfo->Buffer[0];
				nBuffLen	= dwBytesTransferred;
			}

			while (nBuffLen)
			{
				if ((pszFirst = (char *)memchr(pszEnd, '#', nBuffLen)) && (pszEnd = (char *)memchr(pszFirst, '!', nBuffLen)))
				{
					*pszEnd++ = '\0';

					if (pszDivide = (char *)memchr(pszFirst, '/', pszEnd - pszFirst))
					{
						*pszDivide++ = '\0';

						_LPTSENDBUFF lpSendUserData = new _TSENDBUFF;

						if (lpSendUserData)
						{
							lpSendUserData->nCertification = AnsiStrToVal(pszFirst + 1);

							w1 = lpSendUserData->nCertification	^ 0xAA;
							w2 = memlen(pszDivide) - 1;
							lValid = MAKELONG(w1, w2);
							
							nPos = fnEncode6BitBufA((unsigned char *)&lValid, szCC, sizeof(LONG), sizeof(szCC));
							szCC[nPos] = '\0';

							if (memcmp((pszEnd - nPos - 1), szCC, nPos) == 0)
							{
								fnDecodeMessageA(&lpSendUserData->DefMsg, pszDivide);

								*(pszEnd - nPos - 1) = '\0';

								if (lpSendUserData->DefMsg.wIdent >= 100 && lpSendUserData->DefMsg.wIdent <= 200)
								{
									lpSendUserData->pServerInfo = pServerInfo;

									switch (lpSendUserData->DefMsg.wIdent)
									{
										case DB_MAKEITEMRCD2:
										{
											lpSendUserData->lpbtAddData = new BYTE[sizeof(_TMAKEITEMRCD)];
											fnDecode6BitBufA((pszDivide + DEFBLOCKSIZE), (char *)lpSendUserData->lpbtAddData, sizeof(_TMAKEITEMRCD));

											lpSendUserData->lpbtAddData2 = NULL;

											break;
										}
										default:
										{
											nPos = fnDecode6BitBufA((pszDivide + DEFBLOCKSIZE), (char *)&lpSendUserData->HumanLoad, sizeof(lpSendUserData->HumanLoad));
				
											switch (lpSendUserData->DefMsg.wIdent)
											{
												case DB_MAKEITEMRCD:
												{
													lpSendUserData->lpbtAddData = new BYTE[sizeof(_TMAKEITEMRCD)];
													fnDecode6BitBufA((pszDivide + DEFBLOCKSIZE + 75), (char *)lpSendUserData->lpbtAddData, sizeof(_TMAKEITEMRCD));

													lpSendUserData->lpbtAddData2 = NULL;
													break;
												}
												case DB_SAVEHUMANRCD:
												{
													lpSendUserData->lpbtAddData = new BYTE[sizeof(_THUMANRCD)];
													fnDecode6BitBufA((pszDivide + DEFBLOCKSIZE + 75), (char *)lpSendUserData->lpbtAddData, sizeof(_THUMANRCD));

													int nRemainLen = (int)(pszEnd - pszFirst) - (DEFBLOCKSIZE + 75 + HUMANRCDBLOCKSIZE);

													lpSendUserData->lpbtAddData2 = new BYTE[nRemainLen + 1];

													memcpy(lpSendUserData->lpbtAddData2, (pszDivide + DEFBLOCKSIZE + 75 + HUMANRCDBLOCKSIZE), nRemainLen);
													lpSendUserData->lpbtAddData2[nRemainLen] = '\0';

													break;
												}
												default:
													lpSendUserData->lpbtAddData		= NULL;
													lpSendUserData->lpbtAddData2	= NULL;
											}

											break;
										}
									}
									
									g_DBMsgQ.PushQ((BYTE *)lpSendUserData);
								}
								else
									g_ServerMsgQ.PushQ((BYTE *)lpSendUserData);
							}
							else
								delete lpSendUserData;
						}
					}
					
					nBuffLen -= (pszEnd - pszFirst);
				}
				else
					break;
			} // while

			if (pszFirst && nBuffLen)
			{
				memmove(pServerInfo->RemainBuff, pszFirst, nBuffLen);
				pServerInfo->nRemainBuffLen = nBuffLen;
#ifdef _DEBUG
				_RPT2(_CRT_WARN, "Remain Packet : %d, %s\n", nBuffLen, pszFirst);
#endif
			}
			else
				pServerInfo->nRemainBuffLen = 0;

			// Set next overlapped Process
			dwFlags = 0;

			ZeroMemory(&(pServerInfo->Overlapped), sizeof(OVERLAPPED));

			pServerInfo->DataBuf.len	= DATA_BUFSIZE;
			pServerInfo->DataBuf.buf	= pServerInfo->Buffer;
			pServerInfo->nOvFlag		= OVERLAPPED_RECV;

			if (WSARecv(pServerInfo->m_sock, &(pServerInfo->DataBuf), 1, &dwRecvBytes, &dwFlags, &(pServerInfo->Overlapped), NULL) == SOCKET_ERROR)
			{
				if (WSAGetLastError() != ERROR_IO_PENDING)
				{
					InsertLogMsg(_T("WSARecv() failed"));
					
//					CloseSession(pServerInfo);
					continue;
				}
			}
		} // if (OVERLAPPED_RECV)
	}

	return 0;
}
コード例 #20
0
DWORD WINAPI cProxyServer::TsReader(LPVOID pv)
{
	stTsReaderArg *pArg = static_cast<stTsReaderArg *>(pv);
	IBonDriver *pIBon = pArg->pIBon;
	volatile BOOL &StopTsRead = pArg->StopTsRead;
	volatile BOOL &ChannelChanged = pArg->ChannelChanged;
	DWORD &pos = pArg->pos;
	std::list<cProxyServer *> &TsReceiversList = pArg->TsReceiversList;
	cCriticalSection &TsLock = pArg->TsLock;
	DWORD dwSize, dwRemain, now, before = 0;
	float fSignalLevel = 0;
	DWORD ret = 300;
	const DWORD TsPacketBufSize = g_TsPacketBufSize;
	BYTE *pBuf, *pTsBuf = new BYTE[TsPacketBufSize];
#if _DEBUG && DETAILLOG
	DWORD Counter = 0;
#endif

	// 内部でCOMを使用しているBonDriverに対する対策
	HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY);
	// TS読み込みループ
	while (!StopTsRead)
	{
		dwSize = dwRemain = 0;
		{
			LOCK(TsLock);
			if ((((now = ::GetTickCount()) - before) >= 1000) || ChannelChanged)
			{
				fSignalLevel = pIBon->GetSignalLevel();
				before = now;
				ChannelChanged = FALSE;
			}
			if (pIBon->GetTsStream(&pBuf, &dwSize, &dwRemain) && (dwSize != 0))
			{
				if ((pos + dwSize) < TsPacketBufSize)
				{
					::memcpy(&pTsBuf[pos], pBuf, dwSize);
					pos += dwSize;
					if (dwRemain == 0)
					{
						for (std::list<cProxyServer *>::iterator it = TsReceiversList.begin(); it != TsReceiversList.end(); ++it)
							(*it)->makePacket(eGetTsStream, pTsBuf, pos, fSignalLevel);
#if _DEBUG && DETAILLOG
						_RPT3(_CRT_WARN, "makePacket0() : %u : size[%x] / dwRemain[%d]\n", Counter++, pos, dwRemain);
#endif
						pos = 0;
					}
				}
				else
				{
					DWORD left, dwLen = TsPacketBufSize - pos;
					::memcpy(&pTsBuf[pos], pBuf, dwLen);
					for (std::list<cProxyServer *>::iterator it = TsReceiversList.begin(); it != TsReceiversList.end(); ++it)
						(*it)->makePacket(eGetTsStream, pTsBuf, TsPacketBufSize, fSignalLevel);
#if _DEBUG && DETAILLOG
					_RPT3(_CRT_WARN, "makePacket1() : %u : size[%x] / dwRemain[%d]\n", Counter++, TsPacketBufSize, dwRemain);
#endif
					left = dwSize - dwLen;
					pBuf += dwLen;
					while (left >= TsPacketBufSize)
					{
						for (std::list<cProxyServer *>::iterator it = TsReceiversList.begin(); it != TsReceiversList.end(); ++it)
							(*it)->makePacket(eGetTsStream, pBuf, TsPacketBufSize, fSignalLevel);
#if _DEBUG && DETAILLOG
						_RPT2(_CRT_WARN, "makePacket2() : %u : size[%x]\n", Counter++, TsPacketBufSize);
#endif
						left -= TsPacketBufSize;
						pBuf += TsPacketBufSize;
					}
					if (left != 0)
					{
						if (dwRemain == 0)
						{
							for (std::list<cProxyServer *>::iterator it = TsReceiversList.begin(); it != TsReceiversList.end(); ++it)
								(*it)->makePacket(eGetTsStream, pBuf, left, fSignalLevel);
#if _DEBUG && DETAILLOG
							_RPT3(_CRT_WARN, "makePacket3() : %u : size[%x] / dwRemain[%d]\n", Counter++, left, dwRemain);
#endif
							left = 0;
						}
						else
							::memcpy(pTsBuf, pBuf, left);
					}
					pos = left;
				}
			}
		}
		if (dwRemain == 0)
			::Sleep(WAIT_TIME);
	}
	if (SUCCEEDED(hr))
		::CoUninitialize();
	delete[] pTsBuf;
	return ret;
}
コード例 #21
0
ファイル: cbUtil.cpp プロジェクト: motor/clock_stimulus
HRESULT CbRoot::SetBaseHwInfo()
{
    CComPtr<IProp> prop;        

    char tmpString[512];
    
    // we expect the ini file to be in the same directory as the application,
    // namely, this DLL. It's the only way to find the file if it's not
    // in the windows subdirectory

    if (GetModuleFileName(_Module.GetModuleInstance(), tmpString, 512)==0)
        return E_FAIL;
    // replace .dll with .ini
    strrchr(tmpString, '.' )[1]='\0';
    strcat(tmpString,"ini"); 
    _iniFileName=tmpString;


    cbGetBoardName(_BoardNum,tmpString);
    ATLTRACE2(MCC_UL_CALL,3,"cbGetBoardName(_BoardNum = %i, tmpString); result tmpString = %s\n",_BoardNum,tmpString);
    _boardName=tmpString;
    _iniSection=_boardName;  

    CBI_CHECK(cbGetConfig(BOARDINFO, _BoardNum, 0, BIBOARDTYPE, &_BoardType));
    ATLTRACE2(MCC_UL_CALL,3,"cbGetConfig (BOARDINFO,_BoardNum = %d,0,BIBOARDTYPE, &_BoardType); result: _BoardType=%d\n",_BoardNum,_BoardType);
    long id=GetFromIni(_T("ID"),0L);
    if (id==0)
    {
        _engine->WarningMessage(CComBSTR("Board not found in mwmcc.ini file.  Board is not supported but may work.")); 
    }
    // Check to see if this is a DEMO-BOARD (code 45)
    else if (_BoardType == 45)
    {
        // Geck 224706:  When people create a DEMO-BOARD device, they probably didn't mean to.
        // Give them a warning to indicate that they might want to recosider this.
        _engine->WarningMessage(CComBSTR("The ID value selected is associated with Measurement Computing's virtual DEMO-BOARD. This virtual software device provides simulated data for demo purposes. Use a different ID if this was not your intent."));
    }
    else if (id!=_BoardType)
    {
        _engine->WarningMessage(CComBSTR("BoardType from Ini file does not match that returned from universal libray."));
        _RPT2(_CRT_WARN,"BoardType from ini file is %d board type from unilib is %d\n",id,_BoardType);
    }
    

    // device Id
    wchar_t Str[80];
    swprintf(Str, L"%d", _BoardNum);
    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"id"), CComVariant(Str)));		
    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"adaptorname"), CComVariant(L"mcc")));

    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"vendordriverdescription"),
	CComVariant(L"Measurement Computing Universal Library")));
    
    
    // Get the UL Revision numbers
    float DllRevNum, DriverRevNum;
    
	cbGetRevision (&DllRevNum, &DriverRevNum);
    ATLTRACE2(MCC_UL_CALL,3,"cbGetRevision (&DllRevNum,&DriverRevNum); result: DllRevNum=%d,DriverRevNum=%d\n",DllRevNum,DriverRevNum);

	// Make a call to get the decimal (.xxx) value of the minor revision number.
	// Add this to the major revision number (y.xxx)
	DllRevNum += GetDriverMinorRevision();

	CComVariant var = DllRevNum;
	var.ChangeType(VT_BSTR);

    DEBUG_HRESULT( _DaqHwInfo->put_MemberValue(CComBSTR(L"vendordriverversion"), var));

    DEBUG_HRESULT(_DaqHwInfo->put_MemberValue(CComBSTR(L"devicename"),variant_t(_boardName)));
    
    return S_OK;
}
コード例 #22
0
void ProcReceiveBuffer(char *pszPacket, int nRecv)
{
	int					nBuffLen = nRecv;
	char				szBuff[DATA_BUFSIZE];
	char				*pszFirst, *pszEnd = &szBuff[0], *pszDevide;
	_TDEFAULTMESSAGE	DefMsg;
	_TDEFAULTMESSAGE	SendDefMsg;
	int					nCertification;
	WORD				w1, w2;
	LONG				lValid;
	int					nPos;
	char				szCC[32];
	char				szEncodeMsg[256];

	CReadyUserInfo		*pReadUserInfo;
	CUserInfo			*pUserInfo;

	_TCLIENTITEMRCD		tClientItemRcd;

	if (g_nRemainBuffLen)
		memmove(szBuff, g_szRemainBuff, g_nRemainBuffLen);

	memmove(&szBuff[g_nRemainBuffLen], pszPacket, nBuffLen + 1);

	nBuffLen += g_nRemainBuffLen;

	while (nBuffLen)
	{
		if ((pszFirst = (char *)memchr(pszEnd, '#', nBuffLen)) && (pszEnd = (char *)memchr(pszFirst, '!', nBuffLen)))
		{
			*pszEnd++ = '\0';

			if (pszDevide = (char *)memchr(pszFirst, '/', pszEnd - pszFirst))
			{
				*pszDevide++ = '\0';

				nCertification = AnsiStrToVal(pszFirst + 1);

				w1 = nCertification	^ 0xAA;
				w2 = memlen(pszDevide) - 1;
				lValid = MAKELONG(w1, w2);
				
				nPos = fnEncode6BitBufA((unsigned char *)&lValid, szCC, sizeof(LONG), sizeof(szCC));
				szCC[nPos] = '\0';

				if (memcmp((pszEnd - nPos - 1), szCC, nPos) == 0)
				{
					fnDecodeMessageA(&DefMsg, pszDevide);

					*(pszEnd - nPos - 1) = '\0';

					switch (DefMsg.wIdent)
					{
						case DBR_LOADHUMANRCD2:
						{
							CReadyUserInfo2*	pReadyUserInfo2 = new CReadyUserInfo2;

							pReadyUserInfo2->m_dwReadyStartTime = GetTickCount();
							pReadyUserInfo2->m_nNumOfGenItem	= HIBYTE(DefMsg.wParam);
							pReadyUserInfo2->m_nNumOfMagic		= DefMsg.wSeries;
							pReadyUserInfo2->m_nNumOfItem		= LOBYTE(DefMsg.wParam);

							fnDecode6BitBufA((pszDevide + DEFBLOCKSIZE), (char *)&pReadyUserInfo2->m_THumanRcd, sizeof(_THUMANRCD));
							
							memmove(pReadyUserInfo2->pszData, pszDevide + DEFBLOCKSIZE + HUMANRCDBLOCKSIZE, memlen(pszDevide + DEFBLOCKSIZE + HUMANRCDBLOCKSIZE));

							g_xReadyUserInfoList2.AddNewNode(pReadyUserInfo2);

							break;
						}
						case DBR_LOADHUMANRCD:
						{
							pReadUserInfo = (CReadyUserInfo *)DefMsg.nRecog;

							nPos = fnDecode6BitBufA((pszDevide + DEFBLOCKSIZE), (char *)&pReadUserInfo->m_pUserInfo->m_THumanRcd, sizeof(_THUMANRCD));

							char *pszData;

							pszData = (pszDevide + DEFBLOCKSIZE + HUMANRCDBLOCKSIZE);

							if (HIBYTE(DefMsg.wParam))		// Decode General Item
							{
								pReadUserInfo->m_pUserInfo->m_nNumOfGenItems = HIBYTE(DefMsg.wParam);

								_TGENITEMRCD	GenItemRcd;
								char			szVal[5];						

								for (int i = 0; i < HIBYTE(DefMsg.wParam); i++)
								{
									_LPTGENERALITEMRCD lptGenItemRcd = new _TGENERALITEMRCD;

									if (lptGenItemRcd)
									{
										fnDecode6BitBufA(pszData, (char *)&GenItemRcd, sizeof(_TGENITEMRCD));
										
										memcpy(lptGenItemRcd->szMakeIndex, GenItemRcd.szItem, 12);

										ZeroMemory(szVal, sizeof(szVal));

										memcpy(szVal, &lptGenItemRcd->szMakeIndex[1], 3);
										lptGenItemRcd->nStdIndex	= AnsiStrToVal(szVal);
										memcpy(szVal, &lptGenItemRcd->szMakeIndex[4], 4);
										lptGenItemRcd->nDura		= AnsiStrToVal(szVal);
										memcpy(szVal, &lptGenItemRcd->szMakeIndex[8], 4);
										lptGenItemRcd->nDuraMax		= AnsiStrToVal(szVal);

										pReadUserInfo->m_pUserInfo->m_lpTGenItemRcd.AddNewNode(lptGenItemRcd);
								
										pszData += GENITEMRCDBLOCKSIZE;
									}
								}
							}								  

							if (DefMsg.wSeries)		// Decode Magic
							{
								pReadUserInfo->m_pUserInfo->m_nNumOfMagics = DefMsg.wSeries;

								for (int i = 0; i < DefMsg.wSeries; i++)
								{
									_LPTHUMANMAGICRCD lpHumanMagicRcd = new _THUMANMAGICRCD;

									if (lpHumanMagicRcd)
									{
										fnDecode6BitBufA(pszData, (char *)lpHumanMagicRcd, sizeof(_THUMANMAGICRCD));
										pReadUserInfo->m_pUserInfo->m_lpTMagicRcd.AddNewNode(lpHumanMagicRcd);
										pszData += MAGICRCDBLOCKSIZE;

//#ifdef _DEBUG
//										_RPT3(_CRT_WARN, "%d - %d - %d\n", lpHumanMagicRcd->btLevel, lpHumanMagicRcd->btUseKey, lpHumanMagicRcd->nCurrTrain);
//#endif
									}
								}
							}								  

							if (LOBYTE(DefMsg.wParam))		// Decode Item
							{
								pReadUserInfo->m_pUserInfo->m_nNumOfItems = LOBYTE(DefMsg.wParam);
		//						pReadUserInfo->m_pUserInfo->m_lpTItemRcd = (_LPTUSERITEMRCD)GlobalAlloc(GPTR, sizeof(_TUSERITEMRCD) * DefMsg.wParam);

								for (int i = 0; i < LOBYTE(DefMsg.wParam); i++)
								{
									_LPTUSERITEMRCD lpTItemRcd = new _TUSERITEMRCD;

									if (lpTItemRcd)
									{
										fnDecode6BitBufA(pszData, (char *)lpTItemRcd, sizeof(_TUSERITEMRCD));
										pReadUserInfo->m_pUserInfo->m_lpTItemRcd.AddNewNode(lpTItemRcd);
										pszData += ITEMRCDBLOCKSIZE;
									}
								}
							}

							if (DefMsg.wTag)		// Decode Horse
							{
								if (!pReadUserInfo->m_pUserInfo->m_lpTHorseRcd)
									pReadUserInfo->m_pUserInfo->m_lpTHorseRcd = new _THORSERCD;

								fnDecode6BitBufA(pszData, (char *)pReadUserInfo->m_pUserInfo->m_lpTHorseRcd, sizeof(_THORSERCD));
							}

							if (pReadUserInfo->m_pUserInfo->m_pxPlayerObject)
							{
								pReadUserInfo->m_pUserInfo->m_pxPlayerObject->MakeFeature();
								pReadUserInfo->m_pUserInfo->m_pxPlayerObject->Initialize();
								pReadUserInfo->m_pUserInfo->m_pxPlayerObject->m_fIsAlive	= TRUE;

								pReadUserInfo->m_pUserInfo->m_btCurrentMode	= USERMODE_PLAYGAME;
							}

							break;
						}
						case DBR_MAKEITEMRCD:
						{
							pUserInfo = (CUserInfo *)DefMsg.nRecog;

							_LPTUSERITEMRCD lpTItemRcd = new _TUSERITEMRCD;

							if (lpTItemRcd)
							{
								nPos = fnDecode6BitBufA((pszDevide + DEFBLOCKSIZE), (char *)lpTItemRcd, sizeof(_TUSERITEMRCD));
								
								pUserInfo->m_lpTItemRcd.AddNewNode(lpTItemRcd);

								fnMakeDefMessage(&SendDefMsg, SM_ADDITEM, (int)pUserInfo->m_pxPlayerObject, 0, 0, 1);

								if (lpTItemRcd->szMakeIndex[0] != 'G')
								{
									g_pStdItemSpecial[lpTItemRcd->nStdIndex].GetStandardItem(&tClientItemRcd);
									g_pStdItemSpecial[lpTItemRcd->nStdIndex].GetUpgradeStdItem(&tClientItemRcd, lpTItemRcd);
								}

								memcpy(tClientItemRcd.szMakeIndex, lpTItemRcd->szMakeIndex, 12);
								
								tClientItemRcd.nDura		= lpTItemRcd->nDura;
								tClientItemRcd.nDuraMax		= lpTItemRcd->nDuraMax;

								nPos = 	fnEncode6BitBufA((unsigned char *)&tClientItemRcd, szEncodeMsg, sizeof(_TCLIENTITEMRCD), sizeof(szEncodeMsg));
								szEncodeMsg[nPos] = '\0';

								pUserInfo->m_pxPlayerObject->SendSocket(&SendDefMsg, szEncodeMsg);
							}

							break;
						}
						case DBR_MAKEITEMRCD2:
						{
							CPlayerObject* pPlayerObject = (CPlayerObject *)DefMsg.nRecog;
							
							pUserInfo = pPlayerObject->m_pUserInfo;
							
							_LPTUSERITEMRCD lpTItemRcd = new _TUSERITEMRCD;

							if (lpTItemRcd)
							{
								nPos = fnDecode6BitBufA((pszDevide + DEFBLOCKSIZE), (char *)lpTItemRcd, sizeof(_TUSERITEMRCD));
								
								pUserInfo->m_lpTItemRcd.AddNewNode(lpTItemRcd);

								fnMakeDefMessage(&SendDefMsg, SM_ADDITEM, (int)pUserInfo->m_pxPlayerObject, 0, 0, 1);

								if (lpTItemRcd->szMakeIndex[0] != 'G')
								{
									g_pStdItemSpecial[lpTItemRcd->nStdIndex].GetStandardItem(&tClientItemRcd);
									g_pStdItemSpecial[lpTItemRcd->nStdIndex].GetUpgradeStdItem(&tClientItemRcd, lpTItemRcd);
								}

								memcpy(tClientItemRcd.szMakeIndex, lpTItemRcd->szMakeIndex, 12);
								
								tClientItemRcd.nDura		= lpTItemRcd->nDura;
								tClientItemRcd.nDuraMax		= lpTItemRcd->nDuraMax;

								nPos = 	fnEncode6BitBufA((unsigned char *)&tClientItemRcd, szEncodeMsg, sizeof(_TCLIENTITEMRCD), sizeof(szEncodeMsg));
								szEncodeMsg[nPos] = '\0';

								pUserInfo->m_pxPlayerObject->SendSocket(&SendDefMsg, szEncodeMsg);
							}

							break;
						}
					}
				}
			}

			nBuffLen -= (pszEnd - pszFirst);
		}
		else
			break;
	} // while

	if (pszFirst && (nBuffLen > 0))
	{
		memmove(g_szRemainBuff, pszFirst, nBuffLen);
		g_nRemainBuffLen = nBuffLen;
#ifdef _DEBUG
	_RPT2(_CRT_WARN, "ProcReceiveBuffer:%d, %s\n", g_nRemainBuffLen, pszFirst);
#endif
	}
	else
		g_nRemainBuffLen = 0;
}
コード例 #23
0
ファイル: Main.cpp プロジェクト: KGE-INC/VirtualDub
STDMETHODIMP CAVIFileRemote::Open(LPCSTR szFile, UINT mode, LPCOLESTR lpszFileName) {
	HMMIO hmmio = NULL;
	MMCKINFO mmiriff, mmi;
	MMRESULT mmerr;
	HRESULT final = S_OK;

	_RPT2(0,"CAVIFileRemote::Open(\"%s\", %08lx)\n", szFile, mode);

	if (pafTunnel) {
		pafTunnel->Release();
		pafTunnel = NULL;
	}

	if (mode & (OF_CREATE|OF_WRITE)) {
		IPersistFile *ppf;

		if (FAILED(CoCreateInstance(CLSID_AVIFile, NULL, CLSCTX_INPROC_SERVER, another_IID_IAVIFile, (void **)&pafTunnel)))
			return (HRESULT)E_FAIL;

		if (FAILED(pafTunnel->QueryInterface(IID_IPersistFile, (void **)&ppf)))
			return (HRESULT)E_FAIL;

		HRESULT hr = ppf->Load(lpszFileName, mode);

		ppf->Release();

		return hr;
	}

	if (!(hmmio = mmioOpen((char *)szFile, NULL, MMIO_READ)))
		return E_FAIL;

	_RPT0(0,"File opened.\n");

	// RIFF <size> VDRM { PATH <remote-path> }

	try {
		char buf[16];

		_RPT0(0,"Checking for Avisynth signature...\n");

		if (16==mmioRead(hmmio, buf, 16)) {
			buf[9] = 0;
			if (!_stricmp(buf, "#avisynth")) {

				mmioClose(hmmio, 0);

				// Hand it off to the Avisynth handler.

				IPersistFile *ppf;

				// Okay, it's not one of our files.  Now try passing it off
				// to the regular AVI handler!

				_RPT0(0,"Attempt avisynth tunnel create\n");

				if (FAILED(CoCreateInstance(CLSID_Avisynth, NULL, CLSCTX_INPROC_SERVER, another_IID_IAVIFile, (void **)&pafTunnel)))
					return (HRESULT)E_FAIL;

				_RPT0(0,"Attempt avisynth tunnel query -> IPersistFile\n");

				if (FAILED(pafTunnel->QueryInterface(IID_IPersistFile, (void **)&ppf)))
					return (HRESULT)E_FAIL;

				_RPT0(0,"Attempt avisynth tunnel load\n");

				HRESULT hr = ppf->Load(lpszFileName, mode);

				ppf->Release();

				return hr;
			}
		}

		mmioSeek(hmmio, 0, SEEK_SET);

		_RPT0(0,"Attempting to find 'VDRM'...\n");

		mmiriff.fccType = 'MRDV';
		mmerr = mmioDescend(hmmio, &mmiriff, NULL, MMIO_FINDRIFF);
		if (mmerr == MMIOERR_CHUNKNOTFOUND) {
			IPersistFile *ppf;

			mmioClose(hmmio, 0);

			// Okay, it's not one of our files.  Now try passing it off
			// to the regular AVI handler!

			_RPT0(0,"Attempt tunnel create\n");

			if (FAILED(CoCreateInstance(CLSID_AVIFile, NULL, CLSCTX_INPROC_SERVER, another_IID_IAVIFile, (void **)&pafTunnel)))
				return (HRESULT)E_FAIL;

			_RPT0(0,"Attempt tunnel query -> IPersistFile\n");

			if (FAILED(pafTunnel->QueryInterface(IID_IPersistFile, (void **)&ppf)))
				return (HRESULT)E_FAIL;

			_RPT0(0,"Attempt tunnel load\n");

			HRESULT hr = ppf->Load(lpszFileName, mode);

			ppf->Release();

			return hr;
		}

		else if (mmerr != MMSYSERR_NOERROR) throw (HRESULT)E_FAIL;

		_RPT0(0,"Attempting to find 'PATH'...\n");
		mmi.ckid = 'HTAP';
		mmerr = mmioDescend(hmmio, &mmi, &mmiriff, MMIO_FINDCHUNK);
		if (mmerr == MMIOERR_CHUNKNOTFOUND) throw (HRESULT)E_FAIL;
		else if (mmerr != MMSYSERR_NOERROR) throw (HRESULT)E_FAIL;

		_RPT0(0,"Allocate path memory...\n");
		if (!(szPath = new char[mmi.cksize+1]))
			throw (HRESULT)E_OUTOFMEMORY;

		szPath[mmi.cksize]=0;

		_RPT0(0,"Read in path...\n");

		if ((LONG)mmi.cksize != mmioRead(hmmio, szPath, mmi.cksize))
			throw (HRESULT)E_FAIL;

		_RPT1(0,"File parsed, remote-path: [%s]\n", szPath);

		// now attempt to open the link

		ivdsl = GetDubServerInterface();
		if (!ivdsl) throw (HRESULT)E_FAIL;

		_RPT0(0,"Have dub server interface.\n");

		ivdac = ivdsl->FrameServerConnect(szPath);
		if (!ivdac) throw (HRESULT)E_FAIL;

		// retrieve streaminfo and format information

		_RPT0(0,"Connected to frameserver.\n");

		fHasAudio = ivdac->hasAudio();

		_RPT0(0,"Reading video stream info...\n");

		if (!ivdac->readStreamInfo(&vStreamInfo, FALSE, &vSampleFirst, &vSampleLast))
			throw (HRESULT)E_FAIL;

		_RPT0(0,"Reading video format length...\n");

		if ((vFormatLen = ivdac->readFormat(NULL, FALSE))<=0)
			throw (HRESULT)E_FAIL;

		_RPT1(0,"Allocating video format (%ld bytes)...\n", vFormatLen);

		if (!(vFormat = (BITMAPINFOHEADER *)malloc(vFormatLen)))
			throw (HRESULT)E_OUTOFMEMORY;

		_RPT0(0,"Reading video format...\n");

		if (ivdac->readFormat(vFormat, FALSE)<=0)
			throw (HRESULT)E_FAIL;

		if (fHasAudio) {
			_RPT0(0,"Reading audio stream info...\n");

			if (!ivdac->readStreamInfo(&aStreamInfo, TRUE, &aSampleFirst, &aSampleLast))
				throw (HRESULT)E_FAIL;

			_RPT0(0,"Reading audio format length...\n");

			if ((aFormatLen = ivdac->readFormat(NULL, TRUE))<=0)
				throw (HRESULT)E_FAIL;

			_RPT1(0,"Allocating audio format (%ld bytes)...\n", aFormatLen);

			if (!(aFormat = (WAVEFORMATEX *)malloc(aFormatLen)))
				throw (HRESULT)E_OUTOFMEMORY;

			_RPT0(0,"Reading audio format...\n");

			if (ivdac->readFormat(aFormat, TRUE)<=0)
				throw (HRESULT)E_FAIL;
		}

	} catch(HRESULT res) {
		_RPT0(0,"*** failed!\n");

		final = res;
	}
コード例 #24
0
ファイル: ssrc-convert.cpp プロジェクト: Dias19/avisynth64
void __stdcall SSRC::GetAudio(void* buf, __int64 start, __int64 count, IScriptEnvironment* env)
{
  if (skip_conversion) {
		child->GetAudio(buf, start, count, env);
		return;
	}

  count *= vi.AudioChannels();   // This is how SSRC keeps count. We'll do the same

  if (start != next_sample) {  // Reset on seek
    bool skip_restart = false;

    if (start > next_sample) { // Don't seek if within 10 sek, but skip
      if ((next_sample + input_samples * 10) > start) {
        skip_restart = true;
      }
    }

    if (!skip_restart)  { 
      inputReadOffset = MulDiv(start, source_rate, target_rate) -  input_samples;  // Reset at new read position minus ONE second.
      res = SSRC_create(source_rate, target_rate, vi.AudioChannels(), 2, 1, fast);
      _RPT2(0, "SSRC: Resetting position. Next_sample: %d. Start:%d.!\n", (int)next_sample, (int)start);
      next_sample = start - target_rate;
    }
  }


  SFLOAT* DestSamples = (SFLOAT*)buf;
  int ssrc_samples_tbr = count*sizeof(SFLOAT);  // count in bytes
  bool buffer_full = false;


  if (next_sample < start) { // Skip
    int skip_count = (start - next_sample) * vi.AudioChannels();
    _RPT1(0,"SSRC: Skipping %u samples", skip_count);
    int skip_nsamples = skip_count*sizeof(SFLOAT);  // count in bytes
    do {
      int ssrc_samples_av;
      SFLOAT* ssrc_samples = res->GetBuffer(&ssrc_samples_av);

      if (ssrc_samples_av < skip_nsamples) {  // We don't have enough bytes - feed more.

        child->GetAudio(srcbuffer, inputReadOffset, input_samples, env);
        inputReadOffset += input_samples;

        res->Write(srcbuffer, input_samples * vi.AudioChannels());

      } else {  // Now we have enough data
        res->Read(skip_count);
        next_sample += start;
        buffer_full = true;
      }
    } while (!buffer_full);

    buffer_full = false;
  }


  do {
    int ssrc_samples_av;
    SFLOAT* ssrc_samples = res->GetBuffer(&ssrc_samples_av);

    if (ssrc_samples_av < ssrc_samples_tbr) {  // We don't have enough bytes - feed more.

      child->GetAudio(srcbuffer, inputReadOffset, input_samples, env);
      inputReadOffset += input_samples;
      res->Write(srcbuffer, input_samples * vi.AudioChannels());

    } else {  // Now we have enough data

      env->BitBlt((BYTE*)buf, 0, (BYTE*)ssrc_samples, 0, ssrc_samples_tbr , 1);
      res->Read(count);
      buffer_full = true;
    }

  } while (!buffer_full);
  next_sample = start + (count/vi.AudioChannels());

}
コード例 #25
0
void NikonDecompressor::DecompressNikon(ByteStream *metadata, uint32 w, uint32 h, uint32 bitsPS, uint32 offset, uint32 size) {
  uint32 v0 = metadata->getByte();
  uint32 v1 = metadata->getByte();
  uint32 huffSelect = 0;
  uint32 split = 0;
  int pUp1[2];
  int pUp2[2];
  mUseBigtable = true;

  _RPT2(0, "Nef version v0:%u, v1:%u\n", v0, v1);

  if (v0 == 73 || v1 == 88)
    metadata->skipBytes(2110);

  if (v0 == 70) huffSelect = 2;
  if (bitsPS == 14) huffSelect += 3;

  pUp1[0] = metadata->getShort();
  pUp1[1] = metadata->getShort();
  pUp2[0] = metadata->getShort();
  pUp2[1] = metadata->getShort();

  int _max = 1 << bitsPS & 0x7fff;
  uint32 step = 0;
  uint32 csize = metadata->getShort();
  if (csize  > 1)
    step = _max / (csize - 1);
  if (v0 == 68 && v1 == 32 && step > 0 && !uncorrectedRawValues) {
    for (uint32 i = 0; i < csize; i++)
      curve[i*step] = metadata->getShort();
    for (int i = 0; i < _max; i++)
      curve[i] = (curve[i-i%step] * (step - i % step) +
                  curve[i-i%step+step] * (i % step)) / step;
    metadata->setAbsoluteOffset(562);
    split = metadata->getShort();
  } else if (v0 != 70 && csize <= 0x4001 && !uncorrectedRawValues) {
    for (uint32 i = 0; i < csize; i++) {
      curve[i] = metadata->getShort();
    }
    _max = csize;
  }
  initTable(huffSelect);

  mRaw->whitePoint = curve[_max-1];
  mRaw->blackLevel = curve[0];

  ushort16 top = mRaw->whitePoint;
  for (int i = _max; i < 0x8000; i++)
    curve[i] = top;

  uint32 x, y;
  BitPumpMSB bits(mFile->getData(offset), size);
  uchar8 *draw = mRaw->getData();
  uint32 *dest;
  uint32 pitch = mRaw->pitch;

  int pLeft1 = 0;
  int pLeft2 = 0;
  uint32 cw = w / 2;

  for (y = 0; y < h; y++) {
    if (split && y == split) {
      initTable(huffSelect + 1);
    }
    dest = (uint32*) & draw[y*pitch];  // Adjust destination
    pUp1[y&1] += HuffDecodeNikon(bits);
    pUp2[y&1] += HuffDecodeNikon(bits);
    pLeft1 = pUp1[y&1];
    pLeft2 = pUp2[y&1];
    dest[0] = curve[clampbits(pLeft1,15)] | ((uint32)curve[clampbits(pLeft2,15)] << 16);
    for (x = 1; x < cw; x++) {
      bits.checkPos();
      pLeft1 += HuffDecodeNikon(bits);
      pLeft2 += HuffDecodeNikon(bits);
      dest[x] = curve[clampbits(pLeft1,15)] | ((uint32)curve[clampbits(pLeft2,15)] << 16);
    }
  }
}
コード例 #26
0
ファイル: Main.cpp プロジェクト: KGE-INC/VirtualDub
STDAPI DllCanUnloadNow() {
	_RPT2(0,"DllCanUnloadNow(): CAVIFileRemote %ld, CAVIStreamRemote %ld\n", CAVIFileRemote::gRefCnt, CAVIStreamRemote::gRefCnt);

	return (CAVIFileRemote::gRefCnt || CAVIStreamRemote::gRefCnt) ? S_FALSE : S_OK;
}
コード例 #27
0
HRESULT	videoSource::FillBuffer(IMediaSample *pMediaSample)
{
	_RPT2(_CRT_WARN,"FillBuffer %d %d\n",currentFrame,nr);

	BYTE *pData;
	long lDataLen = pMediaSample->GetSize();;
	pMediaSample->GetPointer(&pData);
	
	if (lDataLen < height*scanwidth*3) return E_INVALIDARG;
	
	{
		CAutoLock cAutoLockShared(&m_cSharedState);
		if (currentFrame >= nr || times[currentFrame]*10000000 > m_rtStop) 
		{
			_RPT0(_CRT_WARN,"v stopping\n");
			done=1;
			
			if (stopGraph) return S_FALSE;
			else {
				pMediaSample->SetActualDataLength(0);
				REFERENCE_TIME rtStart,	rtStop;
				
				rtStart	= times[currentFrame-1]*10000000;
				rtStop = m_rtStop;
				pMediaSample->SetTime(&rtStart,	&rtStop);
			
				_RPT0(_CRT_WARN,"v Sleeping \n");
				Sleep(1000);
				return NOERROR;
			}
		}
	
		//height,width,color => flip color,width, flip height
		BYTE* frame = (BYTE*)frames[currentFrame];

		for (int c=0; c<3; c++)
		{
			int c1 = height*width*c;
			int c2 = 2-c;
			for (int w=0; w<width; w++)
			{
				int w1 = height*w;
				int w2 = 3*w;
				for (int h=0; h<height; h++)
				{
					pData[c2+w2+3*scanwidth*(height-1-h)] = frame[c1+w1+h];
				}
			}
		}
	
		REFERENCE_TIME rtStart,	rtStop;
		
		rtStart	= times[currentFrame]*10000000;
		rtStop	= (currentFrame<nr-1)?times[currentFrame+1]*10000000-1:rtStart;
	
		pMediaSample->SetActualDataLength(height*width*3);
		_RPT4(_CRT_WARN,"v SetTime %d %d   %d %d\n",(int)(rtStart>>32),(int)rtStart,(int)(rtStop>>32),(int)rtStop);
		pMediaSample->SetTime(&rtStart,	&rtStop);
	
		currentFrame++;
	}

	pMediaSample->SetSyncPoint(TRUE);
	
	return NOERROR;
}
コード例 #28
0
ファイル: gui_dwrite.cpp プロジェクト: Qubit0-1/vim
DWriteContext::DWriteContext() :
    mDpiScaleX(1.f),
    mDpiScaleY(1.f),
    mDrawing(false),
    mD2D1Factory(NULL),
    mRT(NULL),
    mBrush(NULL),
    mDWriteFactory(NULL),
    mGdiInterop(NULL),
    mRenderingParams(NULL),
    mTextFormat(NULL),
    mLastHFont(NULL),
    mFontWeight(DWRITE_FONT_WEIGHT_NORMAL),
    mFontStyle(DWRITE_FONT_STYLE_NORMAL),
    mTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_DEFAULT)
{
    HRESULT hr;

    HDC screen = ::GetDC(0);
    mDpiScaleX = ::GetDeviceCaps(screen, LOGPIXELSX) / 96.0f;
    mDpiScaleY = ::GetDeviceCaps(screen, LOGPIXELSY) / 96.0f;
    ::ReleaseDC(0, screen);

    hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,
	    __uuidof(ID2D1Factory), NULL,
	    reinterpret_cast<void**>(&mD2D1Factory));
    _RPT2(_CRT_WARN, "D2D1CreateFactory: hr=%p p=%p\n", hr, mD2D1Factory);

    if (SUCCEEDED(hr))
    {
	D2D1_RENDER_TARGET_PROPERTIES props = {
	    D2D1_RENDER_TARGET_TYPE_DEFAULT,
	    { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE },
	    0, 0,
	    D2D1_RENDER_TARGET_USAGE_NONE,
	    D2D1_FEATURE_LEVEL_DEFAULT
	};
	hr = mD2D1Factory->CreateDCRenderTarget(&props, &mRT);
	_RPT2(_CRT_WARN, "CreateDCRenderTarget: hr=%p p=%p\n", hr, mRT);
    }

    if (SUCCEEDED(hr))
    {
	hr = mRT->CreateSolidColorBrush(
		D2D1::ColorF(D2D1::ColorF::Black),
		&mBrush);
	_RPT2(_CRT_WARN, "CreateSolidColorBrush: hr=%p p=%p\n", hr, mBrush);
    }

    if (SUCCEEDED(hr))
    {
	hr = DWriteCreateFactory(
		DWRITE_FACTORY_TYPE_SHARED,
		__uuidof(IDWriteFactory),
		reinterpret_cast<IUnknown**>(&mDWriteFactory));
	_RPT2(_CRT_WARN, "DWriteCreateFactory: hr=%p p=%p\n", hr,
		mDWriteFactory);
    }

    if (SUCCEEDED(hr))
    {
	hr = mDWriteFactory->GetGdiInterop(&mGdiInterop);
	_RPT2(_CRT_WARN, "GetGdiInterop: hr=%p p=%p\n", hr, mGdiInterop);
    }

    if (SUCCEEDED(hr))
    {
	hr = mDWriteFactory->CreateRenderingParams(&mRenderingParams);
	_RPT2(_CRT_WARN, "CreateRenderingParams: hr=%p p=%p\n", hr,
		mRenderingParams);
    }
}
コード例 #29
0
ファイル: Threads.cpp プロジェクト: mikanradojevic/sdkpub
DWORD ctrlTrainThreadFunc( LPVOID param )
{
    SYSTEM_INFO sysInfo;
    int numProc;
    int i;
    DWORD dwTrainThread[32];
    HANDLE hTrainThread[32];
    TrainThreadParams thrParams[32];
    DWORD affMask = 0;
    POSITION pos;
    CPerson* person;
    
    InitializeCriticalSection( &g_critSect );
    g_hevtWakeUpControlThread = CreateEvent( 0, true, false, "WakeUpCtrlTrainThread" );

    GetSystemInfo( &sysInfo );
    numProc = sysInfo.dwNumberOfProcessors;

    numProc = 32;

    if( numProc > 32 ) {
        CloseHandle( g_hevtWakeUpControlThread );
        DeleteCriticalSection( &g_critSect );
        hCtrlTrainThread = 0;
        return 0;
    }

    trainParam.frame->DisableItemsForTrain();


    if( numProc == 1 )
    {
        // Single processor code
        CHMMDemoDoc* doc = ( (StartTrainParams*)param )->doc;
        if( !doc )
            return 0;
        CFaceBase& base = doc->GetFaceBase();
        base.TrainAll( ( (StartTrainParams*)param )->flag );
    }
    else {
        // Multiple processor code
        CHMMDemoDoc* doc = ( (StartTrainParams*)param )->doc;
        if( !doc )
            ExitThread(0);
        CFaceBase& base = doc->GetFaceBase();

        affMask = 0;
        for( i = 0; i < numProc; i ++ )
        {
            affMask |= ( 1 << i );
        }
        for( i = 0; i < numProc; i ++ )
        {
            thrParams[i].threadNum = i;
            thrParams[i].working = true;
            hTrainThread[i] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)trainFunc, &(thrParams[i]), CREATE_SUSPENDED, &(dwTrainThread[i]) );
            thrParams[i].hThread = hTrainThread[i];
            thrParams[i].doNext = false;
            PRIOR SetThreadPriority( hTrainThread[i], THREAD_PRIORITY_BELOW_NORMAL );
            //SetThreadAffinityMask( hTrainThread[i], affMask );
            //SetThreadIdealProcessor( hTrainThread[i], (DWORD)i );
        }

        thrFinishWork = NONE_FINISH_WORK;
        ResetEvent( g_hevtWakeUpControlThread );
        for( i = 0, pos = base.GetPersonList().GetHeadPosition(); pos; )
        {
            person = base.GetPersonList().GetNext(pos);

            _RPT2( _CRT_WARN, "%s %d\n", "pos = ", (int)pos );

            if( (( (StartTrainParams*)param )->flag == TRAIN_UNTRAINED) && person->IsTrained() ) continue;
        
            EnterCriticalSection( &g_critSect );

                _RPT1( _CRT_WARN, "Giving execute to thread #%d\n", i );

                thrParams[i].person = person;
                thrParams[i].doNext = true;
            LeaveCriticalSection( &g_critSect );

            _RPT1( _CRT_WARN, "Resuming thread #%d\n", i );

            ResumeThread( hTrainThread[i] );
            i ++;
            if( i == numProc ) {
                break;
            }
        }
        if( i != numProc ) {
            while( i > 0 ) {
                WaitForSingleObject( g_hevtWakeUpControlThread, INFINITE );
                CHECK_TRAIN_FOR_BREAK( hTrainThread, thrParams, numProc );

                _RPT1( _CRT_WARN, "Main thread gets last event from thread #%d\n", thrFinishWork );

                EnterCriticalSection( &g_critSect );
                    ResetEvent( g_hevtWakeUpControlThread );
                    thrParams[ thrFinishWork ].doNext = false;

                    _RPT1( _CRT_WARN, "Resuming thread #%d\n", thrFinishWork );

                    ResumeThread( hTrainThread[ thrFinishWork ] );
                    thrFinishWork = NONE_FINISH_WORK;
                    i --;
                LeaveCriticalSection( &g_critSect );
            }
        } // if( i == numProc )
        else {
            i = base.GetPersonList().GetCount() - numProc;
            while( i > 0 ) {
                WaitForSingleObject( g_hevtWakeUpControlThread, INFINITE );
                CHECK_TRAIN_FOR_BREAK( hTrainThread, thrParams, numProc );

                _RPT0( _CRT_WARN, "Main thread gets event\n" );

                EnterCriticalSection( &g_critSect );
                    ResetEvent( g_hevtWakeUpControlThread );
                    person = base.GetPersonList().GetNext(pos);

                    _RPT1( _CRT_WARN, "pos = %d\n", (int)pos );

                    while( pos && person->IsTrained() ) {
                        if( (( (StartTrainParams*)param )->flag != TRAIN_UNTRAINED) ) {
                            person = base.GetPersonList().GetNext(pos);
                            i --;
                        }
                    }
        
                    if( person ) {

                        _RPT1( _CRT_WARN, "Giving execute to thread #%d\n", thrFinishWork );

                        thrParams[ thrFinishWork ].person = person;
                        thrParams[ thrFinishWork ].doNext = true;

                        _RPT1( _CRT_WARN, "Resuming thread #%d\n", thrFinishWork );

                        ResumeThread( hTrainThread[ thrFinishWork ] );
                        thrFinishWork = NONE_FINISH_WORK;
                        i --;
                    }
                LeaveCriticalSection( &g_critSect );

                _RPT1( _CRT_WARN, "i = %d\n", i );

                //WaitForSingleObject( g_hevtWakeUpControlThread, INFINITE );
            } // while( i > 0 )

            for( i = 0; i < numProc; i ++ ) {

                int thrNum;
                DWORD resumeRes;

                WaitForSingleObject( g_hevtWakeUpControlThread, INFINITE );
                CHECK_TRAIN_FOR_BREAK( hTrainThread, thrParams, numProc );

                _RPT1( _CRT_WARN, "Main thread gets last event from thread #%d\n", thrFinishWork );
            
                EnterCriticalSection( &g_critSect );
                    ResetEvent( g_hevtWakeUpControlThread );
                    thrNum = thrFinishWork;
                    thrParams[thrNum].doNext = false;

                    _RPT1( _CRT_WARN, "Resuming thread #%d\n", thrFinishWork );

                    resumeRes = ResumeThread( hTrainThread[thrNum] );
                    thrFinishWork = NONE_FINISH_WORK;
                LeaveCriticalSection( &g_critSect );

                _RPT1( _CRT_WARN, "Waiting for finishing thread #%d\n", thrNum );

                while( !resumeRes ) {
                    resumeRes = ResumeThread( hTrainThread[thrNum] );
                }
                WaitForSingleObject( hTrainThread[thrNum], INFINITE );
            }

        } // if( i == numProc ) else
        for( i = 0; i < numProc; i ++ )
        {
            thrParams[i].doNext = false;
            if( thrParams[i].working == true ) {

                _RPT1( _CRT_WARN, "Resuming thread #%d\n", i );

                while( !ResumeThread( hTrainThread[i] ) && thrParams[i].working == true ) {
                    Sleep(0);
                }

                _RPT1( _CRT_WARN, "Waiting for finishing thread #%d\n", i );

                WaitForSingleObject( hTrainThread[i], INFINITE );
            }
        }
        base.Save();
    } // if( numProc == 1 )


    _RPT0( _CRT_WARN, "Main thread: All is Ok!\n" );

    CloseHandle( g_hevtWakeUpControlThread );
    DeleteCriticalSection( &g_critSect );
    hCtrlTrainThread = 0;
    trainParam.frame->EnableItemsAfterTrain();
    return 0;
} // ctrlTrainThreadFunc