void Conduct::setWidget(QWidget *parent) { ui = new Ui::Conduct; ui->setupUi(parent); connect(ui->exit, SIGNAL (clicked()),this, SLOT (Exit()),Qt::DirectConnection); connect(ui->more, SIGNAL(clicked()), this, SLOT(MoreBrightness())); connect(ui->less, SIGNAL(clicked()), this, SLOT(LessBrightness())); connect(ui->slider, SIGNAL(valueChanged(int)),this, SLOT(SetBrightness(int))); connect(ui->instruments, SIGNAL(clicked()), this, SLOT(GoToStrumenti())); connect(ui->go_to_video_survillance, SIGNAL(clicked()), this, SLOT(GoToVideo())); QSignalMapper *mapper = new QSignalMapper( this ); mapper->setMapping( ui->video_manual, 0 ); mapper->setMapping( ui->video_automatic, 1 ); connect(ui->video_manual, SIGNAL(clicked()), mapper, SLOT(map())); connect(ui->video_automatic, SIGNAL(clicked()), mapper, SLOT(map())); connect( mapper, SIGNAL(mapped(int)), this, SLOT(SetVideo(int))); ui->video_automatic->setDown(true); Functions *f = new Functions(); //QString screen = f->Syscall("cat /sys/class/backlight/acpi_video0/brightness", "r"); QString screen = f->Syscall("cat /sys/class/backlight/backlight_lvds.23/brightness", "r"); ui->slider->setValue(screen.toInt()); delete f; }
void Conduct::SetBrightness(int val) { Functions *f = new Functions(); QString command = "echo " + QString::number(val) + " > /sys/class/backlight/backlight_lvds.23/brightness"; f->Syscall(command.toAscii().data(), "w"); delete f; ui->slider->setValue(val); }
void Data::SaveData() { char myCmd[40]; memset(myCmd,0,sizeof(myCmd)); sprintf(myCmd, "/bin/date -s '%04d-%02d-%02d %02d:%02d:%02d'", ui->year->value(), ui->month->value(), +ui->day->value(),ui->hour->value(), ui->minute->value(), ui->second->value()); printf("data %s\n",myCmd); Functions *f = new Functions(); f->Syscall(myCmd, "w"); delete f; Exit(); }
void PatchMgr::getExitSites(Scope &scope, ExitSites &sites) { // All sites in whatever functions we want Functions funcs; getFuncs(scope, funcs); for (Functions::iterator iter = funcs.begin(); iter != funcs.end(); ++iter) { const PatchFunction::Blockset &e = (*iter)->exitBlocks(); for (PatchFunction::Blockset::const_iterator iter2 = e.begin(); iter2 != e.end(); ++iter2) { if (!scope.block || (scope.block == *iter2)) sites.push_back(ExitSite_t(*iter, *iter2)); } } }
void PatchMgr::getFuncCandidates(Scope &scope, Point::Type types, Candidates &ret) { // We can either have a scope of PatchObject and be looking for all // the functions it contains, a scope of a Function, or be looking // for every single function we know about. Functions funcs; getFuncs(scope, funcs); for (Functions::iterator iter = funcs.begin(); iter != funcs.end(); ++iter) { if (types & Point::FuncDuring) ret.push_back(Candidate(Location::Function(*iter), Point::FuncDuring)); if (types & Point::FuncEntry) ret.push_back(Candidate(Location::EntrySite(*iter, (*iter)->entry(), true), Point::FuncEntry)); } }
void PatchMgr::getBlockInstances(Scope &scope, BlockInstances &blocks) { Functions funcs; getFuncs(scope, funcs); for (Functions::iterator iter = funcs.begin(); iter != funcs.end(); ++iter) { const PatchFunction::Blockset &b = (*iter)->blocks(); for (PatchFunction::Blockset::const_iterator iter2 = b.begin(); iter2 != b.end(); ++iter2) { // TODO FIXME: make this more efficient to avoid iunnecessary iteration if (scope.block && scope.block != *iter2) continue; blocks.push_back(BlockInstance(*iter, *iter2)); } } }
Vertex(Vertex *parent, SgAsmFunction *func, const OutputValues &outputs): parent(parent), outputs(outputs), id(0) { functions.insert(func); if (parent) { assert(parent->functions.find(func)!=parent->functions.end()); parent->children.insert(this); } }
// Run each function from the specified set of functions in order to produce an output set for each function. Then insert // the functions into the bottom of the specified PartitionForest. This runs one iteration of partitioning. void partition_functions(RTS_Message *m, PartitionForest &partition, const Functions &functions, PointerDetectors &pointers, InputValues &inputs, PartitionForest::Vertex *parent) { for (Functions::const_iterator fi=functions.begin(); fi!=functions.end(); ++fi) { PointerDetectors::iterator ip = pointers.find(*fi); assert(ip!=pointers.end()); CloneDetection::Outputs<RSIM_SEMANTICS_VTYPE> *outputs = fuzz_test(*fi, inputs, ip->second); #if 1 /*DEBUGGING [Robb Matzke 2013-01-14]*/ std::ostringstream output_values_str; OutputValues output_values = outputs->get_values(); for (OutputValues::iterator ovi=output_values.begin(); ovi!=output_values.end(); ++ovi) output_values_str <<" " <<*ovi; m->mesg("%s: function output values are {%s }", name, output_values_str.str().c_str()); #endif partition.insert(*fi, output_values, parent); } }
void PatchMgr::getInsnInstances(Scope &scope, InsnInstances &insns) { Functions funcs; getFuncs(scope, funcs); for (Functions::iterator iter = funcs.begin(); iter != funcs.end(); ++iter) { const PatchFunction::Blockset &b = (*iter)->blocks(); for (PatchFunction::Blockset::const_iterator iter2 = b.begin(); iter2 != b.end(); ++iter2) { // TODO FIXME: make this more efficient to avoid iunnecessary iteration if (scope.block && scope.block != *iter2) continue; PatchBlock::Insns i; (*iter2)->getInsns(i); for (PatchBlock::Insns::iterator iter3 = i.begin(); iter3 != i.end(); ++iter3) { insns.push_back(InsnInstance(*iter, InsnLoc_t(*iter2, iter3->first, iter3->second))); } } } }
/** Set contents of texture * * @param gl GL functions * @param target Texture target * @param level Mipmap level * @param x X offset * @param y Y offset * @param z Z offset * @param width Width of texture * @param height Height of texture * @param depth Depth of texture * @param format Format of data * @param type Type of data * @param pixels Buffer with image data **/ void subImage(const Functions& gl, GLenum target, GLint level, GLint x, GLint y, GLint z, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) { switch (target) { case GL_TEXTURE_2D: gl.texSubImage2D(target, level, x, y, width, height, format, type, pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "TexSubImage2D"); break; case GL_TEXTURE_2D_ARRAY: gl.texSubImage3D(target, level, x, y, z, width, height, depth, format, type, pixels); GLU_EXPECT_NO_ERROR(gl.getError(), "TexSubImage3D"); break; default: TCU_FAIL("Invalid enum"); break; } }
/** Set contents of texture * * @param gl GL functions * @param target Texture target * @param level Mipmap level * @param internal_format Format of data * @param width Width of texture * @param height Height of texture * @param depth Depth of texture * @param format Format of data * @param type Type of data * @param data Buffer with image data **/ void texImage(const Functions& gl, GLenum target, GLint level, GLenum internal_format, GLuint width, GLuint height, GLuint depth, GLenum format, GLenum type, const GLvoid* data) { switch (target) { case GL_TEXTURE_2D: gl.texImage2D(target, level, internal_format, width, height, 0 /* border */, format, type, data); GLU_EXPECT_NO_ERROR(gl.getError(), "texImage"); break; case GL_TEXTURE_2D_ARRAY: gl.texImage3D(target, level, internal_format, width, height, depth, 0 /* border */, format, type, data); GLU_EXPECT_NO_ERROR(gl.getError(), "texImage"); break; default: TCU_FAIL("Invalid enum"); break; } }
pair<FunctionId,FunctionPtr> FunctionSet::getRandomFunction(int argumentsNumber) const { Functions argFunctions; Functions::const_iterator it = functions_.begin(); //Rewrite funciton with the same number of arguments as argumentsNumber for(auto it = functions_.begin(); it != functions_.end();) { if(it->second.first == argumentsNumber) argFunctions.insert(make_pair(it->first,it->second)); ++it; } if (argFunctions.size() < 1) { string exception = "Nie ma zadnej funkcji o takiej liczbie argumentow"; throw exception; } it = argFunctions.begin(); std::advance(it, rand() % argFunctions.size() ); return this->conversion(it); }
void PatchMgr::getFuncs(Scope &scope, Functions &funcs) { if (scope.wholeProgram) { AddrSpace::ObjMap &objs = as()->objMap(); for (AddrSpace::ObjMap::iterator iter = objs.begin(); iter != objs.end(); ++iter) { iter->second->funcs(std::back_inserter(funcs)); } } else if (scope.obj) { scope.obj->funcs(std::back_inserter(funcs)); } else if (scope.func) { funcs.push_back(scope.func); } }
PointerDetectors detect_pointers(RTS_Message *m, RSIM_Thread *thread, const Functions &functions) { // Choose an SMT solver. This is completely optional. Pointer detection still seems to work fairly well (and much, // much faster) without an SMT solver. SMTSolver *solver = NULL; #if 0 // optional code if (YicesSolver::available_linkage()) solver = new YicesSolver; #endif PointerDetectors retval; CloneDetection::InstructionProvidor *insn_providor = new CloneDetection::InstructionProvidor(thread->get_process()); for (Functions::iterator fi=functions.begin(); fi!=functions.end(); ++fi) { m->mesg("%s: performing pointer detection analysis for \"%s\" at 0x%08"PRIx64, name, (*fi)->get_name().c_str(), (*fi)->get_entry_va()); CloneDetection::PointerDetector pd(insn_providor, solver); pd.initial_state().registers.gpr[x86_gpr_sp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK); pd.initial_state().registers.gpr[x86_gpr_bp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK); //pd.set_debug(stderr); pd.analyze(*fi); retval.insert(std::make_pair(*fi, pd)); #if 1 /*DEBUGGING [Robb P. Matzke 2013-01-24]*/ if (m->get_file()) { const CloneDetection::PointerDetector::Pointers plist = pd.get_pointers(); for (CloneDetection::PointerDetector::Pointers::const_iterator pi=plist.begin(); pi!=plist.end(); ++pi) { std::ostringstream ss; if (pi->type & BinaryAnalysis::PointerAnalysis::DATA_PTR) ss <<"data "; if (pi->type & BinaryAnalysis::PointerAnalysis::CODE_PTR) ss <<"code "; ss <<"pointer at " <<pi->address; m->mesg(" %s", ss.str().c_str()); } } #endif } return retval; }
// Detect functions that are semantically similar by running multiple iterations of partition_functions(). void analyze() { RTS_Message *m = thread->tracing(TRACE_MISC); Functions functions = find_functions(m, thread->get_process()); PointerDetectors pointers = detect_pointers(m, thread, functions); PartitionForest partition; while (partition.nlevels()<MAX_ITERATIONS) { InputValues inputs = choose_inputs(3, 3); size_t level = partition.new_level(inputs); m->mesg("####################################################################################################"); m->mesg("%s: fuzz testing %zu function%s at level %zu", name, functions.size(), 1==functions.size()?"":"s", level); m->mesg("%s: using these input values:\n%s", name, inputs.toString().c_str()); if (0==level) { partition_functions(m, partition, functions, pointers, inputs, NULL); } else { const PartitionForest::Vertices &parent_vertices = partition.vertices_at_level(level-1); for (PartitionForest::Vertices::const_iterator pvi=parent_vertices.begin(); pvi!=parent_vertices.end(); ++pvi) { PartitionForest::Vertex *parent_vertex = *pvi; if (parent_vertex->functions.size()>MAX_SIMSET_SIZE) partition_functions(m, partition, parent_vertex->functions, pointers, inputs, parent_vertex); } } // If the new level doesn't contain any vertices then we must not have needed to repartition anything and we're all // done. if (partition.vertices_at_level(level).empty()) break; } m->mesg("=========================================================================================="); m->mesg("%s: The entire partition forest follows...", name); m->mesg("%s", StringUtility::prefixLines(partition.toString(), std::string(name)+": ").c_str()); m->mesg("=========================================================================================="); m->mesg("%s: Final function similarity sets are:", name); PartitionForest::Vertices leaves = partition.get_leaves(); size_t setno=0; for (PartitionForest::Vertices::iterator vi=leaves.begin(); vi!=leaves.end(); ++vi, ++setno) { PartitionForest::Vertex *leaf = *vi; const Functions &functions = leaf->get_functions(); m->mesg("%s: set #%zu at level %zu has %zu function%s:", name, setno, leaf->get_level(), functions.size(), 1==functions.size()?"":"s"); for (Functions::const_iterator fi=functions.begin(); fi!=functions.end(); ++fi) m->mesg("%s: 0x%08"PRIx64" <%s>", name, (*fi)->get_entry_va(), (*fi)->get_name().c_str()); } m->mesg("%s: dumping final similarity sets to clones.sql", name); partition.dump("clones.sql", "NO_USER", "NO_PASSWD"); }
void JITImpl::init() { if (initialized) return; LLVMLinkInJIT(); LLVMInitializeNativeTarget(); LLVMMemoryBufferRef memBuffer = LLVMExtraCreateMemoryBufferWithPtr(instructionBitcode, instructionBitcodeSize); char *outMessage; if (LLVMParseBitcode(memBuffer, &module, &outMessage)) { std::cerr << "Error loading bitcode: " << outMessage << '\n'; std::abort(); } // TODO experiment with opt level. if (LLVMCreateJITCompilerForModule(&executionEngine, module, 1, &outMessage)) { std::cerr << "Error creating JIT compiler: " << outMessage << '\n'; std::abort(); } builder = LLVMCreateBuilder(); LLVMValueRef callee = LLVMGetNamedFunction(module, "jitInstructionTemplate"); assert(callee && "jitInstructionTemplate() not found in module"); jitFunctionType = LLVMGetElementType(LLVMTypeOf(callee)); functions.init(module); FPM = LLVMCreateFunctionPassManagerForModule(module); LLVMAddTargetData(LLVMGetExecutionEngineTargetData(executionEngine), FPM); LLVMAddBasicAliasAnalysisPass(FPM); LLVMAddJumpThreadingPass(FPM); LLVMAddGVNPass(FPM); LLVMAddJumpThreadingPass(FPM); LLVMAddCFGSimplificationPass(FPM); LLVMAddDeadStoreEliminationPass(FPM); LLVMAddInstructionCombiningPass(FPM); LLVMInitializeFunctionPassManager(FPM); if (DEBUG_JIT) { LLVMExtraRegisterJitDisassembler(executionEngine, LLVMGetTarget(module)); } initialized = true; }
ScriptingService::Functions ScriptingService::loadFunctions( const string& code, const string& filename, bool mrethrow ) { Logger::In in("ScriptingService::loadFunctions"); Parser p; Functions exec; Functions ret; try { Logger::log() << Logger::Info << "Parsing file "<<filename << Logger::endl; ret = p.parseFunction(code, mowner, filename); } catch( const file_parse_exception& exc ) { #ifndef ORO_EMBEDDED Logger::log() << Logger::Error << filename<<" :"<< exc.what() << Logger::endl; if ( mrethrow ) throw; #endif return Functions(); } if ( ret.empty() ) { Logger::log() << Logger::Debug << "No Functions executed from "<< filename << Logger::endl; Logger::log() << Logger::Info << filename <<" : Successfully parsed." << Logger::endl; return Functions(); } else { // Load all listed functions in the TaskContext's Processor: for( Parser::ParsedFunctions::iterator it = ret.begin(); it != ret.end(); ++it) { Logger::log() << "Queueing Function "<< (*it)->getName() << Logger::endl; if ( mowner->engine()->runFunction( it->get() ) == false) { Logger::log() << Logger::Error << "Could not run Function '"<< (*it)->getName() <<"' :" << Logger::nl; Logger::log() << "Processor not accepting or function queue is full." << Logger::endl; } else exec.push_back( *it ); // is being executed. } } return exec; }
int Menu::DisplayMenu() { Display display; Configuration config; Functions func; string PanelHeaders[8] = {" MENU ", " DISPLAY ", " SERVER LIST ", " SET USERNAME ", " SETTINGS ", " ABOUT ", " QUIT ", " NEWS "}; string MenuList[MaxNo_Menu] = {" Server List ", " Set Username ", " Settings ", " About ", " Quit "}; int ypos[MaxNo_Menu] = { 12, 14, 16, 18, 20}; int xpos = 5; config.SetColour(MenuTitleColour); config.SetXYCoord(4, 10); cout << PanelHeaders[0]; config.SetColour(MenuTitleColour); config.SetXYCoord(42, 10); cout << PanelHeaders[1]; // Show Menu int i; config.SetColour(StandardColour); for (i=0; i< MaxNo_Menu; ++i) { config.SetXYCoord(xpos, ypos[i] ); config.SetColour(StandardColour); cout << MenuList[i]; } // Enable Menu i = 0; while(1) { config.SetXYCoord(xpos, ypos[i]); config.SetColour(HoverColour); cout << MenuList[i]; switch( _getch() ) { case 72: if(i>0) { config.SetXYCoord(xpos,ypos[i] ); config.SetColour(StandardColour); // Standard Going Down cout << MenuList[i]; i--; } break; case 80: if(i< MaxNo_Menu-1 ) { config.SetXYCoord(xpos,ypos[i] ); config.SetColour(StandardColour); // Standard Going Up cout << MenuList[i]; i++; } break; case 13: if(i==0) { func.ServerBrowser(PanelHeaders); } if(i==1) { func.SetUsername(PanelHeaders); } if(i==2) { func.Settings(PanelHeaders); } if(i==3) { func.DisplayAbout(PanelHeaders); } if(i==4) { // Exit display.RemoveText(); config.SetColour(MenuTitleColour), config.SetXYCoord(42, 10), cout << PanelHeaders[6]; config.SetColour(StandardColour); char Input; config.SetXYCoord(34,12); cout << "Are you sure you want to exit? [Y/N]: "; cin >> Input; if (toupper(Input) == 'N') { break; } else if (toupper(Input) == 'Y') { config.SetXYCoord(34,15); return 0; } else if (Input == ' ' || Input != toupper('Y') || Input != toupper('N')) { while(Input == ' ' || Input != toupper('Y') || Input != toupper('N')) { config.SetColour(ErrorColour); config.SetXYCoord(34,13),cout << "Error: Please Enter [Y/N]: "; config.SetColour(StandardColour), cin >> Input; if (toupper(Input) == 'N') { break; } else if (toupper(Input) == 'Y') { config.SetXYCoord(34,15); return 0; } } } } break; } }
void VideoThr::run() { bool skip = false, paused = false, oneFrame = false, useLastDelay = false, lastOSDListEmpty = true, maybeFlush = false; double tmp_time = 0.0, sync_last_pts = 0.0, frame_timer = -1.0, sync_timer = 0.0; QMutex emptyBufferMutex; VideoFrame videoFrame; unsigned fast = 0; int tmp_br = 0, frames = 0; canWrite = true; while (!br) { if (deleteFrame) { videoFrame.clear(); frame_timer = -1.0; deleteFrame = false; } if (doScreenshot && !videoFrame.isEmpty()) { QMetaObject::invokeMethod(this, "screenshot", Q_ARG(VideoFrame, videoFrame)); doScreenshot = false; } const bool mustFetchNewPacket = !filters.readyRead(); playC.vPackets.lock(); const bool hasVPackets = playC.vPackets.canFetch(); if (maybeFlush) maybeFlush = playC.endOfStream && !hasVPackets; if ((playC.paused && !oneFrame) || (!(maybeFlush || hasVPackets) && mustFetchNewPacket) || playC.waitForData) { if (playC.paused && !paused) { QMetaObject::invokeMethod(this, "pause"); paused = true; frame_timer = -1.0; } playC.vPackets.unlock(); tmp_br = tmp_time = frames = 0; skip = false; fast = 0; if (!playC.paused) waiting = playC.fillBufferB = true; emptyBufferMutex.lock(); playC.emptyBufferCond.wait(&emptyBufferMutex, MUTEXWAIT_TIMEOUT); emptyBufferMutex.unlock(); if (frame_timer != -1.0) frame_timer = gettime(); continue; } paused = waiting = false; Packet packet; if (hasVPackets && mustFetchNewPacket) packet = playC.vPackets.fetch(); else packet.ts.setInvalid(); playC.vPackets.unlock(); if (playC.nextFrameB) { skip = playC.nextFrameB = false; oneFrame = playC.paused = true; fast = 0; } playC.fillBufferB = true; /* Subtitles packet */ Packet sPacket; playC.sPackets.lock(); if (playC.sPackets.canFetch()) sPacket = playC.sPackets.fetch(); playC.sPackets.unlock(); mutex.lock(); if (br) { mutex.unlock(); break; } /* Subtitles */ const double subsPts = playC.frame_last_pts + playC.frame_last_delay - playC.subtitlesSync; QList<const QMPlay2_OSD *> osdList, osdListToDelete; playC.subsMutex.lock(); if (sDec) //Image subs (pgssub, dvdsub, ...) { if (!sDec->decodeSubtitle(sPacket, subsPts, subtitles, W, H)) { osdListToDelete += subtitles; subtitles = NULL; } } else { if (!sPacket.isEmpty()) { const QByteArray sPacketData = QByteArray::fromRawData((const char *)sPacket.data(), sPacket.size()); if (playC.ass->isASS()) playC.ass->addASSEvent(sPacketData); else playC.ass->addASSEvent(Functions::convertToASS(sPacketData), sPacket.ts, sPacket.duration); } if (!playC.ass->getASS(subtitles, subsPts)) { osdListToDelete += subtitles; subtitles = NULL; } } if (subtitles) { const bool hasDuration = subtitles->duration() >= 0.0; if (deleteSubs || (subtitles->isStarted() && subsPts < subtitles->pts()) || (hasDuration && subsPts > subtitles->pts() + subtitles->duration())) { osdListToDelete += subtitles; subtitles = NULL; } else if (subsPts >= subtitles->pts()) { subtitles->start(); osdList += subtitles; } } playC.subsMutex.unlock(); playC.osdMutex.lock(); if (playC.osd) { if (deleteOSD || playC.osd->left_duration() < 0) { osdListToDelete += playC.osd; playC.osd = NULL; } else osdList += playC.osd; } playC.osdMutex.unlock(); if ((!lastOSDListEmpty || !osdList.isEmpty()) && writer && writer->readyWrite()) { ((VideoWriter *)writer)->writeOSD(osdList); lastOSDListEmpty = osdList.isEmpty(); } while (!osdListToDelete.isEmpty()) delete osdListToDelete.takeFirst(); deleteSubs = deleteOSD = false; /**/ filtersMutex.lock(); if (playC.flushVideo) { filters.clearBuffers(); frame_timer = -1.0; } if (!packet.isEmpty() || maybeFlush) { VideoFrame decoded; const int bytes_consumed = dec->decodeVideo(packet, decoded, playC.flushVideo, skip ? ~0 : (fast >> 1)); if (playC.flushVideo) { useLastDelay = true; //if seeking playC.flushVideo = false; } if (!decoded.isEmpty()) filters.addFrame(decoded, packet.ts); else if (skip) filters.removeLastFromInputBuffer(); tmp_br += bytes_consumed; } const bool ptsIsValid = filters.getFrame(videoFrame, packet.ts); filtersMutex.unlock(); if ((maybeFlush = packet.ts.isValid())) { if (packet.sampleAspectRatio && lastSampleAspectRatio != -1.0 && fabs(lastSampleAspectRatio - packet.sampleAspectRatio) >= 0.000001) //zmiana współczynnika proporcji { lastSampleAspectRatio = -1.0; //Needs to be updated later emit playC.aRatioUpdate(packet.sampleAspectRatio * (double)W / (double)H); //Sets lastSampleAspectRatio because it calls processParams() } if (ptsIsValid || packet.ts > playC.pos) playC.chPos(packet.ts); double delay = packet.ts - playC.frame_last_pts; if (useLastDelay || delay <= 0.0 || (playC.frame_last_pts <= 0.0 && delay > playC.frame_last_delay)) { delay = playC.frame_last_delay; useLastDelay = false; } tmp_time += delay * 1000.0; frames += 1000; if (tmp_time >= 1000.0) { emit playC.updateBitrate(-1, round((tmp_br << 3) / tmp_time), frames / tmp_time); frames = tmp_br = tmp_time = 0; } delay /= playC.speed; playC.frame_last_delay = delay; playC.frame_last_pts = packet.ts; if (playC.skipAudioFrame < 0.0) playC.skipAudioFrame = 0.0; const double true_delay = delay; if (syncVtoA && playC.audio_current_pts > 0.0 && !oneFrame) { double sync_pts = playC.audio_current_pts; if (sync_last_pts == sync_pts) sync_pts += gettime() - sync_timer; else { sync_last_pts = sync_pts; sync_timer = gettime(); } const double diff = packet.ts - (delay + sync_pts - playC.videoSync); const double sync_threshold = qMax(delay, playC.audio_last_delay); const double max_threshold = sync_threshold < 0.1 ? 0.125 : sync_threshold * 1.5; const double fDiff = qAbs(diff); if (fast && !skip && diff > -sync_threshold / 2.0) fast = 0; skip = false; // qDebug() << "diff" << diff << "sync_threshold" << sync_threshold << "max_threshold" << max_threshold; if (fDiff > sync_threshold && fDiff < max_threshold) { if (diff < 0.0) //obraz się spóźnia { delay -= sync_threshold / 10.0; // qDebug() << "speed up" << diff << delay << sync_threshold; } else if (diff > 0.0) //obraz idzie za szybko { delay += sync_threshold / 10.0; // qDebug() << "slow down" << diff << delay << sync_threshold; } } else if (fDiff >= max_threshold) { if (diff < 0.0) //obraz się spóźnia { delay = 0.0; if (fast >= 7) skip = true; } else if (diff > 0.0) //obraz idzie za szybko { if (diff <= 0.5) delay *= 2.0; else if (!playC.skipAudioFrame) playC.skipAudioFrame = diff; } // qDebug() << "Skipping" << diff << skip << fast << delay; } } else if (playC.audio_current_pts <= 0.0 || oneFrame) { skip = false; fast = 0; } if (!videoFrame.isEmpty()) { if (frame_timer != -1.0) { const double delay_diff = gettime() - frame_timer; delay -= delay_diff; if (syncVtoA && true_delay > 0.0 && delay_diff > true_delay) ++fast; else if (fast && delay > 0.0) { if (delay > true_delay / 2.0) delay /= 2.0; if (fast & 1) --fast; } while (delay > 0.0 && !playC.paused && !br && !br2) { const double sleepTime = qMin(delay, 0.1); Functions::s_wait(sleepTime); delay -= sleepTime; } } if (!skip && canWrite) { oneFrame = canWrite = false; QMetaObject::invokeMethod(this, "write", Q_ARG(VideoFrame, videoFrame)); } frame_timer = gettime(); } else if (frame_timer != -1.0) frame_timer = gettime(); } mutex.unlock(); }
void Drawable::resizeEvent( QResizeEvent * ) { getImageSize( writer.aspect_ratio, writer.zoom, width(), height(), W, H, &X, &Y, &dstRect, &writer.outW, &writer.outH, &srcRect ); repaint(); }
double kantorovich (const T &densityT, const Functions &densityF, const Matrix &X, const Vector &weights, Vector &g, SparseMatrix &h) { typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Polygon_2<K> Polygon; typedef K::FT FT; typedef CGAL::Regular_triangulation_filtered_traits_2<K> RT_Traits; typedef CGAL::Regular_triangulation_vertex_base_2<RT_Traits> Vbase; typedef CGAL::Triangulation_vertex_base_with_info_2 <size_t, RT_Traits, Vbase> Vb; typedef CGAL::Regular_triangulation_face_base_2<RT_Traits> Cb; typedef CGAL::Triangulation_data_structure_2<Vb,Cb> Tds; typedef CGAL::Regular_triangulation_2<RT_Traits, Tds> RT; typedef RT::Vertex_handle Vertex_handle_RT; typedef RT::Weighted_point Weighted_point; typedef typename CGAL::Point_2<K> Point; size_t N = X.rows(); assert(weights.rows() == N); assert(weights.cols() == 1); assert(X.cols() == 2); // insert points with indices in the regular triangulation std::vector<std::pair<Weighted_point,size_t> > Xw(N); for (size_t i = 0; i < N; ++i) { Xw[i] = std::make_pair(Weighted_point(Point(X(i,0), X(i,1)), weights(i)), i); } RT dt (Xw.begin(), Xw.end()); dt.infinite_vertex()->info() = -1; // compute the quadratic part typedef MA::Voronoi_intersection_traits<K> Traits; typedef typename MA::Tri_intersector<T,RT,Traits> Tri_isector; typedef typename Tri_isector::Pgon Pgon; typedef Eigen::Triplet<FT> Triplet; std::vector<Triplet> htri; FT total(0), fval(0), total_area(0); g = Vector::Zero(N); MA::voronoi_triangulation_intersection_raw (densityT,dt, [&] (const Pgon &pgon, typename T::Face_handle f, Vertex_handle_RT v) { Tri_isector isector; Polygon p; std::vector<Vertex_handle_RT> adj; for (size_t i = 0; i < pgon.size(); ++i) { size_t ii = (i==0)?(pgon.size()-1):(i-1); //size_t ii = (i+1)%pgon.size(); p.push_back(isector.vertex_to_point(pgon[i], pgon[ii])); adj.push_back((pgon[i].type == Tri_isector::EDGE_DT) ? pgon[i].edge_dt.second : 0); } size_t idv = v->info(); auto fit = densityF.find(f); assert(fit != densityF.end()); auto fv = fit->second; // function to integrate // compute hessian for (size_t i = 0; i < p.size(); ++i) { if (adj[i] == 0) continue; Vertex_handle_RT w = adj[i]; size_t idw = w->info(); FT r = MA::integrate_1<FT>(p.edge(i), fv); FT d = 2*sqrt(CGAL::squared_distance(v->point(), w->point())); htri.push_back(Triplet(idv, idw, -r/d)); htri.push_back(Triplet(idv, idv, +r/d)); } // compute value and gradient FT warea = MA::integrate_1<FT>(p, FT(0), fv); FT intg = MA::integrate_3<FT>(p, FT(0), [&](Point p) { return fv(p) * CGAL::squared_distance(p, v->point()); }); fval = fval + warea * weights[idv] - intg; g[idv] = g[idv] + warea; total += warea; total_area += p.area(); }); h = SparseMatrix(N,N); h.setFromTriplets(htri.begin(), htri.end()); h.makeCompressed(); return fval; }
Playlist::Entries PLS::_read() { Reader *reader = ioCtrl.rawPtr< Reader >(); Entries list; QString playlistPath = filePath(reader->getUrl()); if (playlistPath.startsWith("file://")) playlistPath.remove(0, 7); else playlistPath.clear(); const QList< QByteArray > playlistLines = readLines(); for (int i = 0; i < playlistLines.count(); ++i) { const QByteArray &line = playlistLines[i]; if (line.isEmpty()) continue; int idx = line.indexOf('='); if (idx < 0) continue; int number_idx = -1; for (int i = 0; i < line.length(); ++i) { if (line[i] == '=') break; if (line[i] >= '0' && line[i] <= '9') { number_idx = i; break; } } if (number_idx == -1) continue; QByteArray key = line.left(number_idx); QByteArray value = line.mid(idx+1); int entry_idx = line.mid(number_idx, idx - number_idx).toInt() - 1; prepareList(&list, entry_idx); if (entry_idx < 0 || entry_idx > list.size() - 1) continue; if (key == "File") list[entry_idx].url = Url(value, playlistPath); else if (key == "Title") list[entry_idx].name = value.replace('\001', '\n'); else if (key == "Length") list[entry_idx].length = value.toInt(); else if (key == "QMPlay_sel") list[entry_idx].selected = value.toInt(); else if (key == "QMPlay_queue") list[entry_idx].queue = value.toInt(); else if (key == "QMPlay_GID") list[entry_idx].GID = value.toInt(); else if (key == "QMPlay_parent") list[entry_idx].parent = value.toInt(); } return list; }