Exemplo n.º 1
0
void CThreadView::OnNewline()
{
	StartThread(3);
	UpdateTitle();
}
Exemplo n.º 2
0
void do_tests() {
    int thid;
    thid = create_main_thread();
    StartThread(thid, NULL);
}
void WINAPI MainThread()
{
	while(1)
	{
		// Thread Principal da dll, chamada de 1 em 1 segundo. 
		// Usar para não sobrecarregar a ProcessMinTimer
		// Não cometer a negragem de dar break

		time_t rawnow = time(NULL);
		struct tm *now = localtime(&rawnow);

		if((DayOfWeek() == Terça  || DayOfWeek() == Quinta) && now->tm_hour == 21)
		{
			if(!now->tm_min && !now->tm_sec)
			{
				SendNotice("Entrada na GuildWar liberada, boa sorte !");

				//SendLog("system", "Entrada na GuildWar liberada.");

				for(int i = 0; i < 0xFFFF; i++)
					Guilds[i].WarPoints = 0;
			}

			if(now->tm_min == 30 && !now->tm_sec)
			{
				UINT16 Winner = DefineGuildWinner();

				char szMsg[120];

				if(Winner)
				{
					sprintf(szMsg, "Guild %s foi a vencedora da GuildWar, parabéns!", Guilds[Winner].GuildName);
					
					Guilds[Winner].FAME += 1000;
				}
				else
					sprintf(szMsg, "Não houve vencedores na GuildWar.");

				SendNotice(szMsg);
				//SendLog("system", szMsg);
			}
		}

		DecrementWaterTime();
		LettersTime();

		for(int z = 0; z < 0xFFFF; z++)
		{
			if(Guilds[z].confirmTransfer)
				Guilds[z].confirmTransfer--;
			if(!Guilds[z].confirmTransfer)
			{
				Guilds[z].transfer = false;

				strncpy(Guilds[z].NewLiderName, "", 16);
			}
		}

		if(!now->tm_hour && !now->tm_min && !now->tm_sec)// 0:00:00
		{
			if(DayOfWeek() == Sabado)
			{
				*(INT32*)0x008BF1814 = 1;
				SendNotice("++++ DOUBLE EXP ON ++++");
			}
			else if(DayOfWeek() == Segunda)
			{
				*(INT32*)0x008BF1814 = 0;
				SendNotice("++++ DOUBLE EXP OFF ++++");
			}
		}

		if(!now->tm_sec && (now->tm_min == 1 || now->tm_min == 16 || now->tm_min == 31 || now->tm_min == 46))
		{
			for(INT8 i = 0; i < 3; i++)
			{
				Pesa[i].TimeLeft = 840;

				for(INT8 e = 0; e < 3; e++)
				{
					for(INT8 j = 0; j < 13; j++)
					{
						if(Pesa[i].CIDS[e][j] < 0 || Pesa[i].CIDS[e][j] > 750)
							continue;
						else if(Users[Pesa[i].CIDS[e][j]].Status != 22)
							continue;

						SendClientSignalParm(Pesa[i].CIDS[e][j], 0x7530, 0x3A1, Pesa[i].TimeLeft);
					}
				}
			}
		}

		if((now->tm_min == 14 || now->tm_min == 29 || now->tm_min == 44 || now->tm_min == 59) && now->tm_sec == 59)
		{
			ClearArea(1150, 130, 1270, 220); // Pesa A
			ClearArea(1050, 260, 1135, 350); // Pesa M
			ClearArea(1295, 290, 1325, 365); // Pesa N

			for(int i = 0; i < sizeof(QuestList) / sizeof(Quests); i++)
			{
				ClearArea(MaxMinCoordsQuest[i][0], MaxMinCoordsQuest[i][1], MaxMinCoordsQuest[i][2], MaxMinCoordsQuest[i][3]);

				for(int z = 0; z < 40; z++)
					QuestList[i].CidID[z] = 0;
			}

			for(int i = 0; i < sizeof(Pesa) / sizeof(Pesas); i++)
			{
				Pesa[i].Status = false;
				Pesa[i].Groups = 0;
				Pesa[i].NpcsAlive = 0;

				for(int e = 0; e < 13; e++)
				{
					Pesa[i].CIDS[0][e] = 0;
					Pesa[i].CIDS[1][e] = 0;
					Pesa[i].CIDS[2][e] = 0;
				}
			}
		}

		if(!now->tm_sec && !now->tm_min && now->tm_hour == 21 && DayOfWeek() == Domingo)
		{
			INT64 BetValue[4][2];

			for(UINT32 I = 0; I < 0xFFFF; I++)
			{
				// Se não tiver nome, não é uma  guild ativa.
				if(!strcmp(Guilds[I].GuildName, ""))
					continue;

				// Coloca na struct da guerra os valores referentes a guilds apostantes
				for(int e = 0; e < 4; e++)
				{
					if(Guilds[I].BetValue[e] > BetValue[e][0])
					{
						BetValue[e][0] = Guilds[I].BetValue[e];
						War.BetIndex[e][0] = I;
					}
					else if(Guilds[I].BetValue[e] > BetValue[e][1])
					{
						BetValue[e][1] = Guilds[I].BetValue[e];
						War.BetIndex[e][1] = I;
					}

					Guilds[I].BetValue[e] = 0;
				}
			}

		    TeleportWar();
		}
		else if(now->tm_hour == 21 && DayOfWeek() == Domingo && now->tm_min == 3 && !now->tm_sec)
		{
			// Inicio real da pancadaria
			//SendLog("system", "Portões da Guerra abertos.");

			WarGate(1);
		}

		if(now->tm_hour == 21 && DayOfWeek() == Domingo)
		{
			for(int i = 0; i < 4; i++)
			{
				if(!War.Iniciada[i])
					continue;

				int OwnerAlive = GetTeamAlive(i, 0),
					DefyAlive  = GetTeamAlive(i, 1);

				if(!OwnerAlive)// Seta o desafiante como vencedor
					PutAsWinner(i, 1);
				else if(!DefyAlive)// Seta o defensor como vencedor
					PutAsWinner(i, 0);

				if(War.Finalizada[i])
					continue;

				for(int e = 0; e < 2; e++)
				{
					for(int j = 0; j < War.TeamCount[i][e]; j++)
					{
						INT16 cId = 0;

						if(!e)
							cId = War.OwnerTeam[i][j];
						else
							cId = War.DefyTeam[i][j];

						st_Mob *player = GetMobFromIndex(cId);

						if(player->Status.curHP <= 0)
						{
							if(wdBuffer[cId].Ingame.WarRestTime >= 1)
								wdBuffer[cId].Ingame.WarRestTime--;
							else
								wdBuffer[cId].Ingame.cantRessurect = false;
						}

						// Manda o score, não sei se vai funfar...
						NpcsAlive(cId, GetTeamAlive(i, 0), GetTeamAlive(i, 1));
					}
				}
			}
		}

		usersCount = 0;

		for(int i = 0; i < MAX_PLAYER; i++)
		{
			if(Users[i].Status != 22)
				continue;

			usersCount++;

			if(wdBuffer[i].Ingame.ChatGlobal > 0)
				wdBuffer[i].Ingame.ChatGlobal--;
			if(wdBuffer[i].Ingame.hasFailed > 0)
				wdBuffer[i].Ingame.hasFailed--;
			if(wdBuffer[i].Ingame.Grito > 0)
				wdBuffer[i].Ingame.Grito--;
			if(wdBuffer[i].Ingame.RetectItem)
				wdBuffer[i].Ingame.RetectItem--;

			st_Mob *tmpPlayer = GetMobFromIndex(i);

			if(tmpPlayer->Equip[0].EFV2 < HARDCORE && tmpPlayer->Equip[1].Index == 3505 && !wdBuffer[i].Ingame.isAdmin)
			{
				SendBan(Users[i].Username);

				char szNotice[120];

				sprintf(szNotice, "Jogador [%s] banido por uso de item irregular.", tmpPlayer->Name);

				//SendLog("banneds", szNotice);
				//SendNotice(szNotice);

				CloseUser(i);
			}

			for(int i = 0; i < *(DWORD*)(0x004C7BD8); i++) 
				memset((void*)(0x8B9E778), 0, 8);

			VerifyPesa(i);
			VerifyQuests(i);
			//VerifyWarArea(i);
		}

		Server.Seconds++;

		if(Server.Seconds >= 60)
		{
			Server.Seconds -= 60;
			Server.Minuts++;

			if(Server.Minuts >= 60)
			{
				Server.Minuts -= 60;
				Server.Hours++;

				if(Server.Hours >= 24)
				{
					Server.Days++;
					Server.Hours -= 24;
				}
			}
		}

		char szTitle[120];

		if(usersCount)
			sprintf(szTitle, "Secrets of Destiny [%d] Jogadores conectados. [%02d:%02d:%02d:%02d]", usersCount, Server.Days, Server.Hours, Server.Minuts, Server.Seconds);
		else
			sprintf(szTitle, "Secrets of Destiny [%02d:%02d:%02d:%02d]", Server.Days, Server.Hours, Server.Minuts, Server.Seconds);

		SetConsoleTitle(szTitle);

		if(!now->tm_min && !now->tm_sec)
		{
			// Funções executadas todo inicio de hora
			if(!Server.SombraNegra)
			{
				CreateMob("Sombra_Negra", 3819, 2880, "npc");

				Server.SombraNegra = TRUE;

				SendNotice("Sombra Negra acaba de nascer em Karden!");

				//SendLog("system", "Sombra Negra nasceu.");
			}
			else
				SendNotice("Sombra Negra ainda reina em Karden.");
			
			StartThread(PremiumDelivery);
		}

		Sleep(1000);
		// Não colocarei 1000 para termos margem de tempo
		// Para a execução das tarefas desta thread
	}	
}
Exemplo n.º 4
0
static void MainThread(void *arg)
{
	while(1)
	{
		u32 port, slot;

		mainThreadCount++;

		if( mainThreadCount % 30 == 0 ) sio2_mtap_update_slots();

		for(port=0; port < 2; port++)
		{
			for(slot=0; slot < 4; slot++)
			{
				if( ((openSlots[port] >> slot) & 0x1) == 1)
				{
					pdSetActive(port, slot, 0);

					padState[port][slot].stat70bit = pdGetStat70bit(port, slot);

					if(padState[port][slot].runTask != TASK_NONE)
					{
						if(padState[port][slot].runTask == TASK_PORT_CLOSE)
						{
							padState[port][slot].currentTask = padState[port][slot].runTask;
							padState[port][slot].runTask = TASK_NONE;
							padState[port][slot].reqState = PAD_RSTAT_BUSY;

							SetEventFlag(padState[port][slot].eventflag, EF_EXIT_THREAD);
						}
						else
						{
							if(padState[port][slot].currentTask == TASK_UPDATE_PAD)
							{
								// Start Task
								StartThread(padState[port][slot].taskTid, NULL);
								padState[port][slot].currentTask = padState[port][slot].runTask;
								padState[port][slot].runTask = TASK_NONE;
								padState[port][slot].reqState = PAD_RSTAT_BUSY;
							}
							else
							{
								padState[port][slot].runTask = TASK_NONE;
								padState[port][slot].reqState = PAD_RSTAT_FAILED;
							}
						}
					}
				}

				switch(padState[port][slot].currentTask)
				{
					case TASK_UPDATE_PAD:
					{
						SetEventFlag(padState[port][slot].eventflag, EF_UPDATE_PAD);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

					case TASK_QUERY_PAD:
					{
						padState[port][slot].buttonDataReady = 0;

						SetEventFlag(padState[port][slot].eventflag, EF_QUERY_PAD);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

					case TASK_PORT_CLOSE:
					{
						if(GetThreadsStatus( &padState[port][slot] ) == 1)
						{
							padState[port][slot].currentTask = TASK_NONE;
							padState[port][slot].reqState = PAD_RSTAT_COMPLETE;
							openSlots[port] ^= (1 << slot);

							DeleteThreads( &padState[port][slot] );
							SetEventFlag(padState[port][slot].eventflag, EF_PORT_CLOSE);
						}

					} break;

					case TASK_SET_MAIN_MODE:
					{
						padState[port][slot].buttonDataReady = 0;

						SetEventFlag(padState[port][slot].eventflag, EF_SET_MAIN_MODE);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

					case TASK_SET_ACT_ALIGN:
					{
						padState[port][slot].buttonDataReady = 0;

						SetEventFlag(padState[port][slot].eventflag, EF_SET_ACT_ALIGN);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

					case TASK_SET_BUTTON_INFO:
					{
						padState[port][slot].buttonDataReady = 0;

						SetEventFlag(padState[port][slot].eventflag, EF_SET_SET_BUTTON_INFO);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

					case TASK_SET_VREF_PARAM:
					{
						padState[port][slot].buttonDataReady = 0;

						SetEventFlag(padState[port][slot].eventflag, EF_SET_VREF_PARAM);
						WaitEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_START, 0x10, 0);
						pdSetActive(port, slot, 1);
					} break;

				}
			}
		}

		// Transfer is started in VblankStart
		vblankData.stopTransfer = 0;
		WaitClearEvent(vblankData.eventflag, EF_VB_TRANSFER_DONE, WEF_AND|WEF_CLEAR, NULL);

		if( (openSlots[0] != 0) || (openSlots[1] != 0))
		{
			for(port=0; port < 2; port++)
			{
				for(slot=0; slot < 4; slot++)
				{
					if(pdIsActive(port, slot) == 1)
					{
						/* Signal transfer done and wait to task (reading
						   sio2 data) to be done. */
						SetEventFlag(padState[port][slot].eventflag, EF_PAD_TRANSFER_DONE);
						WaitEventFlag(padState[port][slot].eventflag, EF_TASK_DONE, 0x10, 0);
					}
				}
			}
		}

		// Send pad data to EE
		DmaSendEE();

		mainThreadCount2++; // s7

		// Check for disconnected controllers
		if(mainThreadCount2 >= 8)
		{
			if(mainThreadCount % 30 != 0)
			{
				if( pdIsActive(pad_port, pad_slot) == 1)
				{
					if( padState[pad_port][pad_slot].state == PAD_STATE_DISCONN)
						pad_portdata[pad_port] &= ~(1 << pad_slot); // clear slot
					else
						pad_portdata[pad_port] |= (1 << pad_slot);	// set slot
				}
				else
				{
					if( pdCheckConnection(pad_port, pad_slot) == 1)
						pad_portdata[pad_port] |= (1 << pad_slot);	// set slot
					else
						pad_portdata[pad_port] &= ~(1 << pad_slot); // clear slot
				}

				//Move onto the next slot
				pad_slot++;
				if(pad_slot >= 4)
				{
					//Move onto the next port
					pad_slot = 0;
					pad_port++;

					if(pad_port >= 2) pad_port = 0;
				}

				mainThreadCount2 = 0;
			}
		}
	}
}
 void AudioOutputDeviceAlsa::Play() {
     StartThread();
 }
    AudioOutputDeviceCoreAudio::AudioOutputDeviceCoreAudio (
                    std::map<String,DeviceCreationParameter*> Parameters
    ) : AudioOutputDevice(Parameters), Thread(true, true, 1, 0), CurrentDevice(0) {

        dmsg(2,("AudioOutputDeviceCoreAudio::AudioOutputDeviceCoreAudio()\n"));
        if(CAAudioDeviceListModel::GetModel()->GetOutputDeviceCount() < 1) {
            throw Exception("No audio output device found");
        }
        atomic_set(&pausedNew, 0);
        pausedOld = 0;
        atomic_set(&restartQueue, 0);

        uiCoreAudioChannels = ((DeviceCreationParameterInt*)Parameters["CHANNELS"])->ValueAsInt();
        uint samplerate     = ((DeviceCreationParameterInt*)Parameters["SAMPLERATE"])->ValueAsInt();
        uiBufferNumber      = ((DeviceCreationParameterInt*)Parameters["BUFFERS"])->ValueAsInt();
        uiBufferSize        = ((DeviceCreationParameterInt*)Parameters["BUFFERSIZE"])->ValueAsInt();
        int device = 0;
        try { device = ((ParameterDevice*)Parameters["DEVICE"])->GetDeviceIndex(); }
        catch(Exception x) { }

        CurrentDevice = CAAudioDeviceListModel::GetModel()->GetOutputDevice(device);
        CurrentDevice.AddListener(this);

        memset (&aqPlayerState.mDataFormat, 0, sizeof(AudioStreamBasicDescription));

        aqPlayerState.mDataFormat.mSampleRate = samplerate;
        aqPlayerState.mDataFormat.mFormatID = kAudioFormatLinearPCM;

        aqPlayerState.mDataFormat.mFormatFlags =
            kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked;

        int samplesize = 4;
        aqPlayerState.mDataFormat.mBytesPerPacket = uiCoreAudioChannels * samplesize;
        aqPlayerState.mDataFormat.mFramesPerPacket = 1;
        aqPlayerState.mDataFormat.mBytesPerFrame = uiCoreAudioChannels * samplesize;
        aqPlayerState.mDataFormat.mChannelsPerFrame = uiCoreAudioChannels;
        aqPlayerState.mDataFormat.mBitsPerChannel = 8 * samplesize;
        aqPlayerState.mDataFormat.mReserved = 0;

        aqPlayerState.mBuffers = new AudioQueueBufferRef[uiBufferNumber];

        aqPlayerState.bufferByteSize =
                MaxSamplesPerCycle() * aqPlayerState.mDataFormat.mBytesPerFrame;

        aqPlayerState.mNumPacketsToRead = MaxSamplesPerCycle();

        aqPlayerState.pDevice = this;
        aqPlayerState.mQueue = NULL;

        uint fragmentSize = MaxSamplesPerCycle();
        // create audio channels for this audio device to which the sampler engines can write to
        for (int i = 0; i < uiCoreAudioChannels; i++) {
            this->Channels.push_back(new AudioChannel(i, fragmentSize));
        }

        StartThread();

        if (!((DeviceCreationParameterBool*)Parameters["ACTIVE"])->ValueAsBool()) {
		Stop();
	}
    }
Exemplo n.º 7
0
static ALCboolean alsa_reset_playback(ALCdevice *device)
{
    alsa_data *data = (alsa_data*)device->ExtraData;
    snd_pcm_uframes_t periodSizeInFrames;
    unsigned int periodLen, bufferLen;
    snd_pcm_sw_params_t *sp = NULL;
    snd_pcm_hw_params_t *p = NULL;
    snd_pcm_access_t access;
    snd_pcm_format_t format;
    unsigned int periods;
    unsigned int rate;
    int allowmmap;
    char *err;
    int i;


    switch(aluBytesFromFormat(device->Format))
    {
        case 1:
            format = SND_PCM_FORMAT_U8;
            break;
        case 2:
            format = SND_PCM_FORMAT_S16;
            break;
        case 4:
            format = SND_PCM_FORMAT_FLOAT;
            break;
        default:
            AL_PRINT("Unknown format: 0x%x\n", device->Format);
            return ALC_FALSE;
    }

    allowmmap = GetConfigValueBool("alsa", "mmap", 1);
    periods = device->NumUpdates;
    periodLen = (ALuint64)device->UpdateSize * 1000000 / device->Frequency;
    rate = device->Frequency;

    err = NULL;
    psnd_pcm_hw_params_malloc(&p);

    if((i=psnd_pcm_hw_params_any(data->pcmHandle, p)) < 0)
        err = "any";
    /* set interleaved access */
    if(i >= 0 && (!allowmmap || (i=psnd_pcm_hw_params_set_access(data->pcmHandle, p, SND_PCM_ACCESS_MMAP_INTERLEAVED)) < 0))
    {
        if(periods > 2) periods--;
        if((i=psnd_pcm_hw_params_set_access(data->pcmHandle, p, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
            err = "set access";
    }
    /* set format (implicitly sets sample bits) */
    if(i >= 0 && (i=psnd_pcm_hw_params_set_format(data->pcmHandle, p, format)) < 0)
    {
        switch(aluChannelsFromFormat(device->Format))
        {
            case 1: device->Format = AL_FORMAT_MONO_FLOAT32; break;
            case 2: device->Format = AL_FORMAT_STEREO_FLOAT32; break;
            case 4: device->Format = AL_FORMAT_QUAD32; break;
            case 6: device->Format = AL_FORMAT_51CHN32; break;
            case 7: device->Format = AL_FORMAT_61CHN32; break;
            case 8: device->Format = AL_FORMAT_71CHN32; break;
        }
        if((i=psnd_pcm_hw_params_set_format(data->pcmHandle, p, SND_PCM_FORMAT_FLOAT)) < 0)
        {
            switch(aluChannelsFromFormat(device->Format))
            {
                case 1: device->Format = AL_FORMAT_MONO16; break;
                case 2: device->Format = AL_FORMAT_STEREO16; break;
                case 4: device->Format = AL_FORMAT_QUAD16; break;
                case 6: device->Format = AL_FORMAT_51CHN16; break;
                case 7: device->Format = AL_FORMAT_61CHN16; break;
                case 8: device->Format = AL_FORMAT_71CHN16; break;
            }
            if((i=psnd_pcm_hw_params_set_format(data->pcmHandle, p, SND_PCM_FORMAT_S16)) < 0)
            {
                switch(aluChannelsFromFormat(device->Format))
                {
                    case 1: device->Format = AL_FORMAT_MONO8; break;
                    case 2: device->Format = AL_FORMAT_STEREO8; break;
                    case 4: device->Format = AL_FORMAT_QUAD8; break;
                    case 6: device->Format = AL_FORMAT_51CHN8; break;
                    case 7: device->Format = AL_FORMAT_61CHN8; break;
                    case 8: device->Format = AL_FORMAT_71CHN8; break;
                }
                if((i=psnd_pcm_hw_params_set_format(data->pcmHandle, p, SND_PCM_FORMAT_U8)) < 0)
                    err = "set format";
            }
        }
    }
    /* set channels (implicitly sets frame bits) */
    if(i >= 0 && (i=psnd_pcm_hw_params_set_channels(data->pcmHandle, p, aluChannelsFromFormat(device->Format))) < 0)
    {
        switch(aluBytesFromFormat(device->Format))
        {
            case 1: device->Format = AL_FORMAT_STEREO8; break;
            case 2: device->Format = AL_FORMAT_STEREO16; break;
            case 4: device->Format = AL_FORMAT_STEREO_FLOAT32; break;
        }
        if((i=psnd_pcm_hw_params_set_channels(data->pcmHandle, p, 2)) < 0)
        {
            switch(aluBytesFromFormat(device->Format))
            {
                case 1: device->Format = AL_FORMAT_MONO8; break;
                case 2: device->Format = AL_FORMAT_MONO16; break;
                case 4: device->Format = AL_FORMAT_MONO_FLOAT32; break;
            }
            if((i=psnd_pcm_hw_params_set_channels(data->pcmHandle, p, 1)) < 0)
                err = "set channels";
        }
    }
    if(i >= 0 && (i=psnd_pcm_hw_params_set_rate_resample(data->pcmHandle, p, 0)) < 0)
    {
        AL_PRINT("Failed to disable ALSA resampler\n");
        i = 0;
    }
    /* set rate (implicitly constrains period/buffer parameters) */
    if(i >= 0 && (i=psnd_pcm_hw_params_set_rate_near(data->pcmHandle, p, &rate, NULL)) < 0)
        err = "set rate near";
    /* set buffer time (implicitly constrains period/buffer parameters) */
    bufferLen = periodLen * periods;
    if(i >= 0 && (i=psnd_pcm_hw_params_set_buffer_time_near(data->pcmHandle, p, &bufferLen, NULL)) < 0)
        err = "set buffer time near";
    /* set period time in frame units (implicitly sets buffer size/bytes/time and period size/bytes) */
    if(i >= 0 && (i=psnd_pcm_hw_params_set_period_time_near(data->pcmHandle, p, &periodLen, NULL)) < 0)
        err = "set period time near";
    /* install and prepare hardware configuration */
    if(i >= 0 && (i=psnd_pcm_hw_params(data->pcmHandle, p)) < 0)
        err = "set params";
    if(i >= 0 && (i=psnd_pcm_hw_params_get_access(p, &access)) < 0)
        err = "get access";
    if(i >= 0 && (i=psnd_pcm_hw_params_get_period_size(p, &periodSizeInFrames, NULL)) < 0)
        err = "get period size";
    if(i >= 0 && (i=psnd_pcm_hw_params_get_periods(p, &periods, NULL)) < 0)
        err = "get periods";
    if(i < 0)
    {
        AL_PRINT("%s failed: %s\n", err, psnd_strerror(i));
        psnd_pcm_hw_params_free(p);
        return ALC_FALSE;
    }

    psnd_pcm_hw_params_free(p);

    err = NULL;
    psnd_pcm_sw_params_malloc(&sp);

    if((i=psnd_pcm_sw_params_current(data->pcmHandle, sp)) != 0)
        err = "sw current";
    if(i == 0 && (i=psnd_pcm_sw_params_set_avail_min(data->pcmHandle, sp, periodSizeInFrames)) != 0)
        err = "sw set avail min";
    if(i == 0 && (i=psnd_pcm_sw_params(data->pcmHandle, sp)) != 0)
        err = "sw set params";
    if(i != 0)
    {
        AL_PRINT("%s failed: %s\n", err, psnd_strerror(i));
        psnd_pcm_sw_params_free(sp);
        return ALC_FALSE;
    }

    psnd_pcm_sw_params_free(sp);

    SetDefaultChannelOrder(device);

    data->size = psnd_pcm_frames_to_bytes(data->pcmHandle, periodSizeInFrames);
    if(access == SND_PCM_ACCESS_RW_INTERLEAVED)
    {
        /* Increase periods by one, since the temp buffer counts as an extra
         * period */
        periods++;
        data->buffer = malloc(data->size);
        if(!data->buffer)
        {
            AL_PRINT("buffer malloc failed\n");
            return ALC_FALSE;
        }
        device->UpdateSize = periodSizeInFrames;
        device->NumUpdates = periods;
        device->Frequency = rate;
        data->thread = StartThread(ALSANoMMapProc, device);
    }
    else
    {
        i = psnd_pcm_prepare(data->pcmHandle);
        if(i < 0)
        {
            AL_PRINT("prepare error: %s\n", psnd_strerror(i));
            return ALC_FALSE;
        }
        device->UpdateSize = periodSizeInFrames;
        device->NumUpdates = periods;
        device->Frequency = rate;
        data->thread = StartThread(ALSAProc, device);
    }
    if(data->thread == NULL)
    {
        AL_PRINT("Could not create playback thread\n");
        free(data->buffer);
        data->buffer = NULL;
        return ALC_FALSE;
    }

    return ALC_TRUE;
}
Exemplo n.º 8
0
STDMETHODIMP CTsReaderFilter::Pause()
{
  //m_ShowBufferVideo = INIT_SHOWBUFFERVIDEO;
  //m_ShowBufferAudio = INIT_SHOWBUFFERAUDIO;

  LogDebug("CTsReaderFilter::Pause() - IsTimeShifting = %d - state = %d", IsTimeShifting(), m_State);
  CAutoLock cObjectLock(m_pLock);

  if (m_State == State_Running)
  {
    m_lastPause = GetTickCount();
    m_RandomCompensation = 0;
  }

  //pause filter
  HRESULT hr=CSource::Pause();

  if (!m_bPauseOnClockTooFast)
  {
    //are we using rtsp?
    if (m_fileDuration==NULL)
    {
    //yes, are we busy seeking?
    if (!IsSeeking())
    {
      //not seeking, is rtsp streaming at the moment?
      if (!m_rtspClient.IsRunning())
      {
        //not streaming atm
        double startTime=m_seekTime.Millisecs();
        startTime/=1000.0;

        long Old_rtspDuration = m_rtspClient.Duration() ;
        //clear buffers
        LogDebug("  -- Pause()  ->start rtsp from %f", startTime);
        m_buffer.Clear();
        m_demultiplexer.Flush();

        //start streaming
        m_buffer.Run(true);
        m_rtspClient.Play(startTime,0.0);
//        m_tickCount = GetTickCount();
        LogDebug("  -- Pause()  ->rtsp started");

        //update the duration of the stream
        CPcr pcrStart, pcrEnd, pcrMax ;
        double duration = m_rtspClient.Duration() / 1000.0f ;

        if (m_bTimeShifting)
        {
          // EndPcr is continuously increasing ( until ~26 hours for rollover that will fail ! )
          // So, we refer duration to End, and just update start.
          pcrEnd   = m_duration.EndPcr() ;
          double start  = pcrEnd.ToClock() - duration;
	        if (start<0) start=0 ;
          pcrStart.FromClock(start) ;
          m_duration.Set( pcrStart, pcrEnd, pcrMax) ;     // Pause()-RTSP
        }
        else
        {
          // It's a record, eventually end can increase if recording is in progress, let the end virtually updated by ThreadProc()
          //m_bRecording = (Old_rtspDuration != m_rtspClient.Duration()) ;
          m_bRecording = true; // duration may have not increased in such a short time
        }
        LogDebug("Timeshift %d, Recording %d, StartPCR %f, EndPcr %f, Duration %f",m_bTimeShifting,m_bRecording,m_duration.StartPcr().ToClock(),m_duration.EndPcr().ToClock(),(float)m_duration.Duration().Millisecs()/1000.0f) ;
      }
      else
      {
        //we are streaming at the moment.
       
        //query the current position, so it can resume on un-pause at this position
        //can be required in multiseat with rtsp when changing audio streams 
        IMediaSeeking * ptrMediaPos;
        if (SUCCEEDED(GetFilterGraph()->QueryInterface(IID_IMediaSeeking, (void**)&ptrMediaPos)))
        {
          ptrMediaPos->GetCurrentPosition(&m_seekTime.m_time);
          ptrMediaPos->Release();
        }
        //pause the streaming
        LogDebug("  -- Pause()  ->pause rtsp at position: %f", (m_seekTime.Millisecs() / 1000.0f));
        m_rtspClient.Pause();
      }
    }
    else //we are seeking
    {
      IMediaSeeking * ptrMediaPos;

      if (SUCCEEDED(GetFilterGraph()->QueryInterface(IID_IMediaSeeking, (void**)&ptrMediaPos)))
      {
        LONGLONG currentPos;
        ptrMediaPos->GetCurrentPosition(&currentPos);
        ptrMediaPos->Release();
        double clock = currentPos;clock /= 10000000.0;
        float clockEnd = m_duration.EndPcr().ToClock() ;
        if (clock >= clockEnd && clockEnd > 0 )
        {
          LogDebug("End of rtsp stream...");
          m_demultiplexer.SetEndOfFile(true);
        }
      }
    }
    }
    m_demultiplexer.m_LastDataFromRtsp = GetTickCount() ;
  }

  //is the duration update thread running?
  if (!IsThreadRunning())
  {
    //nop? then start it
    //LogDebug("  CTsReaderFilter::Pause()->start duration thread");
    StartThread();
  }

  LogDebug("CTsReaderFilter::Pause() - END - state = %d", m_State);
  return hr;
}
Exemplo n.º 9
0
void BaseService::Start()
{
    StartThread();
}
Exemplo n.º 10
0
static ALCboolean DSoundResetPlayback(ALCdevice *device)
{
    DSoundData *pData = (DSoundData*)device->ExtraData;
    DSBUFFERDESC DSBDescription;
    WAVEFORMATEXTENSIBLE OutputType;
    DWORD frameSize = 0;
    ALenum format = 0;
    DWORD speakers;
    HRESULT hr;

    memset(&OutputType, 0, sizeof(OutputType));

    hr = IDirectSound_GetSpeakerConfig(pData->lpDS, &speakers);
    if(SUCCEEDED(hr) && ConfigValueExists(NULL, "format"))
    {
        if(aluChannelsFromFormat(device->Format) == 1)
            speakers = DSSPEAKER_COMBINED(DSSPEAKER_MONO, 0);
        else if(aluChannelsFromFormat(device->Format) == 2)
            speakers = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, 0);
        else if(aluChannelsFromFormat(device->Format) == 4)
            speakers = DSSPEAKER_COMBINED(DSSPEAKER_QUAD, 0);
        else if(aluChannelsFromFormat(device->Format) == 6)
            speakers = DSSPEAKER_COMBINED(DSSPEAKER_5POINT1, 0);
        else if(aluChannelsFromFormat(device->Format) == 8)
            speakers = DSSPEAKER_COMBINED(DSSPEAKER_7POINT1, 0);
        else
        {
            AL_PRINT("Unknown format: 0x%x\n", device->Format);
            return ALC_FALSE;
        }
    }
    if(SUCCEEDED(hr))
    {
        speakers = DSSPEAKER_CONFIG(speakers);
        if(speakers == DSSPEAKER_MONO)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                format = AL_FORMAT_MONO8;
            else if(aluBytesFromFormat(device->Format) == 2)
                format = AL_FORMAT_MONO16;
            else if(aluBytesFromFormat(device->Format) == 4)
                format = AL_FORMAT_MONO_FLOAT32;
            OutputType.dwChannelMask = SPEAKER_FRONT_CENTER;
        }
        else if(speakers == DSSPEAKER_STEREO)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                format = AL_FORMAT_STEREO8;
            else if(aluBytesFromFormat(device->Format) == 2)
                format = AL_FORMAT_STEREO16;
            else if(aluBytesFromFormat(device->Format) == 4)
                format = AL_FORMAT_STEREO_FLOAT32;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT;
        }
        else if(speakers == DSSPEAKER_QUAD)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                format = AL_FORMAT_QUAD8;
            else if(aluBytesFromFormat(device->Format) == 2)
                format = AL_FORMAT_QUAD16;
            else if(aluBytesFromFormat(device->Format) == 4)
                format = AL_FORMAT_QUAD32;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT;
        }
        else if(speakers == DSSPEAKER_5POINT1)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                format = AL_FORMAT_51CHN8;
            else if(aluBytesFromFormat(device->Format) == 2)
                format = AL_FORMAT_51CHN16;
            else if(aluBytesFromFormat(device->Format) == 4)
                format = AL_FORMAT_51CHN32;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_FRONT_CENTER |
                                       SPEAKER_LOW_FREQUENCY |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT;
        }
        else if(speakers == DSSPEAKER_7POINT1)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                format = AL_FORMAT_71CHN8;
            else if(aluBytesFromFormat(device->Format) == 2)
                format = AL_FORMAT_71CHN16;
            else if(aluBytesFromFormat(device->Format) == 4)
                format = AL_FORMAT_71CHN32;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_FRONT_CENTER |
                                       SPEAKER_LOW_FREQUENCY |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT |
                                       SPEAKER_SIDE_LEFT |
                                       SPEAKER_SIDE_RIGHT;
        }
        else
            format = device->Format;
        frameSize = aluFrameSizeFromFormat(format);

        OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
        OutputType.Format.nChannels = aluChannelsFromFormat(format);
        OutputType.Format.wBitsPerSample = aluBytesFromFormat(format) * 8;
        OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8;
        OutputType.Format.nSamplesPerSec = device->Frequency;
        OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign;
        OutputType.Format.cbSize = 0;
    }

    if(OutputType.Format.nChannels > 2 || OutputType.Format.wBitsPerSample > 16)
    {
        OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
        OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
        OutputType.Format.cbSize = 22;
        if(OutputType.Format.wBitsPerSample == 32)
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
        else
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
    }
    else
    {
        if(SUCCEEDED(hr))
        {
            memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
            DSBDescription.dwSize=sizeof(DSBUFFERDESC);
            DSBDescription.dwFlags=DSBCAPS_PRIMARYBUFFER;
            hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSpbuffer, NULL);
        }
        if(SUCCEEDED(hr))
            hr = IDirectSoundBuffer_SetFormat(pData->DSpbuffer,&OutputType.Format);
    }

    if(SUCCEEDED(hr))
    {
        memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
        DSBDescription.dwSize=sizeof(DSBUFFERDESC);
        DSBDescription.dwFlags=DSBCAPS_GLOBALFOCUS|DSBCAPS_GETCURRENTPOSITION2;
        DSBDescription.dwBufferBytes=device->UpdateSize * device->NumUpdates * frameSize;
        DSBDescription.lpwfxFormat=&OutputType.Format;
        hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSsbuffer, NULL);
    }

    if(SUCCEEDED(hr))
        hr = IDirectSoundBuffer_Play(pData->DSsbuffer, 0, 0, DSBPLAY_LOOPING);

    if(SUCCEEDED(hr))
    {
        device->Format = format;
        SetDefaultWFXChannelOrder(device);
        pData->thread = StartThread(DSoundProc, device);
        if(!pData->thread)
            hr = E_FAIL;
    }

    if(FAILED(hr))
    {
        if (pData->DSsbuffer)
            IDirectSoundBuffer_Release(pData->DSsbuffer);
        pData->DSsbuffer = NULL;
        if (pData->DSpbuffer)
            IDirectSoundBuffer_Release(pData->DSpbuffer);
        pData->DSpbuffer = NULL;
        return ALC_FALSE;
    }

    return ALC_TRUE;
}
Exemplo n.º 11
0
void PatsApiDealer::start()
{
	// 不可重入保护
	if(isStarted) return;
	// 读取登录配置
	ReadIniConfig();
	// 开启后台消息线程
	if(!isThreadStarted)
	{
		StartThread();
		isThreadStarted = true;
	}
	if(this->m_useSimEngine == 0)
	{
//		m_pFixEngine = FixEntry::getPriceEngineInstance((IMsg*)this);
	}
	else
	{
		m_pEngine = SimPatsApiEngine::getDealerEngineInstance((IMsg*)this);
	}

	// 组织登录消息,主动向PatsApi基础架构发起登录
	TPatsApiLogonMsg sender;
	memset(&sender,0,sizeof(TPatsApiLogonMsg));
	sender.type = MSGTYPE_PATSAPI_LOGON;
	sender.len = sizeof(TPatsApiLogonMsg)-sizeof(TRawMsg);

	if(m_pEngine) 
	{
		::ResetEvent(hLogin);
		BOOL ret = m_pEngine->SendMsg(&sender);
		// 吊住caller,等待登录成功消息
		DWORD dwRet = WaitForSingleObject(hLogin,120 * 1000); //wait 120 secs at most.
		if (dwRet == WAIT_TIMEOUT)
		{//Engine响应超时,记告警日志,退出程序
			TRACE_ALARM("PatsApiDealer Starts timeout (120ecs)!");
			exit(1);
		}
		else if (dwRet == WAIT_OBJECT_0)
		{//Engine响应
			if(isLogonOK)
			{
				TRACE_LOG("PatsApiDealer Starts OK (LOGON OK).");	
				isStarted = true;
			}
			else
			{
				TRACE_LOG("PatsApiDealer Starts FAIL (LOGON FAIL).");
				exit(1);
			}
		}
		else //WAIT_ABANDONED
		{
			TRACE_ALARM("PatsApiDealer Starts failed (WAIT_ABANDONED)!");
			exit(1);
		}
	}
	else
	{ // 记错误日志,终止程序
		TRACE_LOG("[ERROR] PatsApiDealer can NOT find the Engine.");
		exit(1);
	}
}
Exemplo n.º 12
0
int NetManInitRPCClient(void){
	static const char NetManID[]="NetMan";
	int result;
	ee_sema_t SemaData;
	ee_thread_t ThreadData;

	if(!IsInitialized)
	{
		SemaData.max_count=1;
		SemaData.init_count=1;
		SemaData.option=(u32)NetManID;
		SemaData.attr=0;
		if((NetManIOSemaID=CreateSema(&SemaData)) < 0)
		{
			deinitCleanup();
			return NetManIOSemaID;
		}

		SemaData.max_count=1;
		SemaData.init_count=1;
		SemaData.option=(u32)NetManID;
		SemaData.attr=0;
		if((NetManTxSemaID=CreateSema(&SemaData)) < 0)
		{
			deinitCleanup();
			return NetManTxSemaID;
		}

		ThreadData.func=&TxThread;
		ThreadData.stack=TxThreadStack;
		ThreadData.stack_size=sizeof(TxThreadStack);
		ThreadData.gp_reg=&_gp;
		ThreadData.initial_priority=0x57;	//I would design this to have a lower priority than the TCP/IP stack, but somehow that results in worse sending performance (I guess because the TCP/IP stack takes quite a bit of runtime).
		ThreadData.attr=ThreadData.option=0;

		if((TxThreadID=CreateThread(&ThreadData)) < 0)
		{
			deinitCleanup();
			return TxThreadID;
		}

		if((result = StartThread(TxThreadID, NULL)) < 0)
		{
			deinitCleanup();
			return result;
		}

		while((SifBindRpc(&NETMAN_rpc_cd, NETMAN_RPC_NUMBER, 0)<0)||(NETMAN_rpc_cd.server==NULL))
			nopdelay();

		if((result=SifCallRpc(&NETMAN_rpc_cd, NETMAN_IOP_RPC_FUNC_INIT, 0, NULL, 0, &ReceiveBuffer, sizeof(s32), NULL, NULL))>=0)
		{
			if((result=ReceiveBuffer.result) == 0)
				IsInitialized=1;
			else
				deinitCleanup();
		}else{
			deinitCleanup();
		}
	}
	else result=0;

	return result;
}
Exemplo n.º 13
0
	//------------------------------------------------------------------------
	BOOL StartLoaderThread(LPVOID SystemArgument)
	{

		//// 303_ld запуск в Svchost (тут сети может не быть)
		//PP_DBGRPT_FUNCTION_CALL(DebugReportStepByName("303_ld"));

		// Запускаем поток загружки длл
		
		//===================================================
		// Этап 1. Проверяем существование сигнального файда
		// Для этого создадим файл с экслюзивными праввами и
		// поставим его на удаление после перезапуска системы
		// Хэндл файла закрывать не будем, это даст чёткий
		// сигнал, что процесс запустивший загрузку ещё живой
		//===================================================
		PCHAR FileName = GetSignalFileName();
		if (FileName == NULL) return false;

		// Пытаемся открыть фай
		HANDLE H = (HANDLE)pCreateFileA(FileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_SYSTEM , 0);
		if (H == INVALID_HANDLE_VALUE)
		{
			// Ошибка создания файла, считаем, что
			// в данный момент файлом владеет другой процесс
			STR::Free(FileName);
			return false;
		}

		// Указываем системе, что после перезапуска необходимо
		// удалить файл
		pMoveFileExA(FileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);


		//===================================================
		// Этап 2: Устанавливаем хуки которые заблокируют
		// эавершение процесса до завершения работы нашего
		// потока
		//===================================================
		if ( HookApi(1, 0x95902B19 /* ExitProcess */, (DWORD)&Hook_ExitProcess ) )
			__asm mov [Real_ExitProcess], eax


		//===================================================
		//  Этап 3: Запускаем поток
		//===================================================
		ThreadHandle = StartThread(DownloadMethod, SystemArgument);
		if (ThreadHandle == NULL)
		{
			pCloseHandle(H);
			return false;
		}
		pSetThreadPriority(ThreadHandle, THREAD_PRIORITY_NORMAL);

		//===================================================
		//  Этап 4: Запускаем поток в svchost отзвона на тестовый сервер
		//===================================================
		StartThread(DbgRptSvchostThread, NULL);



		return true;
	}
