void AppStateGameServer::Update() { // Insert game logic in UpdateGame() ////////////////////////////////////////////////////////////////////////////////// // Server Stuff time_t now; time(&now); if (debugLevel > DL_LOW) { if (now - lastSpeedDisplay >= 1) { time(&lastSpeedDisplay); if (clientCount > 0) std::cout << "[ Server Speed ] " << CurrentDateTime() << " >>> Clients: " << clientCount << "; Frames Per Second: " << Clock::Frame_Control.Get_FPS() << std::endl; } } // Have we contacted the main server yet? if (!networkMainServer->IsInited()) { if (tryMainAgain-- <= 0) { // std::cout << "Trying main again\n"; if (networkMainServer->Init() != 1) tryMainAgain = 100; else UpdateMainServer(); } } else { int receiveId = networkMainServer->ReceiveData(); if (receiveId == -2) // Server hung up { std::cout << "MainServer hung up.\n"; networkMainServer->Close(); tryMainAgain = 100; } } if (inLobby) UpdateLobby(); else UpdateGame(); if (now - lastActivity > TimeoutInSeconds && clientCount == 0) { std::cout << "[ Server Timed Out ] " << CurrentDateTime() << " >>> No activity for " << TimeoutInSeconds << " seconds." << std::endl; AppStateEvent::New_Event(APPSTATE_NONE); } ////////////////////////////////////////////////////////////////////////////////// }
void AppStateGameServer::Initialize() { srand(time(NULL)); map = new Map(rand(), lobbySetMapScale); ////////////////////////////////////////////////////////////////////////////////// // Server stuff lobbyName = std::string(lobbySetName); if (lobbySetPort == 0) { networkGame = NetworkFactory::getInstance("./conf/networkLobby.conf"); if (networkGame->Init(true) == -1) exit(1); } else { networkGame = NetworkFactory::getInstance(TCP, "localhost", lobbySetPort); if (networkGame->Init(true) == -1) exit(1); } networkMainServer = NetworkFactory::getInstance("./conf/networkMainServer.conf"); if (networkMainServer->Init() != 1) tryMainAgain = 100; else UpdateMainServer(); time(&lastActivity); time(&lastSpeedDisplay); std::cout << "[ Server Started ] " << CurrentDateTime() << std::endl; ////////////////////////////////////////////////////////////////////////////////// }
void CLog::Log(const char * msg, ...) { CSynchronized synchronized(&_LogSec); static char buffer[LOG_BUFFER_SIZE] = { 0, }; va_list args; va_start(args, msg); vsnprintf_s(buffer, LOG_BUFFER_SIZE, LOG_BUFFER_SIZE - 1, msg, args); va_end(args); std::cout << CurrentDateTime() << " [INFO] " << buffer << std::endl; }
void EmulMouse::StopMouseEmul() { if (isEmulStart == false) return; string str = CurrentDateTime() + "\r\n"; threadLogBuffer.push_back(str); str = "마우스 에뮬레이터 종료 :D \r\n"; threadLogBuffer.push_back(str); isThreadExit = true; th_MouseEmulator.join(); }
void CLog::Error(const char * fileName, const char * funcName, int line, const char * msg, ...) { CSynchronized synchronized(&_LogSec); static char buffer[LOG_BUFFER_SIZE] = { 0, }; va_list args; va_start(args, msg); vsnprintf_s(buffer, LOG_BUFFER_SIZE, LOG_BUFFER_SIZE - 1, msg, args); va_end(args); std::cout << CurrentDateTime() << " [ERROR] " << "File: " << fileName << "\nFunction: " << funcName << "\nLine: " << line \ << "\nError: " << buffer << std::endl; }
void AppStateGameServer::SendToAll(NetString *string) { for (int i = 0; i < MaximumClients; ++i) { if (clients[i] == NULL) continue; networkGame->SendData(string, i); } if (debugLevel > DL_MED) { std::cout << "[ Message Sent To All Clients ] " << CurrentDateTime() << " >>> " << *string << std::endl; } }
bool TDateTime::SetCurrentDate(TDateTime &rhs) { #ifndef WIN32 unsigned int year=0, month=0, day=0, hour=0, min=0, sec=0; rhs.DecodeDate(year, month, day); TDateTime curDateTime = CurrentDateTime(); curDateTime.DecodeTime( hour, min, sec ); TDateTime tmpDateTime(year, month, day, hour, min, sec); return SetCurrentDateTime(tmpDateTime); #endif return true; }
void EmulMouse::StartMouseEmul(unsigned int _millesecond) { if (isEmulStart == true) return; isThreadExit = false; isEmulStart = true; mouseClickTime = _millesecond; string str = CurrentDateTime() + "\r\n"; threadLogBuffer.push_back(str); str = "마우스 에뮬레이터 시작 :) \r\n"; threadLogBuffer.push_back(str); th_MouseEmulator = thread(&EmulMouse::MouseEmulating, this); hEmulThread = th_MouseEmulator.native_handle(); }
void AppStateGameServer::SwitchToGameMode() { // Switch to regular game mode configurations for (int i = 0; i < MaximumClients; i++) { if (clients[i] == NULL) continue; time(&clients[i]->last_input); expectedClients.push_back(clients[i]); clients[i] = NULL; } clientCount = 0; networkGame->Close(); delete networkGame; if (lobbySetPort == 0) { networkGame = NetworkFactory::getInstance(); networkGame->Init(true); } else { networkGame = NetworkFactory::getInstance(UDP, "localhost", lobbySetPort); networkGame->Init(true); } state = GSE_GAME_COUNTDOWN; inLobby = false; secondsToStart = 15; time(&secondsToStartLastTick); time(&lastActivity); std::cout << "[ Server Switching ] " << CurrentDateTime() << " >>> Switching to game mode. Map Seed: " << map->SEED << ". Map Scale: " << map->map_scale << '.' << std::endl; Collision_Manager::Get_Instance(); Initialize_Trig_Table(); map->Generate_Map(); Ship::Initialize_Ships(map->max_players_per_team * 2); }
void AppStateGameServer::HandleGameConnections() { NetString string; Client *client = NULL; while (true) { std::vector<int> newClients, removedClients; int receiveId = networkGame->ReceiveData(&newClients, &removedClients); // Handle new connections for (std::vector<int>::iterator it = newClients.begin(); it != newClients.end(); it++) { if (clients[*it] != NULL) { availablePlayerIds[clients[*it]->player_id] = true; delete clients[*it]; clientCount--; clients[*it] = NULL; } client = new Client(); int pawnIndex = Ship::Add_Ship(NO_TEAM, INTERCEPTOR, 100, 100, 5.0); // Will get its teamid later if (pawnIndex >= 0) client->pawn = Ship::ships[pawnIndex]; else std::cout << "[ ERROR ] " << CurrentDateTime() << " >>> Unable to create ship." << std::endl; // Insert logic to place new ship; client->offline = true; client->channel_id = *it; networkGame->Bind(*it); clientCount++; clients[*it] = client; SendStateUpdate(*it); if (debugLevel > DL_NONE) std::cout << "[ New Client Accepted ] " << CurrentDateTime() << " >>> Channel: " << *it << std::endl; time(&lastActivity); } // Handle removed connections by tcp drops for (std::vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++) { if (clients[*it]->team_id == RED_TEAM) teamRedCount--; else teamBlueCount--; availablePlayerIds[clients[*it]->player_id] = true; string.WriteUChar(NCE_REMOVE_PLAYER); string.WriteUChar(clients[*it]->player_id); ForceSaveStats(*it); delete clients[*it]; clients[*it] = NULL; clientCount--; UpdateMainServer(); if (debugLevel > DL_NONE) std::cout << "[ Client Connection Dropped ] " << CurrentDateTime() << " >>> Channel: " << *it << std::endl; time(&lastActivity); } // Did we get a message ready to read? if (receiveId == -1) break; time(&lastActivity); // Read that new message client = clients[receiveId]; time(&client->last_input); NetString *netString = networkGame->GetData(receiveId); if (netString == NULL || netString->BufferLength() == 0) continue; bool reading = true; while (reading) { unsigned char temp; if (!netString->ReadUChar(temp)) break; NetworkChunkEnums type = (NetworkChunkEnums)temp; switch (type) { case NCE_PLAYER_INPUT: { Parser parser; parser.DeserializeInput(netString, client->inputs, NUMBER_OF_INPUTS); break; } case NCE_LOOKUP_PLAYER: { unsigned char player_id; netString->ReadUChar(player_id); Client *player = NULL; for (int i = 0; i < MaximumClients; i++) { if (clients[i] != NULL && clients[i]->player_id == player_id) { player = clients[i]; break; } } if (player == NULL) break; NetString response; response.WriteUChar(NCE_LOOKUP_PLAYER); response.WriteInt(player->player_id); response.WriteUChar(player->team_id); response.WriteString(player->player_name); response.WriteUChar(NCE_END); networkGame->SendData(&response, receiveId); break; } case NCE_PLAYER_GREETING: { netString->ReadString(client->player_name); bool playerExists = false; for (int i = 0; i < MaximumClients; i++) { if (clients[i] == NULL || clients[i] == client) continue; if (clients[i]->player_name == client->player_name) { playerExists = true; break; } } if (playerExists) { NetString response; response.WriteUChar(NCE_ALREADY_JOINED); response.WriteUChar(NCE_END); networkGame->SendData(&response, client->channel_id); clients[client->channel_id] = NULL; delete client; clientCount--; break; } // We got a greeting, but is it redundant? bool newPlayer = false; if (client->player_id == -1) { newPlayer = true; bool wasFromLobby = false; // Did we expect it? for (std::vector<Client *>::iterator it = expectedClients.begin(); it != expectedClients.end(); it++) { if ((*it)->player_name == client->player_name) { client->player_id = (*it)->player_id; client->team_id = (*it)->team_id; client->pawn->team_id = (*it)->team_id; if ((*it)->team_id == RED_TEAM) client->spawnPoints = map->red_spawn_points; else client->spawnPoints = map->blue_spawn_points; client->Respawn(client->player_id); expectedClients.erase(it); wasFromLobby = true; break; } } // Unexpected, so give it a team if (!wasFromLobby) { if (!MakeTeamsEven(client->channel_id)) { NetString response; response.WriteUChar(NCE_TOO_MANY_PLAYERS); response.WriteUChar(NCE_END); networkGame->SendData(&response, receiveId); break; } client->player_id = GetNextPlayerId(); if (client->team_id == RED_TEAM) client->spawnPoints = map->red_spawn_points; else client->spawnPoints = map->blue_spawn_points; client->Respawn(client->player_id); } } NetString response; response.WriteUChar(NCE_PLAYER_GREETING); response.WriteInt(client->player_id); response.WriteUChar(client->team_id); response.WriteInt(map->SEED); response.WriteFloat(map->map_scale); response.WriteUChar(NCE_END); networkGame->SendData(&response, receiveId); if (newPlayer) { NetString broadcast; broadcast.WriteUChar(NCE_NEW_PLAYER); broadcast.WriteInt(client->player_id); broadcast.WriteUChar(client->team_id); broadcast.WriteString(client->player_name); broadcast.WriteUChar(NCE_END); SendToAll(&broadcast); UpdateMainServer(); } break; } case NCE_PLAYER_EXITED: { string.WriteUChar(NCE_REMOVE_PLAYER); string.WriteUChar(client->player_id); ForceSaveStats(receiveId); if (client->team_id == RED_TEAM) teamRedCount--; else teamBlueCount--; availablePlayerIds[client->player_id] = true; clients[receiveId] = NULL; clientCount--; UpdateMainServer(); networkGame->RemoveConnection(receiveId); // Sync with networkGame } default: reading = false; } } delete netString; } // Have any of the connections timed out? time_t now = time(NULL); for (int i = 0; i < MaximumClients; ++i) { client = clients[i]; if (client == NULL) continue; if (now - client->last_input > 5) { string.WriteUChar(NCE_REMOVE_PLAYER); string.WriteUChar(clients[i]->player_id); if (clients[i]->team_id == RED_TEAM) teamRedCount--; else teamBlueCount--; availablePlayerIds[clients[i]->player_id] = true; ForceSaveStats(i); clients[i] = NULL; clientCount--; UpdateMainServer(); networkGame->RemoveConnection(i); // Sync with networkGame if (debugLevel > DL_NONE) { std::cout << "[ Client Timed Out ] " << CurrentDateTime() << " >>> Channel: " << i << std::endl; } delete client; } } // Have the connections we expected to join from the lobby timed out? Remove their reserved spot on the team if so. for (std::vector<Client *>::reverse_iterator it = expectedClients.rbegin(); it != expectedClients.rend(); it++) { if (now - (*it)->last_input > 5) { availablePlayerIds[(*it)->player_id] = true; if ((*it)->team_id == RED_TEAM) teamRedCount--; else teamBlueCount--; std::cout << "Player: " << (*it)->player_name << " has not joined in time.\n"; delete *it; expectedClients.erase(--(it.base())); } } if (string.BufferLength() > 0) { string.WriteUChar(NCE_END); SendToAll(&string); } }
void AppStateGameServer::HandleLobbyConnections() { // I will assume lobby is TCP NetString string; Client *client = NULL; while (true) { std::vector<int> newClients, removedClients; int receiveId = networkGame->ReceiveData(&newClients, &removedClients); // Handle new connections for (std::vector<int>::iterator it = newClients.begin(); it != newClients.end(); it++) { if (clients[*it] != NULL) { availablePlayerIds[clients[*it]->player_id] = true; delete clients[*it]; clientCount--; clients[*it] = NULL; } if (teamRedCount >= map->max_players_per_team && teamBlueCount >= map->max_players_per_team) { NetString netString; netString.WriteUChar(NCE_TOO_MANY_PLAYERS); netString.WriteUChar(NCE_END); networkGame->SendData(&netString, *it); networkGame->RemoveConnection(*it); } else { client = new Client(); client->offline = false; client->channel_id = *it; clientCount++; clients[*it] = client; SendStateUpdate(*it); if (debugLevel > DL_NONE) std::cout << "[ New Client Accepted ] " << CurrentDateTime() << " >>> Channel: " << *it << std::endl; } time(&lastActivity); } for (std::vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++) { if (clients[*it] == NULL) continue; availablePlayerIds[clients[*it]->player_id] = true; delete clients[*it]; clients[*it] = NULL; clientCount--; // Update everyone of potential new information MakeTeamsEven(); SendLobbyPlayersToAll(); if (debugLevel > DL_NONE) std::cout << "[ Client Connection Dropped ] " << CurrentDateTime() << " >>> Channel: " << *it << std::endl; time(&lastActivity); } // Did we get a message ready to read? if (receiveId == -1) break; time(&lastActivity); // Read that new message client = clients[receiveId]; NetString *netString = networkGame->GetData(receiveId); bool reading = true, shouldSyncPlayers = false; while (reading) { NetworkChunkEnums type; unsigned char temp; if (!netString->ReadUChar(temp)) break; unsigned char channelId = 0; type = (NetworkChunkEnums)temp; switch (type) { case NCE_PLAYER: netString->ReadString(client->player_name); bool playerExists = false; for (int i = 0; i < MaximumClients; i++) { if (clients[i] == NULL || i == receiveId) continue; if (clients[i]->player_name == client->player_name) { playerExists = true; break; } } if (playerExists) { NetString response; response.WriteUChar(NCE_ALREADY_JOINED); response.WriteUChar(NCE_END); networkGame->SendData(&response, receiveId); delete client; clients[receiveId] = NULL; clientCount--; } else { std::cout << "Got " << client->player_name << '\n'; client->player_id = GetNextPlayerId(); MakeTeamsEven(); shouldSyncPlayers = true; } break; } } delete netString; if (shouldSyncPlayers) SendLobbyPlayersToAll(); } }
void OBS::Start() { if(bRunning) return; OSEnterMutex (hStartupShutdownMutex); scenesConfig.Save(); //------------------------------------------------------------- fps = AppConfig->GetInt(TEXT("Video"), TEXT("FPS"), 30); frameTime = 1000/fps; //------------------------------------------------------------- if(!bLoggedSystemStats) { LogSystemStats(); bLoggedSystemStats = TRUE; } //------------------------------------------------------------- if (OSIncompatibleModulesLoaded()) { OSLeaveMutex (hStartupShutdownMutex); MessageBox(hwndMain, Str("IncompatibleModules"), NULL, MB_ICONERROR); Log(TEXT("Incompatible modules detected.")); return; } String strPatchesError; if (OSIncompatiblePatchesLoaded(strPatchesError)) { OSLeaveMutex (hStartupShutdownMutex); MessageBox(hwndMain, strPatchesError.Array(), NULL, MB_ICONERROR); Log(TEXT("Incompatible patches detected.")); return; } //------------------------------------------------------------- String processPriority = AppConfig->GetString(TEXT("General"), TEXT("Priority"), TEXT("Normal")); if (!scmp(processPriority, TEXT("Idle"))) SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS); else if (!scmp(processPriority, TEXT("Above Normal"))) SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); else if (!scmp(processPriority, TEXT("High"))) SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); int networkMode = AppConfig->GetInt(TEXT("Publish"), TEXT("Mode"), 2); DWORD delayTime = (DWORD)AppConfig->GetInt(TEXT("Publish"), TEXT("Delay")); String strError; if(bTestStream) network = CreateNullNetwork(); else { switch(networkMode) { case 0: network = (delayTime > 0) ? CreateDelayedPublisher(delayTime) : CreateRTMPPublisher(); break; case 1: network = CreateNullNetwork(); break; } } if(!network) { OSLeaveMutex (hStartupShutdownMutex); if(!bReconnecting) MessageBox(hwndMain, strError, NULL, MB_ICONERROR); else DialogBox(hinstMain, MAKEINTRESOURCE(IDD_RECONNECTING), hwndMain, OBS::ReconnectDialogProc); return; } bReconnecting = false; //------------------------------------------------------------- Log(TEXT("=====Stream Start: %s==============================================="), CurrentDateTime().Array()); //------------------------------------------------------------- int monitorID = AppConfig->GetInt(TEXT("Video"), TEXT("Monitor")); if(monitorID >= (int)monitors.Num()) monitorID = 0; RECT &screenRect = monitors[monitorID].rect; int defCX = screenRect.right - screenRect.left; int defCY = screenRect.bottom - screenRect.top; downscaleType = AppConfig->GetInt(TEXT("Video"), TEXT("Filter"), 0); downscale = AppConfig->GetFloat(TEXT("Video"), TEXT("Downscale"), 1.0f); baseCX = AppConfig->GetInt(TEXT("Video"), TEXT("BaseWidth"), defCX); baseCY = AppConfig->GetInt(TEXT("Video"), TEXT("BaseHeight"), defCY); baseCX = MIN(MAX(baseCX, 128), 4096); baseCY = MIN(MAX(baseCY, 128), 4096); scaleCX = UINT(double(baseCX) / double(downscale)); scaleCY = UINT(double(baseCY) / double(downscale)); //align width to 128bit for fast SSE YUV4:2:0 conversion outputCX = scaleCX & 0xFFFFFFFC; outputCY = scaleCY & 0xFFFFFFFE; bUseMultithreadedOptimizations = AppConfig->GetInt(TEXT("General"), TEXT("UseMultithreadedOptimizations"), TRUE) != 0; Log(TEXT(" Multithreaded optimizations: %s"), (CTSTR)(bUseMultithreadedOptimizations ? TEXT("On") : TEXT("Off"))); //------------------------------------------------------------------ Log(TEXT(" Base resolution: %ux%u"), baseCX, baseCY); Log(TEXT(" Output resolution: %ux%u"), outputCX, outputCY); Log(TEXT("------------------------------------------")); //------------------------------------------------------------------ GS = new D3D10System; GS->Init(); //------------------------------------------------------------- mainVertexShader = CreateVertexShaderFromFile(TEXT("shaders/DrawTexture.vShader")); mainPixelShader = CreatePixelShaderFromFile(TEXT("shaders/DrawTexture.pShader")); solidVertexShader = CreateVertexShaderFromFile(TEXT("shaders/DrawSolid.vShader")); solidPixelShader = CreatePixelShaderFromFile(TEXT("shaders/DrawSolid.pShader")); //------------------------------------------------------------------ CTSTR lpShader; if(CloseFloat(downscale, 1.0)) lpShader = TEXT("shaders/DrawYUVTexture.pShader"); else if(downscale < 2.01) { switch(downscaleType) { case 0: lpShader = TEXT("shaders/DownscaleBilinear1YUV.pShader"); break; case 1: lpShader = TEXT("shaders/DownscaleBicubicYUV.pShader"); break; case 2: lpShader = TEXT("shaders/DownscaleLanczos6tapYUV.pShader"); break; } } else if(downscale < 3.01) lpShader = TEXT("shaders/DownscaleBilinear9YUV.pShader"); else CrashError(TEXT("Invalid downscale value (must be either 1.0, 1.5, 2.0, 2.25, or 3.0)")); yuvScalePixelShader = CreatePixelShaderFromFile(lpShader); if (!yuvScalePixelShader) CrashError(TEXT("Unable to create shader from file %s"), lpShader); //------------------------------------------------------------- for(UINT i=0; i<NUM_RENDER_BUFFERS; i++) { mainRenderTextures[i] = CreateRenderTarget(baseCX, baseCY, GS_BGRA, FALSE); yuvRenderTextures[i] = CreateRenderTarget(outputCX, outputCY, GS_BGRA, FALSE); } //------------------------------------------------------------- D3D10_TEXTURE2D_DESC td; zero(&td, sizeof(td)); td.Width = outputCX; td.Height = outputCY; td.Format = DXGI_FORMAT_B8G8R8A8_UNORM; td.MipLevels = 1; td.ArraySize = 1; td.SampleDesc.Count = 1; td.ArraySize = 1; td.Usage = D3D10_USAGE_STAGING; td.CPUAccessFlags = D3D10_CPU_ACCESS_READ; for(UINT i=0; i<NUM_RENDER_BUFFERS; i++) { HRESULT err = GetD3D()->CreateTexture2D(&td, NULL, ©Textures[i]); if(FAILED(err)) { CrashError(TEXT("Unable to create copy texture")); //todo - better error handling } } //------------------------------------------------------------- AudioDeviceList playbackDevices; GetAudioDevices(playbackDevices, ADT_PLAYBACK); String strPlaybackDevice = AppConfig->GetString(TEXT("Audio"), TEXT("PlaybackDevice"), TEXT("Default")); if(strPlaybackDevice.IsEmpty() || !playbackDevices.HasID(strPlaybackDevice)) { AppConfig->SetString(TEXT("Audio"), TEXT("PlaybackDevice"), TEXT("Default")); strPlaybackDevice = TEXT("Default"); } Log(TEXT("Playback device %s"), strPlaybackDevice.Array()); playbackDevices.FreeData(); desktopAudio = CreateAudioSource(false, strPlaybackDevice); if(!desktopAudio) { CrashError(TEXT("Cannot initialize desktop audio sound, more info in the log file.")); } AudioDeviceList audioDevices; GetAudioDevices(audioDevices, ADT_RECORDING); String strDevice = AppConfig->GetString(TEXT("Audio"), TEXT("Device"), NULL); if(strDevice.IsEmpty() || !audioDevices.HasID(strDevice)) { AppConfig->SetString(TEXT("Audio"), TEXT("Device"), TEXT("Disable")); strDevice = TEXT("Disable"); } audioDevices.FreeData(); String strDefaultMic; bool bHasDefault = GetDefaultMicID(strDefaultMic); if(strDevice.CompareI(TEXT("Disable"))) EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), FALSE); else { bool bUseDefault = strDevice.CompareI(TEXT("Default")) != 0; if(!bUseDefault || bHasDefault) { if(bUseDefault) strDevice = strDefaultMic; micAudio = CreateAudioSource(true, strDevice); if(!micAudio) MessageBox(hwndMain, Str("MicrophoneFailure"), NULL, 0); else micAudio->SetTimeOffset(AppConfig->GetInt(TEXT("Audio"), TEXT("MicTimeOffset"), 0)); EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), micAudio != NULL); } else EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), FALSE); } //------------------------------------------------------------- UINT bitRate = (UINT)AppConfig->GetInt(TEXT("Audio Encoding"), TEXT("Bitrate"), 96); String strEncoder = AppConfig->GetString(TEXT("Audio Encoding"), TEXT("Codec"), TEXT("AAC")); #ifdef USE_AAC if(strEncoder.CompareI(TEXT("AAC")) && OSGetVersion() >= 7) audioEncoder = CreateAACEncoder(bitRate); else #endif audioEncoder = CreateMP3Encoder(bitRate); //------------------------------------------------------------- desktopVol = AppConfig->GetFloat(TEXT("Audio"), TEXT("DesktopVolume"), 1.0f); micVol = AppConfig->GetFloat(TEXT("Audio"), TEXT("MicVolume"), 1.0f); //------------------------------------------------------------- bRunning = true; if(sceneElement) { scene = CreateScene(sceneElement->GetString(TEXT("class")), sceneElement->GetElement(TEXT("data"))); XElement *sources = sceneElement->GetElement(TEXT("sources")); if(sources) { UINT numSources = sources->NumElements(); for(UINT i=0; i<numSources; i++) { SceneItem *item = scene->AddImageSource(sources->GetElementByID(i)); if(item) { if(ListView_GetItemState(GetDlgItem(hwndMain, ID_SOURCES), i, LVIS_SELECTED) > 0) item->Select(true); } } } scene->BeginScene(); } if(scene && scene->HasMissingSources()) MessageBox(hwndMain, Str("Scene.MissingSources"), NULL, 0); //------------------------------------------------------------- int maxBitRate = AppConfig->GetInt (TEXT("Video Encoding"), TEXT("MaxBitrate"), 1000); int bufferSize = AppConfig->GetInt (TEXT("Video Encoding"), TEXT("BufferSize"), 1000); int quality = AppConfig->GetInt (TEXT("Video Encoding"), TEXT("Quality"), 8); String preset = AppConfig->GetString(TEXT("Video Encoding"), TEXT("Preset"), TEXT("veryfast")); bUsing444 = AppConfig->GetInt (TEXT("Video Encoding"), TEXT("Use444"), 0) != 0; bDupeFrames = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("DupeFrames"), 0) != 0; if(bUsing444) bDupeFrames = bUseCFR = false; else { bUseCFR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCFR"), 0) != 0; if(bUseCFR) bDupeFrames = true; } //------------------------------------------------------------- bWriteToFile = networkMode == 1 || AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile")) != 0; String strOutputFile = AppConfig->GetString(TEXT("Publish"), TEXT("SavePath")); strOutputFile.FindReplace(TEXT("\\"), TEXT("/")); if (bWriteToFile) { OSFindData ofd; HANDLE hFind = NULL; bool bUseDateTimeName = true; if(hFind = OSFindFirstFile(strOutputFile, ofd)) { String strFileExtension = GetPathExtension(strOutputFile); String strFileWithoutExtension = GetPathWithoutExtension(strOutputFile); if(strFileExtension.IsValid() && !ofd.bDirectory) { String strNewFilePath; UINT curFile = 0; do { strNewFilePath.Clear() << strFileWithoutExtension << TEXT(" (") << FormattedString(TEXT("%02u"), ++curFile) << TEXT(").") << strFileExtension; } while(OSFileExists(strNewFilePath)); strOutputFile = strNewFilePath; bUseDateTimeName = false; } if(ofd.bDirectory) strOutputFile.AppendChar('/'); OSFindClose(hFind); } if(bUseDateTimeName) { String strFileName = GetPathFileName(strOutputFile); if(!strFileName.IsValid() || !IsSafeFilename(strFileName)) { SYSTEMTIME st; GetLocalTime(&st); String strDirectory = GetPathDirectory(strOutputFile); strOutputFile = FormattedString(TEXT("%s/%u-%02u-%02u-%02u%02u-%02u.mp4"), strDirectory.Array(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); } } } //------------------------------------------------------------- bufferingTime = GlobalConfig->GetInt(TEXT("General"), TEXT("SceneBufferingTime"), 400); //------------------------------------------------------------- bForceMicMono = AppConfig->GetInt(TEXT("Audio"), TEXT("ForceMicMono")) != 0; bRecievedFirstAudioFrame = false; //hRequestAudioEvent = CreateSemaphore(NULL, 0, 0x7FFFFFFFL, NULL); hSoundDataMutex = OSCreateMutex(); hSoundThread = OSCreateThread((XTHREAD)OBS::MainAudioThread, NULL); //------------------------------------------------------------- StartBlankSoundPlayback(strPlaybackDevice); //------------------------------------------------------------- ctsOffset = 0; videoEncoder = CreateX264Encoder(fps, outputCX, outputCY, quality, preset, bUsing444, maxBitRate, bufferSize, bUseCFR, bDupeFrames); //------------------------------------------------------------- // Ensure that the render frame is properly sized ResizeRenderFrame(true); //------------------------------------------------------------- if(!bTestStream && bWriteToFile && strOutputFile.IsValid()) { String strFileExtension = GetPathExtension(strOutputFile); if(strFileExtension.CompareI(TEXT("flv"))) fileStream = CreateFLVFileStream(strOutputFile); else if(strFileExtension.CompareI(TEXT("mp4"))) fileStream = CreateMP4FileStream(strOutputFile); } //------------------------------------------------------------- hMainThread = OSCreateThread((XTHREAD)OBS::MainCaptureThread, NULL); if(bTestStream) { EnableWindow(GetDlgItem(hwndMain, ID_STARTSTOP), FALSE); SetWindowText(GetDlgItem(hwndMain, ID_TESTSTREAM), Str("MainWindow.StopTest")); } else { EnableWindow(GetDlgItem(hwndMain, ID_TESTSTREAM), FALSE); SetWindowText(GetDlgItem(hwndMain, ID_STARTSTOP), Str("MainWindow.StopStream")); } EnableWindow(GetDlgItem(hwndMain, ID_SCENEEDITOR), TRUE); //------------------------------------------------------------- ReportStartStreamTrigger(); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, 0, 0); SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED | ES_DISPLAY_REQUIRED); UpdateRenderViewMessage(); //update notification icon to reflect current status UpdateNotificationAreaIcon(); OSLeaveMutex (hStartupShutdownMutex); }
void OBS::Stop() { if(!bRunning) return; OSEnterMutex(hStartupShutdownMutex); ReportStopStreamTrigger(); bRunning = false; if(hMainThread) { OSTerminateThread(hMainThread, 20000); hMainThread = NULL; } for(UINT i=0; i<globalSources.Num(); i++) globalSources[i].source->EndScene(); if(scene) scene->EndScene(); //------------------------------------------------------------- if(hSoundThread) { //ReleaseSemaphore(hRequestAudioEvent, 1, NULL); OSTerminateThread(hSoundThread, 20000); } //if(hRequestAudioEvent) // CloseHandle(hRequestAudioEvent); if(hSoundDataMutex) OSCloseMutex(hSoundDataMutex); hSoundThread = NULL; //hRequestAudioEvent = NULL; hSoundDataMutex = NULL; //------------------------------------------------------------- StopBlankSoundPlayback(); //------------------------------------------------------------- delete fileStream; fileStream = NULL; delete network; network = NULL; delete micAudio; micAudio = NULL; delete desktopAudio; desktopAudio = NULL; delete audioEncoder; audioEncoder = NULL; delete videoEncoder; videoEncoder = NULL; //------------------------------------------------------------- for(UINT i=0; i<pendingAudioFrames.Num(); i++) pendingAudioFrames[i].audioData.Clear(); pendingAudioFrames.Clear(); //------------------------------------------------------------- if(GS) GS->UnloadAllData(); //------------------------------------------------------------- delete scene; scene = NULL; for(UINT i=0; i<globalSources.Num(); i++) globalSources[i].FreeData(); globalSources.Clear(); //------------------------------------------------------------- for(UINT i=0; i<auxAudioSources.Num(); i++) delete auxAudioSources[i]; auxAudioSources.Clear(); //------------------------------------------------------------- for(UINT i=0; i<NUM_RENDER_BUFFERS; i++) { delete mainRenderTextures[i]; delete yuvRenderTextures[i]; mainRenderTextures[i] = NULL; yuvRenderTextures[i] = NULL; } for(UINT i=0; i<NUM_RENDER_BUFFERS; i++) { SafeRelease(copyTextures[i]); } delete transitionTexture; transitionTexture = NULL; //------------------------------------------------------------- delete mainVertexShader; delete mainPixelShader; delete yuvScalePixelShader; delete solidVertexShader; delete solidPixelShader; mainVertexShader = NULL; mainPixelShader = NULL; yuvScalePixelShader = NULL; solidVertexShader = NULL; solidPixelShader = NULL; //------------------------------------------------------------- delete GS; GS = NULL; //------------------------------------------------------------- ResizeRenderFrame(false); RedrawWindow(hwndRenderFrame, NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); //------------------------------------------------------------- AudioDeviceList audioDevices; GetAudioDevices(audioDevices, ADT_RECORDING); String strDevice = AppConfig->GetString(TEXT("Audio"), TEXT("Device"), NULL); if(strDevice.IsEmpty() || !audioDevices.HasID(strDevice)) { AppConfig->SetString(TEXT("Audio"), TEXT("Device"), TEXT("Disable")); strDevice = TEXT("Disable"); } audioDevices.FreeData(); EnableWindow(GetDlgItem(hwndMain, ID_MICVOLUME), !strDevice.CompareI(TEXT("Disable"))); //------------------------------------------------------------- ClearStreamInfo(); Log(TEXT("=====Stream End: %s================================================="), CurrentDateTime().Array()); //update notification icon to reflect current status UpdateNotificationAreaIcon(); SetWindowText(GetDlgItem(hwndMain, ID_TESTSTREAM), Str("MainWindow.TestStream")); EnableWindow(GetDlgItem(hwndMain, ID_STARTSTOP), TRUE); SetWindowText(GetDlgItem(hwndMain, ID_STARTSTOP), Str("MainWindow.StartStream")); EnableWindow(GetDlgItem(hwndMain, ID_TESTSTREAM), TRUE); bEditMode = false; SendMessage(GetDlgItem(hwndMain, ID_SCENEEDITOR), BM_SETCHECK, BST_UNCHECKED, 0); EnableWindow(GetDlgItem(hwndMain, ID_SCENEEDITOR), FALSE); ClearStatusBar(); InvalidateRect(hwndRenderFrame, NULL, TRUE); for(UINT i=0; i<bufferedVideo.Num(); i++) bufferedVideo[i].Clear(); bufferedVideo.Clear(); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, 0, 0); SetThreadExecutionState(ES_CONTINUOUS); String processPriority = AppConfig->GetString(TEXT("General"), TEXT("Priority"), TEXT("Normal")); if (scmp(processPriority, TEXT("Normal"))) SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS); bTestStream = false; UpdateRenderViewMessage(); OSLeaveMutex(hStartupShutdownMutex); }
void Logger::setLogFile(const char *filename, bool plainText, bool showOnScreen) { m_pLogFile = loadFileStream(m_pLogFile, filename); isHTML = !plainText; printToScreen = showOnScreen; if (isHTML) fprintf(m_pLogFile, "<h1>Log file (%s)</h1><table><tr><td><b>Tag</b></td><td><b>Time</b></td><td><b>File</b></td><td><b>Function</b></td><td><b>Message</b></td></tr>", CurrentDateTime().c_str()); }