Пример #1
0
bool mrutils::Gnuplot::init(const char * term, const char * file) {
    init_ = true; valid = false;

    // check dispay on unix systems
    #if ( defined(unix) || defined(__unix) || defined(__unix__) ) && !defined(__APPLE__)
        if (getenv("DISPLAY") == NULL) return bye("can't open display");
    #endif

    char path[1024], *p;
    if (!(p = getPath(path))) return bye("can't find executable");

    valid = true; // set here so the commands below will run

    #if defined(__APPLE__)
        // image rendering is MUCH faster than aqua and ~2x faster than x11
        if (term == NULL) term = "png";
    #endif

    if (term != NULL) {
        if (0==stricmp(term,"jpg") || 0==stricmp(term,"jpeg")) {
            if (file != NULL && *file != 0) {
                strcpy(strcpy(p, " > "),file);
            } else {
                strcpy(p, " | /Users/mikerobe/bin/img --persist -f -");
                //strcpy(p, " | xv -");
            }
            gnucmd = MR_POPEN(path,"w");
            if (!gnucmd) return bye("unable to open pipe to gnuplot");
            //cmd("set terminal jpeg enhanced font \"/usr/x11/lib/x11/fonts/TTF/luxirr.ttf\" 10 size 800,480");
            cmd("set terminal jpeg enhanced font \"/Library/Fonts/Arial.ttf\" 9 size 800,480");
            //cmd("set terminal pngcairo dashed font \"/usr/x11/lib/x11/fonts/TTF/luxirr.ttf, 10\" size 800,480");
            //cmd("set terminal svg font \"/usr/x11/lib/x11/fonts/TTF/luxirr.ttf\" fsize 10");
            isImage = true;
        } else if (0==stricmp(term,"png")) {
            if (file != NULL && *file != 0) {
                strcpy(strcpy(p, " > "),file);
            } else {
                //strcpy(p, " | /Users/mikerobe/bin/img -f -");
                strcpy(p, " | /Users/mikerobe/bin/img --persist -f -");
                //strcpy(p, " | xv -");
            }
            gnucmd = MR_POPEN(path,"w");
            if (!gnucmd) return bye("unable to open pipe to gnuplot");
            //cmd("set terminal pngcairo dashed font \"/usr/x11/lib/x11/fonts/TTF/luxirr.ttf, 10\" size 800,480");
            
            // pngcairo doesn't seem to exist anymore
            //cmd("set terminal pngcairo enhanced dashed font \"Arial, 9\" size 800,480");

            cmd("set terminal png enhanced font \"/Library/Fonts/Arial.ttf\" 9 size 800,480");
            isImage = true;
        } else if (0==stricmp(term,"stdout")) {
            gnucmd = stdout;
        } else if (0==stricmp(term,"stderr")) {
            gnucmd = stderr;
        } else {
            isImage = false;
            strcpy(p, " -persist");
            gnucmd = MR_POPEN(path,"w");
            if (!gnucmd) return bye("unable to open pipe to gnuplot");
            fprintf(gnucmd,"set terminal %s\n",term);
            fflush(gnucmd);
        }
    } else {
        strcpy(p, " -persist");
        gnucmd = MR_POPEN(path,"w");
        if (!gnucmd) return bye("unable to open pipe to gnuplot");

        #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__TOS_WIN__)
            cmd("set terminal windows enhanced");
        #elif defined(__APPLE__)
            cmd("set terminal aqua dashed 1");
        #elif ( defined(unix) || defined(__unix) || defined(__unix__) ) && !defined(__APPLE__)
            cmd("set terminal x11 enhanced");
        #endif
    }

    cmd("set lmargin 9");
    cmd("set rmargin 9");
    cmd("set tmargin 2");
    cmd("set bmargin 2");
    cmd("set border 0");

    points();

    return true;
}
Пример #2
0
	bool luks::unmount(const QString& deviceNode)
	{
		ExternalCommand cmd(QStringLiteral("cryptsetup"), QStringList() << QStringLiteral("luksClose") << mapperName(deviceNode));
		return cmd.run(-1) && cmd.exitCode() == 0;
	}
Пример #3
0
void Browse::positionEditor( char * fileName, ulong line, uint col,
                             int hiliteLen )
//-----------------------------------------------------------------
{
    FileInfo finf( fileName );

    if( finf.exists() ) {
        if( optManager()->isEditorDLL() ) {
            if( _editorDLL->isInitialized() ) {
                if( _editorDLL->EDITConnect() ) {
                    _editorDLL->EDITFile( fileName, "" );
                    _editorDLL->EDITLocate( line, col, hiliteLen );
                    _editorDLL->EDITShowWindow( EDIT_SHOWNORMAL );
                } else {
                    errMessage( "Unable to connect to editor" );
                }
            } else {
                ASSERTION( 0 /* uh-oh -- the menu item should be grayed */ );
            }
        } else {
            WString cmd( optManager()->getEditorName() );
            WString editorParms( optManager()->getEditorParms() );

            cmd.concat( ' ' ); // space after editor name before parms
            int parmsize = editorParms.size();

            for( int i=0; i < parmsize; i++ ) {
                switch( editorParms[i] ) {
                case '%':
                    switch( editorParms[i+1] ) {
                    case 'f': // file name
                        cmd.concat( fileName );
                        break;
                    case 'r': // row to go to
                        cmd.concatf( "%ld", line );
                        break;
                    case 'c': // column to go to
                        cmd.concatf( "%d", col );
                        break;
                    case 'l': // length of hilight
                        cmd.concatf( "%d", hiliteLen );
                        break;
                    #if 0
                    case 'h': // helpid
                        cmd.concat( x.stringAt( 5 ) );
                        break;
                    case 'e': // error message
                        cmd.concat( x.stringAt( 6 ) );
                        break;
                    #endif
                    case '%': // a real '%'
                        cmd.concat( '%' );
                        break;
                    default:
                        // ignore the '%' and the character
                        break;
                    }
                    i+=2; // skip % and following char
                default:
                    cmd.concat( editorParms[i] );
                    break;
                }
            }
            WSystemService::sysExec( cmd, WWinStateShowNormal, 0 );
        }
    } else {
        errMessage( "File \"%s\" not found", fileName );
    }
}
Пример #4
0
    // Send a poll command to all OCCs
    errlHndl_t sendOccPoll(const bool i_flushAllErrors)
    {
        errlHndl_t l_err = NULL;
        uint8_t * l_poll_rsp = NULL;

        // Loop through all functional OCCs
        std::vector<Occ*> occList = occMgr::instance().getOccArray();
        for (std::vector<Occ*>::iterator itr = occList.begin();
             (itr < occList.end()) && (NULL == l_err);
             ++itr)
        {
            Occ * occ = (*itr);
            const uint8_t occInstance = occ->getInstance();

            bool continuePolling = false;
            do
            {
                // create 1 byte buffer for poll command data
                const uint8_t l_cmdData[1] = { 0x10 /*version*/ };

                OccCmd cmd(occ, OCC_CMD_POLL, sizeof(l_cmdData), l_cmdData);
                l_err = cmd.sendOccCmd();
                if (l_err != NULL)
                {
                    // Poll failed
                    TMGT_ERR("sendOccPoll: OCC%d poll failed with rc=0x%04X",
                             occInstance, l_err->reasonCode());
                }
                else
                {
                    // Poll succeeded, check response
                    uint32_t l_poll_rsp_size = cmd.getResponseData(l_poll_rsp);
                    if (l_poll_rsp_size >= OCC_POLL_DATA_MIN_SIZE)
                    {
                        if (i_flushAllErrors)
                        {
                            const occPollRspStruct_t *currentPollRsp =
                                (occPollRspStruct_t *) l_poll_rsp;
                            if (currentPollRsp->errorId != 0)
                            {
                                // An error was returned, keep polling OCC
                                continuePolling = true;
                            }
                            else
                            {
                                continuePolling = false;
                            }
                        }
                        occ->pollRspHandler(l_poll_rsp, l_poll_rsp_size);
                    }
                    else
                    {
                        TMGT_ERR("sendOccPoll: OCC%d poll command response "
                                 "failed with invalid data length %d",
                                 occInstance, l_poll_rsp_size);
                        /*@
                         * @errortype
                         * @reasoncode HTMGT_RC_INVALID_LENGTH
                         * @moduleid  HTMGT_MOD_OCC_POLL
                         * @userdata1 OCC instance
                         * @devdesc Invalid POLL response length
                         */
                        bldErrLog(l_err, HTMGT_MOD_OCC_POLL,
                                  HTMGT_RC_INVALID_LENGTH,
                                  occInstance, 0, 0, 0,
                                  ERRORLOG::ERRL_SEV_INFORMATIONAL);
                    }
                }
            }
            while (continuePolling);

        } // for each OCC

        return l_err;

    } // end sendOccPoll()