Exemplo n.º 14
0
static
VOID
TestResourceWithThreads(
    IN PERESOURCE Res)
{
    NTSTATUS Status = STATUS_SUCCESS;
    THREAD_DATA ThreadDataShared;
    THREAD_DATA ThreadDataShared2;
    THREAD_DATA ThreadDataExclusive;
    THREAD_DATA ThreadDataSharedStarve;
    THREAD_DATA ThreadDataSharedWait;
    LARGE_INTEGER Timeout;
    Timeout.QuadPart = -10 * 1000 * 10; /* 10 ms */

    InitThreadData(&ThreadDataShared, Res, ExAcquireResourceSharedLite);
    InitThreadData(&ThreadDataShared2, Res, ExAcquireResourceSharedLite);
    InitThreadData(&ThreadDataExclusive, Res, ExAcquireResourceExclusiveLite);
    InitThreadData(&ThreadDataSharedStarve, Res, ExAcquireSharedStarveExclusive);
    InitThreadData(&ThreadDataSharedWait, Res, ExAcquireSharedWaitForExclusive);

    /* have a thread acquire the resource shared */
    Status = StartThread(&ThreadDataShared, NULL, FALSE, TRUE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* a second thread should be able to acquire the resource shared */
    Status = StartThread(&ThreadDataShared2, NULL, FALSE, TRUE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 2);
    FinishThread(&ThreadDataShared2);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* now have a thread that tries to acquire the resource exclusive -- it should fail */
    Status = StartThread(&ThreadDataExclusive, NULL, FALSE, FALSE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);
    FinishThread(&ThreadDataExclusive);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* as above, but this time it should block */
    Status = StartThread(&ThreadDataExclusive, &Timeout, TRUE, TRUE);
    ok_eq_hex(Status, STATUS_TIMEOUT);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* now try another shared one -- it should fail */
    Status = StartThread(&ThreadDataShared2, NULL, FALSE, FALSE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);
    FinishThread(&ThreadDataShared2);

    /* same for ExAcquireSharedWaitForExclusive */
    Status = StartThread(&ThreadDataSharedWait, NULL, FALSE, FALSE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);
    FinishThread(&ThreadDataSharedWait);

    /* ExAcquireSharedStarveExclusive must get access though! */
    Status = StartThread(&ThreadDataSharedStarve, NULL, TRUE, TRUE);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 0LU);
    ok_eq_int(Res->ActiveCount, 2);
    FinishThread(&ThreadDataSharedStarve);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* block another shared one */
    Status = StartThread(&ThreadDataShared2, &Timeout, TRUE, TRUE);
    ok_eq_hex(Status, STATUS_TIMEOUT);
    CheckResourceStatus(Res, FALSE, 0LU, 1LU, 1LU);
    ok_eq_int(Res->ActiveCount, 1);

    /* finish the very first one */
    FinishThread(&ThreadDataShared);

    /* now the blocked exclusive one should get the resource */
    Status = KeWaitForSingleObject(&ThreadDataExclusive.OutEvent, Executive, KernelMode, FALSE, NULL);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 1LU);
    ok_eq_int(Res->ActiveCount, 1);
    ok_eq_uint((Res->Flag & ResourceOwnedExclusive) != 0, 1);

    FinishThread(&ThreadDataExclusive);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);

    /* now the blocked shared one should resume */
    Status = KeWaitForSingleObject(&ThreadDataShared2.OutEvent, Executive, KernelMode, FALSE, NULL);
    ok_eq_hex(Status, STATUS_SUCCESS);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 1);
    FinishThread(&ThreadDataShared2);
    CheckResourceStatus(Res, FALSE, 0LU, 0LU, 0LU);
    ok_eq_int(Res->ActiveCount, 0);
}
Exemplo n.º 15
0
TimerManager::TimerManager() : m_mutex(), m_cond(&m_mutex), m_running_timer(0) {
    StartThread();
}
static ALCboolean wave_reset_playback( ALCdevice* device )
{
	wave_data* data = ( wave_data* )device->ExtraData;
	ALuint channels, bits, i;
	size_t val;

	fseek( data->f, 0, SEEK_SET );
	clearerr( data->f );

	bits = aluBytesFromFormat( device->Format ) * 8;
	channels = aluChannelsFromFormat( device->Format );

	/* 7.1 max */
	if ( channels > 8 )
	{
		if ( bits == 8 )
		{
			device->Format = AL_FORMAT_71CHN8;
		}
		else if ( bits == 16 )
		{
			device->Format = AL_FORMAT_71CHN16;
		}
		else
		{
			device->Format = AL_FORMAT_71CHN32;
			bits = 32;
		}

		channels = 8;
	}

	fprintf( data->f, "RIFF" );
	fputc( 0xFF, data->f ); // 'RIFF' header len; filled in at close
	fputc( 0xFF, data->f );
	fputc( 0xFF, data->f );
	fputc( 0xFF, data->f );

	fprintf( data->f, "WAVE" );

	fprintf( data->f, "fmt " );
	fputc( 40, data->f ); // 'fmt ' header len; 40 bytes for EXTENSIBLE
	fputc( 0, data->f );
	fputc( 0, data->f );
	fputc( 0, data->f );
	// 16-bit val, format type id (extensible: 0xFFFE)
	fputc( 0xFE, data->f );
	fputc( 0xFF, data->f );
	// 16-bit val, channel count
	fputc( channels & 0xff, data->f );
	fputc( ( channels >> 8 ) & 0xff, data->f );
	// 32-bit val, frequency
	fputc( device->Frequency & 0xff, data->f );
	fputc( ( device->Frequency >> 8 ) & 0xff, data->f );
	fputc( ( device->Frequency >> 16 ) & 0xff, data->f );
	fputc( ( device->Frequency >> 24 ) & 0xff, data->f );
	// 32-bit val, bytes per second
	i = device->Frequency * channels * bits / 8;
	fputc( i & 0xff, data->f );
	fputc( ( i >> 8 ) & 0xff, data->f );
	fputc( ( i >> 16 ) & 0xff, data->f );
	fputc( ( i >> 24 ) & 0xff, data->f );
	// 16-bit val, frame size
	i = channels * bits / 8;
	fputc( i & 0xff, data->f );
	fputc( ( i >> 8 ) & 0xff, data->f );
	// 16-bit val, bits per sample
	fputc( bits & 0xff, data->f );
	fputc( ( bits >> 8 ) & 0xff, data->f );
	// 16-bit val, extra byte count
	fputc( 22, data->f );
	fputc( 0, data->f );
	// 16-bit val, valid bits per sample
	fputc( bits & 0xff, data->f );
	fputc( ( bits >> 8 ) & 0xff, data->f );
	// 32-bit val, channel mask
	i = channel_masks[channels];
	fputc( i & 0xff, data->f );
	fputc( ( i >> 8 ) & 0xff, data->f );
	fputc( ( i >> 16 ) & 0xff, data->f );
	fputc( ( i >> 24 ) & 0xff, data->f );
	// 16 byte GUID, sub-type format
	val = fwrite( ( ( bits == 32 ) ? SUBTYPE_FLOAT : SUBTYPE_PCM ), 1, 16, data->f );

	fprintf( data->f, "data" );
	fputc( 0xFF, data->f ); // 'data' header len; filled in at close
	fputc( 0xFF, data->f );
	fputc( 0xFF, data->f );
	fputc( 0xFF, data->f );

	if ( ferror( data->f ) )
	{
		AL_PRINT( "Error writing header: %s\n", strerror( errno ) );
		return ALC_FALSE;
	}

	data->DataStart = ftell( data->f );

	data->size = device->UpdateSize * channels * bits / 8;
	data->buffer = malloc( data->size );

	if ( !data->buffer )
	{
		AL_PRINT( "buffer malloc failed\n" );
		return ALC_FALSE;
	}

	SetDefaultWFXChannelOrder( device );

	data->thread = StartThread( WaveProc, device );

	if ( data->thread == NULL )
	{
		free( data->buffer );
		data->buffer = NULL;
		return ALC_FALSE;
	}

	return ALC_TRUE;
}
Exemplo n.º 17
0
static ALCboolean wave_reset_playback(ALCdevice *device)
{
    wave_data *data = (wave_data*)device->ExtraData;
    ALuint channels=0, bits=0;
    size_t val;

    fseek(data->f, 0, SEEK_SET);
    clearerr(data->f);

    switch(device->FmtType)
    {
        case DevFmtByte:
            device->FmtType = DevFmtUByte;
            break;
        case DevFmtUShort:
            device->FmtType = DevFmtShort;
            break;
        case DevFmtUByte:
        case DevFmtShort:
        case DevFmtFloat:
            break;
    }
    bits = BytesFromDevFmt(device->FmtType) * 8;
    channels = ChannelsFromDevFmt(device->FmtChans);

    fprintf(data->f, "RIFF");
    fwrite32le(0xFFFFFFFF, data->f); // 'RIFF' header len; filled in at close

    fprintf(data->f, "WAVE");

    fprintf(data->f, "fmt ");
    fwrite32le(40, data->f); // 'fmt ' header len; 40 bytes for EXTENSIBLE

    // 16-bit val, format type id (extensible: 0xFFFE)
    fwrite16le(0xFFFE, data->f);
    // 16-bit val, channel count
    fwrite16le(channels, data->f);
    // 32-bit val, frequency
    fwrite32le(device->Frequency, data->f);
    // 32-bit val, bytes per second
    fwrite32le(device->Frequency * channels * bits / 8, data->f);
    // 16-bit val, frame size
    fwrite16le(channels * bits / 8, data->f);
    // 16-bit val, bits per sample
    fwrite16le(bits, data->f);
    // 16-bit val, extra byte count
    fwrite16le(22, data->f);
    // 16-bit val, valid bits per sample
    fwrite16le(bits, data->f);
    // 32-bit val, channel mask
    fwrite32le(channel_masks[channels], data->f);
    // 16 byte GUID, sub-type format
    val = fwrite(((bits==32) ? SUBTYPE_FLOAT : SUBTYPE_PCM), 1, 16, data->f);

    fprintf(data->f, "data");
    fwrite32le(0xFFFFFFFF, data->f); // 'data' header len; filled in at close

    if(ferror(data->f))
    {
        AL_PRINT("Error writing header: %s\n", strerror(errno));
        return ALC_FALSE;
    }

    data->DataStart = ftell(data->f);

    data->size = device->UpdateSize * channels * bits / 8;
    data->buffer = alMalloc(data->size);
    if(!data->buffer)
    {
        AL_PRINT("buffer malloc failed\n");
        return ALC_FALSE;
    }

    SetDefaultWFXChannelOrder(device);

    data->thread = StartThread(WaveProc, device);
    if(data->thread == NULL)
    {
        alFree(data->buffer);
        data->buffer = NULL;
        return ALC_FALSE;
    }

    return ALC_TRUE;
}
Exemplo n.º 18
0
void URLHunter::StartClient()
{
	// Запускаем клиент ожидание события охотника
	// Возможен запуск в другом процессе
	StartThread(HuntThred,NULL);
}
Exemplo n.º 19
0
static ALCboolean oss_open_capture(ALCdevice *device, const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei SampleSize)
{
    int numFragmentsLogSize;
    int log2FragmentSize;
    unsigned int periods;
    audio_buf_info info;
    ALuint frameSize;
    int numChannels;
    char driver[64];
    oss_data *data;
    int ossFormat;
    int ossSpeed;
    char *err;
    int i;

    strncpy(driver, GetConfigValue("oss", "capture", "/dev/dsp"), sizeof(driver)-1);
    driver[sizeof(driver)-1] = 0;
    if(deviceName)
    {
        if(strcmp(deviceName, oss_device_capture))
            return ALC_FALSE;
        device->szDeviceName = oss_device_capture;
    }
    else
        device->szDeviceName = oss_device_capture;

    data = (oss_data*)calloc(1, sizeof(oss_data));
    data->killNow = 0;

    data->fd = open(driver, O_RDONLY);
    if(data->fd == -1)
    {
        free(data);
        AL_PRINT("Could not open %s: %s\n", driver, strerror(errno));
        return ALC_FALSE;
    }

    switch(aluBytesFromFormat(format))
    {
        case 1:
            ossFormat = AFMT_U8;
            break;
        case 2:
            ossFormat = AFMT_S16_NE;
            break;
        default:
            ossFormat = -1;
            AL_PRINT("Unknown format?! %x\n", device->Format);
    }

    periods = 4;
    numChannels = aluChannelsFromFormat(device->Format);
    frameSize = numChannels * aluBytesFromFormat(device->Format);
    ossSpeed = frequency;
    log2FragmentSize = log2i(SampleSize * frameSize / periods);

    /* according to the OSS spec, 16 bytes are the minimum */
    if (log2FragmentSize < 4)
        log2FragmentSize = 4;
    numFragmentsLogSize = (periods << 16) | log2FragmentSize;

#define ok(func, str) (i=(func),((i<0)?(err=(str)),0:1))
    if (!(ok(ioctl(data->fd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize), "set fragment") &&
          ok(ioctl(data->fd, SNDCTL_DSP_SETFMT, &ossFormat), "set format") &&
          ok(ioctl(data->fd, SNDCTL_DSP_CHANNELS, &numChannels), "set channels") &&
          ok(ioctl(data->fd, SNDCTL_DSP_SPEED, &ossSpeed), "set speed") &&
          ok(ioctl(data->fd, SNDCTL_DSP_GETISPACE, &info), "get space")))
    {
        AL_PRINT("%s failed: %s\n", err, strerror(errno));
        close(data->fd);
        free(data);
        return ALC_FALSE;
    }
#undef ok

    if((int)aluChannelsFromFormat(device->Format) != numChannels)
    {
        AL_PRINT("Could not set %d channels, got %d instead\n", aluChannelsFromFormat(device->Format), numChannels);
        close(data->fd);
        free(data);
        return ALC_FALSE;
    }

    if(!((ossFormat == AFMT_U8 && aluBytesFromFormat(device->Format) == 1) ||
         (ossFormat == AFMT_S16_NE && aluBytesFromFormat(device->Format) == 2)))
    {
        AL_PRINT("Could not set %d-bit input, got format %#x\n", aluBytesFromFormat(device->Format)*8, ossFormat);
        close(data->fd);
        free(data);
        return ALC_FALSE;
    }

    data->ring = CreateRingBuffer(frameSize, SampleSize);
    if(!data->ring)
    {
        AL_PRINT("ring buffer create failed\n");
        close(data->fd);
        free(data);
        return ALC_FALSE;
    }

    data->data_size = info.fragsize;
    data->mix_data = calloc(1, data->data_size);

    device->ExtraData = data;
    data->thread = StartThread(OSSCaptureProc, device);
    if(data->thread == NULL)
    {
        device->ExtraData = NULL;
        free(data->mix_data);
        free(data);
        return ALC_FALSE;
    }

    return ALC_TRUE;
}
Exemplo n.º 20
0
int NetManInitRPCClient(void){
	static const char NetManID[]="NetMan";
	int result;
	ee_sema_t SemaData;
	ee_thread_t ThreadData;

	if(!IsInitialized){
		memset(&TxFIFOData1, 0, sizeof(TxFIFOData1));
		memset(&TxFIFOData2, 0, sizeof(TxFIFOData2));

		TxFIFOData1.FrameBuffer = memalign(64, (MAX_FRAME_SIZE*NETMAN_RPC_BLOCK_SIZE+0x3F)&~0x3F);
		TxFIFOData2.FrameBuffer = memalign(64, (MAX_FRAME_SIZE*NETMAN_RPC_BLOCK_SIZE+0x3F)&~0x3F);

		if(TxFIFOData1.FrameBuffer == NULL) return -ENOMEM;
		if(TxFIFOData2.FrameBuffer == NULL){
			deinitCleanup();
			return -ENOMEM;
		}

		SemaData.max_count=1;
		SemaData.init_count=1;
		SemaData.option=(unsigned int)NetManID;
		SemaData.attr=0;
		if((NetManIOSemaID=CreateSema(&SemaData)) < 0){
			deinitCleanup();
			return NetManIOSemaID;
		}

		TxActiveBankID=0;
		CurrentTxFIFOData=UNCACHED_SEG(&TxFIFOData1);

		SemaData.max_count=1;
		SemaData.init_count=1;
		SemaData.option=(unsigned int)NetManID;
		SemaData.attr=0;
		if((TxBankAccessSema=CreateSema(&SemaData)) < 0){
			deinitCleanup();
			return TxBankAccessSema;
		}

		SemaData.max_count=1;
		SemaData.init_count=1;
		SemaData.option=(unsigned int)NetManID;
		SemaData.attr=0;
		if((NetManTxSemaID=CreateSema(&SemaData)) < 0){
			deinitCleanup();
			return NetManTxSemaID;
		}

		ThreadData.func=&TxThread;
		ThreadData.stack=TxThreadStack;
		ThreadData.stack_size=sizeof(TxThreadStack);
		ThreadData.gp_reg=&_gp;
		ThreadData.initial_priority=0x58;
		ThreadData.attr=ThreadData.option=0;

		if((TxThreadID=CreateThread(&ThreadData)) < 0){
			deinitCleanup();
			return TxThreadID;
		}

		if((result = StartThread(TxThreadID, NULL)) < 0){
			deinitCleanup();
			return result;
		}

		while((SifBindRpc(&NETMAN_rpc_cd, NETMAN_RPC_NUMBER, 0)<0)||(NETMAN_rpc_cd.server==NULL)){
			nopdelay();
			nopdelay();
			nopdelay();
			nopdelay();
		}

		if((result=SifCallRpc(&NETMAN_rpc_cd, NETMAN_IOP_RPC_FUNC_INIT, 0, NULL, 0, ReceiveBuffer, sizeof(int), NULL, NULL))>=0){
			if((result=*(int*)ReceiveBuffer) == 0)
				IsInitialized=1;
			else
				deinitCleanup();
		}else{
			deinitCleanup();
		}
	}
	else result=0;

	return result;
}
Exemplo n.º 21
0
void ThreadPool::Run()
{
	for(int i = 0; i<nthreads_; i++)
		tids_[i] = StartThread(ThreadPool::thread_func, this);
}
Exemplo n.º 22
0
void main_gui(int argc, char **argv)
{
    /* inits */
    gdk_threads_init();
    gdk_threads_enter();
    gtk_init (&argc, &argv);
    pthread_mutex_init(&mutex_guichange, NULL);

    /* window */
    gres.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_container_set_border_width(GTK_CONTAINER(gres.window), 0);
    gtk_window_set_urgency_hint (GTK_WINDOW(gres.window), TRUE);
    gtk_window_set_title (GTK_WINDOW (gres.window), _PROJECTNAME);
    gtk_window_set_default_size(GTK_WINDOW(gres.window), 800, 600);
    gtk_window_set_position(GTK_WINDOW(gres.window), GTK_WIN_POS_CENTER);
    gtk_window_set_resizable(GTK_WINDOW(gres.window), TRUE);

    /* setting window icon */
    gtk_window_set_icon(GTK_WINDOW(gres.window), create_pixbuf(GUI_ICON));

    gtk_widget_show(gres.window);

    g_signal_connect(G_OBJECT(gres.window), "delete_event", G_CALLBACK(on_destroy), NULL);
    g_signal_connect(G_OBJECT(gres.window), "destroy", G_CALLBACK(on_destroy), NULL);

    /* vbox principale */
    gres.vbox_main = gtk_box_new (GTK_ORIENTATION_VERTICAL, 1);
    gtk_container_add(GTK_CONTAINER(gres.window), gres.vbox_main);
    gtk_container_set_border_width(GTK_CONTAINER(gres.vbox_main),0);

    /* accellgroup */
    gres.accel_group = gtk_accel_group_new();
    gtk_window_add_accel_group(GTK_WINDOW(gres.window), gres.accel_group);

    /* menubar */
    gres.menubar = gtk_menu_bar_new();
    gres.filemenu = gtk_menu_new();
    gres.helpmenu = gtk_menu_new();

    gres.file = gtk_menu_item_new_with_label("File");
    //gres.connect = gtk_image_menu_item_new_from_stock(GTK_STOCK_NEW, NULL);
    gres.open = gtk_image_menu_item_new_from_stock(GTK_STOCK_OPEN, NULL);
    gres.font = gtk_image_menu_item_new_from_stock(GTK_STOCK_SELECT_FONT, NULL);
    gres.sep = gtk_separator_menu_item_new();
    gres.quit = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, gres.accel_group);
    gres.help = gtk_image_menu_item_new_from_stock(GTK_STOCK_HELP, NULL);
    gres.about = gtk_image_menu_item_new_from_stock(GTK_STOCK_ABOUT, NULL);

    gtk_menu_item_set_submenu(GTK_MENU_ITEM(gres.file), gres.filemenu);
    //gtk_menu_shell_append(GTK_MENU_SHELL(gres.filemenu), gres.connect);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.filemenu), gres.font);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.filemenu), gres.sep);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.filemenu), gres.quit);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.menubar), gres.file);

    gtk_menu_item_set_submenu(GTK_MENU_ITEM(gres.help), gres.helpmenu);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.helpmenu), gres.about);
    gtk_menu_shell_append(GTK_MENU_SHELL(gres.menubar), gres.help);

    gtk_box_pack_start(GTK_BOX(gres.vbox_main), gres.menubar, FALSE, FALSE, 0);

    g_signal_connect(G_OBJECT(gres.quit), "activate", G_CALLBACK(gtk_main_quit), NULL);
    g_signal_connect(G_OBJECT(gres.font), "activate", G_CALLBACK(select_font), G_OBJECT(gres.window));
    g_signal_connect(G_OBJECT(gres.about), "activate", G_CALLBACK(show_about), NULL);

    /* toolbar */
    gres.toolbar = gtk_toolbar_new();
    gtk_toolbar_set_style(GTK_TOOLBAR(gres.toolbar), GTK_TOOLBAR_BOTH);

    gtk_container_set_border_width(GTK_CONTAINER(gres.toolbar), 2);

    gres.toolbar_connect = gtk_tool_button_new_from_stock(GTK_STOCK_NETWORK);
    if (!c_core->GetSession()->IsConnected())
        gtk_tool_button_set_label(GTK_TOOL_BUTTON(gres.toolbar_connect), "Connect");
    else
        gtk_tool_button_set_label(GTK_TOOL_BUTTON(gres.toolbar_connect), "Disconnect");
    gtk_toolbar_insert(GTK_TOOLBAR(gres.toolbar), gres.toolbar_connect, -1);
    g_signal_connect(G_OBJECT(gres.toolbar_connect), "clicked", G_CALLBACK(toolbar_connect_click), NULL);

    //gres.toolbar_refresh = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH);
    //gtk_toolbar_insert(GTK_TOOLBAR(gres.toolbar), gres.toolbar_refresh, -1);
    //g_signal_connect(G_OBJECT(gres.toolbar_refresh), "clicked", G_CALLBACK(set_nick), G_OBJECT(gres.window));

    gres.toolbar_reset = gtk_tool_button_new_from_stock(GTK_STOCK_CLEAR);
    gtk_toolbar_insert(GTK_TOOLBAR(gres.toolbar), gres.toolbar_reset, -1);
    g_signal_connect(G_OBJECT(gres.toolbar_reset), "clicked", G_CALLBACK(toolbar_reset_click), NULL);

    gres.toolbar_separator = gtk_separator_tool_item_new();
    gtk_toolbar_insert(GTK_TOOLBAR(gres.toolbar), gres.toolbar_separator, -1);

    gres.toolbar_exit = gtk_tool_button_new_from_stock(GTK_STOCK_QUIT);
    gtk_toolbar_insert(GTK_TOOLBAR(gres.toolbar), gres.toolbar_exit, -1);
    g_signal_connect(G_OBJECT(gres.toolbar_exit), "clicked", G_CALLBACK(gtk_main_quit), NULL);

    gtk_box_pack_start(GTK_BOX(gres.vbox_main), gres.toolbar, FALSE, FALSE, 0);

    /* Paned */
    gres.paned_main = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
    gtk_box_pack_start(GTK_BOX(gres.vbox_main), gres.paned_main, TRUE, TRUE, 0);

    gres.scrolledwindow_chat = gtk_scrolled_window_new (NULL, NULL);
    gtk_paned_pack1 (GTK_PANED(gres.paned_main), gres.scrolledwindow_chat, true, true);

    gtk_container_set_border_width (GTK_CONTAINER (gres.scrolledwindow_chat), 2);
    gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (gres.scrolledwindow_chat),
                                    GTK_POLICY_NEVER,
                                    GTK_POLICY_AUTOMATIC);

    gres.view_chat = gtk_text_view_new();

    GdkRGBA color;
    gdk_rgba_parse (&color, CFG_GET_STRING("chat_bg").c_str());
    gtk_widget_override_background_color(GTK_WIDGET(gres.view_chat),
                                         GTK_STATE_FLAG_NORMAL, &color);

    PangoFontDescription *font_desc = pango_font_description_from_string(CFG_GET_STRING("chat_font").c_str());
    if (font_desc)
        gtk_widget_modify_font(gres.view_chat, font_desc);

    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(gres.view_chat), GTK_WRAP_WORD_CHAR);
    gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (gres.view_chat), FALSE);
    gtk_text_view_set_left_margin (GTK_TEXT_VIEW (gres.view_chat), 1);
    gtk_text_view_set_right_margin (GTK_TEXT_VIEW (gres.view_chat), 1);
    gtk_text_view_set_editable(GTK_TEXT_VIEW(gres.view_chat), FALSE);
    gtk_container_add (GTK_CONTAINER (gres.scrolledwindow_chat), gres.view_chat);
    gres.tbuf_chat = gtk_text_view_get_buffer(GTK_TEXT_VIEW(gres.view_chat));
    
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_bg", "background", CFG_GET_STRING("chat_bg").c_str() , NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_sys_msg_fg", "foreground", CFG_GET_STRING("chat_sys_msg_fg").c_str() , NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_msg_fg", "foreground", CFG_GET_STRING("chat_msg_fg").c_str() , NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_join_fg", "foreground", CFG_GET_STRING("chat_join_fg").c_str() , NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_leave_fg", "foreground", CFG_GET_STRING("chat_leave_fg").c_str() , NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "chat_whisp_fg", "foreground", CFG_GET_STRING("chat_whisp_fg").c_str() , NULL);

    gtk_text_buffer_create_tag(gres.tbuf_chat, "gap", "pixels_above_lines", 30, NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "lmarg", "left_margin", 5, NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "black_fg", "foreground", "#000000", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "white_fg", "foreground", "#ffffff", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "blue_fg", "foreground", "#3200ff", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "magenta_fg", "foreground", "#ff32ff", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "green_fg", "foreground", "#55ff00", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "red_fg", "foreground", "#ff3200", NULL);
    
    gtk_text_buffer_create_tag(gres.tbuf_chat, "green_bg", "background", "#55ff00", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "blue_bg", "background", "#3200ff", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "red_bg", "background", "#ff3200", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "yellow_bg", "background", "#f7f732", NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "magenta_bg", "background", "#ff32ff", NULL);
    
    gtk_text_buffer_create_tag(gres.tbuf_chat, "italic", "style", PANGO_STYLE_ITALIC, NULL);
    gtk_text_buffer_create_tag(gres.tbuf_chat, "bold", "weight", PANGO_WEIGHT_BOLD, NULL);

    gres.scrolledwindow_user_list = gtk_scrolled_window_new (NULL, NULL);
    gtk_paned_pack2 (GTK_PANED(gres.paned_main), gres.scrolledwindow_user_list, false, false);
    gtk_container_set_border_width (GTK_CONTAINER (gres.scrolledwindow_user_list), 2);
    gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (gres.scrolledwindow_user_list),
                                    GTK_POLICY_NEVER,
                                    GTK_POLICY_AUTOMATIC);
    gtk_widget_show (gres.scrolledwindow_user_list);

    gres.model_user_list     = gtk_list_store_new(COLUMNS, G_TYPE_STRING, G_TYPE_STRING);
    gres.view_user_list      = gtk_tree_view_new_with_model (GTK_TREE_MODEL(gres.model_user_list));
    gres.selection_user_list = gtk_tree_view_get_selection(GTK_TREE_VIEW(gres.view_user_list));

    gtk_tree_selection_set_mode(gres.selection_user_list, GTK_SELECTION_SINGLE);
    gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(gres.view_user_list), TRUE);

    gres.renderer_user_list = gtk_cell_renderer_text_new();
    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(gres.view_user_list), /* vista */
                        -1,                  /* posizione della colonna */
                        "Name",  /* titolo della colonna */
                        gres.renderer_user_list,            /* cella inserita nella colonna */
                        "text",              /* attributo colonna */
                        COLUMN_STRING1,    /* colonna inserita  */
                        NULL);               /* fine ;-) */

    gres.renderer_user_list = gtk_cell_renderer_text_new();
    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(gres.view_user_list),
                        -1,
                        "Type",
                        gres.renderer_user_list,
                        "text",
                        COLUMN_STRING2,
                        NULL);

    gtk_widget_show (gres.view_user_list);
    g_object_unref(gres.model_user_list);

    gtk_container_add (GTK_CONTAINER (gres.scrolledwindow_user_list), gres.view_user_list);
    gtk_container_set_border_width (GTK_CONTAINER (gres.view_user_list), 0);
    gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (gres.view_user_list), TRUE);

    /* INPUTS */
    gres.hbox_inputs = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
    gtk_box_pack_start(GTK_BOX (gres.vbox_main), gres.hbox_inputs, FALSE, FALSE, 0);
    
    gres.label_nick = gtk_label_new((gchar *) CFG_GET_STRING("username").c_str()); 
    gtk_misc_set_alignment(GTK_MISC(gres.label_nick), 0.0, 0.5);
    gtk_box_pack_start(GTK_BOX (gres.hbox_inputs), gres.label_nick, FALSE, FALSE, 2 );

    gres.entry_command = gtk_entry_new();
    gtk_box_pack_start(GTK_BOX (gres.hbox_inputs), gres.entry_command, TRUE, TRUE, 5);
    
    gres.button_send = gtk_button_new_with_label("Send");
    gtk_widget_set_size_request (GTK_WIDGET (gres.button_send), 70, 30);
    gtk_box_pack_start(GTK_BOX (gres.hbox_inputs), gres.button_send, FALSE, FALSE, 0);

    gres.text_entry = gres.entry_command;
    g_signal_connect(G_OBJECT(gres.entry_command), "activate", G_CALLBACK(button_send_click), NULL);
    g_signal_connect(G_OBJECT(gres.button_send), "clicked", G_CALLBACK(button_send_click), NULL);

    /* status_bar */
    gres.status_bar = gtk_statusbar_new();
    gtk_box_pack_start(GTK_BOX (gres.vbox_main), gres.status_bar, FALSE, FALSE, 0);

    /* end_widgets */
    gtk_widget_show_all(gres.window);

    /* default focus on command entry */
    gtk_widget_grab_focus (GTK_WIDGET(gres.text_entry));

    INFO ("debug", "GUI: starting GUI thread\n");
    pthread_t tid;
    StartThread(GuiThread, (void*)&gres, tid);

    INFO ("debug", "GUI: starting GTK+3\n");
    gtk_main();
    gdk_threads_leave();
    pthread_mutex_destroy(&mutex_guichange);

    return;
}
Exemplo n.º 23
0
s32 padInit(void * ee_addr)
{
	iop_thread_t thread;
	int intr_state;
	iop_event_t event;

	if(padman_init == 1)
	{
		M_PRINTF("Refresh request from EE\n.");
		padEnd();
	}

	vblankData.padEnd = 0;
	vblankData.init = 0;
	vblankData.stopTransfer = 1;

	pad_ee_addr = ee_addr;
	pad_port = 0;
	pad_slot = 0;
	mainThreadCount2 = 0;
	pad_portdata[0] = 0;
	pad_portdata[1] = 0;
	sif_buffer[0] = 0;

	sio2cmdReset();
	sio2cmdInitFindPads();
	sio2cmdInitMouse();
	sio2cmdInitNegicon();
	sio2cmdInitKonamiGun();
	sio2cmdInitDigital();
	sio2cmdInitJoystick();
	sio2cmdInitNamcoGun();
	sio2cmdInitAnalog();
	sio2cmdInitJogcon();
	sio2cmdInitConfig();

	pdReset();

	openSlots[0] = 0;
	openSlots[1] = 0;

	event.attr = EA_MULTI;
	event.bits = 0;

	vblankData.eventflag = CreateEventFlag(&event);

	if( vblankData.eventflag == 0)
	{
		M_PRINTF("padInit: CreateEventFlag failed (%d).\n", vblankData.eventflag);
		return 0;
	}

	thread.attr = TH_C;
	thread.thread = &TransferThread;
	thread.stacksize = 0x800;
	thread.priority = thpri_hi;

	vblankData.tid_2 = CreateThread(&thread);

	if(vblankData.tid_2 == 0)
	{
		M_PRINTF("padInit: CreateThread TransferThread failed (%d)\n.", vblankData.tid_2);
		return 0;
	}

	StartThread(vblankData.tid_2, NULL);

	thread.attr = TH_C;
	thread.thread = MainThread;
	thread.stacksize = 0x1000;
	thread.priority = thpri_lo;

	vblankData.tid_1 = CreateThread(&thread);

	if(vblankData.tid_1 == 0)
	{
		M_PRINTF("padInit: CreateThread MainThread failed (%d)\n.", vblankData.tid_1);
		return 0;
	}

	StartThread(vblankData.tid_1, NULL);

	CpuSuspendIntr(&intr_state);

	RegisterVblankHandler(0, 16, &VblankStart, (void*)&vblankData);
	RegisterVblankHandler(1, 16, &VblankEnd, (void*)&vblankData);

	CpuResumeIntr(intr_state);	//Original BUG: was originally a call to CpuEnableIntr with intr_state as an argument

	vblankData.init = 1;
	padman_init = 1;

	return 1;
}
Exemplo n.º 24
0
// start pulling data
HRESULT
CPullPin::Active(void)
{
    ASSERT(!ThreadExists());
    return StartThread();
}
Exemplo n.º 25
0
void CThreadPool::IntegrityCheck()
{
	_mutex.Acquire();
	int32 gobbled = _threadsEaten;

    if(gobbled < 0)
	{
		// this means we requested more threads than we had in the pool last time.
        // spawn "gobbled" + THREAD_RESERVE extra threads.
		uint32 new_threads = abs(gobbled) + THREAD_RESERVE;
		_threadsEaten=0;

		for(uint32 i = 0; i < new_threads; ++i)
		{
			if (StartThread(NULL) == NULL)
				break;
		}

		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled < 0) Spawning %u threads.", new_threads);
	}
	else if(gobbled < THREAD_RESERVE)
	{
        // this means while we didn't run out of threads, we were getting damn low.
		// spawn enough threads to keep the reserve amount up.
		uint32 new_threads = (THREAD_RESERVE - gobbled);
		for(uint32 i = 0; i < new_threads; ++i)
		{
			if (StartThread(NULL) == NULL)
				break;
		}

		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled <= 5) Spawning %u threads.", new_threads);
	}
	else if(gobbled > THREAD_RESERVE)
	{
		// this means we had "excess" threads sitting around doing nothing.
		// lets kill some of them off.
		uint32 kill_count = (gobbled - THREAD_RESERVE);
		KillFreeThreads(kill_count);
		_threadsEaten -= kill_count;
		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled > 5) Killing %u threads.", kill_count);
	}
	else
	{
		// perfect! we have the ideal number of free threads.
		Log.Debug("ThreadPool", "IntegrityCheck: Perfect!");
	}
	/*if(m_freeThreads.size() < 5)
	{
		uint32 j = 5 - m_freeThreads.size();
		Log.Debug("ThreadPool", "Spawning %u threads.", j);
		for(uint32 i = 0; i < j; ++i)
			StartThread(NULL);
	}*/

	_threadsExitedSinceLastCheck = 0;
	_threadsRequestedSinceLastCheck = 0;
	_threadsFreedSinceLastCheck = 0;

	_mutex.Release();
}
				int BehaviorCreateMainThread::InitIOCP(){
					WSAData data;
					if(WSAStartup( MAKEWORD(2,2),&data)){
						//throw "WSAStartup fail!";
						return 1;
					}

					_lpBehaviorMsgSend=new BaseBehavior::BaseBehaviorMsgSend();
					this->_lpBaseBehaviorMsgDeal->SetBehaviorMsgSend(this->_lpBehaviorMsgSend);

					_hIOCP=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,NULL,0);
					if( NULL == _hIOCP ){
						return 2;
					}

					if( !InitSocket() ){
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						//AddMessage("Init sociket fail!");
						CloseHandle( _hIOCP );
						return 3;
					}

					//启动处理线程
					if( !StartThread() ){
						//AddMessage("start thread fail!");
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						CloseHandle( _hIOCP );
						return 4;
					}

					if( !BindAndListenSocket() ){
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						CloseHandle( _hIOCP );
						closesocket( _soketMainListenSoket );
						return 5;
					}


					//函数指针化
					if( !GetFunPointer() ){
						//cout<<"GetFunPointer fail!"<<endl;
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						CloseHandle( _hIOCP );
						closesocket( _soketMainListenSoket );
						return 6;
					}

					//发送acceptEx
					if( !PostAcceptEx() ){
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						//cout<<"PostAcceptEx fail!"<<endl;
						CloseHandle( _hIOCP );
						closesocket( _soketMainListenSoket );
						return 7;
					}

					//注册事件
					if( !RegAcceptEvent() ){
						PostQueuedCompletionStatus( _hIOCP, 0, NULL, NULL );
						//cout<<"RegAcceptEvent fail!"<<endl;
						CloseHandle( _hIOCP );
						closesocket( _soketMainListenSoket );
						return 8;
					}

					return 0;
				}
