void vinum_daemon(void) { int s; struct daemonq *request; curproc->p_flag |= P_INMEM | P_SYSTEM; /* we're a system process */ daemon_save_config(); /* start by saving the configuration */ daemonpid = curproc->p_pid; /* mark our territory */ while (1) { tsleep(&vinum_daemon, PRIBIO, "vinum", 0); /* wait for something to happen */ /* * It's conceivable that, as the result of an * I/O error, we'll be out of action long * enough that another daemon gets started. * That's OK, just give up gracefully. */ if (curproc->p_pid != daemonpid) { /* we've been ousted in our sleep */ if (daemon_options & daemon_verbose) log(LOG_INFO, "vinum: abdicating\n"); return; } while (daemonq != NULL) { /* we have work to do, */ s = splhigh(); /* don't get interrupted here */ request = daemonq; /* get the request */ daemonq = daemonq->next; /* and detach it */ if (daemonq == NULL) /* got to the end, */ dqend = NULL; /* no end any more */ splx(s); switch (request->type) { /* * We had an I/O error on a request. Go through the * request and try to salvage it */ case daemonrq_ioerror: if (daemon_options & daemon_verbose) { struct request *rq = request->info.rq; log(LOG_WARNING, "vinum: recovering I/O request: %p\n%s dev %d.%d, offset 0x%x, length %ld\n", rq, rq->bp->b_flags & B_READ ? "Read" : "Write", major(rq->bp->b_dev), minor(rq->bp->b_dev), rq->bp->b_blkno, rq->bp->b_bcount); } recover_io(request->info.rq); /* the failed request */ break; /* * Write the config to disk. We could end up with * quite a few of these in a row. Only honour the * last one */ case daemonrq_saveconfig: if ((daemonq == NULL) /* no more requests */ ||(daemonq->type != daemonrq_saveconfig)) { /* or the next isn't the same */ if (((daemon_options & daemon_noupdate) == 0) /* we're allowed to do it */ &&((vinum_conf.flags & VF_READING_CONFIG) == 0)) { /* and we're not building the config now */ /* * We obviously don't want to save a * partial configuration. Less obviously, * we don't need to do anything if we're * asked to write the config when we're * building it up, because we save it at * the end. */ if (daemon_options & daemon_verbose) log(LOG_INFO, "vinum: saving config\n"); daemon_save_config(); /* save it */ } } break; case daemonrq_return: /* been told to stop */ if (daemon_options & daemon_verbose) log(LOG_INFO, "vinum: stopping\n"); daemon_options |= daemon_stopped; /* note that we've stopped */ Free(request); while (daemonq != NULL) { /* backed up requests, */ request = daemonq; /* get the request */ daemonq = daemonq->next; /* and detach it */ Free(request); /* then free it */ } wakeup(&vinumclose); /* and wake any waiting vinum(8)s */ return; case daemonrq_ping: /* tell the caller we're here */ if (daemon_options & daemon_verbose) log(LOG_INFO, "vinum: ping reply\n"); wakeup(&vinum_finddaemon); /* wake up the caller */ break; case daemonrq_closedrive: /* close a drive */ close_drive(request->info.drive); /* do it */ break; case daemonrq_init: /* initialize a plex */ /* XXX */ case daemonrq_revive: /* revive a subdisk */ /* XXX */ /* FALLTHROUGH */ default: log(LOG_WARNING, "Invalid request\n"); break; } if (request->privateinuse) /* one of ours, */ request->privateinuse = 0; /* no longer in use */ else Free(request); /* return it */ } } }
/* METODA WCZYTUJ¥CA DANE Za³o¿enia pliku s¹ proste. Na pocz¹tku podstawowe dane, a dalej jedziemy ze œcianami i ca³¹ reszt¹ danych. */ const bool CLevel::LoadLevel( const std::string &filename ) { if( filename == "" ) { Log.Error( "GLEVEL( " + file + " ): £añcuch znaków jest pusty!" ); return false; } // Najpierw definiujemy wskaŸnik na plik i go otwieramy std::fstream stream( filename, std::ios::in ); if( !stream ) { Log.Error( "GLEVEL( " + file + " ): Plik nie istnieje, lub podana œcie¿ka jest b³êdna: " + filename ); return false; } // definiujemy zmienne pomocnicze std::string str; // Pobieramy wersje poziomu oraz j¹ sprawdzamy str = GetClearLine( stream ); if( !sscanf_s( str.c_str(), "E3DTLEV=%u", &Version ) ) { Log.Error( "GLEVEL( " + file + " ): Nieprawid³owy plik poziomu!" ); return false; } if( Version > GAME_VERSION ) { Log.Error( "GLEVEL( " + file + " ): Zbyt wysoka wersja pliku!" ); return false; } /* Wczeœnijsze if'y by³y, by uzyskaæ pewnoœæ, ¿e wszystko z nowym plikiem jest w porz¹dku. Dlaczego tyle zachodu? By unikn¹æ sytuacji, kiedy ³adujemy plik, na ju¿ istniej¹cy level. Level istnieje, wiêc go kasujemy i czytamy plik. A teraz Zonk! Nie ma pliku! I co? zostajemy na lodzie bez levelu :). Teraz wiecie o co chodzi :) */ if( loaded ) { Log.Report( "GLEVEL( " + file + " ): Prze³adowanie poziomu na : " + filename ); Free(); Player.Reset(); } Log.Log( "GLEVEL( " + file + " ): Wczytywanie poziomu: " + filename ); //GUI.SendConMsg( "Wczytywanie poziomu: " + filename, false ); file = filename; while( stream ) { str = GetLine( stream ); if( str == "END E3DTLEV" ) break; str = ClearWhiteSpace( str ); if( str == "HEADER" ) { if( !LoadHeader( stream ) ) { Log.Error( "GLEVEL( " + file + " ): B³¹d odczytu nag³ówka!" ); continue; } } else if( str == "TEXTURES" ) { if( !LoadTextures( stream ) ) { Log.Error( "GLEVEL( " + file + " ): B³¹d odczytu tekstur!" ); continue; } } else if( str == "WALLS" ) { if( !LoadWalls( stream ) ) { Log.Error( "GLEVEL( " + file + " ): B³¹d odczytu œcian!" ); continue; } } else if( str == "ITEMLIST" ) { if( !LoadItemList( stream ) ) { Log.Error( "GLEVEL( " + file + " ): B³¹d odczytu listy przedmiotów!" ); continue; } } else Log.Error( "GLEVEL( " + file + " ): Nierozpoznany ci¹g " + str + "!" ); } for( unsigned row = 0; row < Rows; row++ ) { for( unsigned col = 0; col < Cols; col++ ) GetBlock( col, row )->Set( row, col, blockWidth, blockHeight, blockDepth ); } Player.SetStartPos( this->GetBlockPos( PlayerStartBlock ) ); Player.SetStartAngle( (float)PlayerStartAngle ); Player.Reset(); this->AddEntity( &Player ); loaded = true; BuildVisual(); BuildPhysic(); return true; }
void TXUfree(void) { if(TXUok!=TRUE) Bug("TXUok"); Free(TXUpat); Free(TXUtex); TXUok=FALSE; }
XnDeviceModule::~XnDeviceModule() { Free(); }
Room *load_RoomData(char *filename, unsigned int number, int flags) { Room *r; File *f; int (*load_func)(File *, Room *, int) = NULL; int version; if (filename == NULL || !*filename || (r = new_Room()) == NULL) return NULL; if ((f = Fopen(filename)) == NULL) { destroy_Room(r); return NULL; } r->number = number; version = fileformat_version(f); switch(version) { case -1: log_err("load_RoomData(): error trying to determine file format version of %s", filename); load_func = NULL; break; case 0: Frewind(f); load_func = load_RoomData_version0; break; case 1: load_func = load_RoomData_version1; break; default: log_err("load_RoomData(): don't know how to load version %d of %s", version, filename); } if (load_func != NULL && !load_func(f, r, flags)) { Fclose(f); r->flags &= ROOM_ALL; /* force the room name for Mail> and Home> so that find_abbrevRoom() won't act strangely when these names are different in the files for some strange reason */ if (r->number == MAIL_ROOM) { Free(r->name); r->name = cstrdup("Mail"); } if (r->number == HOME_ROOM) { Free(r->name); r->name = cstrdup("Home"); } if (r->number == MAIL_ROOM) r->max_msgs = PARAM_MAX_MAIL_MSGS; else if (r->max_msgs < 1) r->max_msgs = PARAM_MAX_MESSAGES; if (PARAM_HAVE_CHATROOMS && (r->flags & ROOM_CHATROOM) && r->chat_history == NULL) r->chat_history = new_StringQueue(); if (!PARAM_HAVE_CHATROOMS && (r->flags & ROOM_CHATROOM) && r->number != HOME_ROOM) { r->flags &= ~ROOM_CHATROOM; r->flags |= ROOM_DIRTY; } (void)sort_StringList(&r->room_aides, alphasort_StringList); (void)sort_StringList(&r->invited, alphasort_StringList); (void)sort_StringList(&r->kicked, alphasort_StringList); return r; } destroy_Room(r); Fclose(f); return NULL; }
// Load the device module bool Win32LoadSecModule(SECURE *sec) { SEC_DATA_WIN32 *w; HINSTANCE hInst; CK_FUNCTION_LIST_PTR api = NULL; CK_RV (*get_function_list)(CK_FUNCTION_LIST_PTR_PTR); // Validate arguments if (sec == NULL) { return false; } if (sec->Dev->Id == 9) { char username[MAX_SIZE]; DWORD size; // Because the device driver of Juki-Net needs the contents // of the Software\JPKI registry key on HKLU of SYSTEM, // if there is no key, copy the key from the value of other user // if (MsRegIsValue(REG_CURRENT_USER, "Software\\JPKI", "Name") == false || // MsRegIsValue(REG_CURRENT_USER, "Software\\JPKI", "RWType") == false) size = sizeof(username); GetUserName(username, &size); if (StrCmpi(username, "System") == 0) { TOKEN_LIST *t = MsRegEnumKey(REG_USERS, NULL); if (t != NULL) { UINT i; for (i = 0;i < t->NumTokens;i++) { char tmp[MAX_PATH]; if (StrCmpi(t->Token[i], ".DEFAULT") != 0 && StrCmpi(t->Token[i], "S-1-5-18") != 0) { Format(tmp, sizeof(tmp), "%s\\Software\\JPKI", t->Token[i]); if (MsRegIsValue(REG_USERS, tmp, "Name") && MsRegIsValue(REG_USERS, tmp, "RWType")) { char *name = MsRegReadStr(REG_USERS, tmp, "Name"); char *port = MsRegReadStr(REG_USERS, tmp, "Port"); UINT type = MsRegReadInt(REG_USERS, tmp, "RWType"); MsRegWriteStr(REG_CURRENT_USER, "Software\\JPKI", "Name", name); MsRegWriteStr(REG_CURRENT_USER, "Software\\JPKI", "Port", port); MsRegWriteInt(REG_CURRENT_USER, "Software\\JPKI", "RWType", type); Free(name); Free(port); break; } } } FreeToken(t); } } } // Load the Library hInst = Win32SecureLoadLibraryEx(sec->Dev->ModuleName, 0); if (hInst == NULL) { // Failure return false; } // Get the API get_function_list = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR)) GetProcAddress(hInst, "C_GetFunctionList"); if (get_function_list == NULL) { // Failure FreeLibrary(hInst); return false; } get_function_list(&api); if (api == NULL) { // Failure FreeLibrary(hInst); return false; } sec->Data = ZeroMalloc(sizeof(SEC_DATA_WIN32)); w = sec->Data; w->hInst = hInst; sec->Api = api; return true; }
CToolsPanelContainer::~CToolsPanelContainer() { Free(); }
static int SDLGL_OpenVideo(void *obj, Uint w, Uint h, int depth, Uint flags) { char buf[256]; AG_Driver *drv = obj; AG_DriverSw *dsw = obj; AG_DriverSDLGL *sgl = obj; Uint32 sFlags = SDL_OPENGL; int newDepth; /* Set the requested display options. */ if (flags & AG_VIDEO_RESIZABLE) { sFlags |= SDL_RESIZABLE; } if (flags & AG_VIDEO_ANYFORMAT) { sFlags |= SDL_ANYFORMAT; } if (flags & AG_VIDEO_HWPALETTE) { sFlags |= SDL_HWPALETTE; } if (flags & AG_VIDEO_DOUBLEBUF) { sFlags |= SDL_DOUBLEBUF; } if (flags & AG_VIDEO_FULLSCREEN) { sFlags |= SDL_FULLSCREEN; } if (flags & AG_VIDEO_NOFRAME) { sFlags |= SDL_NOFRAME; } if (flags & AG_VIDEO_OVERLAY) dsw->flags |= AG_DRIVER_SW_OVERLAY; if (flags & AG_VIDEO_BGPOPUPMENU) dsw->flags |= AG_DRIVER_SW_BGPOPUP; /* Apply the output capture settings. */ if (AG_Defined(drv, "out")) { char *ext; AG_GetString(drv, "out", buf, sizeof(buf)); if ((ext = strrchr(buf, '.')) != NULL && ext[1] != '\0') { if (Strcasecmp(&ext[1], "jpeg") == 0 || Strcasecmp(&ext[1], "jpg") == 0) { sgl->outMode = AG_SDLGL_OUT_JPEG; if ((sgl->outPath = TryStrdup(buf)) == NULL) return (-1); } else if (Strcasecmp(&ext[1], "png") == 0) { sgl->outMode = AG_SDLGL_OUT_PNG; if ((sgl->outPath = TryStrdup(buf)) == NULL) return (-1); } else { AG_SetError("Invalid out= argument: `%s'", buf); return (-1); } if (AG_Defined(drv, "outFirst")) { AG_GetString(drv, "outFirst", buf, sizeof(buf)); sgl->outFrame = atoi(buf); } else { sgl->outFrame = 0; } if (AG_Defined(drv, "outLast")) { AG_GetString(drv, "outLast", buf, sizeof(buf)); sgl->outLast = atoi(buf); } } } /* Set the video mode. Force hardware palette in 8bpp. */ AG_SDL_GetPrefDisplaySettings(drv, &w, &h, &depth); Verbose(_("SDLGL: Setting mode %ux%u (%d bpp)\n"), w, h, depth); newDepth = SDL_VideoModeOK(w, h, depth, sFlags); if (newDepth == 8) { Verbose(_("Enabling hardware palette")); sFlags |= SDL_HWPALETTE; } if ((sgl->s = SDL_SetVideoMode((int)w, (int)h, newDepth, sFlags)) == NULL) { AG_SetError("Setting %dx%dx%d mode: %s", w, h, newDepth, SDL_GetError()); return (-1); } SDL_EnableUNICODE(1); if ((drv->videoFmt = AG_SDL_GetPixelFormat(sgl->s)) == NULL) { goto fail; } dsw->w = sgl->s->w; dsw->h = sgl->s->h; dsw->depth = (Uint)drv->videoFmt->BitsPerPixel; Verbose(_("SDLGL: New display (%dbpp)\n"), (int)drv->videoFmt->BitsPerPixel); /* Create the cursors. */ if (AG_SDL_InitDefaultCursor(sgl) == -1 || AG_InitStockCursors(drv) == -1) goto fail; /* Set background color. */ dsw->bgColor = AG_ColorFromString(AG_GetStringP(drv,"bgColor"), NULL); /* Initialize our OpenGL context and viewport. */ if (AG_GL_InitContext(sgl, &sgl->gl) == -1) { goto fail; } AG_GL_SetViewport(&sgl->gl, AG_RECT(0, 0, dsw->w, dsw->h)); if (!(dsw->flags & AG_DRIVER_SW_OVERLAY)) ClearBackground(dsw); /* Initialize the output capture buffer. */ Free(sgl->outBuf); if ((sgl->outBuf = AG_TryMalloc(dsw->w*dsw->h*4)) == NULL) { AG_Verbose("Out of memory for buffer; disabling capture\n"); sgl->outMode = AG_SDLGL_OUT_NONE; } if (flags & AG_VIDEO_FULLSCREEN) { if (SDL_WM_ToggleFullScreen(sgl->s)) dsw->flags |= AG_DRIVER_SW_FULLSCREEN; } return (0); fail: if (drv->videoFmt) { AG_PixelFormatFree(drv->videoFmt); drv->videoFmt = NULL; } return (-1); }
//******************************************** // Destructor //******************************************** Texture::~Texture() { Free(); }
//todo: this function is an abomination, this is just disgusting. fix it. //...seriously, this is really, really horrible. I mean this is amazingly bad. void OBS::MainCaptureLoop() { int curRenderTarget = 0, curYUVTexture = 0, curCopyTexture = 0; int copyWait = NUM_RENDER_BUFFERS-1; bSentHeaders = false; bFirstAudioPacket = true; bool bLogLongFramesProfile = GlobalConfig->GetInt(TEXT("General"), TEXT("LogLongFramesProfile"), LOGLONGFRAMESDEFAULT) != 0; float logLongFramesProfilePercentage = GlobalConfig->GetFloat(TEXT("General"), TEXT("LogLongFramesProfilePercentage"), 10.f); Vect2 baseSize = Vect2(float(baseCX), float(baseCY)); Vect2 outputSize = Vect2(float(outputCX), float(outputCY)); Vect2 scaleSize = Vect2(float(scaleCX), float(scaleCY)); HANDLE hMatrix = yuvScalePixelShader->GetParameterByName(TEXT("yuvMat")); HANDLE hScaleVal = yuvScalePixelShader->GetParameterByName(TEXT("baseDimensionI")); //---------------------------------------- // x264 input buffers int curOutBuffer = 0; bool bUsingQSV = videoEncoder->isQSV();//GlobalConfig->GetInt(TEXT("Video Encoding"), TEXT("UseQSV")) != 0; bUsing444 = false; EncoderPicture lastPic; EncoderPicture outPics[NUM_OUT_BUFFERS]; for(int i=0; i<NUM_OUT_BUFFERS; i++) { if(bUsingQSV) { outPics[i].mfxOut = new mfxFrameSurface1; memset(outPics[i].mfxOut, 0, sizeof(mfxFrameSurface1)); mfxFrameData& data = outPics[i].mfxOut->Data; videoEncoder->RequestBuffers(&data); } else { outPics[i].picOut = new x264_picture_t; x264_picture_init(outPics[i].picOut); } } if(bUsing444) { for(int i=0; i<NUM_OUT_BUFFERS; i++) { outPics[i].picOut->img.i_csp = X264_CSP_BGRA; //although the x264 input says BGR, x264 actually will expect packed UYV outPics[i].picOut->img.i_plane = 1; } } else { if(!bUsingQSV) for(int i=0; i<NUM_OUT_BUFFERS; i++) x264_picture_alloc(outPics[i].picOut, X264_CSP_NV12, outputCX, outputCY); } int bCongestionControl = AppConfig->GetInt (TEXT("Video Encoding"), TEXT("CongestionControl"), 0); bool bDynamicBitrateSupported = App->GetVideoEncoder()->DynamicBitrateSupported(); int defaultBitRate = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("MaxBitrate"), 1000); int currentBitRate = defaultBitRate; QWORD lastAdjustmentTime = 0; UINT adjustmentStreamId = 0; //std::unique_ptr<ProfilerNode> encodeThreadProfiler; //---------------------------------------- // time/timestamp stuff bool bWasLaggedFrame = false; totalStreamTime = 0; lastAudioTimestamp = 0; //---------------------------------------- // start audio capture streams desktopAudio->StartCapture(); if(micAudio) micAudio->StartCapture(); //---------------------------------------- // status bar/statistics stuff DWORD fpsCounter = 0; int numLongFrames = 0; int numTotalFrames = 0; bytesPerSec = 0; captureFPS = 0; curFramesDropped = 0; curStrain = 0.0; PostMessage(hwndMain, OBS_UPDATESTATUSBAR, 0, 0); QWORD lastBytesSent[3] = {0, 0, 0}; DWORD lastFramesDropped = 0; double bpsTime = 0.0; double lastStrain = 0.0f; DWORD numSecondsWaited = 0; //---------------------------------------- // 444->420 thread data int numThreads = MAX(OSGetTotalCores()-2, 1); HANDLE *h420Threads = (HANDLE*)Allocate(sizeof(HANDLE)*numThreads); Convert444Data *convertInfo = (Convert444Data*)Allocate(sizeof(Convert444Data)*numThreads); zero(h420Threads, sizeof(HANDLE)*numThreads); zero(convertInfo, sizeof(Convert444Data)*numThreads); for(int i=0; i<numThreads; i++) { convertInfo[i].width = outputCX; convertInfo[i].height = outputCY; convertInfo[i].hSignalConvert = CreateEvent(NULL, FALSE, FALSE, NULL); convertInfo[i].hSignalComplete = CreateEvent(NULL, FALSE, FALSE, NULL); convertInfo[i].bNV12 = bUsingQSV; convertInfo[i].numThreads = numThreads; if(i == 0) convertInfo[i].startY = 0; else convertInfo[i].startY = convertInfo[i-1].endY; if(i == (numThreads-1)) convertInfo[i].endY = outputCY; else convertInfo[i].endY = ((outputCY/numThreads)*(i+1)) & 0xFFFFFFFE; } bool bEncode; bool bFirstFrame = true; bool bFirstImage = true; bool bFirstEncode = true; bool bUseThreaded420 = bUseMultithreadedOptimizations && (OSGetTotalCores() > 1) && !bUsing444; List<HANDLE> completeEvents; if(bUseThreaded420) { for(int i=0; i<numThreads; i++) { h420Threads[i] = OSCreateThread((XTHREAD)Convert444Thread, convertInfo+i); completeEvents << convertInfo[i].hSignalComplete; } } //---------------------------------------- QWORD streamTimeStart = GetQPCTimeNS(); QWORD lastStreamTime = 0; QWORD firstFrameTimeMS = streamTimeStart/1000000; QWORD frameLengthNS = 1000000000/fps; while(WaitForSingleObject(hVideoEvent, INFINITE) == WAIT_OBJECT_0) { if (bShutdownVideoThread) break; QWORD renderStartTime = GetQPCTimeNS(); totalStreamTime = DWORD((renderStartTime-streamTimeStart)/1000000); bool bRenderView = !IsIconic(hwndMain) && bRenderViewEnabled; QWORD renderStartTimeMS = renderStartTime/1000000; QWORD curStreamTime = latestVideoTimeNS; if (!lastStreamTime) lastStreamTime = curStreamTime-frameLengthNS; QWORD frameDelta = curStreamTime-lastStreamTime; //if (!lastStreamTime) // lastStreamTime = renderStartTime-frameLengthNS; //QWORD frameDelta = renderStartTime-lastStreamTime; double fSeconds = double(frameDelta)*0.000000001; //lastStreamTime = renderStartTime; bool bUpdateBPS = false; profileIn("video thread frame"); //Log(TEXT("Stream Time: %llu"), curStreamTime); //Log(TEXT("frameDelta: %lf"), fSeconds); //------------------------------------ if(bRequestKeyframe && keyframeWait > 0) { keyframeWait -= int(frameDelta); if(keyframeWait <= 0) { GetVideoEncoder()->RequestKeyframe(); bRequestKeyframe = false; } } if(!bPushToTalkDown && pushToTalkTimeLeft > 0) { pushToTalkTimeLeft -= int(frameDelta); OSDebugOut(TEXT("time left: %d\r\n"), pushToTalkTimeLeft); if(pushToTalkTimeLeft <= 0) { pushToTalkTimeLeft = 0; bPushToTalkOn = false; } } //------------------------------------ OSEnterMutex(hSceneMutex); if (bPleaseEnableProjector) ActuallyEnableProjector(); else if(bPleaseDisableProjector) DisableProjector(); if(bResizeRenderView) { GS->ResizeView(); bResizeRenderView = false; } //------------------------------------ if(scene) { profileIn("scene->Preprocess"); scene->Preprocess(); for(UINT i=0; i<globalSources.Num(); i++) globalSources[i].source->Preprocess(); profileOut; scene->Tick(float(fSeconds)); for(UINT i=0; i<globalSources.Num(); i++) globalSources[i].source->Tick(float(fSeconds)); } //------------------------------------ QWORD curBytesSent = network->GetCurrentSentBytes(); curFramesDropped = network->NumDroppedFrames(); bpsTime += fSeconds; if(bpsTime > 1.0f) { if(numSecondsWaited < 3) ++numSecondsWaited; //bytesPerSec = DWORD(curBytesSent - lastBytesSent); bytesPerSec = DWORD(curBytesSent - lastBytesSent[0]) / numSecondsWaited; if(bpsTime > 2.0) bpsTime = 0.0f; else bpsTime -= 1.0; if(numSecondsWaited == 3) { lastBytesSent[0] = lastBytesSent[1]; lastBytesSent[1] = lastBytesSent[2]; lastBytesSent[2] = curBytesSent; } else lastBytesSent[numSecondsWaited] = curBytesSent; captureFPS = fpsCounter; fpsCounter = 0; bUpdateBPS = true; } fpsCounter++; curStrain = network->GetPacketStrain(); EnableBlending(TRUE); BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA); //------------------------------------ // render the mini render texture LoadVertexShader(mainVertexShader); LoadPixelShader(mainPixelShader); SetRenderTarget(mainRenderTextures[curRenderTarget]); Ortho(0.0f, baseSize.x, baseSize.y, 0.0f, -100.0f, 100.0f); SetViewport(0, 0, baseSize.x, baseSize.y); if(scene) scene->Render(); //------------------------------------ if(bTransitioning) { if(!transitionTexture) { transitionTexture = CreateTexture(baseCX, baseCY, GS_BGRA, NULL, FALSE, TRUE); if(transitionTexture) { D3D10Texture *d3dTransitionTex = static_cast<D3D10Texture*>(transitionTexture); D3D10Texture *d3dSceneTex = static_cast<D3D10Texture*>(mainRenderTextures[lastRenderTarget]); GetD3D()->CopyResource(d3dTransitionTex->texture, d3dSceneTex->texture); } else bTransitioning = false; } else if(transitionAlpha >= 1.0f) { delete transitionTexture; transitionTexture = NULL; bTransitioning = false; } } if(bTransitioning) { EnableBlending(TRUE); transitionAlpha += float(fSeconds)*5.0f; if(transitionAlpha > 1.0f) transitionAlpha = 1.0f; } else EnableBlending(FALSE); //------------------------------------ // render the mini view thingy if (bProjector) { SetRenderTarget(projectorTexture); Vect2 renderFrameSize, renderFrameOffset; Vect2 projectorSize = Vect2(float(projectorWidth), float(projectorHeight)); float projectorAspect = (projectorSize.x / projectorSize.y); float baseAspect = (baseSize.x / baseSize.y); if (projectorAspect < baseAspect) { float fProjectorWidth = float(projectorWidth); renderFrameSize = Vect2(fProjectorWidth, fProjectorWidth / baseAspect); renderFrameOffset = Vect2(0.0f, (projectorSize.y-renderFrameSize.y) * 0.5f); } else { float fProjectorHeight = float(projectorHeight); renderFrameSize = Vect2(fProjectorHeight * baseAspect, fProjectorHeight); renderFrameOffset = Vect2((projectorSize.x-renderFrameSize.x) * 0.5f, 0.0f); } DrawPreview(renderFrameSize, renderFrameOffset, projectorSize, curRenderTarget, Preview_Projector); SetRenderTarget(NULL); } if(bRenderView) { // Cache const Vect2 renderFrameSize = GetRenderFrameSize(); const Vect2 renderFrameOffset = GetRenderFrameOffset(); const Vect2 renderFrameCtrlSize = GetRenderFrameControlSize(); SetRenderTarget(NULL); DrawPreview(renderFrameSize, renderFrameOffset, renderFrameCtrlSize, curRenderTarget, bFullscreenMode ? Preview_Fullscreen : Preview_Standard); //draw selections if in edit mode if(bEditMode && !bSizeChanging) { if(scene) { LoadVertexShader(solidVertexShader); LoadPixelShader(solidPixelShader); solidPixelShader->SetColor(solidPixelShader->GetParameter(0), 0xFF0000); scene->RenderSelections(solidPixelShader); } } } else if(bForceRenderViewErase) { InvalidateRect(hwndRenderFrame, NULL, TRUE); UpdateWindow(hwndRenderFrame); bForceRenderViewErase = false; } //------------------------------------ // actual stream output LoadVertexShader(mainVertexShader); LoadPixelShader(yuvScalePixelShader); Texture *yuvRenderTexture = yuvRenderTextures[curRenderTarget]; SetRenderTarget(yuvRenderTexture); switch(colorDesc.matrix) { case ColorMatrix_GBR: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[0] : (float*)yuvMat[0]); break; case ColorMatrix_YCgCo: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[1] : (float*)yuvMat[1]); break; case ColorMatrix_BT2020NCL: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[2] : (float*)yuvMat[2]); break; case ColorMatrix_BT709: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[3] : (float*)yuvMat[3]); break; case ColorMatrix_SMPTE240M: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[4] : (float*)yuvMat[4]); break; default: yuvScalePixelShader->SetMatrix(hMatrix, colorDesc.fullRange ? (float*)yuvFullMat[5] : (float*)yuvMat[5]); } if(downscale < 2.01) yuvScalePixelShader->SetVector2(hScaleVal, 1.0f/baseSize); else if(downscale < 3.01) yuvScalePixelShader->SetVector2(hScaleVal, 1.0f/(outputSize*3.0f)); Ortho(0.0f, outputSize.x, outputSize.y, 0.0f, -100.0f, 100.0f); SetViewport(0.0f, 0.0f, outputSize.x, outputSize.y); //why am I using scaleSize instead of outputSize for the texture? //because outputSize can be trimmed by up to three pixels due to 128-bit alignment. //using the scale function with outputSize can cause slightly inaccurate scaled images if(bTransitioning) { BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO); DrawSpriteEx(transitionTexture, 0xFFFFFFFF, 0.0f, 0.0f, scaleSize.x, scaleSize.y, 0.0f, 0.0f, 1.0f, 1.0f); BlendFunction(GS_BLEND_FACTOR, GS_BLEND_INVFACTOR, transitionAlpha); } DrawSpriteEx(mainRenderTextures[curRenderTarget], 0xFFFFFFFF, 0.0f, 0.0f, outputSize.x, outputSize.y, 0.0f, 0.0f, 1.0f, 1.0f); //------------------------------------ if (bProjector && !copyWait) projectorSwap->Present(0, 0); if(bRenderView && !copyWait) static_cast<D3D10System*>(GS)->swap->Present(0, 0); OSLeaveMutex(hSceneMutex); //------------------------------------ // present/upload profileIn("GPU download and conversion"); bEncode = true; if(copyWait) { copyWait--; bEncode = false; } else { //audio sometimes takes a bit to start -- do not start processing frames until audio has started capturing if(!bRecievedFirstAudioFrame) { static bool bWarnedAboutNoAudio = false; if (renderStartTimeMS-firstFrameTimeMS > 10000 && !bWarnedAboutNoAudio) { bWarnedAboutNoAudio = true; //AddStreamInfo (TEXT ("WARNING: OBS is not receiving audio frames. Please check your audio devices."), StreamInfoPriority_Critical); } bEncode = false; } else if(bFirstFrame) { firstFrameTimestamp = lastStreamTime/1000000; bFirstFrame = false; } if(!bEncode) { if(curYUVTexture == (NUM_RENDER_BUFFERS-1)) curYUVTexture = 0; else curYUVTexture++; } } lastStreamTime = curStreamTime; if(bEncode) { UINT prevCopyTexture = (curCopyTexture == 0) ? NUM_RENDER_BUFFERS-1 : curCopyTexture-1; ID3D10Texture2D *copyTexture = copyTextures[curCopyTexture]; profileIn("CopyResource"); if(!bFirstEncode && bUseThreaded420) { WaitForMultipleObjects(completeEvents.Num(), completeEvents.Array(), TRUE, INFINITE); copyTexture->Unmap(0); } D3D10Texture *d3dYUV = static_cast<D3D10Texture*>(yuvRenderTextures[curYUVTexture]); GetD3D()->CopyResource(copyTexture, d3dYUV->texture); profileOut; ID3D10Texture2D *prevTexture = copyTextures[prevCopyTexture]; if(bFirstImage) //ignore the first frame bFirstImage = false; else { HRESULT result; D3D10_MAPPED_TEXTURE2D map; if(SUCCEEDED(result = prevTexture->Map(0, D3D10_MAP_READ, 0, &map))) { int prevOutBuffer = (curOutBuffer == 0) ? NUM_OUT_BUFFERS-1 : curOutBuffer-1; int nextOutBuffer = (curOutBuffer == NUM_OUT_BUFFERS-1) ? 0 : curOutBuffer+1; EncoderPicture &prevPicOut = outPics[prevOutBuffer]; EncoderPicture &picOut = outPics[curOutBuffer]; EncoderPicture &nextPicOut = outPics[nextOutBuffer]; if(!bUsing444) { profileIn("conversion to 4:2:0"); if(bUseThreaded420) { for(int i=0; i<numThreads; i++) { convertInfo[i].input = (LPBYTE)map.pData; convertInfo[i].inPitch = map.RowPitch; if(bUsingQSV) { mfxFrameData& data = nextPicOut.mfxOut->Data; videoEncoder->RequestBuffers(&data); convertInfo[i].outPitch = data.Pitch; convertInfo[i].output[0] = data.Y; convertInfo[i].output[1] = data.UV; } else { convertInfo[i].output[0] = nextPicOut.picOut->img.plane[0]; convertInfo[i].output[1] = nextPicOut.picOut->img.plane[1]; convertInfo[i].output[2] = nextPicOut.picOut->img.plane[2]; } SetEvent(convertInfo[i].hSignalConvert); } if(bFirstEncode) bFirstEncode = bEncode = false; } else { if(bUsingQSV) { mfxFrameData& data = picOut.mfxOut->Data; videoEncoder->RequestBuffers(&data); LPBYTE output[] = {data.Y, data.UV}; Convert444toNV12((LPBYTE)map.pData, outputCX, map.RowPitch, data.Pitch, outputCY, 0, outputCY, output); } else Convert444toNV12((LPBYTE)map.pData, outputCX, map.RowPitch, outputCX, outputCY, 0, outputCY, picOut.picOut->img.plane); prevTexture->Unmap(0); } profileOut; } if(bEncode) { //encodeThreadProfiler.reset(::new ProfilerNode(TEXT("EncodeThread"), true)); //encodeThreadProfiler->MonitorThread(hEncodeThread); curFramePic = &picOut; } curOutBuffer = nextOutBuffer; } else { //We have to crash, or we end up deadlocking the thread when the convert threads are never signalled if (result == DXGI_ERROR_DEVICE_REMOVED) { String message; HRESULT reason = GetD3D()->GetDeviceRemovedReason(); switch (reason) { case DXGI_ERROR_DEVICE_RESET: case DXGI_ERROR_DEVICE_HUNG: message = TEXT("Your video card or driver froze and was reset. Please check for possible hardware / driver issues."); break; case DXGI_ERROR_DEVICE_REMOVED: message = TEXT("Your video card disappeared from the system. Please check for possible hardware / driver issues."); break; case DXGI_ERROR_DRIVER_INTERNAL_ERROR: message = TEXT("Your video driver reported an internal error. Please check for possible hardware / driver issues."); break; case DXGI_ERROR_INVALID_CALL: message = TEXT("Your video driver reported an invalid call. Please check for possible driver issues."); break; default: message = TEXT("DXGI_ERROR_DEVICE_REMOVED"); break; } message << TEXT(" This error can also occur if you have enabled opencl in x264 custom settings."); CrashError (TEXT("Texture->Map failed: 0x%08x 0x%08x\r\n\r\n%s"), result, reason, message.Array()); } else CrashError (TEXT("Texture->Map failed: 0x%08x"), result); } } if(curCopyTexture == (NUM_RENDER_BUFFERS-1)) curCopyTexture = 0; else curCopyTexture++; if(curYUVTexture == (NUM_RENDER_BUFFERS-1)) curYUVTexture = 0; else curYUVTexture++; if (bCongestionControl && bDynamicBitrateSupported && !bTestStream && totalStreamTime > 15000) { if (curStrain > 25) { if (renderStartTimeMS - lastAdjustmentTime > 1500) { if (currentBitRate > 100) { currentBitRate = (int)(currentBitRate * (1.0 - (curStrain / 400))); App->GetVideoEncoder()->SetBitRate(currentBitRate, -1); if (!adjustmentStreamId) adjustmentStreamId = App->AddStreamInfo (FormattedString(TEXT("Congestion detected, dropping bitrate to %d kbps"), currentBitRate).Array(), StreamInfoPriority_Low); else App->SetStreamInfo(adjustmentStreamId, FormattedString(TEXT("Congestion detected, dropping bitrate to %d kbps"), currentBitRate).Array()); bUpdateBPS = true; } lastAdjustmentTime = renderStartTimeMS; } } else if (currentBitRate < defaultBitRate && curStrain < 5 && lastStrain < 5) { if (renderStartTimeMS - lastAdjustmentTime > 5000) { if (currentBitRate < defaultBitRate) { currentBitRate += (int)(defaultBitRate * 0.05); if (currentBitRate > defaultBitRate) currentBitRate = defaultBitRate; } App->GetVideoEncoder()->SetBitRate(currentBitRate, -1); /*if (!adjustmentStreamId) App->AddStreamInfo (FormattedString(TEXT("Congestion clearing, raising bitrate to %d kbps"), currentBitRate).Array(), StreamInfoPriority_Low); else App->SetStreamInfo(adjustmentStreamId, FormattedString(TEXT("Congestion clearing, raising bitrate to %d kbps"), currentBitRate).Array());*/ App->RemoveStreamInfo(adjustmentStreamId); adjustmentStreamId = 0; bUpdateBPS = true; lastAdjustmentTime = renderStartTimeMS; } } } } lastRenderTarget = curRenderTarget; if(curRenderTarget == (NUM_RENDER_BUFFERS-1)) curRenderTarget = 0; else curRenderTarget++; if(bUpdateBPS || !CloseDouble(curStrain, lastStrain) || curFramesDropped != lastFramesDropped) { PostMessage(hwndMain, OBS_UPDATESTATUSBAR, 0, 0); lastStrain = curStrain; lastFramesDropped = curFramesDropped; } //------------------------------------ // we're about to sleep so we should flush the d3d command queue profileIn("flush"); GetD3D()->Flush(); profileOut; profileOut; profileOut; //frame //------------------------------------ // frame sync QWORD renderStopTime = GetQPCTimeNS(); if(bWasLaggedFrame = (frameDelta > frameLengthNS)) { numLongFrames++; if(bLogLongFramesProfile && (numLongFrames/float(max(1, numTotalFrames)) * 100.) > logLongFramesProfilePercentage) DumpLastProfileData(); } //OSDebugOut(TEXT("Frame adjust time: %d, "), frameTimeAdjust-totalTime); numTotalFrames++; } DisableProjector(); //encodeThreadProfiler.reset(); if(!bUsing444) { if(bUseThreaded420) { for(int i=0; i<numThreads; i++) { if(h420Threads[i]) { convertInfo[i].bKillThread = true; SetEvent(convertInfo[i].hSignalConvert); OSTerminateThread(h420Threads[i], 10000); h420Threads[i] = NULL; } if(convertInfo[i].hSignalConvert) { CloseHandle(convertInfo[i].hSignalConvert); convertInfo[i].hSignalConvert = NULL; } if(convertInfo[i].hSignalComplete) { CloseHandle(convertInfo[i].hSignalComplete); convertInfo[i].hSignalComplete = NULL; } } if(!bFirstEncode) { ID3D10Texture2D *copyTexture = copyTextures[curCopyTexture]; copyTexture->Unmap(0); } } if(bUsingQSV) for(int i = 0; i < NUM_OUT_BUFFERS; i++) delete outPics[i].mfxOut; else for(int i=0; i<NUM_OUT_BUFFERS; i++) { x264_picture_clean(outPics[i].picOut); delete outPics[i].picOut; } } Free(h420Threads); Free(convertInfo); Log(TEXT("Total frames rendered: %d, number of late frames: %d (%0.2f%%) (it's okay for some frames to be late)"), numTotalFrames, numLongFrames, (double(numLongFrames)/double(numTotalFrames))*100.0); }
int read_config(char *file, srv_t * srv) { FILE *fp; char s[LINEBUF], *cp, *sp, pluginname[256]; char section = 0, *dbname = 0, *dbload = 0; unsigned int n = 0; long lval; int i; plugin_t *plugins, *pl = 0; dback_t *dbp = 0; const conf_com_t *ccp; spocp_result_t r; /* * should never be necessary if (!srv->root) srv->root = ruleset_new(0); */ if (!srv->root->db) srv->root->db = db_new(); plugins = srv->plugin; if ((fp = fopen(file, "r")) == NULL) { traceLog(LOG_ERR, "Could not find or open the configuration file \"%s\"", file); return 0; } while (fgets(s, LINEBUF, fp)) { n++; rmcrlf(s); if (*s == 0 || *s == '#') continue; /* * New section */ if (*s == '[') { cp = find_balancing(s + 1, '[', ']'); if (cp == 0) { traceLog(LOG_ERR, err_msg, n, "Section specification"); return 0; } *cp = 0; sp = s + 1; if (strcasecmp(sp, "server") == 0) section = SYSTEM; else if (strcasecmp(sp, "dback") == 0) section = DBACK; else { section = PLUGIN; strlcpy(pluginname, sp, sizeof( pluginname)); pl = 0; } continue; } /* * Within a section The directives are of the form: * key *SP * "=" *SP val *(*SP val) * val = 1*nonspacechar / '"' char '"' */ rm_lt_sp(s, 1); /* remove leading and trailing blanks */ /* * empty line or comment */ if (*s == 0 || *s == '#') continue; cp = strchr(s, '='); if (cp == 0) { traceLog(LOG_ERR, err_msg, n, "syntax error"); continue; } sp = cp; for (*cp++ = '\0'; *cp && (*cp == ' ' || *cp == '\t'); cp++) *cp = '\0'; for (sp--; sp >= s && (*sp == ' ' || *sp == '\t'); sp--) *sp = '\0'; /* * no key, not good */ if (*s == '\0') continue; switch (section) { case SYSTEM: for (i = 1; keyword[i]; i++) if (strcasecmp(keyword[i], s) == 0) break; if (keyword[i] == 0) { #ifdef HAVE_SASL if((strncmp("sasl_", s, 5) == 0)) add_overflow_directive(s, cp); else #endif traceLog(LOG_ERR, err_msg, n, "Unknown keyword"); continue; } switch (i) { case RULEFILE: if (srv->rulefile) free(srv->rulefile); srv->rulefile = Strdup(cp); break; case CERTIFICATE: if (srv->certificateFile) free(srv->certificateFile); srv->certificateFile = Strdup(cp); break; case PRIVATEKEY: if (srv->privateKey) free(srv->privateKey); srv->privateKey = Strdup(cp); break; case CALIST: if (srv->caList) free(srv->caList); srv->caList = Strdup(cp); break; case DHFILE: if (srv->dhFile) free(srv->dhFile); srv->dhFile = Strdup(cp); break; case ENTROPYFILE: if (srv->SslEntropyFile) free(srv->SslEntropyFile); srv->SslEntropyFile = Strdup(cp); break; case PASSWD: if (srv->passwd) free(srv->passwd); srv->passwd = Strdup(cp); break; case LOGGING: if (srv->logfile) free(srv->logfile); srv->logfile = Strdup(cp); break; case TIMEOUT: if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval >= 0 && lval <= YEAR) srv->timeout = (unsigned int) lval; else { traceLog(LOG_ERR, err_msg, n, "Value out of range"); srv->timeout = DEFAULT_TIMEOUT; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric value"); srv->timeout = DEFAULT_TIMEOUT; } break; case UNIXDOMAINSOCKET: if (srv->uds) free(srv->uds); srv->uds = Strdup(cp); break; case PORT: if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval > 0L && lval < 65536) { srv->port = (unsigned int) lval; } else { traceLog(LOG_ERR, err_msg, n, "Number out of range"); srv->port = DEFAULT_PORT; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric value"); } break; case NTHREADS: if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval <= 0) { traceLog(LOG_ERR, err_msg, n, "Value out of range"); return 0; } else { int level = (int) lval; srv->threads = level; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric specification"); return 0; } break; case SSLVERIFYDEPTH: if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval > 0L) { srv->sslverifydepth = (unsigned int) lval; } else { traceLog(LOG_ERR, err_msg, n, "number out of range"); srv->sslverifydepth = 0; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric value"); } break; case PIDFILE: if (srv->pidfile) Free(srv->pidfile); srv->pidfile = Strdup(cp); break; case MAXCONN: if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval > 0L) { srv->nconn = (unsigned int) lval; } else { traceLog(LOG_ERR, err_msg, n, "Number out of range"); srv->sslverifydepth = 0; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric value"); } break; #ifdef HAVE_SSL case CLIENTCERT: if (strcasecmp(cp, "none") == 0) srv->clientcert = NONE; else if (strcasecmp(cp, "demand") == 0) srv->clientcert = DEMAND; else if (strcasecmp(cp, "hard") == 0) srv->clientcert = HARD; break; #endif case NAME: if (srv->name) Free(srv->name); srv->name = Strdup(cp); break; } break; case PLUGIN: if (pl == 0) { if (strcmp(s, "load") != 0) { traceLog(LOG_ERR, err_msg, n, "First directive in plugin sector has to be \"load\""); section = 0; } if ((pl = plugin_load(plugins, pluginname, cp)) == 0) section = 0; else { /* * The last one is placed last */ for (; pl->next; pl = pl->next); } if (plugins == 0) plugins = pl; } else { if (strcmp(s, "poolsize") == 0) { if (numstr(cp, &lval) == SPOCP_SUCCESS) { if (lval <= 0) { traceLog(LOG_ERR, err_msg, n, "Value out of range"); } else { int level = (int) lval; if (pl->dyn == 0) pl->dyn = pdyn_new (level); if (pl->dyn->size == 0) pl->dyn->size = level; } } else { traceLog(LOG_ERR, err_msg, n, "Non numeric specification"); } } else if (strcmp(s, "cachetime") == 0) { if (plugin_add_cachedef(pl, cp) == FALSE ) traceLog(LOG_ERR, err_msg, n, "Cachetime def"); } else if (pl->ccmds == 0) { /* No * directives * allowed */ traceLog(LOG_ERR, err_msg, n, "Directive where there should not be one"); } else { for (ccp = pl->ccmds; ccp; ccp++) { int np=0, j; char **arr; arr = strchop(cp,&np); for (j=0; j<np; j++) traceLog(LOG_ERR, "%s:%s", cp, arr[j]); if (strcmp(ccp->name, s) == 0) { r = ccp->func(&pl-> conf, ccp-> cmd_data, np, arr); if (r != SPOCP_SUCCESS) { traceLog (LOG_ERR, err_msg, n, ccp-> errmsg); } charmatrix_free( arr ); break; } } if (ccp == 0) { traceLog(LOG_ERR,err_msg, n, "Unknown directive"); } } } break; case DBACK: if (dbp == 0) { if (strcmp(s, "name") == 0) { dbname = Strdup(cp); if (dbname && dbload) { dbp = dback_load(dbname, dbload); free(dbname); free(dbload); } } else if (strcmp(s, "load") == 0) { dbload = Strdup(cp); if (dbname && dbload) { dbp = dback_load(dbname, dbload); free(dbname); free(dbload); } } else traceLog(LOG_ERR,err_msg, n, "Unknown directive"); } else { for (ccp = dbp->ccmds; ccp && *ccp->name; ccp++) { if (strcmp(ccp->name, s) == 0) { r = ccp->func(&dbp->conf, ccp->cmd_data, 1, &cp); if (r != SPOCP_SUCCESS) { traceLog(LOG_ERR,err_msg, n, ccp->errmsg); } break; } } if (ccp == 0) { traceLog(LOG_ERR,err_msg, n, "Unknown directive"); } } break; } } fclose(fp); if (srv->pidfile == 0) srv->pidfile = Strdup("spocd.pid"); if (srv->timeout == 0) srv->timeout = DEFAULT_TIMEOUT; if (srv->threads == 0) srv->threads = DEFAULT_NTHREADS; if (srv->sslverifydepth == 0) srv->sslverifydepth = DEFAULT_SSL_DEPTH; srv->plugin = plugins; srv->dback = dbp; return 1; }
CLibrary::~CLibrary() { Free(); }
/* * For the admin device: * /dev/md/admin -> /devices/pseudo/md@0:admin * * For metadevice: * /dev/md/dsk/foobar --> /devices/pseudo/md@0:0,100,blk * /dev/md/rdsk/foobar --> /devices/pseudo/md@0:0,100,raw * * Where 'foobar' is user specified arbitrary name and '100' * is the minor number returned by MD_IOCMAKE_DEV ioctl * */ static int md_create(di_minor_t minor, di_node_t node) { char mn[MAXNAMELEN + 1]; char path[PATH_MAX + 1]; char set_path[PATH_MAX +1]; char sym_path[PATH_MAX + 1]; int set = -1, ret; char *type, *dir; char *device_name; dev_t minor_devt = di_minor_devt(minor); int key; mdsetname_t *sp = NULL; md_error_t ep; /* * Initialize sdssc entry points. Don't worry about the return * value here since the interface functions will get initialized * correctly regardless. */ (void) sdssc_bind_library(); (void) strcpy(mn, di_minor_name(minor)); /* * Check whether we are being requested to setup the admin * device link or one of the metadevice links. They need * to be treated differently. */ if (strcmp(mn, "admin") == 0) { /* there is only one admin link and always in /dev/md/admin */ (void) devfsadm_mklink("md/admin", node, minor, 0); } else { /* * Extract out the minor components and create the * appropriate links. The node looks like: * md@<set>,<mdev>,<type> * where the <set> number is the named diskset, * <mdev> is the metadevice number, and <type> * is the trailing "blk" or "raw" indication. * * NOTE: when <set> is non-zero, we need to create * under the "shared" directory entry instead of linking * into the top level dsk/rdsk directories. */ ret = sscanf(mn, "%d,", &set); if (ret == 1 && (type = strrchr(mn, ',')) != NULL) { type++; if (strcmp(type, "blk") == 0) { dir = "dsk"; } else { dir = "rdsk"; } (void) memset(&ep, '\0', sizeof (ep)); if ((device_name = meta_getnmentbydev(set, MD_SIDEWILD, minor_devt, NULL, NULL, &key, &ep)) == NULL) { (void) close_admin(&ep); return (DEVFSADM_CONTINUE); } if (set == 0) { /* this is a simple md */ (void) snprintf(path, sizeof (path), "md/%s/%s", dir, basename(device_name)); } else { /* this is a shared md */ (void) snprintf(path, sizeof (path), "md/shared/%d/%s/%s", set, dir, basename(device_name)); /* * flush the caches so the next call to * metasetnosetname will get us the * updated cache. */ metaflushnames(0); if ((sp = metasetnosetname(set, &ep)) != NULL) { (void) snprintf(set_path, sizeof (set_path), "md/shared/%d", sp->setno); (void) snprintf(sym_path, sizeof (sym_path), "md/%s", sp->setname); } } (void) devfsadm_mklink(path, node, minor, 0); Free(device_name); if (sp != NULL) { (void) devfsadm_secondary_link(sym_path, set_path, 0); } } } (void) close_admin(&ep); return (DEVFSADM_CONTINUE); }
VBObject::~VBObject(void) { Free(); }
static void internal_glmer_ranef_update(GlmerStruct GS, SEXP b) { SEXP bhat, bprop = PROTECT(duplicate(b)), bVar = GET_SLOT(GS->mer, lme4_bVarSym), Omega = GET_SLOT(GS->mer, lme4_OmegaSym); int i, ione = 1, j, k; double *b = REAL(GET_SLOT(GS->mer, lme4_ranefSym); double devr, one = 1; bhat = R_NilValue; /* subtract deviance at b */ devr = -random_effects_deviance(GS, b); for (i = 0; i < GS->nf; i++) { SEXP Bi = VECTOR_ELT(b, i); int *dims = INTEGER(getAttrib(Bi, R_DimSymbol)); int nlev = dims[0], nci = dims[1]; int ncisqr = nci * nci, ntot = nlev * nci; double *bcopy = Calloc(ntot, double), *bi = REAL(Bi), *bhati = REAL(VECTOR_ELT(bhat, i)), *bpropi = REAL(VECTOR_ELT(bprop, i)), *bVari = REAL(VECTOR_ELT(bVar, i)), *chol = Calloc(ncisqr, double), *delta = Calloc(nci, double), *omgfac = Memcpy(Calloc(ncisqr, double), REAL(VECTOR_ELT(Omega, i)), ncisqr); /* subtract quadratic form in */ /* Omega[[i]] at b */ F77_CALL(dpotrf)("U", &nci, omgfac, &nci, &j); if (j) error(_("Leading %d minor of Omega[[%d]] not positive definite"), j, i + 1); Memcpy(bcopy, bi, ntot); F77_CALL(dtrmm)("R", "U", "T", "N", &nlev, &nci, &one, omgfac, &nci, bcopy, &nlev); for (k = 0; k < ntot; k++) devr -= bcopy[k] * bcopy[k]; /* form bprop and proposal density */ for (k = 0; k < nlev; k++) { /* proposal density at b */ for (j = 0; j < nci; j++) delta[j] = bi[k + j * nlev] - bhati[k + j * nlev]; Memcpy(chol, &(bVari[k * ncisqr]), ncisqr); F77_CALL(dpotrf)("U", &nci, chol, &nci, &j); if (j) error(_("Leading %d minor of bVar[[%d]][,,%d] not positive definite"), j, i + 1, k + 1); F77_CALL(dtrsv)("U", "T", "N", &nci, chol, &nci, delta, &ione); for (j = 0; j < nci; j++) { double nrm = norm_rand(); /* proposal deviate */ devr += delta[j] * delta[j] - nrm * nrm; delta[j] = nrm; } /* scale by Cholesky inverse */ F77_CALL(dtrmv)("U", "T", "N", &nci, chol, &nci, delta, &ione); /* add mean */ for (j = 0; j < nci; j++) bpropi[k + j * nlev] = bhati[k + j * nlev] + delta[j]; } /* add quadratic form in */ /* Omega[[i]] at bprop */ Memcpy(bcopy, bpropi, ntot); F77_CALL(dtrmm)("R", "U", "T", "N", &nlev, &nci, &one, omgfac, &nci, bcopy, &nlev); for (k = 0; k < ntot; k++) devr += bcopy[k] * bcopy[k]; Free(bcopy); Free(chol); Free(delta); Free(omgfac); } /* add deviance at bprop */ /* devr += random_effects_deviance(GS, bprop); */ if (unif_rand() < exp(-0.5 * devr)) for (i = 0; i < GS->nf; i++) { /* copy each face of b */ SEXP Bi = VECTOR_ELT(b, i); int *dims = INTEGER(getAttrib(Bi, R_DimSymbol)); Memcpy(REAL(Bi), REAL(VECTOR_ELT(bprop, i)), dims[0] * dims[1]); } if (asLogical(internal_getElement(GS->cv, "msVerbose"))) { double *b0 = REAL(VECTOR_ELT(bprop, 0)); Rprintf("%5.3f:", exp(-0.5 * devr)); for (k = 0; k < 5; k++) Rprintf("%#10g ", b0[k]); Rprintf("\n"); } UNPROTECT(2); }
int main(int argc, char** argv) { leveldb_t* db; leveldb_comparator_t* cmp; leveldb_cache_t* cache; leveldb_env_t* env; leveldb_options_t* options; leveldb_readoptions_t* roptions; leveldb_writeoptions_t* woptions; char* err = NULL; snprintf(dbname, sizeof(dbname), "/tmp/leveldb_c_test-%d", ((int) geteuid())); StartPhase("create_objects"); cmp = leveldb_comparator_create(NULL, CmpDestroy, CmpCompare, CmpName); env = leveldb_create_default_env(); cache = leveldb_cache_create_lru(100000); options = leveldb_options_create(); leveldb_options_set_comparator(options, cmp); leveldb_options_set_error_if_exists(options, 1); leveldb_options_set_cache(options, cache); leveldb_options_set_env(options, env); leveldb_options_set_info_log(options, NULL); leveldb_options_set_write_buffer_size(options, 100000); leveldb_options_set_paranoid_checks(options, 1); leveldb_options_set_max_open_files(options, 10); leveldb_options_set_block_size(options, 1024); leveldb_options_set_block_restart_interval(options, 8); leveldb_options_set_compression(options, leveldb_no_compression); roptions = leveldb_readoptions_create(); leveldb_readoptions_set_verify_checksums(roptions, 1); leveldb_readoptions_set_fill_cache(roptions, 0); woptions = leveldb_writeoptions_create(); leveldb_writeoptions_set_sync(woptions, 1); StartPhase("destroy"); leveldb_destroy_db(options, dbname, &err); Free(&err); StartPhase("open_error"); db = leveldb_open(options, dbname, &err); CheckCondition(err != NULL); Free(&err); StartPhase("open"); leveldb_options_set_create_if_missing(options, 1); db = leveldb_open(options, dbname, &err); CheckNoError(err); CheckGet(db, roptions, "foo", NULL); StartPhase("put"); leveldb_put(db, woptions, "foo", 3, "hello", 5, &err); CheckNoError(err); CheckGet(db, roptions, "foo", "hello"); StartPhase("writebatch"); { leveldb_writebatch_t* wb = leveldb_writebatch_create(); leveldb_writebatch_put(wb, "foo", 3, "a", 1); leveldb_writebatch_clear(wb); leveldb_writebatch_put(wb, "bar", 3, "b", 1); leveldb_writebatch_put(wb, "box", 3, "c", 1); leveldb_writebatch_delete(wb, "bar", 3); leveldb_write(db, woptions, wb, &err); CheckNoError(err); CheckGet(db, roptions, "foo", "hello"); CheckGet(db, roptions, "bar", NULL); CheckGet(db, roptions, "box", "c"); int pos = 0; leveldb_writebatch_iterate(wb, &pos, CheckPut, CheckDel); CheckCondition(pos == 3); leveldb_writebatch_destroy(wb); } StartPhase("iter"); { leveldb_iterator_t* iter = leveldb_create_iterator(db, roptions); CheckCondition(!leveldb_iter_valid(iter)); leveldb_iter_seek_to_first(iter); CheckCondition(leveldb_iter_valid(iter)); CheckIter(iter, "box", "c"); leveldb_iter_next(iter); CheckIter(iter, "foo", "hello"); leveldb_iter_prev(iter); CheckIter(iter, "box", "c"); leveldb_iter_prev(iter); CheckCondition(!leveldb_iter_valid(iter)); leveldb_iter_seek_to_last(iter); CheckIter(iter, "foo", "hello"); leveldb_iter_seek(iter, "b", 1); CheckIter(iter, "box", "c"); leveldb_iter_get_error(iter, &err); CheckNoError(err); leveldb_iter_destroy(iter); } StartPhase("approximate_sizes"); { int i; int n = 20000; char keybuf[100]; char valbuf[100]; uint64_t sizes[2]; const char* start[2] = { "a", "k00000000000000010000" }; size_t start_len[2] = { 1, 21 }; const char* limit[2] = { "k00000000000000010000", "z" }; size_t limit_len[2] = { 21, 1 }; leveldb_writeoptions_set_sync(woptions, 0); for (i = 0; i < n; i++) { snprintf(keybuf, sizeof(keybuf), "k%020d", i); snprintf(valbuf, sizeof(valbuf), "v%020d", i); leveldb_put(db, woptions, keybuf, strlen(keybuf), valbuf, strlen(valbuf), &err); CheckNoError(err); } leveldb_approximate_sizes(db, 2, start, start_len, limit, limit_len, sizes); CheckCondition(sizes[0] > 0); CheckCondition(sizes[1] > 0); } StartPhase("property"); { char* prop = leveldb_property_value(db, "nosuchprop"); CheckCondition(prop == NULL); prop = leveldb_property_value(db, "leveldb.stats"); CheckCondition(prop != NULL); Free(&prop); } StartPhase("snapshot"); { const leveldb_snapshot_t* snap; snap = leveldb_create_snapshot(db); leveldb_delete(db, woptions, "foo", 3, &err); CheckNoError(err); leveldb_readoptions_set_snapshot(roptions, snap); CheckGet(db, roptions, "foo", "hello"); leveldb_readoptions_set_snapshot(roptions, NULL); CheckGet(db, roptions, "foo", NULL); leveldb_release_snapshot(db, snap); } StartPhase("repair"); { leveldb_close(db); leveldb_options_set_create_if_missing(options, 0); leveldb_options_set_error_if_exists(options, 0); leveldb_repair_db(options, dbname, &err); CheckNoError(err); db = leveldb_open(options, dbname, &err); CheckNoError(err); CheckGet(db, roptions, "foo", NULL); CheckGet(db, roptions, "bar", NULL); CheckGet(db, roptions, "box", "c"); } StartPhase("cleanup"); leveldb_close(db); leveldb_options_destroy(options); leveldb_readoptions_destroy(roptions); leveldb_writeoptions_destroy(woptions); leveldb_cache_destroy(cache); leveldb_comparator_destroy(cmp); leveldb_env_destroy(env); fprintf(stderr, "PASS\n"); return 0; }
/** * Compute the approximation to the deviance using adaptive * Gauss-Hermite quadrature (AGQ). When nAGQ == 1 this is the Laplace * approximation. * * @param pars pointer to a numeric vector of parameters * @param GSp pointer to a GlmerStruct object * @param nAGQp pointer to a scalar integer representing the number of * points in AGQ to use * * @return the approximation to the deviance as computed using AGQ */ SEXP glmer_devAGQ(SEXP pars, SEXP GSp, SEXP nAGQp) { GlmerStruct GS = (GlmerStruct) R_ExternalPtrAddr(GSp); SEXP Omega = GET_SLOT(GS->mer, lme4_OmegaSym), bVar = GET_SLOT(GS->mer, lme4_bVarSym); int i, j, k, nAGQ = asInteger(nAGQp); int n2 = (nAGQ + 1)/2, *Gp = INTEGER(GET_SLOT(GS->mer, lme4_GpSym)), *nc = INTEGER(GET_SLOT(GS->mer, lme4_ncSym)); double *f0, LaplaceDev = 0, AGQadjst = 0, *bhat = REAL(GET_SLOT(GS->mer, lme4_ranefSym)); if (!isReal(pars) || LENGTH(pars) != GS->npar) error(_("`%s' must be a numeric vector of length %d"), "pars", GS->npar); if (GS->nf > 1 && nAGQ > 1) { warning(_("AGQ not available for multiple grouping factors - using Laplace")); nAGQ = 1; } if (!internal_bhat(GS, REAL(pars), REAL(pars) + (GS->p))) return ScalarReal(DBL_MAX); for (i = 0; i < GS->nf; i++) { int nci = nc[i]; int ncip1 = nci + 1, ncisqr = nci * nci, nlev = (Gp[i + 1] - Gp[i])/nci; double *omgf = REAL(GET_SLOT(M_dpoMatrix_chol(VECTOR_ELT(Omega, i)), lme4_xSym)), *bVi = Memcpy(Calloc(ncisqr * nlev, double), REAL(VECTOR_ELT(bVar, i)), ncisqr * nlev); for (j = 0; j < nci; j++) { /* nlev * logDet(Omega_i) */ LaplaceDev += 2 * nlev * log(omgf[j * ncip1]); } for (k = 0; k < nlev; k++) { double *bVik = bVi + k * ncisqr; F77_CALL(dpotrf)("U", &nci, bVik, &nci, &j); if (j) error(_("Leading %d minor of bVar[[%d]][,,%d] not positive definite"), j, i + 1, k + 1); for (j = 0; j < nci; j++) LaplaceDev -= 2 * log(bVik[j * ncip1]); } f0 = Calloc(nlev, double); rel_dev_1(GS, bhat, nlev, nci, i, (double *) NULL, omgf, bVi, f0); for (k = 0; k < nlev; k++) LaplaceDev += f0[k]; if (nAGQ > 1) { double *fx = Calloc(nlev, double), *rellik = Calloc(nlev, double), *delb = Calloc(nci, double); if (nci > 1) error(_("code not yet written")); AZERO(rellik, nlev); /* zero accumulator */ for (k = 0; k < n2; k++) { delb[0] = GHQ_x[nAGQ][k]; if (delb[0]) { rel_dev_1(GS, bhat, nlev, nci, i, delb, omgf, bVi, fx); for (j = 0; j < nlev; j++) { rellik[j] += GHQ_w[nAGQ][k] * exp(-(fx[j] - f0[j])/2); } delb[0] *= -1; rel_dev_1(GS, bhat, nlev, nci, i, delb, omgf, bVi, fx); for (j = 0; j < nlev; j++) { rellik[j] += GHQ_w[nAGQ][k] * exp(-(fx[j] - f0[j])/2); } } else { for (j = 0; j < nlev; j++) rellik[j] += GHQ_w[nAGQ][k]; } } for (j = 0; j < nlev; j++) AGQadjst -= 2 * log(rellik[j]); Free(fx); Free(rellik); } Free(f0); Free(bVi); }
/** Virtual destructor calls Free() to delete the objects contained in the linked list, in a thread-safe manner.*/ virtual ~VCriticalLinkedListManager() { Free(); }
CEncoder::~CEncoder() { Free(); }
/* ================ idEvent::~idEvent() ================ */ idEvent::~idEvent() { Free(); }
void finalizeIAL(IntArrayList *a) { Free(a->p); }
RobotManager::~RobotManager(void) { Free(); }
bool DHCPOptionParser::Parse( struct dhcp_packet *dp ) { int code; int len; unsigned char *data; int i, j; if( memcmp( dp->options, DHCP_OPTIONS_COOKIE, 4 )) return false; Free(); for( i = 4; ( code = dp->options[ i++ ]) != DHO_END; ) { if( code == DHO_PAD ) continue; len = dp->options[ i++ ]; data = &dp->options[ i ]; switch( code ) { case DHO_DHCP_MESSAGE_TYPE : mMsgType = *data; break; case DHO_DHCP_SERVER_IDENTIFIER : mSID = *reinterpret_cast< struct in_addr * >( data ); break; case DHO_DHCP_LEASE_TIME : mLeaseTime = *reinterpret_cast< u_int32_t * >( data ); break; case DHO_SUBNET_MASK : mSubnetMask = *reinterpret_cast< struct in_addr * >( data ); break; case DHO_ROUTERS : { mRouterCount = static_cast< u_int8_t >( len / 4 ); mRouterList = new struct in_addr[ mRouterCount ]; for( j = 0; j < len; j += 4 ) mRouterList[ j / 4 ] = *reinterpret_cast < struct in_addr *> ( &data[ j ]); break; } case DHO_DOMAIN_NAME_SERVERS : { mDNSCount = static_cast< u_int8_t >( len / 4 ); mDNSList = new struct in_addr[ mDNSCount ]; for( j = 0; j < len; j += 4 ) mDNSList[ j / 4 ] = *reinterpret_cast < struct in_addr *>( &data[ j ]); break; } case DHO_DOMAIN_NAME : mDomainName = new char[ len + 1 ](); memcpy( mDomainName, data, len ); break; } i += len; } return true; }
TextureMap::~TextureMap() { Free(); }
int load_RoomData_version0(File *f, Room *r, int flags) { char buf[MAX_LONGLINE]; StringList *sl; int i; /* name */ if (Fgets(f, buf, MAX_LINE) == NULL) goto err_load_room; cstrip_line(buf); Free(r->name); r->name = cstrdup(buf); if (flags & LOAD_ROOM_DATA) { /* generation/creation date */ if (Fgets(f, buf, MAX_LINE) == NULL) goto err_load_room; cstrip_line(buf); r->generation = cstrtoul(buf, 10); /* flags */ if (Fgets(f, buf, MAX_LINE) == NULL) goto err_load_room; cstrip_line(buf); r->flags = (unsigned int)cstrtoul(buf, 16); r->flags &= ROOM_ALL; /* reset non-existant flags */ /* roominfo_changed */ if (Fgets(f, buf, MAX_LINE) == NULL) goto err_load_room; cstrip_line(buf); r->roominfo_changed = (unsigned int)cstrtoul(buf, 10); } else LOAD_ROOM_SKIPLINES(3); /* info */ destroy_StringIO(r->info); r->info = NULL; if (PARAM_HAVE_RESIDENT_INFO || (flags & LOAD_ROOM_INFO)) { while(Fgets(f, buf, MAX_LINE) != NULL) { if (!*buf) break; if (r->info == NULL && (r->info = new_StringIO()) == NULL) continue; put_StringIO(r->info, buf); write_StringIO(r->info, "\n", 1); } } else LOAD_ROOM_SKIPLIST; /* room aides */ listdestroy_StringList(r->room_aides); r->room_aides = NULL; if (flags & LOAD_ROOM_AIDES) { while(Fgets(f, buf, MAX_LINE) != NULL) { cstrip_line(buf); if (!*buf) break; if (user_exists(buf) && (sl = new_StringList(buf)) != NULL) r->room_aides = add_StringList(&r->room_aides, sl); } r->room_aides = rewind_StringList(r->room_aides); } else LOAD_ROOM_SKIPLIST; /* invited */ listdestroy_StringList(r->invited); r->invited = NULL; if (flags & LOAD_ROOM_INVITED) { while(Fgets(f, buf, MAX_LINE) != NULL) { cstrip_line(buf); if (!*buf) break; if (user_exists(buf) && (sl = new_StringList(buf)) != NULL) r->invited = add_StringList(&r->invited, sl); } r->invited = rewind_StringList(r->invited); } else LOAD_ROOM_SKIPLIST; /* kicked */ listdestroy_StringList(r->kicked); r->kicked = NULL; if (flags & LOAD_ROOM_KICKED) { while(Fgets(f, buf, MAX_LINE) != NULL) { cstrip_line(buf); if (!*buf) break; if (user_exists(buf) && (sl = new_StringList(buf)) != NULL) r->kicked = add_StringList(&r->kicked, sl); } r->kicked = rewind_StringList(r->kicked); } else LOAD_ROOM_SKIPLIST; /* chat history */ if ((flags & LOAD_ROOM_CHAT_HISTORY) && (r->flags & ROOM_CHATROOM)) { if (r->chat_history == NULL && (r->chat_history = new_StringQueue()) == NULL) LOAD_ROOM_SKIPLIST; else { r->chat_history->tail = (ListType *)Fgetlist(f); r->chat_history->head = (ListType *)unwind_StringList((StringList *)r->chat_history->tail); r->chat_history->count = count_List(r->chat_history->tail); } } else LOAD_ROOM_SKIPLIST; return 0; err_load_room: return -1; }
/** * Determine the deviance components associated with each of the * levels of a grouping factor at the conditional modes or a value * offset from the conditional modes by delb. * * @param GS pointer to a GlmerStruct * @param b conditional modes of the random effects * @param Gp group pointers * @param nc number of columns in the model matrix for the kth * grouping factor * @param k index (0-based) of the grouping factor * @param delb vector of length nc giving the changes in the * orthonormalized random effects * @param OmgFac Cholesky factor of the inverse of the penalty matrix * for this grouping factor * @param bVfac 3-dimensional array holding the factors of the * conditional variance-covariance matrix of the random effects FIXME: This is wrong. It is bVar[[i]] not bVfac that is being passed. This only affects the AGQ method. * @param devcmp array to hold the deviance components * * @return devcmp */ static double* rel_dev_1(GlmerStruct GS, const double b[], int nlev, int nc, int k, const double delb[], const double OmgFac[], const double bVfac[], double devcmp[]) { SEXP devs; int *fv = INTEGER(VECTOR_ELT(GET_SLOT(GS->mer, lme4_flistSym), k)), i, j; double *bcp = (double *) NULL; AZERO(devcmp, nlev); if (delb) { int ione = 1, ntot = nlev * nc; double sumsq = 0; /* copy the contents of b */ bcp = Memcpy(Calloc(ntot, double), b, ntot); if (nc == 1) { sumsq = delb[0] * delb[0]; for (i = 0; i < nlev; i++) b[i] += delb[0] * bVfac[i]; } else { int ncsq = nc * nc; double *tmp = Calloc(nc, double); for (i = 0; i < nlev; i++) { Memcpy(tmp, delb, nc); F77_CALL(dtrmv)("U", "N", "N", &nc, &(bVfac[i * ncsq]), &nc, tmp, &ione); for (j = 0; j < nc; j++) b[i + j * nc] = tmp[j]; } /* sum of squares of delb */ for (j = 0; j < nc; j++) sumsq += delb[j] * delb[j]; } for (i = 0; i < nlev; i++) devcmp[i] = -sumsq; } internal_mer_fitted(GS->mer, GS->offset, REAL(GS->eta)); eval_check_store(GS->linkinv, GS->rho, GS->mu); devs = PROTECT(eval_check(GS->dev_resids, GS->rho, REALSXP, GS->n)); for (i = 0; i < GS->n; i++) devcmp[fv[i] - 1] += REAL(devs)[i]; UNPROTECT(1); if (nc == 1) { for (i = 0; i < nlev; i++) { double tmp = *OmgFac * b[i]; devcmp[i] += tmp * tmp; } } else { double *tmp = Calloc(nc, double); int ione = 1; for (i = 0; i < nlev; i++) { for (j = 0; j < nc; j++) tmp[j] = b[i + j * nlev]; F77_CALL(dtrmv)("U", "N", "N", &nc, OmgFac, &nc, tmp, &ione); for (j = 0; j < nc; j++) devcmp[i] += tmp[j] * tmp[j]; } } if (delb) { Memcpy(b, bcp, ntot); Free(bcp); } return devcmp; }
void PNMfree(void) { PNMok=FALSE; Free(PNMpatchs); }
/** * Determine the conditional modes and the conditional variance of the * fixed effects given the data and the current random effects. * Create a Metropolis-Hasting proposal step from the multivariate * normal density, determine the acceptance probability and, if the * step is to be accepted, overwrite the contents of fixed with the * new contents. * * @param GS a GlmerStruct * @param b list of random effects * @param fixed current value of the fixed effects * * @return updated value of the fixed effects */ static double * internal_glmer_fixef_update(GlmerStruct GS, SEXP b, double fixed[]) { SEXP dmu_deta, var; int i, ione = 1, it, j, lwork = -1; double *ans = Calloc(GS->p, double), /* proposal point */ *md = Calloc(GS->p, double), /* conditional modes */ *w = Calloc(GS->n, double), *work, *wtd = Calloc(GS->n * GS->p, double), *z = Calloc(GS->n, double), crit, devr, one = 1, tmp, zero = 0; if (!isNewList(b) || LENGTH(b) != GS->nf) error(_("%s must be a %s of length %d"), "b", "list", GS->nf); for (i = 0; i < GS->nf; i++) { SEXP bi = VECTOR_ELT(b, i); if (!isReal(bi) || !isMatrix(bi)) error(_("b[[%d]] must be a numeric matrix"), i); } AZERO(z, GS->n); /* -Wall */ Memcpy(md, fixed, GS->p); /* calculate optimal size of work array */ F77_CALL(dgels)("N", &(GS->n), &(GS->p), &ione, wtd, &(GS->n), z, &(GS->n), &tmp, &lwork, &j); if (j) /* shouldn't happen */ error(_("%s returned error code %d"), "dgels", j); lwork = (int) tmp; work = Calloc(lwork, double); AZERO(GS->off, GS->n); /* fitted values from random effects */ /* fitted_ranef(GET_SLOT(GS->mer, lme4_flistSym), GS->unwtd, b, */ /* INTEGER(GET_SLOT(GS->mer, lme4_ncSym)), GS->off); */ for (i = 0; i < GS->n; i++) (GS->etaold)[i] = ((GS->off)[i] += (GS->offset)[i]); for (it = 0, crit = GS->tol + 1; it < GS->maxiter && crit > GS->tol; it++) { /* fitted values from current beta */ F77_CALL(dgemv)("N", &(GS->n), &(GS->p), &one, GS->X, &(GS->n), md, &ione, &zero, REAL(GS->eta), &ione); /* add in random effects and offset */ vecIncrement(REAL(GS->eta), (GS->off), GS->n); /* check for convergence */ crit = conv_crit(GS->etaold, REAL(GS->eta), GS->n); /* obtain mu, dmu_deta, var */ eval_check_store(GS->linkinv, GS->rho, GS->mu); dmu_deta = PROTECT(eval_check(GS->mu_eta, GS->rho, REALSXP, GS->n)); var = PROTECT(eval_check(GS->var, GS->rho, REALSXP, GS->n)); /* calculate weights and working residual */ for (i = 0; i < GS->n; i++) { w[i] = GS->wts[i] * REAL(dmu_deta)[i]/sqrt(REAL(var)[i]); z[i] = w[i] * (REAL(GS->eta)[i] - (GS->off)[i] + ((GS->y)[i] - REAL(GS->mu)[i]) / REAL(dmu_deta)[i]); } UNPROTECT(2); /* weighted copy of the model matrix */ for (j = 0; j < GS->p; j++) for (i = 0; i < GS->n; i++) wtd[i + j * GS->n] = GS->X[i + j * GS->n] * w[i]; /* weighted least squares solution */ F77_CALL(dgels)("N", &(GS->n), &(GS->p), &ione, wtd, &(GS->n), z, &(GS->n), work, &lwork, &j); if (j) error(_("%s returned error code %d"), "dgels", j); Memcpy(md, z, GS->p); } /* wtd contains the Cholesky factor of * the precision matrix */ devr = normal_kernel(GS->p, md, wtd, GS->n, fixed); devr -= fixed_effects_deviance(GS, fixed); for (i = 0; i < GS->p; i++) { double var = norm_rand(); ans[i] = var; devr -= var * var; } F77_CALL(dtrsv)("U", "N", "N", &(GS->p), wtd, &(GS->n), ans, &ione); for (i = 0; i < GS->p; i++) ans[i] += md[i]; devr += fixed_effects_deviance(GS, ans); crit = exp(-0.5 * devr); /* acceptance probability */ tmp = unif_rand(); if (asLogical(internal_getElement(GS->cv, "msVerbose"))) { Rprintf("%5.3f: ", crit); for (j = 0; j < GS->p; j++) Rprintf("%#10g ", ans[j]); Rprintf("\n"); } if (tmp < crit) Memcpy(fixed, ans, GS->p); Free(ans); Free(md); Free(w); Free(work); Free(wtd); Free(z); return fixed; }
XnFileDevice::~XnFileDevice() { Free(); }
void Main_RepopulateTabs (BOOL fDestroyInvalid) { static BOOL fInHere = FALSE; if (!fInHere) { fInHere = TRUE; if (IsWindowVisible (g.hMain)) fDestroyInvalid = FALSE; // First we'll have to look around and see what credentials we currently // have. This call just updates g.aCreds[]; it doesn't do anything else. // (void)GetCurrentCredentials(); // We want one tab on the main dialog for each g.aCredentials entry, // and one tab for Advanced. // HWND hTab = GetDlgItem (g.hMain, IDC_TABS); // Generate a list of the lParams we'll be giving tabs... // LPTSTR *aTabs = NULL; size_t cTabs = 0; size_t iTabOut = 0; size_t nCreds = 0; lock_ObtainMutex(&g.credsLock); size_t iCreds; for (iCreds = 0; iCreds < g.cCreds; ++iCreds) { if (g.aCreds[ iCreds ].szCell[0]) ++nCreds; } if (!nCreds) { fDestroyInvalid = TRUE; } if (!fDestroyInvalid) { int nTabs = TabCtrl_GetItemCount(hTab); for (int iTab = 0; iTab < nTabs; ++iTab) { LPTSTR pszTab = (LPTSTR)GetTabParam (hTab, iTab); if (ISCELLTAB(pszTab) && (*pszTab)) { if (REALLOC (aTabs, cTabs, 1+iTabOut, cREALLOC_TABS)) aTabs[ iTabOut++ ] = CloneString(pszTab); } } } if (nCreds == 0) { if (REALLOC (aTabs, cTabs, 1+iTabOut, cREALLOC_TABS)) aTabs[ iTabOut++ ] = CloneString (TEXT("")); } else for (iCreds = 0; iCreds < g.cCreds; ++iCreds) { if (g.aCreds[ iCreds ].szCell[0]) { size_t ii; for (ii = 0; ii < iTabOut; ++ii) { if (!ISCELLTAB (aTabs[ii])) continue; if (!lstrcmpi (g.aCreds[ iCreds ].szCell, aTabs[ ii ])) break; } if (ii == iTabOut) { if (REALLOC (aTabs, cTabs, 1+iTabOut, cREALLOC_TABS)) aTabs[ iTabOut++ ] = CloneString (g.aCreds[ iCreds ].szCell); } } } lock_ReleaseMutex(&g.credsLock); if (REALLOC (aTabs, cTabs, 1+iTabOut, cREALLOC_TABS)) aTabs[ iTabOut++ ] = dwTABPARAM_MOUNT; if (g.fIsWinNT) { if (REALLOC (aTabs, cTabs, 1+iTabOut, cREALLOC_TABS)) aTabs[ iTabOut++ ] = dwTABPARAM_ADVANCED; } // Now erase the current tabs, and re-add new ones. Remember which tab is // currently selected, so we can try to go back to it later. // int iTabSel = 0; if (TabCtrl_GetItemCount(hTab)) { LPTSTR pszTabSel = (LPTSTR)GetTabParam (hTab, TabCtrl_GetCurSel(hTab)); for (size_t iSel = 0; iSel < iTabOut; ++iSel) { if ((!ISCELLTAB(pszTabSel)) && (!ISCELLTAB(aTabs[iSel])) && (pszTabSel == aTabs[iSel])) iTabSel = iSel; else if (ISCELLTAB(pszTabSel) && ISCELLTAB(aTabs[iSel]) && !lstrcmpi (pszTabSel, aTabs[iSel])) iTabSel = iSel; } } int nTabs = TabCtrl_GetItemCount(hTab); for (int iTab = 0; iTab < nTabs; ++iTab) { LPTSTR pszTab = (LPTSTR)GetTabParam (hTab, iTab); if (ISCELLTAB(pszTab)) FreeString (pszTab); } TabCtrl_DeleteAllItems (hTab); for (size_t ii = 0; ii < iTabOut; ++ii) { TCHAR szTitle[cchRESOURCE]; if (aTabs[ii] == dwTABPARAM_ADVANCED) GetString (szTitle, IDS_ADVANCED); else if (aTabs[ii] == dwTABPARAM_MOUNT) GetString (szTitle, IDS_MOUNT); else if ((nCreds <= 1) || (aTabs[ii][0] == TEXT('\0'))) GetString (szTitle, IDS_CREDENTIALS); else lstrcpy (szTitle, aTabs[ii]); TC_ITEM Item; memset (&Item, 0x00, sizeof(Item)); Item.mask = TCIF_PARAM | TCIF_TEXT; Item.pszText = szTitle; Item.cchTextMax = cchRESOURCE; Item.lParam = (LPARAM)(aTabs[ii]); TabCtrl_InsertItem (hTab, ii, &Item); } if (aTabs != NULL) Free (aTabs); TabCtrl_SetCurSel (hTab, iTabSel); Main_OnSelectTab (); fInHere = FALSE; } }