Пример #5
0
static int tzdd_proxy_thread(void *data)
{
	tzdd_dev_t *dev;
	tee_msg_head_t *tee_msg_send_head = NULL;

	//uint32_t nice;

	uint32_t res_size = 0;
	uint32_t msg_flag;

	uint32_t ret;
	bool list_ret;
	bool is_lpm_blocked = false;

	struct sched_param param;

	set_cpus_allowed_ptr(current, cpumask_of(0));
	TZDD_DBG("tzdd_proxy_thread on cpu %d\n", smp_processor_id());

	param.sched_priority = MAX_RT_PRIO - 1;

	sched_setscheduler(current, SCHED_FIFO, &param);
#if 0
	nice = task_nice(current);
	TZDD_DBG("tzdd_proxy_thread: nice = %d\n", nice);
#endif

	dev = (tzdd_dev_t *) data;

	while (1) {
		while (tzdd_get_first_req(&tee_msg_send_head)) {
			TZDD_DBG
			    ("%s: tee_msg_send_head (0x%08x) =\
			    {magic (%c%c%c%c),\
			    size (0x%08x)},\
			    cmd (0x%x)\n",\
			     __func__, (uint32_t) tee_msg_send_head,
			     tee_msg_send_head->magic[0],
			     tee_msg_send_head->magic[1],
			     tee_msg_send_head->magic[2],
			     tee_msg_send_head->magic[3],
			     tee_msg_send_head->msg_sz,
			     *((uint32_t *) (tee_msg_send_head) + 8));

			list_ret =
			    tzdd_del_node_from_req_list(&
							(tee_msg_send_head->
							 node));
			OSA_ASSERT(list_ret);

			tzdd_pt_send(tee_msg_send_head);

			if (false == is_lpm_blocked) {
				/* block LPM D1P and deeper than D1P */
#ifdef __ENABLE_PM_
				osa_wait_for_sem(_g_pm_lock, INFINITE);
				pm_qos_update_request(&_g_tzdd_lpm_cons,
					PM_QOS_CPUIDLE_BLOCK_AXI_VALUE);
#endif
				is_lpm_blocked = true;
			}
			tee_add_time_record_point("npct");
			/* Call IPI to TW */
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
			g_pre_ipi_num++;
#endif
			tee_cm_smi(CALL_IPI);
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
			g_pst_ipi_num++;
#endif
			tee_add_time_record_point("npbt");
			_g_tzdd_send_num++;
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
			g_msg_sent++;
#endif
		}

		res_size = tee_cm_get_data_size();

		while (res_size) {

			msg_flag = tzdd_pt_recv();
			if (msg_flag == TEE_MSG_IGNORE_COUNTER) {
				/* do nothing */
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
				g_msg_ignd++;
#endif
			} else {	/* TEE_MSG_FAKE && TEE_MSG_NORMAL */
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
				if (TEE_MSG_NORMAL == msg_flag)
					g_msg_recv++;
				else if (TEE_MSG_FAKE == msg_flag)
					g_msg_fake++;
				else
					OSA_ASSERT(0);
#endif
				_g_tzdd_send_num--;
			}

			res_size = tee_cm_get_data_size();
		}
		tee_add_time_record_point("nprm");
		if (_g_tzdd_send_num) {
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
			g_pre_dmy_num++;
#endif
			if (tee_cm_tw_is_idle()) {
				g_wait_for = 1;
				g_wait_for_idle++;
				ret = osa_wait_for_sem(dev->pt_sem, 5);
				g_wait_for = 0;
				if (ret != OSA_OK) {
					tee_cm_smi(0);
				}
			} else {
				tee_cm_smi(0);
			}
#ifdef TEE_DEBUG_ENALBE_PROC_FS_LOG
			g_pst_dmy_num++;
#endif
		} else {
			/* release D1P LPM constraint */
			if (true == is_lpm_blocked) {
#ifdef __ENABLE_PM_
				pm_qos_update_request(&_g_tzdd_lpm_cons,
					PM_QOS_CPUIDLE_BLOCK_DEFAULT_VALUE);
				osa_release_sem(_g_pm_lock);
#endif
				is_lpm_blocked = false;
			}

			tee_add_time_record_point("npwa");
			g_wait_for = 2;
			g_wait_for_command++;
			ret = osa_wait_for_sem(dev->pt_sem, INFINITE);
			g_wait_for = 0;
			OSA_ASSERT(!ret);

			if (true == _g_pt_thread_stop_flag) {
				TZDD_DBG("tzdd_proxy_thread(),P-break\n");
				break;
			}
			tee_add_time_record_point("npet");
		}
	}
Пример #6
0
	void call(std::string const& name, agi::Context*c) {
		Command &cmd = *find_command(name)->second;
		if (cmd.Validate(c))
			cmd(c);
	}
Пример #7
0
void CheckExternalScripts::add_script(const Plugin::ExecuteRequestMessage::Request &request, Plugin::ExecuteResponseMessage::Response *response) {

	namespace po = boost::program_options;
	namespace pf = nscapi::protobuf::functions;
	po::variables_map vm;
	po::options_description desc;
	std::string script, arguments, alias;
	bool wrapped;

	desc.add_options()
		("help", "Show help.")

		("script", po::value<std::string>(&script), 
		"Script to add")

		("alias", po::value<std::string>(&alias), 
		"Name of command to execute script (defaults to basename of script)")

		("arguments", po::value<std::string>(&arguments), 
		"Arguments for script.")

		("wrapped", po::bool_switch(&wrapped), 
		"Add this to add a wrapped script such as ps1, vbs or similar..")

		;

	try {
		nscapi::program_options::basic_command_line_parser cmd(request);
		cmd.options(desc);

		po::parsed_options parsed = cmd.run();
		po::store(parsed, vm);
		po::notify(vm);
	} catch (const std::exception &e) {
			return nscapi::program_options::invalid_syntax(desc, request.command(), "Invalid command line: " + utf8::utf8_from_native(e.what()), *response);
	}

	if (vm.count("help")) {
		nscapi::protobuf::functions::set_response_good(*response, nscapi::program_options::help(desc));
		return;
	}
	boost::filesystem::path file = get_core()->expand_path(script);
	if (!wrapped) {
		if (!boost::filesystem::is_regular(file)) {
			nscapi::protobuf::functions::set_response_bad(*response, "Script not found: " + file.string());
			return;
		}
	}
	if (alias.empty()) {
		alias = boost::filesystem::basename(file.filename());
	}

	nscapi::protobuf::functions::settings_query s(get_id());
	if (!wrapped)
		s.set("/settings/external scripts/scripts", alias, script + " " + arguments);
	else
		s.set("/settings/external scripts/wrapped scripts", alias, script + " " + arguments);
	s.set(MAIN_MODULES_SECTION, "CheckExternalScripts", "enabled");
	s.save();
	get_core()->settings_query(s.request(), s.response());
	if (!s.validate_response()) {
		nscapi::protobuf::functions::set_response_bad(*response, s.get_response_error());
		return;
	}
	std::string actual = "";
	if (wrapped)
		actual = "\nActual command is: " + generate_wrapped_command(script + " " + arguments);
	nscapi::protobuf::functions::set_response_good(*response, "Added " + alias + " as " + script + actual);
}
Пример #8
0
int main(int argc, char** argv) {
	extern bool VERBOSE, SILENCIEUX;
    extern int ITERATIONS_DECOMPRESSION, NB_THREADS;
	extern int TAILLE_MIN_DECOUPE, NB_MAX_DECOUPE;

		/* *************** Lecture des entrées *************** */

	try {
		TCLAP::CmdLine cmd("Algorithme de compression fractal", ' ', "0.42");

        // Paramètres de compression
		TCLAP::ValueArg<int> argTailleGros("b", "big", "La taille des gros carrés (compression)", false, 96, "int");
		TCLAP::ValueArg<int> argTaillePetit("s", "small", "La taille des petits carrés (compression)", false, 48, "int");
		TCLAP::ValueArg<int> argNbIterations("n", "nb-iterations", "Le nombre d'itérations à la décompression", false, ITERATIONS_DECOMPRESSION, "int");
		TCLAP::ValueArg<int> argThreads("", "threads", "Nombre de threads maximum utilisés", false, NB_THREADS, "int");
        // Fichiers d'entrée
		TCLAP::ValueArg<std::string> argFractalFile("f", "fractal-file", "Le fichier .ifs", false, "out.ifs", "string");
		TCLAP::ValueArg<std::string> argNormalFile("p", "png-file", "Le fichier .png", false, "out.png", "string");
        // Affichage
		TCLAP::SwitchArg argVerbose("v", "verbose", "Afficher le debugage", cmd, !VERBOSE);
		TCLAP::SwitchArg argQuiet("q", "quiet", "Retire les affichages courants de la console", cmd, SILENCIEUX);
        // Type d'image
		TCLAP::SwitchArg argCouleur("c", "couleur", "L'image doit être compressée en couleur", cmd, false);
		TCLAP::SwitchArg argTransparence("t", "transparence", "L'image doit être compressée avec transparence", cmd, false);
        // Type de travail
		TCLAP::SwitchArg argCompresser("z", "compress", "Le fichier entré doit être compressé", cmd, false);
		TCLAP::SwitchArg argExtraire("x", "extract", "Le fichier entré doit être extrait", cmd, false);
		TCLAP::ValueArg<int> argExamples("e", "examples", "Génère un set de fichiers types, donner leur taille en argument", false, 0, "int");

		cmd.add( argNormalFile );
		cmd.add( argFractalFile );
		cmd.add( argTaillePetit );
		cmd.add( argTailleGros );
		cmd.add( argNbIterations );
		cmd.add( argThreads );
		cmd.add( argExamples );
		cmd.parse( argc, argv );

		VERBOSE = argVerbose.getValue();
		SILENCIEUX = argQuiet.getValue();
        ITERATIONS_DECOMPRESSION = argNbIterations.getValue();
        NB_THREADS = argThreads.getValue();

		const char* fractalFile = argFractalFile.getValue().c_str();
		const char* normalFile = argNormalFile.getValue().c_str();
		int taillePetit = argTaillePetit.getValue();
		int tailleGros = argTailleGros.getValue();
        bool couleur = argCouleur.getValue();
        bool transparence = argTransparence.getValue();

		TAILLE_MIN_DECOUPE = taillePetit / NB_MAX_DECOUPE;

		/* *************** Fin du traitement des entrées *************** */

		DEBUG << "Flotant : " << sizeof(Flotant16b) << "octets" << std::endl;
		DEBUG << "En tete : " << sizeof(Pack_Entete) << "octets" << std::endl;
		DEBUG << "ISF : " << sizeof(Pack_IFS) << "octets" << std::endl;
		DEBUG << "Correspondance : " << sizeof(Pack_Correspondance) << "octets" << std::endl;

		if( argCompresser.getValue() ) { // Doit encoder
			ImageFractale imgF = ImageFractale::compresser(normalFile, taillePetit, tailleGros, couleur, transparence);
			imgF.enregistrer(fractalFile);
			imgF.debugSplit();
			imgF.exporter("debug.png");
		}

		if( argExtraire.getValue() ) { // Doit décoder
			ImageFractale img( fractalFile );
			img.debugSplit();
			img.exporter( normalFile );
		}

		if( argExamples.getValue() > 0 ) { // Génération de fichiers types
			FigureFractale::generer_exemples(argExamples.getValue());
		}
	}
	catch (TCLAP::ArgException &e) {
		std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}
}
Пример #9
0
int main(int argc, char *argv[])
{
    LOGOG_INITIALIZE();
    logog::Cout* logog_cout (new logog::Cout);
    BaseLib::LogogSimpleFormatter *custom_format (new BaseLib::LogogSimpleFormatter);
    logog_cout->SetFormatter(*custom_format);

    TCLAP::CmdLine cmd("Simple mesh search test", ' ', "0.1");

    // Define a value argument and add it to the command line.
    // A value arg defines a flag and a type of value that it expects,
    // such as "-m meshfile".
    TCLAP::ValueArg<std::string> mesh_arg("m","mesh","input mesh file",true,"test.msh","string");

    // Add the argument mesh_arg to the CmdLine object. The CmdLine object
    // uses this Arg to parse the command line.
    cmd.add( mesh_arg );

    TCLAP::ValueArg<unsigned> number_arg("n","number-of-test-points","the number of test points",true,10000,"positive number");
    cmd.add( number_arg );

    TCLAP::ValueArg<bool> contiguous_arg("c","use-contiguous-memory","use a contiguous memory for the test",false,true,"yes or no | 1 or 0");
    cmd.add( contiguous_arg );

    cmd.parse( argc, argv );

    std::string fname (mesh_arg.getValue());

    FileIO::Legacy::MeshIO mesh_io;
#ifndef WIN32
    BaseLib::MemWatch mem_watch;
    unsigned long mem_without_mesh (mem_watch.getVirtMemUsage());
#endif
    BaseLib::RunTime run_time;
    run_time.start();
    MeshLib::Mesh* mesh (mesh_io.loadMeshFromFile(fname));
#ifndef WIN32
    unsigned long mem_with_mesh (mem_watch.getVirtMemUsage());
    INFO ("mem for mesh: %i MB", (mem_with_mesh - mem_without_mesh)/(1024*1024));
#endif
    INFO ("time for reading: %f s", run_time.elapsed());

    // *** preparing test data
    std::vector<MeshLib::Node*> const& nodes(mesh->getNodes());
    std::vector<GeoLib::Point*> pnts_for_search;
    unsigned n(std::min(static_cast<unsigned>(nodes.size()), number_arg.getValue()));
    for (size_t k(0); k<n; k++) {
        pnts_for_search.push_back(new GeoLib::Point(nodes[k]));
    }

    std::vector<size_t> idx_found_nodes;
    testMeshGridAlgorithm(mesh, pnts_for_search, idx_found_nodes, contiguous_arg.getValue());

    for (size_t k(0); k<n; k++) {
        delete pnts_for_search[k];
    }

    delete mesh;
    delete custom_format;
    delete logog_cout;
    LOGOG_SHUTDOWN();
}
int AddOldTransferPgsCmd::Add(const std::string& _dbName,const ArgObjType & argObj)
{ 
	AddOldTransferPgsCmd cmd(_dbName); 
	cmd.SingleExecute(0, argObj); 
	return cmd.changed; 
}
Пример #11
0
void ExportBeepPlayer::playSilence(float duration)
{
    QString cmd("sleep ");
    cmd += QString::number(duration / 1000);
    std::cout << cmd.toStdString() << std::endl;
}
Пример #12
0
void MavlinkComm::_handleMessage(mavlink_message_t * msg) {

    uint32_t timeStamp = micros();

    switch (msg->msgid) {
        _board->getDebug()->printf_P(PSTR("message received: %d"), msg->msgid);

    case MAVLINK_MSG_ID_HEARTBEAT: {
        mavlink_heartbeat_t packet;
        mavlink_msg_heartbeat_decode(msg, &packet);
        _lastHeartBeat = micros();
        break;
    }

    case MAVLINK_MSG_ID_GPS_RAW: {
        // decode
        mavlink_gps_raw_t packet;
        mavlink_msg_gps_raw_decode(msg, &packet);

        _navigator->setTimeStamp(timeStamp);
        _navigator->setLat(packet.lat * deg2Rad);
        _navigator->setLon(packet.lon * deg2Rad);
        _navigator->setAlt(packet.alt);
        _navigator->setYaw(packet.hdg * deg2Rad);
        _navigator->setGroundSpeed(packet.v);
        _navigator->setAirSpeed(packet.v);
        //_board->getDebug()->printf_P(PSTR("received hil gps raw packet\n"));
        /*
         _board->getDebug()->printf_P(PSTR("received lat: %f deg\tlon: %f deg\talt: %f m\n"),
         packet.lat,
         packet.lon,
         packet.alt);
         */
        break;
    }

    case MAVLINK_MSG_ID_HIL_STATE: {
        // decode
        mavlink_hil_state_t packet;
        mavlink_msg_hil_state_decode(msg, &packet);
        _navigator->setTimeStamp(timeStamp);
        _navigator->setRoll(packet.roll);
        _navigator->setPitch(packet.pitch);
        _navigator->setYaw(packet.yaw);
        _navigator->setRollRate(packet.rollspeed);
        _navigator->setPitchRate(packet.pitchspeed);
        _navigator->setYawRate(packet.yawspeed);
        _navigator->setVN(packet.vx/ 1e2);
        _navigator->setVE(packet.vy/ 1e2);
        _navigator->setVD(packet.vz/ 1e2);
        _navigator->setLat_degInt(packet.lat);
        _navigator->setLon_degInt(packet.lon);
        _navigator->setAlt(packet.alt / 1e3);
        _navigator->setXAccel(packet.xacc/ 1e3);
        _navigator->setYAccel(packet.xacc/ 1e3);
        _navigator->setZAccel(packet.xacc/ 1e3);
        break; 
    } 

    case MAVLINK_MSG_ID_ATTITUDE: {
        // decode
        mavlink_attitude_t packet;
        mavlink_msg_attitude_decode(msg, &packet);

        // set dcm hil sensor
        _navigator->setTimeStamp(timeStamp);
        _navigator->setRoll(packet.roll);
        _navigator->setPitch(packet.pitch);
        _navigator->setYaw(packet.yaw);
        _navigator->setRollRate(packet.rollspeed);
        _navigator->setPitchRate(packet.pitchspeed);
        _navigator->setYawRate(packet.yawspeed);
        //_board->getDebug()->printf_P(PSTR("received hil attitude packet\n"));
        break;
    }

    case MAVLINK_MSG_ID_ACTION: {
        // decode
        mavlink_action_t packet;
        mavlink_msg_action_decode(msg, &packet);
        if (_checkTarget(packet.target, packet.target_component))
            break;

        // do action
        sendText(SEVERITY_LOW, PSTR("action received"));
        switch (packet.action) {

        case MAV_ACTION_STORAGE_READ:
            AP_Var::load_all();
            break;

        case MAV_ACTION_STORAGE_WRITE:
            AP_Var::save_all();
            break;

        case MAV_ACTION_MOTORS_START:
            _controller->setMode(MAV_MODE_READY);
            break;

        case MAV_ACTION_CALIBRATE_GYRO:
        case MAV_ACTION_CALIBRATE_MAG:
        case MAV_ACTION_CALIBRATE_ACC:
        case MAV_ACTION_CALIBRATE_PRESSURE:
            _controller->setMode(MAV_MODE_LOCKED);
            _navigator->calibrate();
            break;

        case MAV_ACTION_EMCY_KILL:
        case MAV_ACTION_CONFIRM_KILL:
        case MAV_ACTION_MOTORS_STOP:
        case MAV_ACTION_SHUTDOWN:
            _controller->setMode(MAV_MODE_LOCKED);
            break;

        case MAV_ACTION_LAUNCH:
        case MAV_ACTION_TAKEOFF:
            _guide->setMode(MAV_NAV_LIFTOFF);
            break;

        case MAV_ACTION_LAND:
            _guide->setCurrentIndex(0);
            _guide->setMode(MAV_NAV_LANDING);
            break;

        case MAV_ACTION_EMCY_LAND:
            _guide->setMode(MAV_NAV_LANDING);
            break;

        case MAV_ACTION_LOITER:
        case MAV_ACTION_HALT:
            _guide->setMode(MAV_NAV_LOITER);
            break;

        case MAV_ACTION_SET_AUTO:
            _controller->setMode(MAV_MODE_AUTO);
            break;

        case MAV_ACTION_SET_MANUAL:
            _controller->setMode(MAV_MODE_MANUAL);
            break;

        case MAV_ACTION_RETURN:
            _guide->setMode(MAV_NAV_RETURNING);
            break;

        case MAV_ACTION_NAVIGATE:
        case MAV_ACTION_CONTINUE:
            _guide->setMode(MAV_NAV_WAYPOINT);
            break;

        case MAV_ACTION_CALIBRATE_RC:
        case MAV_ACTION_REBOOT:
        case MAV_ACTION_REC_START:
        case MAV_ACTION_REC_PAUSE:
        case MAV_ACTION_REC_STOP:
            sendText(SEVERITY_LOW, PSTR("action not implemented"));
            break;
        default:
            sendText(SEVERITY_LOW, PSTR("unknown action"));
            break;
        }
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_REQUEST_LIST: {
        sendText(SEVERITY_LOW, PSTR("waypoint request list"));

        // decode
        mavlink_waypoint_request_list_t packet;
        mavlink_msg_waypoint_request_list_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // Start sending waypoints
        mavlink_msg_waypoint_count_send(_channel, msg->sysid, msg->compid,
                                        _guide->getNumberOfCommands());

        _cmdTimeLastSent = millis();
        _cmdTimeLastReceived = millis();
        _sendingCmds = true;
        _receivingCmds = false;
        _cmdDestSysId = msg->sysid;
        _cmdDestCompId = msg->compid;
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_REQUEST: {
        sendText(SEVERITY_LOW, PSTR("waypoint request"));

        // Check if sending waypiont
        if (!_sendingCmds)
            break;

        // decode
        mavlink_waypoint_request_t packet;
        mavlink_msg_waypoint_request_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        _board->getDebug()->printf_P(PSTR("sequence: %d\n"),packet.seq);
        AP_MavlinkCommand cmd(packet.seq);

        mavlink_waypoint_t wp = cmd.convert(_guide->getCurrentIndex());
        mavlink_msg_waypoint_send(_channel, _cmdDestSysId, _cmdDestCompId,
                                  wp.seq, wp.frame, wp.command, wp.current, wp.autocontinue,
                                  wp.param1, wp.param2, wp.param3, wp.param4, wp.x, wp.y,
                                  wp.z);

        // update last waypoint comm stamp
        _cmdTimeLastSent = millis();
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_ACK: {
        sendText(SEVERITY_LOW, PSTR("waypoint ack"));

        // decode
        mavlink_waypoint_ack_t packet;
        mavlink_msg_waypoint_ack_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // check for error
        //uint8_t type = packet.type; // ok (0), error(1)

        // turn off waypoint send
        _sendingCmds = false;
        break;
    }

    case MAVLINK_MSG_ID_PARAM_REQUEST_LIST: {
        sendText(SEVERITY_LOW, PSTR("param request list"));

        // decode
        mavlink_param_request_list_t packet;
        mavlink_msg_param_request_list_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // Start sending parameters - next call to ::update will kick the first one out

        _queuedParameter = AP_Var::first();
        _queuedParameterIndex = 0;
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_CLEAR_ALL: {
        sendText(SEVERITY_LOW, PSTR("waypoint clear all"));

        // decode
        mavlink_waypoint_clear_all_t packet;
        mavlink_msg_waypoint_clear_all_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // clear all waypoints
        uint8_t type = 0; // ok (0), error(1)
        _guide->setNumberOfCommands(1);
        _guide->setCurrentIndex(0);

        // send acknowledgement 3 times to makes sure it is received
        for (int i = 0; i < 3; i++)
            mavlink_msg_waypoint_ack_send(_channel, msg->sysid,
                                          msg->compid, type);

        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_SET_CURRENT: {
        sendText(SEVERITY_LOW, PSTR("waypoint set current"));

        // decode
        mavlink_waypoint_set_current_t packet;
        mavlink_msg_waypoint_set_current_decode(msg, &packet);
        Serial.print("Packet Sequence:");
        Serial.println(packet.seq);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // set current waypoint
        Serial.print("Current Index:");
        Serial.println(_guide->getCurrentIndex());
        Serial.flush();
        _guide->setCurrentIndex(packet.seq);
        mavlink_msg_waypoint_current_send(_channel,
                                          _guide->getCurrentIndex());
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT_COUNT: {
        sendText(SEVERITY_LOW, PSTR("waypoint count"));

        // decode
        mavlink_waypoint_count_t packet;
        mavlink_msg_waypoint_count_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // start waypoint receiving
        if (packet.count > _cmdMax) {
            packet.count = _cmdMax;
        }
        _cmdNumberRequested = packet.count;
        _cmdTimeLastReceived = millis();
        _receivingCmds = true;
        _sendingCmds = false;
        _cmdRequestIndex = 0;
        break;
    }

    case MAVLINK_MSG_ID_WAYPOINT: {
        sendText(SEVERITY_LOW, PSTR("waypoint"));

        // Check if receiving waypiont
        if (!_receivingCmds) {
            //sendText(SEVERITY_HIGH, PSTR("not receiving commands"));
            break;
        }

        // decode
        mavlink_waypoint_t packet;
        mavlink_msg_waypoint_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // check if this is the requested waypoint
        if (packet.seq != _cmdRequestIndex) {
            char warningMsg[50];
            sprintf(warningMsg,
                    "waypoint request out of sequence: (packet) %d / %d (ap)",
                    packet.seq, _cmdRequestIndex);
            sendText(SEVERITY_HIGH, warningMsg);
            break;
        }

        _board->getDebug()->printf_P(PSTR("received waypoint x: %f\ty: %f\tz: %f\n"),
                              packet.x,
                              packet.y,
                              packet.z);

        // store waypoint
        AP_MavlinkCommand command(packet);
        //sendText(SEVERITY_HIGH, PSTR("waypoint stored"));
        _cmdRequestIndex++;
        if (_cmdRequestIndex == _cmdNumberRequested) {
            sendMessage(MAVLINK_MSG_ID_WAYPOINT_ACK);
            _receivingCmds = false;
            _guide->setNumberOfCommands(_cmdNumberRequested);

            // make sure curernt waypoint still exists
            if (_cmdNumberRequested > _guide->getCurrentIndex()) {
                _guide->setCurrentIndex(0);
                mavlink_msg_waypoint_current_send(_channel,
                                          _guide->getCurrentIndex());
            }

            //sendText(SEVERITY_LOW, PSTR("waypoint ack sent"));
        } else if (_cmdRequestIndex > _cmdNumberRequested) {
            _receivingCmds = false;
        }
        _cmdTimeLastReceived = millis();
        break;
    }

    case MAVLINK_MSG_ID_PARAM_SET: {
        sendText(SEVERITY_LOW, PSTR("param set"));
        AP_Var *vp;
        AP_Meta_class::Type_id var_type;

        // decode
        mavlink_param_set_t packet;
        mavlink_msg_param_set_decode(msg, &packet);
        if (_checkTarget(packet.target_system, packet.target_component))
            break;

        // set parameter

        char key[_paramNameLengthMax + 1];
        strncpy(key, (char *) packet.param_id, _paramNameLengthMax);
        key[_paramNameLengthMax] = 0;

        // find the requested parameter
        vp = AP_Var::find(key);
        if ((NULL != vp) && // exists
                !isnan(packet.param_value) && // not nan
                !isinf(packet.param_value)) { // not inf

            // add a small amount before casting parameter values
            // from float to integer to avoid truncating to the
            // next lower integer value.
            const float rounding_addition = 0.01;

            // fetch the variable type ID
            var_type = vp->meta_type_id();

            // handle variables with standard type IDs
            if (var_type == AP_Var::k_typeid_float) {
                ((AP_Float *) vp)->set_and_save(packet.param_value);

            } else if (var_type == AP_Var::k_typeid_float16) {
                ((AP_Float16 *) vp)->set_and_save(packet.param_value);

            } else if (var_type == AP_Var::k_typeid_int32) {
                ((AP_Int32 *) vp)->set_and_save(
                    packet.param_value + rounding_addition);

            } else if (var_type == AP_Var::k_typeid_int16) {
                ((AP_Int16 *) vp)->set_and_save(
                    packet.param_value + rounding_addition);

            } else if (var_type == AP_Var::k_typeid_int8) {
                ((AP_Int8 *) vp)->set_and_save(
                    packet.param_value + rounding_addition);
            } else {
                // we don't support mavlink set on this parameter
                break;
            }

            // Report back the new value if we accepted the change
            // we send the value we actually set, which could be
            // different from the value sent, in case someone sent
            // a fractional value to an integer type
            mavlink_msg_param_value_send(_channel, (int8_t *) key,
                                         vp->cast_to_float(), _countParameters(), -1); // XXX we don't actually know what its index is...
        }

        break;
    } // end case


    }
}
Пример #13
0
int I_PickIWad (WadStuff *wads, int numwads, bool showwin, int defaultiwad)
{
	int i;

	if (!showwin)
	{
		return defaultiwad;
	}

#if !defined(__APPLE__)
	const char *str;
	if((str=getenv("KDE_FULL_SESSION")) && strcmp(str, "true") == 0)
	{
		FString cmd("kdialog --title \""GAMESIG" "DOTVERSIONSTR": Select an IWAD to use\""
		            " --menu \"ZDoom found more than one IWAD\n"
		            "Select from the list below to determine which one to use:\"");

		for(i = 0; i < numwads; ++i)
		{
			const char *filepart = strrchr(wads[i].Path, '/');
			if(filepart == NULL)
				filepart = wads[i].Path;
			else
				filepart++;
			// Menu entries are specified in "tag" "item" pairs, where when a
			// particular item is selected (and the Okay button clicked), its
			// corresponding tag is printed to stdout for identification.
			cmd.AppendFormat(" \"%d\" \"%s (%s)\"", i, wads[i].Name.GetChars(), filepart);
		}

		if(defaultiwad >= 0 && defaultiwad < numwads)
		{
			const char *filepart = strrchr(wads[defaultiwad].Path, '/');
			if(filepart == NULL)
				filepart = wads[defaultiwad].Path;
			else
				filepart++;
			cmd.AppendFormat(" --default \"%s (%s)\"", wads[defaultiwad].Name.GetChars(), filepart);
		}

		FILE *f = popen(cmd, "r");
		if(f != NULL)
		{
			char gotstr[16];

			if(fgets(gotstr, sizeof(gotstr), f) == NULL ||
			   sscanf(gotstr, "%d", &i) != 1)
				i = -1;

			// Exit status = 1 means the selection was canceled (either by
			// Cancel/Esc or the X button), not that there was an error running
			// the program. In that case, nothing was printed so fgets will
			// have failed. Other values can indicate an error running the app,
			// so fall back to whatever else can be used.
			int status = pclose(f);
			if(WIFEXITED(status) && (WEXITSTATUS(status) == 0 || WEXITSTATUS(status) == 1))
				return i;
		}
	}
#endif
#ifndef NO_GTK
	if (GtkAvailable)
	{
		return I_PickIWad_Gtk (wads, numwads, showwin, defaultiwad);
	}
#elif defined(__APPLE__)
	return I_PickIWad_Cocoa (wads, numwads, showwin, defaultiwad);
#endif
	
	printf ("Please select a game wad (or 0 to exit):\n");
	for (i = 0; i < numwads; ++i)
	{
		const char *filepart = strrchr (wads[i].Path, '/');
		if (filepart == NULL)
			filepart = wads[i].Path;
		else
			filepart++;
		printf ("%d. %s (%s)\n", i+1, wads[i].Name.GetChars(), filepart);
	}
	printf ("Which one? ");
	scanf ("%d", &i);
	if (i > numwads)
		return -1;
	return i-1;
}
Пример #14
0
int main (int argc, char *argv[]) {
  /* Program Option parsing */

  int num_frames = 1;
  int threads = 1;
  bool disable_output = false;
  bool colourise_quantiser = false;
  bool colourise_padding = false;
  bool colourise_unpadded = false;
  bool quartersize = false;
  bool verbose = false;

  std::string input_filename;
  std::string output_filename;

  try {
    TCLAP::CmdLine cmd("VC2 HQ profile Decoder Example\n"
                       "All input files must be vc2 streams\n"
                       "All output files will be yuv422p10le\n", '=', "0.1", true);

    TCLAP::SwitchArg     verbose_arg             ("v", "verbose",        "verbose mode",                                    cmd, false);
    TCLAP::ValueArg<int> num_frames_arg          ("n", "num-frames",     "Number of frames to decode", false, 1, "integer", cmd);
    TCLAP::ValueArg<int> num_threads_arg         ("t", "threads",        "Number of threads",          false, 1, "integer", cmd);
    TCLAP::SwitchArg     disable_output_args     ("d", "disable-output",      "disable output",                                  cmd, false);
    TCLAP::SwitchArg     colourise_quantiser_args("q", "colourise-quantiser", "colourise based on quantiser levels",             cmd, false);
    TCLAP::SwitchArg     colourise_padding_args  ("p", "colourise-padding", "colourise based on padding levels",               cmd, false);
    TCLAP::SwitchArg     colourise_unpadded_args ("u", "colourise-unpadded", "colourise based on lack of padding",              cmd, false);
    
    TCLAP::UnlabeledValueArg<std::string> input_file_arg("input_file",   "encoded input file",         true, "", "string",  cmd);
    TCLAP::UnlabeledValueArg<std::string> output_file_arg("output_file", "output file (defaults to input file + .yuv)", false, "", "string", cmd);

    cmd.parse( argc, argv );

    num_frames          = num_frames_arg.getValue();
    threads             = num_threads_arg.getValue();
    disable_output      = disable_output_args.getValue();
    colourise_quantiser = colourise_quantiser_args.getValue();
    colourise_padding   = colourise_padding_args.getValue();
    colourise_unpadded  = colourise_unpadded_args.getValue();
    verbose             = verbose_arg.getValue();

    input_filename = input_file_arg.getValue();
    output_filename = output_file_arg.getValue();
  } catch (TCLAP::ArgException &e) {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1;
  }

  if (output_filename == "")
    output_filename = input_filename + ".yuv";

  /* Variables for storing input and output buffers */
  char *idata;
  size_t input_length = 0;
  uint16_t **odata = new uint16_t*[num_frames];   // Output frame pointers
  uint16_t ***opics = new uint16_t**[num_frames*2]; // Output picture pointers (which may be different for interlaced sequences)
  for (int i = 0; i < num_frames * 2; i++) {
    opics[i] = new uint16_t*[3];
  }
  int ostride[3];
  int num_frames_decoded_from_sequence = 0;
  int total_frames_decoded = 0;




  
  /* Initialise decoder */
  vc2decode_init();
  VC2DecoderHandle decoder = vc2decode_create();

  /* Configure decoder */
  {
    VC2DecoderParamsUser params;
    memset((void *)&params, 0, sizeof(params));

    params.threads = threads;
    params.colourise_quantiser = colourise_quantiser;
    params.colourise_padding   = colourise_padding;
    params.colourise_unpadded  = colourise_unpadded;


    /* QuarterSize is only really sensible for HD */
    if (quartersize) {
      params.partial_decode = true;
      params.partial_decode_width  = 1920/2;
      params.partial_decode_height = 1080/2;

      params.partial_decode_offset_x  = 0;
      params.partial_decode_offset_y  = 540;
    }


    {
      VC2DecoderResult r = vc2decode_set_parameters(decoder, params);
      if (r != VC2DECODER_OK) {
        printf("Parameter Error: %d\n", r);
        return 1;
      }
    }
  }


  /* Read input data */
  {
    FILE *f = FOPEN(input_filename.c_str(), "rb");
    if (!f) {
      fprintf(stderr, "Could not open: %s\n", input_filename.c_str());
      perror("Invalid input file: ");
      return 1;
    }
    int r = fseek(f, 0L, SEEK_END);
    if (r < 0) {
      perror("Error seeking in input file");
      return 1;
    }
    input_length = ftell(f);
    rewind(f);

    idata = (char *)malloc(input_length);
    size_t s = fread(idata, 1, input_length, f);
    if (s != input_length) {
      if (ferror(f))
        fprintf(stderr, "Error reading file\n");
      else
        fprintf(stderr, "Improper Length on Input File\n");
      return 1;
    }

    fclose(f);

    printf("Read %lubytes of input data\n", input_length);
  }


  /* Set the output fmt to something invalid to start with */
  VC2DecoderOutputFormat fmt;
  fmt.width            = 0;
  fmt.height           = 0;
  fmt.signal_range     = 0;
  fmt.source_sampling  = 0;
  fmt.frame_rate_numer = 0;
  fmt.frame_rate_denom = 0;
  fmt.interlaced       = 0;

  ostride[0] = 0;
  ostride[1] = 0;
  ostride[2] = 0;

  for (int i = 0; i < num_frames; i++) {
    odata[i] = NULL;
  }




  /* Begin the main program loop */
  int err = 0;
  uint64_t time_taken = 0;
  while (total_frames_decoded < num_frames) {
    VC2DecoderResult r;

    /* Reset to the start of the input data */
    char *id = idata;
    char *iend = idata + input_length;

    /* We are at the start of a sequence, so synchronise */
    r = vc2decode_synchronise(decoder, &id, iend - id, true);
    if (r != VC2DECODER_OK_RECONFIGURED) {
      fprintf(stderr, "Error synchronising to sequence");
      err = 1;
      break;
    }

    /* We have synchronised, so get the output format */
    VC2DecoderOutputFormat new_fmt;
    r = vc2decode_get_output_format(decoder, &new_fmt);
    if (r != VC2DECODER_OK) {
      fprintf(stderr, "Output format error: %d\n", r);
      err = 1;
      break;
    }

    /* Reconfigure output buffers if this format doesn't
       match the current one */
    if (fmt.width != new_fmt.width ||
        fmt.height != new_fmt.height ||
        fmt.interlaced != new_fmt.interlaced) {
      fmt = new_fmt;

      for (int i = 0; i < num_frames; i++) {
        if (odata[i])
          free(odata[i]);
        odata[i] = (uint16_t *)malloc(fmt.width*fmt.height*2*sizeof(uint16_t));
      }

      if (fmt.interlaced) {
        ostride[0] = fmt.width*2;
        ostride[1] = fmt.width;
        ostride[2] = fmt.width;
        for (int i = 0; i < num_frames; i++) {
          opics[2*i + 0][0] = odata[i];
          opics[2*i + 0][1] = odata[i] + fmt.width*fmt.height;
          opics[2*i + 0][2] = odata[i] + fmt.width*fmt.height + fmt.width*fmt.height/2;

          opics[2*i + 1][0] = odata[i] + fmt.width;
          opics[2*i + 1][1] = odata[i] + fmt.width*fmt.height + fmt.width/2;
          opics[2*i + 1][2] = odata[i] + fmt.width*fmt.height + fmt.width*fmt.height/2 + fmt.width/2;
        }
      } else {
        ostride[0] = fmt.width;
        ostride[1] = fmt.width/2;
        ostride[2] = fmt.width/2;
        for (int i = 0; i < num_frames; i++) {
          opics[i][0] = odata[i];
          opics[i][1] = odata[i] + fmt.width*fmt.height;
          opics[i][2] = odata[i] + fmt.width*fmt.height + fmt.width*fmt.height/2;
        }
      }
    }

    /* Decode Pictures from stream */
    int picture = 0;
    int64_t start, end;
    start = gettime();
    while (total_frames_decoded < num_frames) {
      r = vc2decode_decode_one_picture(decoder, &id, iend - id, opics[picture], ostride, true);

      /* If End of Sequence break from loop */
      if (r == VC2DECODER_OK_EOS) {
        break;
      }

      /* If a picture has been sucessfully decoded continue */
      if (r == VC2DECODER_OK_PICTURE) {
        if (!fmt.interlaced || (picture%2))
          total_frames_decoded++;
        picture++;
        if (id == NULL) {
          fprintf(stderr, "Premature end of stream\n");
          break;
        }
        continue;
      }

      /* If a reconfiguration has been triggered this is an invalid sequence, flag that */
      if (r == VC2DECODER_OK_RECONFIGURED) {
        fprintf(stderr, "Warning: this sequence changes parameters part way through\n");
        break;
      }

      /* Otherwise we have an error */
      if (r < 0) {
        fprintf(stderr, "Error decoding:\n");
        fprintf(stderr, "  %s\n", VC2DecoderErrorString[-r]);
        err=1;
        break;
      }

      fprintf(stderr, "Unknown Return value: %d\n", r);
      break;
    }
    end = gettime();
    /* We have reached the end of a sequence, or have decoded enough frames */

    /*If an error has occurred bail */
    if (err)
      break;

    /*If no pictures were decoded bail */
    if (picture == 0) {
      fprintf(stderr, "No pictures in sequence!\n");
      err = 1;
      break;
    }

    /* Otherwise update the record of how many decoded frames have been recorded */
    int num_frames_decoded_from_this_sequence = (fmt.interlaced)?(picture/2):(picture);
    if (num_frames_decoded_from_this_sequence > num_frames_decoded_from_sequence)
      num_frames_decoded_from_sequence = num_frames_decoded_from_this_sequence;

    /* And update the record of time taken to decode */
    time_taken += end - start;
  }

  /* If there has been no error print the speed */
  if (!err) {
    printf("--------------------------------------------------\n");
    printf("  %d frames decoded in %5.3fs\n", total_frames_decoded, time_taken/1000000.0);
    printf("  %5.3ffps\n", total_frames_decoded*1000000.0/time_taken);
    printf("--------------------------------------------------\n");
  }

  /* If there has been no error get decoder statistics  */
  if (!err) {
    VC2DecoderSequenceInfo info;
    vc2decode_sequence_info(decoder, &info);

    print_sequence_info(info, verbose);
  }

  /*
     If there is no error and output is enabled write the output to a file

     This code actually performs an endianess swap and some bit shifting on the output
     data to put it into the desired format (10-bit data in the high order bits of 16-bit
     words in network byte order).
   */
  if (!err && !disable_output) {
    try {
      FILE *of = FOPEN(output_filename.c_str(), "wb");

      for (int i = 0; i < num_frames_decoded_from_sequence; i++) {

        for (int y = 0; y < fmt.height; y++) {
          size_t s = fwrite(&odata[i][(y*fmt.width)], 1, fmt.width*sizeof(uint16_t), of);
          if (s != fmt.width*sizeof(uint16_t))
            throw std::runtime_error("Writing Error");
        }
        for (int y = 0; y < fmt.height*2; y++) {
          size_t s = fwrite(&odata[i][(fmt.height*fmt.width + y*fmt.width/2)], 1, fmt.width/2*sizeof(uint16_t), of);
          if (s != fmt.width/2*sizeof(uint16_t))
            throw std::runtime_error("Writing Error");
        }
      }
      printf("Wrote out %d frames\n", num_frames_decoded_from_sequence);
      fclose(of);
    } catch(...) {
      fprintf(stderr, "Error writing output\n");
      err = 1;
    }
  }

  /* Destroy the decoder */
  vc2decode_destroy(decoder);


  /* Deallocate buffers */
  free(idata);

  for (int i = 0; i < num_frames; i++)
    if (odata[i])
      free(odata[i]);

  delete[] odata;
  for (int i = 0; i < num_frames * 2; i++)
    delete[] opics[i];
  delete[] opics;

  return err;
}
Пример #15
0
void CheckExternalScripts::configure(const Plugin::ExecuteRequestMessage::Request &request, Plugin::ExecuteResponseMessage::Response *response) {

	namespace po = boost::program_options;
	namespace pf = nscapi::protobuf::functions;
	po::variables_map vm;
	po::options_description desc;
	std::string arguments = "false";
	const std::string path = "/settings/external scripts/server";

	pf::settings_query q(get_id());
	q.get(path, "allow arguments", false);
	q.get(path, "allow nasty characters", false);


	get_core()->settings_query(q.request(), q.response());
	if (!q.validate_response()) {
		nscapi::protobuf::functions::set_response_bad(*response, q.get_response_error());
		return;
	}
	BOOST_FOREACH(const pf::settings_query::key_values &val, q.get_query_key_response()) {
		if (val.path == path && val.key && *val.key == "allow arguments" && val.get_bool())
			arguments = "true";
		else if (val.path == path && val.key && *val.key == "allow nasty characters" && val.get_bool())
			arguments = "safe";
	}
	desc.add_options()
		("help", "Show help.")

		("arguments", po::value<std::string>(&arguments)->default_value(arguments)->implicit_value("safe"), 
		"Allow arguments. false=don't allow, safe=allow non escape chars, all=allow all arguments.")

		;

	try {
		nscapi::program_options::basic_command_line_parser cmd(request);
		cmd.options(desc);

		po::parsed_options parsed = cmd.run();
		po::store(parsed, vm);
		po::notify(vm);
	} catch (const std::exception &e) {
		return nscapi::program_options::invalid_syntax(desc, request.command(), "Invalid command line: " + utf8::utf8_from_native(e.what()), *response);
	}

	if (vm.count("help")) {
		nscapi::protobuf::functions::set_response_good(*response, nscapi::program_options::help(desc));
		return;
	}
	std::stringstream result;

	nscapi::protobuf::functions::settings_query s(get_id());
	s.set(MAIN_MODULES_SECTION, "CheckExternalScripts", "enabled");
	if (arguments == "all" || arguments == "unsafe") {
		result << "UNSAFE Arguments are allowed." << std::endl;
		s.set(path, "allow arguments", "true");
		s.set(path, "allow nasty characters", "true");
	} else if (arguments == "safe" || arguments == "true") {
		result << "SAFE Arguments are allowed." << std::endl;
		s.set(path, "allow arguments", "true");
		s.set(path, "allow nasty characters", "false");
	} else {
		result << "Arguments are NOT allowed." << std::endl;
		s.set(path, "allow arguments", "false");
		s.set(path, "allow nasty characters", "false");
	}
	s.save();
	get_core()->settings_query(s.request(), s.response());
	if (!s.validate_response())
		nscapi::protobuf::functions::set_response_bad(*response, s.get_response_error());
	else
		nscapi::protobuf::functions::set_response_good(*response, result.str());
}
Пример #16
0
int main( int argc, const char** argv )
{
  std::string filename;
  std::string configFile = "";
  bool outputJson = false;
  int seektoms = 0;
  bool detectRegion = false;
  std::string templateRegion;
  std::string country;
  int topn;

  TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion());

  TCLAP::UnlabeledValueArg<std::string>  fileArg( "image_file", "Image containing license plates", false, "", "image_file_path"  );

  
  TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
  TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms");
  TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file");
  TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code");
  TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");

  TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format.  Default=off", cmd, false);
  TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image.  Default=off", cmd, false);
  TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates.  Default=off", cmd, false);

  try
  {
    cmd.add( templateRegionArg );
    cmd.add( seekToMsArg );
    cmd.add( topNArg );
    cmd.add( configFileArg );
    cmd.add( fileArg );
    cmd.add( countryCodeArg );

    
    if (cmd.parse( argc, argv ) == false)
    {
      // Error occured while parsing.  Exit now.
      return 1;
    }

    filename = fileArg.getValue();

    country = countryCodeArg.getValue();
    seektoms = seekToMsArg.getValue();
    outputJson = jsonSwitch.getValue();
    configFile = configFileArg.getValue();
    detectRegion = detectRegionSwitch.getValue();
    templateRegion = templateRegionArg.getValue();
    topn = topNArg.getValue();
    measureProcessingTime = clockSwitch.getValue();
  }
  catch (TCLAP::ArgException &e)    // catch any exceptions
  {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
    return 1;
  }

  
  cv::Mat frame;

  Alpr alpr(country, configFile);
  alpr.setTopN(topn);

  if (detectRegion)
    alpr.setDetectRegion(detectRegion);

  if (templateRegion.empty() == false)
    alpr.setDefaultRegion(templateRegion);

  if (alpr.isLoaded() == false)
  {
    std::cerr << "Error loading OpenALPR" << std::endl;
    return 1;
  }

  if (filename.empty())
  {
    std::string filename;
    while (std::getline(std::cin, filename))
    {
      if (fileExists(filename.c_str()))
      {
	frame = cv::imread( filename );
	detectandshow( &alpr, frame, "", outputJson);
      }
      else
      {
	std::cerr << "Image file not found: " << filename << std::endl;
      }

    }
  }
  else if (filename == "webcam")
  {
    int framenum = 0;
    cv::VideoCapture cap(0);
    if (!cap.isOpened())
    {
      std::cout << "Error opening webcam" << std::endl;
      return 1;
    }

    while (cap.read(frame))
    {
      detectandshow(&alpr, frame, "", outputJson);
      sleep_ms(10);
      framenum++;
    }
  }
  else if (startsWith(filename, "http://") || startsWith(filename, "https://"))
  {
    int framenum = 0;
    
    VideoBuffer videoBuffer;
    
    videoBuffer.connect(filename, 5);
    
    cv::Mat latestFrame;
    
    while (program_active)
    {
      std::vector<cv::Rect> regionsOfInterest;
      int response = videoBuffer.getLatestFrame(&latestFrame, regionsOfInterest);
      
      if (response != -1)
      {
        detectandshow( &alpr, latestFrame, "", outputJson);
      }
      
      // Sleep 10ms
      sleep_ms(10);
    }
    
    videoBuffer.disconnect();
    
    std::cout << "Video processing ended" << std::endl;
  }
  else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") || 
	   hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg"))
  {
    if (fileExists(filename.c_str()))
    {
      int framenum = 0;

      cv::VideoCapture cap=cv::VideoCapture();
      cap.open(filename);
      cap.set(CV_CAP_PROP_POS_MSEC, seektoms);

      while (cap.read(frame))
      {
        if (SAVE_LAST_VIDEO_STILL)
        {
          cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame);
        }
        std::cout << "Frame: " << framenum << std::endl;

        detectandshow( &alpr, frame, "", outputJson);
        //create a 1ms delay
        sleep_ms(1);
        framenum++;
      }
    }
    else
    {
      std::cerr << "Video file not found: " << filename << std::endl;
    }
  }
  else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") || 
	   hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif"))
  {
    if (fileExists(filename.c_str()))
    {
      frame = cv::imread( filename );

      bool plate_found = detectandshow( &alpr, frame, "", outputJson);
      
      if (!plate_found && !outputJson)
	std::cout << "No license plates found." << std::endl;
    }
    else
    {
      std::cerr << "Image file not found: " << filename << std::endl;
    }
  }
  else if (DirectoryExists(filename.c_str()))
  {
    std::vector<std::string> files = getFilesInDir(filename.c_str());

    std::sort( files.begin(), files.end(), stringCompare );

    for (int i = 0; i< files.size(); i++)
    {
      if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png"))
      {
        std::string fullpath = filename + "/" + files[i];
        std::cout << fullpath << std::endl;
        frame = cv::imread( fullpath.c_str() );
        if (detectandshow( &alpr, frame, "", outputJson))
        {
          //while ((char) cv::waitKey(50) != 'c') { }
        }
        else
        {
          //cv::waitKey(50);
        }
      }
    }
  }
  else
  {
    std::cerr << "Unknown file type" << std::endl;
    return 1;
  }

  return 0;
}
int main(int argc, char *argv[])
{
//    if(argc > 0)
//        g_ApplicationPath = Files::dirname(argv[0]);
//    g_ApplicationPath = DirMan(g_ApplicationPath).absolutePath();

    DirMan imagesDir;
    std::vector<std::string> fileList;
    FreeImage_Initialise();

    LazyFixTool_Setup setup;

    try
    {
        // Define the command line object.
        TCLAP::CmdLine  cmd(V_FILE_DESC "\n"
                            "Copyright (c) 2017-2019 Vitaly Novichkov <*****@*****.**>\n"
                            "This program is distributed under the GNU GPLv3+ license\n", ' ', V_FILE_VERSION V_FILE_RELEASE);

        TCLAP::SwitchArg switchNoBackups("n",       "no-backup", "Don't create backup", false);
        TCLAP::SwitchArg switchDigRecursive("d",    "dig-recursive", "Look for images in subdirectories", false);
        TCLAP::SwitchArg switchDigRecursiveDEP("w", "dig-recursive-old", "Look for images in subdirectories [deprecated]", false);

        TCLAP::ValueArg<std::string> outputDirectory("O", "output",
                "path to a directory where the fixed images will be saved",
                false, "", "/path/to/output/directory/");
        TCLAP::UnlabeledMultiArg<std::string> inputFileNames("filePath(s)",
                "Input GIF file(s)",
                true,
                "Input file path(s)");

        cmd.add(&switchNoBackups);
        cmd.add(&switchDigRecursive);
        cmd.add(&switchDigRecursiveDEP);
        cmd.add(&outputDirectory);
        cmd.add(&inputFileNames);

        cmd.parse(argc, argv);

        setup.noMakeBackup      = switchNoBackups.getValue();
        setup.walkSubDirs     = switchDigRecursive.getValue() | switchDigRecursiveDEP.getValue();
        //nopause         = switchNoPause.getValue();

        setup.pathOut     = outputDirectory.getValue();

        for(const std::string &fpath : inputFileNames.getValue())
        {
            if(Files::hasSuffix(fpath, "m.gif"))
                continue;
            else if(DirMan::exists(fpath))
                setup.pathIn = fpath;
            else
            {
                fileList.push_back(fpath);
                setup.listOfFiles = true;
            }
        }

        if((argc <= 1) || (setup.pathIn.empty() && !setup.listOfFiles))
        {
            fprintf(stderr, "\n"
                            "ERROR: Missing input files!\n"
                            "Type \"%s --help\" to display usage.\n\n", argv[0]);
            return 2;
        }
    }
    catch(TCLAP::ArgException &e)   // catch any exceptions
    {
        std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
        return 2;
    }

    fprintf(stderr, "============================================================================\n"
                    "Lazily-made image masks fix tool by Wohlstand. Version " V_FILE_VERSION V_FILE_RELEASE "\n"
                    "============================================================================\n"
                    "This program is distributed under the GNU GPLv3 license \n"
                    "============================================================================\n");
    fflush(stderr);

    if(!setup.listOfFiles)
    {
        if(setup.pathIn.empty())
            goto WrongInputPath;
        if(!DirMan::exists(setup.pathIn))
            goto WrongInputPath;

        imagesDir.setPath(setup.pathIn);
        setup.pathIn = imagesDir.absolutePath();
    }

    if(!setup.pathOut.empty())
    {
        if(!DirMan::exists(setup.pathOut) && !DirMan::mkAbsPath(setup.pathOut))
            goto WrongOutputPath;

        setup.pathOut = DirMan(setup.pathOut).absolutePath();
        setup.pathOutSame   = false;
    }
    else
    {
        setup.pathOut       = setup.pathIn;
        setup.pathOutSame   = true;
    }

    delEndSlash(setup.pathIn);
    delEndSlash(setup.pathOut);

    printf("============================================================================\n"
           "Converting images...\n"
           "============================================================================\n");
    fflush(stdout);

    if(!setup.listOfFiles)
        std::cout << ("Input path:  " + setup.pathIn + "\n");

    std::cout << ("Output path: " + setup.pathOut + "\n");

    std::cout << "============================================================================\n";
    std::cout.flush();

    if(setup.listOfFiles)// Process a list of flies
    {
        for(std::string &file : fileList)
        {
            std::string fname   = Files::basename(file);
            setup.pathIn = DirMan(Files::dirname(file)).absolutePath();
            if(setup.pathOutSame)
                setup.pathOut = DirMan(Files::dirname(file)).absolutePath();
            doLazyFixer(setup.pathIn, fname , setup.pathOut, setup);
        }
    }
    else // Process directories with a source files
    {
        imagesDir.getListOfFiles(fileList, {".gif"});
        if(!setup.walkSubDirs) //By directories
        {
            for(std::string &fname : fileList)
                doLazyFixer(setup.pathIn, fname, setup.pathOut, setup);
        }
        else
        {
            imagesDir.beginWalking({".gif"});
            std::string curPath;
            while(imagesDir.fetchListFromWalker(curPath, fileList))
            {
                if(Files::hasSuffix(curPath, "/_backup"))
                    continue; //Skip backup directories
                for(std::string &file : fileList)
                {
                    if(setup.pathOutSame)
                        setup.pathOut = curPath;
                    doLazyFixer(curPath, file, setup.pathOut, setup);
                }
            }
        }
    }

    printf("============================================================================\n"
           "                      Conversion has been completed!\n"
           "============================================================================\n"
           "Successfully fixed:         %d\n"
           "Masks are not found:        %d\n"
           "Backups created:            %d\n"
           "Fixes failed:               %d\n"
           "\n",
           setup.count_success,
           setup.count_nomask,
           setup.count_backups,
           setup.count_failed);
    fflush(stdout);
    return (setup.count_failed == 0) ? 0 : 1;

WrongInputPath:
    std::cout.flush();
    std::cerr.flush();
    printf("============================================================================\n"
           "                           Wrong input path!\n"
           "============================================================================\n");
    fflush(stdout);
    return 2;

WrongOutputPath:
    std::cout.flush();
    std::cerr.flush();
    printf("============================================================================\n"
           "                          Wrong output path!\n"
           "============================================================================\n");
    fflush(stdout);
    return 2;
}