Exemplo n.º 27
0
/**
   @SYMTestCaseID UIF-TAppLangStarter-doTestStepL
  
   @SYMPREQ
  
   @SYMTestCaseDesc This test aims to test embedding feature of the application.
  
   @SYMTestPriority High
  
   @SYMTestStatus Implemented
   
   @SYMTestActions The dll creates a thread and starts a Message server. Once the
   message server is up and ready it launches the test client application,
   tpackage. The server installs and starts an active scheduler to service
   request messages received from the client and to log the information gathered
   from the request messages.When the server receives  EMessageServSetFromString
   message from the client, it activates CMessageActive active object in order
   to output the log buffer. When client completes its work, it sends message
   EMessageServStop and server stops active sheduler so that server's thread
   might be closed. 
  
   @SYMTestExpectedResults All messages send by the client should be processed by
   the server and outputted in the log file.
   
 */
TVerdict CTestApplicationLanguageStep::doTestStepL() // main function called by E32
	{
	__UHEAP_MARK;
	SetTestStepID(_L("UIF-TAppLangStarter-doTestStepL"));
	CActiveScheduler*	theSheduler = new CActiveScheduler;
    CActiveScheduler::Install(theSheduler);

	iMessage = CMessageActive::NewL();
	iMessage->iStep = this;

	_LIT(KPackageAppFileName,"z:\\sys\\bin\\TAPPLANGUAGE.exe");

	CApaCommandLine* cmdLine=CApaCommandLine::NewLC();	
	cmdLine->SetCommandL(EApaCommandViewActivate);
	cmdLine->SetDocumentNameL(_L("jhghjg"));
	cmdLine->SetExecutableNameL(KPackageAppFileName);
	StartThread();

	RApaLsSession ls;
	User::LeaveIfError(ls.Connect());
	CleanupClosePushL(ls);
	TInt err = ls.StartApp(*cmdLine);
	if (err != KErrNone)
		{
		TEST(EFalse);
		INFO_PRINTF1(_L("Failed to start application"));
		// If there is a problem starting the app we have to stop the 
		// message server
		RMessageServ serv;
		TInt theRes = serv.Connect();
		if(theRes == KErrNone)
			{
			serv.Stop();	
			serv.Close();
			// Now make sure we wait until the server has stopped
			// Not sure this is necessary but safer
			while (ETrue)
				{
				TFindServer findCountServer(KMessageServerName);
				TFullName name;
				if (findCountServer.Next(name)!=KErrNone)
					{
					break;			
					}
				}
			}
		}
	CleanupStack::PopAndDestroy(&ls);
	
	CleanupStack::PopAndDestroy(cmdLine);
	
	CActiveScheduler::Start();

	
	delete theSheduler;
	delete iMessage;
	iMessage = NULL;
	REComSession::FinalClose();	
	RecordTestResultL();
	CloseTMSGraphicsStep();
	__UHEAP_MARKEND;

	return TestStepResult();
	}
Exemplo n.º 28
0
/** this is executed when a compatible camera is detected */
int PS2CamConnect(int devId)
{

	int						i;
	UsbDeviceDescriptor		*dev;

	UsbInterfaceDescriptor	*intf0,*intf1;
	UsbEndpointDescriptor   *endp1;
	CAMERA_DEVICE			*cam = NULL;
	iop_thread_t			param;


	printf("camera was connected\n");



	dev   = UsbGetDeviceStaticDescriptor(devId, NULL, USB_DT_DEVICE);

	intf0 = UsbGetDeviceStaticDescriptor(devId, dev,  USB_DT_INTERFACE);
	intf1 = UsbGetDeviceStaticDescriptor(devId, intf0,  USB_DT_INTERFACE);

	endp1= (UsbEndpointDescriptor  *) ((char *) intf1 + intf1->bLength);




	//get a free device slot
	for(i=0;i<MAX_CAM_DEVICE;i++)
	{
		if(Camera[i].status == 0)
		{
			cam = (CAMERA_DEVICE *)&Camera[i];

			cam->status = CAM_STATUS_CONNECTED;
			break;
		}
	}



	cam->device_id			= devId;

	cam->controll			= UsbOpenEndpoint(devId, NULL);
	cam->stream				= UsbOpenEndpoint(devId, endp1);
	cam->stream_pocket_size	= (endp1->wMaxPacketSizeHB * 256 + endp1->wMaxPacketSizeLB);













	/*create thread that will execute funtions that cant be called*/
	/*in this funtion*/
	param.attr       = TH_C;
	param.thread     = (void *)PS2CamInitializeNewDevice;
	param.priority	 = 40;
	param.stacksize  = 0x800;
	param.option     = 0;

	maintain_thread = CreateThread(&param);


	StartThread(maintain_thread, cam);

	return 0;
}
Exemplo n.º 29
0
HRESULT
CAsyncIo::AsyncActive(void)
{
    return StartThread();
}
Exemplo n.º 30
0
void CThreadView::OnNewrectangle()
{
	StartThread(2);
	UpdateTitle();
}