int main (int argc, char * argv[]) { bool trace_parsing; bool trace_scanning; po::options_description visible_options(std::string("Usage: ") + argv[0] + " [options] file ...\nOptions"); visible_options.add_options() ("help", "display this help") ("output,o", po::value<std::string>(), "output file (stdout is used by default)") ("trace_parsing,p", po::value(&trace_parsing)->zero_tokens(), "trace parsing") ("trace_scanning,s", po::value(&trace_scanning)->zero_tokens(), "trace scanning") ("max_var_len,M", po::value<size_t>()->default_value(10), "max length of obfuscated variable name") ("min_var_len,m", po::value<size_t>()->default_value(1), "min length of obfuscated variable name") ; po::options_description hidden_options("Hidden options"); hidden_options.add_options() ("input", po::value< std::vector<std::string> >(), "input file") ; po::options_description cmdline_options; cmdline_options.add(visible_options).add(hidden_options); po::positional_options_description p; p.add("input", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm); po::notify(vm); if (vm.count("help") || argc == 1) { std::cout << visible_options << std::endl; return EXIT_SUCCESS; } if (!vm.count("input")) { std::cerr << "At least 1 input file must be specified" << std::endl; return EXIT_FAILURE; } std::ostream * output = vm.count("output") ? new std::ofstream(vm["output"].as<std::string>()) : &std::cout; obfuscation::obfuscator o(*output, vm["min_var_len"].as<size_t>(), vm["max_var_len"].as<size_t>(), trace_parsing, trace_scanning); int res = 0; for (const auto & filename : vm["input"].as< std::vector<std::string> >()) { res |= o.obfuscate(filename); } if (vm.count("output")) { delete output; } return res; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); std::string source; std::string file_name; //TODO: figure out if path is file or folder. std::string snapshot_path; po::options_description visible_options("OPTIONS"); try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description config("CONFIGURATION"); config.add_options() ("snapshot-path,f", po::value<std::string>(&snapshot_path), "The path to which in which snapshots will be saved." "If a folder is designated, the base file name will be SOURCE." "The timestamp of the snapshot will be prepended to the file name." "Defaults to the current directory.") ; po::options_description hidden("HIDDEN OPTIONS"); hidden.add_options() ("source", po::value<std::string>(&source), "The name of the frame SOURCE that supplies frames to view.\n") ; po::positional_options_description positional_options; positional_options.add("source", -1); po::options_description all_options("ALL OPTIONS"); all_options.add(options).add(config).add(hidden); visible_options.add(options).add(config); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat Frame Viewer version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("source")) { printUsage(visible_options); std::cerr << oat::Error("A SOURCE must be specified. Exiting.\n"); return -1; } if (!variable_map.count("snapshot-path")) { snapshot_path = bfs::current_path().string(); } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return -1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.\n"); return -1; } // Create component std::shared_ptr<Viewer> viewer; // Make the viewer // TODO: use a method to create snapshot file name instead of the constructor // This will allow you to get rid of these extra try-catch blocks try { viewer = std::make_shared<Viewer>(source, snapshot_path); } catch (const std::runtime_error& ex) { std::cerr << oat::Error(ex.what()) << "\n"; // Exit failure return -1; } catch (...) { std::cerr << oat::Error("Unknown exception.\n"); // Exit failure return -1; } try { // Tell user std::cout << oat::whoMessage(viewer->get_name(), "Listening to source " + oat::sourceText(source) + ".\n") << oat::whoMessage(viewer->get_name(), "Press 's' on the viewer window to take a snapshot.\n") << oat::whoMessage(viewer->get_name(), "Press CTRL+C to exit.\n"); // Infinite loop until ctrl-c or end of stream signal run(viewer); // Tell user std::cout << oat::whoMessage(viewer->get_name(), "Exiting.\n"); // Exit return 0; } catch (const std::runtime_error& ex) { std::cerr << oat::whoError(viewer->get_name(), ex.what()) << "\n"; } catch (const cv::Exception& ex) { std::cerr << oat::whoError(viewer->get_name(), ex.msg) << "\n"; } catch (...) { std::cerr << oat::whoError(viewer->get_name(), "Unknown exception.\n"); } // Exit failure return -1; }
int main(int argc, char *argv[]) { try { LogPolicy::GetInstance().Unmute(); TIMER_START(preparing); TIMER_START(expansion); boost::filesystem::path config_file_path, input_path, restrictions_path, profile_path; unsigned int requested_num_threads; bool use_elevation; // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( "config,c", boost::program_options::value<boost::filesystem::path>(&config_file_path) ->default_value("contractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); config_options.add_options()( "restrictions,r", boost::program_options::value<boost::filesystem::path>(&restrictions_path), "Restrictions file in .osrm.restrictions format")( "profile,p", boost::program_options::value<boost::filesystem::path>(&profile_path) ->default_value("profile.lua"),"Path to LUA routing profile")( "elevation,e", boost::program_options::value<bool>(&use_elevation)->default_value(true), "Process node elevations")( "threads,t", boost::program_options::value<unsigned int>(&requested_num_threads)->default_value(tbb::task_scheduler_init::default_num_threads()), "Number of threads to use"); // hidden options, will be allowed both on command line and in config file, but will not be // shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()( "input,i", boost::program_options::value<boost::filesystem::path>(&input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options( "Usage: " + boost::filesystem::basename(argv[0]) + " <input.osrm> [options]"); visible_options.add(generic_options).add(config_options); // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), option_variables); if (option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return 0; } if (option_variables.count("help")) { SimpleLogger().Write() << "\n" << visible_options; return 0; } boost::program_options::notify(option_variables); if (!option_variables.count("restrictions")) { restrictions_path = std::string(input_path.string() + ".restrictions"); } if (!option_variables.count("input")) { SimpleLogger().Write() << "\n" << visible_options; return 0; } if (!boost::filesystem::is_regular_file(input_path)) { SimpleLogger().Write(logWARNING) << "Input file " << input_path.string() << " not found!"; return 1; } if (!boost::filesystem::is_regular_file(profile_path)) { SimpleLogger().Write(logWARNING) << "Profile " << profile_path.string() << " not found!"; return 1; } if (1 > requested_num_threads) { SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return 1; } const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads(); SimpleLogger().Write() << "Input file: " << input_path.filename().string(); SimpleLogger().Write() << "Restrictions file: " << restrictions_path.filename().string(); SimpleLogger().Write() << "Profile: " << profile_path.filename().string(); SimpleLogger().Write() << "Using elevation: " << use_elevation; SimpleLogger().Write() << "Threads: " << requested_num_threads; if (recommended_num_threads != requested_num_threads) { SimpleLogger().Write(logWARNING) << "The recommended number of threads is " << recommended_num_threads << "! This setting may have performance side-effects."; } tbb::task_scheduler_init init(requested_num_threads); LogPolicy::GetInstance().Unmute(); boost::filesystem::ifstream restriction_stream(restrictions_path, std::ios::binary); TurnRestriction restriction; FingerPrint fingerprint_loaded, fingerprint_orig; unsigned number_of_usable_restrictions = 0; restriction_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); if (!fingerprint_loaded.TestPrepare(fingerprint_orig)) { SimpleLogger().Write(logWARNING) << ".restrictions was prepared with different build.\n" "Reprocess to get rid of this warning."; } restriction_stream.read((char *)&number_of_usable_restrictions, sizeof(unsigned)); restriction_list.resize(number_of_usable_restrictions); if (number_of_usable_restrictions > 0) { restriction_stream.read((char *)&(restriction_list[0]), number_of_usable_restrictions * sizeof(TurnRestriction)); } restriction_stream.close(); boost::filesystem::ifstream in; in.open(input_path, std::ios::in | std::ios::binary); const std::string node_filename = input_path.string() + ".nodes"; const std::string edge_out = input_path.string() + ".edges"; const std::string geometry_filename = input_path.string() + ".geometry"; const std::string graphOut = input_path.string() + ".hsgr"; const std::string rtree_nodes_path = input_path.string() + ".ramIndex"; const std::string rtree_leafs_path = input_path.string() + ".fileIndex"; /*** Setup Scripting Environment ***/ // Create a new lua state lua_State *lua_state = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(lua_state); // open utility libraries string library; luaL_openlibs(lua_state); // adjust lua load path luaAddScriptFolderToLoadPath(lua_state, profile_path.string().c_str()); // Now call our function in a lua script if (0 != luaL_dofile(lua_state, profile_path.string().c_str())) { std::cerr << lua_tostring(lua_state, -1) << " occured in scripting block" << std::endl; return 1; } EdgeBasedGraphFactory::SpeedProfileProperties speed_profile; if (0 != luaL_dostring(lua_state, "return traffic_signal_penalty\n")) { std::cerr << lua_tostring(lua_state, -1) << " occured in scripting block" << std::endl; return 1; } speed_profile.trafficSignalPenalty = 10 * lua_tointeger(lua_state, -1); SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " << speed_profile.trafficSignalPenalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { std::cerr << lua_tostring(lua_state, -1) << " occured in scripting block" << std::endl; return 1; } speed_profile.uTurnPenalty = 10 * lua_tointeger(lua_state, -1); speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function"); #ifdef WIN32 #pragma message ("Memory consumption on Windows can be higher due to memory alignment") #else static_assert(sizeof(ImportEdge) == 20, "changing ImportEdge type has influence on memory consumption!"); #endif std::vector<ImportEdge> edge_list; NodeID number_of_node_based_nodes = readBinaryOSRMGraphFromStream(in, edge_list, barrier_node_list, traffic_light_list, &internal_to_external_node_map, restriction_list, use_elevation); in.close(); if (edge_list.empty()) { SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return 1; } SimpleLogger().Write() << restriction_list.size() << " restrictions, " << barrier_node_list.size() << " bollard nodes, " << traffic_light_list.size() << " traffic lights"; /*** * Building an edge-expanded graph from node-based input and turn restrictions */ SimpleLogger().Write() << "Generating edge-expanded graph representation"; std::shared_ptr<NodeBasedDynamicGraph> node_based_graph = NodeBasedDynamicGraphFromImportEdges(number_of_node_based_nodes, edge_list); std::unique_ptr<RestrictionMap> restriction_map = std::unique_ptr<RestrictionMap>(new RestrictionMap(node_based_graph, restriction_list)); EdgeBasedGraphFactory *edge_based_graph_factor = new EdgeBasedGraphFactory(node_based_graph, std::move(restriction_map), barrier_node_list, traffic_light_list, internal_to_external_node_map, speed_profile); edge_list.clear(); edge_list.shrink_to_fit(); edge_based_graph_factor->Run(edge_out, geometry_filename, lua_state); restriction_list.clear(); restriction_list.shrink_to_fit(); barrier_node_list.clear(); barrier_node_list.shrink_to_fit(); traffic_light_list.clear(); traffic_light_list.shrink_to_fit(); unsigned number_of_edge_based_nodes = edge_based_graph_factor->GetNumberOfEdgeBasedNodes(); BOOST_ASSERT(number_of_edge_based_nodes != std::numeric_limits<unsigned>::max()); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; #ifndef WIN32 static_assert(sizeof(EdgeBasedEdge) == 16, "changing ImportEdge type has influence on memory consumption!"); #endif edge_based_graph_factor->GetEdgeBasedEdges(edgeBasedEdgeList); std::vector<EdgeBasedNode> node_based_edge_list; edge_based_graph_factor->GetEdgeBasedNodes(node_based_edge_list); delete edge_based_graph_factor; // TODO actually use scoping: Split this up in subfunctions node_based_graph.reset(); TIMER_STOP(expansion); // Building grid-like nearest-neighbor data structure SimpleLogger().Write() << "building r-tree ..."; StaticRTree<EdgeBasedNode> *rtree = new StaticRTree<EdgeBasedNode>(node_based_edge_list, rtree_nodes_path.c_str(), rtree_leafs_path.c_str(), internal_to_external_node_map); delete rtree; IteratorbasedCRC32<std::vector<EdgeBasedNode>> crc32; unsigned node_based_edge_list_CRC32 = crc32(node_based_edge_list.begin(), node_based_edge_list.end()); node_based_edge_list.clear(); node_based_edge_list.shrink_to_fit(); SimpleLogger().Write() << "CRC32: " << node_based_edge_list_CRC32; /*** * Writing info on original (node-based) nodes */ SimpleLogger().Write() << "writing node map ..."; boost::filesystem::ofstream node_stream(node_filename, std::ios::binary); const unsigned size_of_mapping = internal_to_external_node_map.size(); node_stream.write((char *)&size_of_mapping, sizeof(unsigned)); if (size_of_mapping > 0) { node_stream.write((char *)&(internal_to_external_node_map[0]), size_of_mapping * sizeof(NodeInfo)); } node_stream.close(); internal_to_external_node_map.clear(); internal_to_external_node_map.shrink_to_fit(); /*** * Contracting the edge-expanded graph */ SimpleLogger().Write() << "initializing contractor"; Contractor *contractor = new Contractor(number_of_edge_based_nodes, edgeBasedEdgeList); TIMER_START(contraction); contractor->Run(); TIMER_STOP(contraction); SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; DeallocatingVector<QueryEdge> contracted_edge_list; contractor->GetEdges(contracted_edge_list); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ std::sort(contracted_edge_list.begin(), contracted_edge_list.end()); unsigned max_used_node_id = 0; unsigned contracted_edge_count = contracted_edge_list.size(); SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count << " edges"; boost::filesystem::ofstream hsgr_output_stream(graphOut, std::ios::binary); hsgr_output_stream.write((char *)&fingerprint_orig, sizeof(FingerPrint)); for (const QueryEdge &edge : contracted_edge_list) { BOOST_ASSERT(UINT_MAX != edge.source); BOOST_ASSERT(UINT_MAX != edge.target); max_used_node_id = std::max(max_used_node_id, edge.source); max_used_node_id = std::max(max_used_node_id, edge.target); } SimpleLogger().Write(logDEBUG) << "input graph has " << number_of_edge_based_nodes << " nodes"; SimpleLogger().Write(logDEBUG) << "contracted graph has " << max_used_node_id << " nodes"; max_used_node_id += 1; std::vector<StaticGraph<EdgeData>::NodeArrayEntry> node_array; node_array.resize(number_of_edge_based_nodes + 1); SimpleLogger().Write() << "Building node array"; StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; StaticGraph<EdgeData>::EdgeIterator last_edge = edge; for (StaticGraph<EdgeData>::NodeIterator node = 0; node < max_used_node_id; ++node) { last_edge = edge; while ((edge < contracted_edge_count) && (contracted_edge_list[edge].source == node)) { ++edge; } node_array[node].first_edge = position; //=edge position += edge - last_edge; // remove } for (unsigned sentinel_counter = max_used_node_id; sentinel_counter != node_array.size(); ++sentinel_counter) { // sentinel element, guarded against underflow node_array[sentinel_counter].first_edge = contracted_edge_count; } unsigned node_array_size = node_array.size(); // serialize crc32, aka checksum hsgr_output_stream.write((char *)&node_based_edge_list_CRC32, sizeof(unsigned)); // serialize number of nodes hsgr_output_stream.write((char *)&node_array_size, sizeof(unsigned)); // serialize number of edges hsgr_output_stream.write((char *)&contracted_edge_count, sizeof(unsigned)); // serialize all nodes if (node_array_size > 0) { hsgr_output_stream.write((char *)&node_array[0], sizeof(StaticGraph<EdgeData>::NodeArrayEntry) * node_array_size); } // serialize all edges SimpleLogger().Write() << "Building edge array"; edge = 0; int number_of_used_edges = 0; StaticGraph<EdgeData>::EdgeArrayEntry current_edge; for (unsigned edge = 0; edge < contracted_edge_list.size(); ++edge) { // no eigen loops BOOST_ASSERT(contracted_edge_list[edge].source != contracted_edge_list[edge].target); current_edge.target = contracted_edge_list[edge].target; current_edge.data = contracted_edge_list[edge].data; // every target needs to be valid BOOST_ASSERT(current_edge.target < max_used_node_id); #ifndef NDEBUG if (current_edge.data.distance <= 0) { SimpleLogger().Write(logWARNING) << "Edge: " << edge << ",source: " << contracted_edge_list[edge].source << ", target: " << contracted_edge_list[edge].target << ", dist: " << current_edge.data.distance; SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " << contracted_edge_list[edge].source << "/" << node_array.size() - 1; return 1; } #endif hsgr_output_stream.write((char *)¤t_edge, sizeof(StaticGraph<EdgeData>::EdgeArrayEntry)); ++number_of_used_edges; } hsgr_output_stream.close(); TIMER_STOP(preparing); SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; SimpleLogger().Write() << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) << " nodes/sec and " << (number_of_edge_based_nodes / TIMER_SEC(expansion)) << " edges/sec"; SimpleLogger().Write() << "Contraction: " << (number_of_edge_based_nodes / TIMER_SEC(contraction)) << " nodes/sec and " << number_of_used_edges / TIMER_SEC(contraction) << " edges/sec"; node_array.clear(); SimpleLogger().Write() << "finished preprocessing"; } catch (boost::program_options::too_many_positional_options_error &) { SimpleLogger().Write(logWARNING) << "Only one file can be specified"; return 1; } catch (boost::program_options::error &e) { SimpleLogger().Write(logWARNING) << e.what(); return 1; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << "Exception occured: " << e.what() << std::endl; return 1; } return 0; }
// generate boost::program_options object for the routing part inline unsigned GenerateServerProgramOptions(const int argc, const char *argv[], ServerPaths &paths, std::string &ip_address, int &ip_port, int &requested_num_threads, bool &use_shared_memory, bool &trial, int &max_locations_distance_table, int &max_locations_map_matching) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( "config,c", boost::program_options::value<boost::filesystem::path>(&paths["config"]) ->default_value("server.ini"), "Path to a configuration file")( "trial", boost::program_options::value<bool>(&trial)->implicit_value(true), "Quit after initialization"); // declare a group of options that will be allowed both on command line // as well as in a config file boost::program_options::options_description config_options("Configuration"); config_options.add_options()( "hsgrdata", boost::program_options::value<boost::filesystem::path>(&paths["hsgrdata"]), ".hsgr file")("nodesdata", boost::program_options::value<boost::filesystem::path>(&paths["nodesdata"]), ".nodes file")( "edgesdata", boost::program_options::value<boost::filesystem::path>(&paths["edgesdata"]), ".edges file")("geometry", boost::program_options::value<boost::filesystem::path>(&paths["geometries"]), ".geometry file")( "ramindex", boost::program_options::value<boost::filesystem::path>(&paths["ramindex"]), ".ramIndex file")( "fileindex", boost::program_options::value<boost::filesystem::path>(&paths["fileindex"]), "File index file")( "namesdata", boost::program_options::value<boost::filesystem::path>(&paths["namesdata"]), ".names file")("timestamp", boost::program_options::value<boost::filesystem::path>(&paths["timestamp"]), ".timestamp file")( "ip,i", boost::program_options::value<std::string>(&ip_address)->default_value("0.0.0.0"), "IP address")("port,p", boost::program_options::value<int>(&ip_port)->default_value(5000), "TCP/IP port")( "threads,t", boost::program_options::value<int>(&requested_num_threads)->default_value(8), "Number of threads to use")( "shared-memory,s", boost::program_options::value<bool>(&use_shared_memory)->implicit_value(true), "Load data from shared memory")( "max-table-size,m", boost::program_options::value<int>(&max_locations_distance_table)->default_value(1000000), "Max. locations supported in distance table query")( "max-matching-size,m", boost::program_options::value<int>(&max_locations_map_matching)->default_value(2), "Max. locations supported in map matching query"); // hidden options, will be allowed both on command line and in config // file, but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()( "base,b", boost::program_options::value<boost::filesystem::path>(&paths["base"]), "base path to .osrm file"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("base", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options( boost::filesystem::basename(argv[0]) + " <base.osrm> [<options>]"); visible_options.add(generic_options).add(config_options); // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), option_variables); if (option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return INIT_OK_DO_NOT_START_ENGINE; } if (option_variables.count("help")) { SimpleLogger().Write() << visible_options; return INIT_OK_DO_NOT_START_ENGINE; } boost::program_options::notify(option_variables); // parse config file auto path_iterator = paths.find("config"); if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) && !option_variables.count("base")) { SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string(); std::string ini_file_contents = read_file_lower_content(path_iterator->second); std::stringstream config_stream(ini_file_contents); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); boost::program_options::notify(option_variables); return INIT_OK_START_ENGINE; } if (1 > requested_num_threads) { throw osrm::exception("Number of threads must be a positive number"); } if (!use_shared_memory && option_variables.count("base")) { return INIT_OK_START_ENGINE; } if (use_shared_memory && !option_variables.count("base")) { return INIT_OK_START_ENGINE; } if (1 > max_locations_distance_table) { throw osrm::exception("Max location for distance table must be a positive number"); } if (2 > max_locations_map_matching) { throw osrm::exception("Max location for map matching must be at least two"); } SimpleLogger().Write() << visible_options; return INIT_OK_DO_NOT_START_ENGINE; }
return_code ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extractor_config) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( "config,c", boost::program_options::value<boost::filesystem::path>( &extractor_config.config_file_path)->default_value("extractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); config_options.add_options()("profile,p", boost::program_options::value<boost::filesystem::path>( &extractor_config.profile_path)->default_value("profile.lua"), "Path to LUA routing profile")( "threads,t", boost::program_options::value<unsigned int>(&extractor_config.requested_num_threads) ->default_value(tbb::task_scheduler_init::default_num_threads()), "Number of threads to use"); // hidden options, will be allowed both on command line and in config file, but will not be // shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()("input,i", boost::program_options::value<boost::filesystem::path>( &extractor_config.input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options( boost::filesystem::basename(argv[0]) + " <input.osm/.osm.bz2/.osm.pbf> [options]"); visible_options.add(generic_options).add(config_options); // parse command line options try { boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), option_variables); if (option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return return_code::exit; } if (option_variables.count("help")) { SimpleLogger().Write() << visible_options; return return_code::exit; } boost::program_options::notify(option_variables); // parse config file if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) { SimpleLogger().Write() << "Reading options from: " << extractor_config.config_file_path.string(); std::string ini_file_contents = read_file_lower_content(extractor_config.config_file_path); std::stringstream config_stream(ini_file_contents); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); boost::program_options::notify(option_variables); } if (!option_variables.count("input")) { SimpleLogger().Write() << visible_options; return return_code::exit; } } catch (std::exception &e) { SimpleLogger().Write(logWARNING) << e.what(); return return_code::fail; } return return_code::ok; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); std::string sink; std::string type; std::string file_path; double frames_per_second = 30; size_t index = 0; std::vector<std::string> config_fk; bool config_used = false; po::options_description visible_options("OPTIONAL ARGUMENTS"); std::unordered_map<std::string, char> type_hash; type_hash["wcam"] = 'a'; type_hash["gige"] = 'b'; type_hash["file"] = 'c'; type_hash["test"] = 'd'; try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description config("CONFIGURATION"); config.add_options() ("index,i", po::value<size_t>(&index), "Index of camera to capture images from.") ("file,f", po::value<std::string>(&file_path), "Path to video file if \'file\' is selected as the server TYPE.\n" "Path to image file if \'test\' is selected as the server TYPE.") ("fps,r", po::value<double>(&frames_per_second), "Frames per second. Overriden by information in configuration file if provided.") ("config,c", po::value<std::vector<std::string> >()->multitoken(), "Configuration file/key pair.") ; po::options_description hidden("HIDDEN OPTIONS"); hidden.add_options() ("type", po::value<std::string>(&type), "Camera TYPE.") ("sink", po::value<std::string>(&sink), "The name of the sink through which images collected by the camera will be served.\n") ; po::positional_options_description positional_options; positional_options.add("type", 1); positional_options.add("sink", 1); visible_options.add(options).add(config); po::options_description all_options("ALL OPTIONS"); all_options.add(options).add(config).add(hidden); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat Frame Server version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("type")) { printUsage(visible_options); std::cout << oat::Error("A TYPE must be specified. Exiting.\n"); return -1; } if (!variable_map.count("sink")) { printUsage(visible_options); std::cout << oat::Error("A SINK must be specified. Exiting.\n"); return -1; } if (!variable_map["config"].empty()) { config_fk = variable_map["config"].as<std::vector<std::string> >(); if (config_fk.size() == 2) { config_used = true; } else { printUsage(visible_options); std::cerr << oat::Error("Configuration must be supplied as file key pair.\n"); return -1; } } if ((type.compare("file") == 0 || type.compare("test") == 0 ) && !variable_map.count("file")) { printUsage(visible_options); std::cout << oat::Error("When TYPE=file or test, a file path must be specified. Exiting.\n"); return -1; } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return 1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.") << "\n"; } // Create the specified TYPE of detector std::shared_ptr<oat::FrameServer> server; switch (type_hash[type]) { case 'a': { server = std::make_shared<oat::WebCam>(sink); break; } case 'b': { #ifndef USE_FLYCAP std::cerr << oat::Error("Oat was not compiled with Point-Grey " "flycapture support, so TYPE=gige is not available.\n"); return -1; #else server = std::make_shared<oat::PGGigECam>(sink, index, frames_per_second); #endif break; } case 'c': { server = std::make_shared<oat::FileReader>(sink, file_path, frames_per_second); break; } case 'd': { server = std::make_shared<oat::TestFrame>(sink, file_path); break; } default: { printUsage(visible_options); std::cout << oat::Error("Invalid TYPE specified. Exiting.\n"); return -1; } } // The business try { // TODO: For most of the server types, these methods don't do much or // nothing. Should they really be part of the FrameServer interface? if (config_used) server->configure(config_fk[0], config_fk[1]); else server->configure(); // Tell user std::cout << oat::whoMessage(server->name(), "Steaming to sink " + oat::sinkText(sink) + ".\n") << oat::whoMessage(server->name(), "Press CTRL+C to exit.\n"); // Infinite loop until ctrl-c or end of stream signal run(server); // Tell user std::cout << oat::whoMessage(server->name(), "Exiting.\n"); // Exit return 0; } catch (const cpptoml::parse_exception &ex) { std::cerr << oat::whoError(server->name(), "Failed to parse configuration file " + config_fk[0] + "\n") << oat::whoError(server->name(), ex.what()) << "\n"; } catch (const std::runtime_error &ex) { std::cerr << oat::whoError(server->name(), ex.what()) << "\n"; } catch (const cv::Exception &ex) { std::cerr << oat::whoError(server->name(), ex.what()) << "\n"; } catch (const boost::interprocess::interprocess_exception &ex) { std::cerr << oat::whoError(server->name(), ex.what()) << "\n"; } catch (...) { std::cerr << oat::whoError(server->name(), "Unknown exception.\n"); } // Exit failure return -1; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); std::string source; std::string file_name; std::string save_path; po::options_description visible_options("OPTIONS"); try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description config("CONFIGURATION"); config.add_options() ("filename,n", po::value<std::string>(&file_name), "The base snapshot file name.\n" "The timestamp of the snapshot will be prepended to this name." "If not provided, the SOURCE name will be used.\n") ("folder,f", po::value<std::string>(&save_path), "The folder in which snapshots will be saved.") ; po::options_description hidden("HIDDEN OPTIONS"); hidden.add_options() ("source", po::value<std::string>(&source), "The name of the frame SOURCE that supplies frames to view.\n") ; po::positional_options_description positional_options; positional_options.add("source", -1); po::options_description all_options("ALL OPTIONS"); all_options.add(options).add(hidden); visible_options.add(options).add(config); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat Frame Viewer version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("source")) { printUsage(visible_options); std::cerr << oat::Error("A SOURCE must be specified. Exiting.\n"); return -1; } if (!variable_map.count("folder")) { save_path = "."; } if (!variable_map.count("filename")) { file_name = ""; } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return -1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.\n"); return -1; } // Make the viewer Viewer viewer(source, save_path, file_name); // Tell user std::cout << oat::whoMessage(viewer.get_name(), "Listening to source " + oat::sourceText(source) + ".\n") << oat::whoMessage(viewer.get_name(), "Press 's' on the viewer window to take a snapshot.\n") << oat::whoMessage(viewer.get_name(), "Press CTRL+C to exit.\n"); try { // Infinite loop until ctrl-c or end of stream signal run(&viewer); // Tell user std::cout << oat::whoMessage(viewer.get_name(), "Exiting.\n"); // Exit return 0; } catch (const std::runtime_error& ex) { std::cerr << oat::whoError(viewer.get_name(), ex.what()) << "\n"; } catch (const cv::Exception& ex) { std::cerr << oat::whoError(viewer.get_name(), ex.msg) << "\n"; } catch (...) { std::cerr << oat::whoError(viewer.get_name(), "Unknown exception.\n"); } // Exit failure return -1; }
return_code ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &contractor_config) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( "config,c", boost::program_options::value<boost::filesystem::path>(&contractor_config.config_file_path) ->default_value("contractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); config_options.add_options()( "restrictions,r", boost::program_options::value<boost::filesystem::path>(&contractor_config.restrictions_path), "Restrictions file in .osrm.restrictions format")( "profile,p", boost::program_options::value<boost::filesystem::path>(&contractor_config.profile_path) ->default_value("profile.lua"), "Path to LUA routing profile")( "threads,t", boost::program_options::value<unsigned int>(&contractor_config.requested_num_threads) ->default_value(tbb::task_scheduler_init::default_num_threads()), "Number of threads to use"); // hidden options, will be allowed both on command line and in config file, but will not be // shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()( "input,i", boost::program_options::value<boost::filesystem::path>(&contractor_config.osrm_input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options( "Usage: " + boost::filesystem::basename(argv[0]) + " <input.osrm> [options]"); visible_options.add(generic_options).add(config_options); // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv) .options(cmdline_options) .positional(positional_options) .run(), option_variables); const auto &temp_config_path = option_variables["config"].as<boost::filesystem::path>(); if (boost::filesystem::is_regular_file(temp_config_path)) { boost::program_options::store(boost::program_options::parse_config_file<char>( temp_config_path.string().c_str(), cmdline_options, true), option_variables); } if (option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return return_code::exit; } if (option_variables.count("help")) { SimpleLogger().Write() << "\n" << visible_options; return return_code::exit; } boost::program_options::notify(option_variables); if (!option_variables.count("restrictions")) { contractor_config.restrictions_path = contractor_config.osrm_input_path.string() + ".restrictions"; } if (!option_variables.count("input")) { SimpleLogger().Write() << "\n" << visible_options; return return_code::fail; } return return_code::ok; }
int main (int argc, char *argv[]) { try { LogPolicy::GetInstance().Unmute(); double startup_time = get_timestamp(); boost::filesystem::path config_file_path, input_path, profile_path; int requested_num_threads; // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options() ("version,v", "Show version") ("help,h", "Show this help message") ("config,c", boost::program_options::value<boost::filesystem::path>(&config_file_path)->default_value("extractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); config_options.add_options() ("profile,p", boost::program_options::value<boost::filesystem::path>(&profile_path)->default_value("profile.lua"), "Path to LUA routing profile") ("threads,t", boost::program_options::value<int>(&requested_num_threads)->default_value(8), "Number of threads to use"); // hidden options, will be allowed both on command line and in config file, but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options() ("input,i", boost::program_options::value<boost::filesystem::path>(&input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options(boost::filesystem::basename(argv[0]) + " <input.osm/.osm.bz2/.osm.pbf> [options]"); visible_options.add(generic_options).add(config_options); // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv). options(cmdline_options).positional(positional_options).run(), option_variables); if(option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return 0; } if(option_variables.count("help")) { SimpleLogger().Write() << visible_options; return 0; } boost::program_options::notify(option_variables); // parse config file if(boost::filesystem::is_regular_file(config_file_path)) { SimpleLogger().Write() << "Reading options from: " << config_file_path.c_str(); std::string config_str; PrepareConfigFile( config_file_path.c_str(), config_str ); std::stringstream config_stream( config_str ); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); boost::program_options::notify(option_variables); } if(!option_variables.count("input")) { SimpleLogger().Write(logWARNING) << "No input file specified"; SimpleLogger().Write() << visible_options; return -1; } if(1 > requested_num_threads) { SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return -1; } SimpleLogger().Write() << "Input file: " << input_path.filename().string(); SimpleLogger().Write() << "Profile: " << profile_path.filename().string(); SimpleLogger().Write() << "Threads: " << requested_num_threads; /*** Setup Scripting Environment ***/ ScriptingEnvironment scriptingEnvironment(profile_path.c_str()); omp_set_num_threads( std::min( omp_get_num_procs(), requested_num_threads) ); bool file_has_pbf_format(false); std::string output_file_name(input_path.c_str()); std::string restrictionsFileName(input_path.c_str()); std::string::size_type pos = output_file_name.find(".osm.bz2"); if(pos==std::string::npos) { pos = output_file_name.find(".osm.pbf"); if(pos!=std::string::npos) { file_has_pbf_format = true; } } if(pos==std::string::npos) { pos = output_file_name.find(".pbf"); if(pos!=std::string::npos) { file_has_pbf_format = true; } } if(pos!=std::string::npos) { output_file_name.replace(pos, 8, ".osrm"); restrictionsFileName.replace(pos, 8, ".osrm.restrictions"); } else { pos=output_file_name.find(".osm"); if(pos!=std::string::npos) { output_file_name.replace(pos, 5, ".osrm"); restrictionsFileName.replace(pos, 5, ".osrm.restrictions"); } else { output_file_name.append(".osrm"); restrictionsFileName.append(".osrm.restrictions"); } } StringMap stringMap; ExtractionContainers externalMemory; stringMap[""] = 0; extractCallBacks = new ExtractorCallbacks(&externalMemory, &stringMap); BaseParser* parser; if(file_has_pbf_format) { parser = new PBFParser(input_path.c_str(), extractCallBacks, scriptingEnvironment); } else { parser = new XMLParser(input_path.c_str(), extractCallBacks, scriptingEnvironment); } if(!parser->ReadHeader()) { throw OSRMException("Parser not initialized!"); } SimpleLogger().Write() << "Parsing in progress.."; double parsing_start_time = get_timestamp(); parser->Parse(); SimpleLogger().Write() << "Parsing finished after " << (get_timestamp() - parsing_start_time) << " seconds"; if( externalMemory.all_edges_list.empty() ) { SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return -1; } externalMemory.PrepareData(output_file_name, restrictionsFileName); delete parser; delete extractCallBacks; SimpleLogger().Write() << "extraction finished after " << get_timestamp() - startup_time << "s"; SimpleLogger().Write() << "To prepare the data for routing, run: " << "./osrm-prepare " << output_file_name << std::endl; } catch(boost::program_options::too_many_positional_options_error& e) { SimpleLogger().Write(logWARNING) << "Only one input file can be specified"; return -1; } catch(boost::program_options::error& e) { SimpleLogger().Write(logWARNING) << e.what(); return -1; } catch(std::exception & e) { SimpleLogger().Write(logWARNING) << "Unhandled exception: " << e.what(); return -1; } return 0; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); std::vector<std::string> sources; std::string sink; std::string type; std::vector<std::string> config_fk; bool config_used = false; po::options_description visible_options("OPTIONS"); std::unordered_map<std::string, char> type_hash; type_hash["mean"] = 'a'; try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description config("CONFIGURATION"); config.add_options() ("config,c", po::value<std::vector<std::string> >()->multitoken(), "Configuration file/key pair.") ; po::options_description hidden("HIDDEN OPTIONS"); hidden.add_options() ("type", po::value<std::string>(&type), "Type of test position combiner to use.") ("sources", po::value< std::vector<std::string> >(), "The names the SOURCES supplying the Position2D objects to be combined.") ("sink", po::value<std::string>(&sink), "The name of the SINK to which combined position Position2D objects will be published.") ; po::positional_options_description positional_options; positional_options.add("type", 1); positional_options.add("sources", -1); // If not overridden by explicit --sink, last positional argument is sink. po::options_description all_options("OPTIONS"); all_options.add(options).add(config).add(hidden); visible_options.add(options).add(config); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat Position Combiner version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("type")) { printUsage(visible_options); std::cerr << oat::Error("A TYPE must be specified.\n"); return -1; } if (!variable_map.count("sources")) { printUsage(visible_options); std::cerr << oat::Error("At least two SOURCES and a SINK must be specified.\n"); return -1; } sources = variable_map["sources"].as< std::vector<std::string> >(); if (sources.size() < 3) { printUsage(visible_options); std::cerr << oat::Error("At least two SOURCES and a SINK must be specified.\n"); return -1; } if (!variable_map.count("sink")) { // If not overridden by explicit --sink, last positional argument is the sink. sink = sources.back(); sources.pop_back(); } if (!variable_map["config"].empty()) { config_fk = variable_map["config"].as<std::vector<std::string> >(); if (config_fk.size() == 2) { config_used = true; } else { printUsage(visible_options); std::cerr << oat::Error("Configuration must be supplied as file key pair.\n"); return -1; } } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return -1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.\n"); return -1; } // Create component std::shared_ptr<oat::PositionCombiner> combiner; // Refine component type switch (type_hash[type]) { case 'a': { combiner = std::make_shared<oat::MeanPosition>(sources, sink); break; } default: { printUsage(visible_options); std::cerr << oat::Error("Invalid TYPE specified.\n"); return -1; } } // The business try { if (config_used) combiner->configure(config_fk[0], config_fk[1]); // Tell user std::cout << oat::whoMessage(combiner->name(), "Listening to sources "); for (auto s : sources) std::cout << oat::sourceText(s) << " "; std::cout << ".\n" << oat::whoMessage(combiner->name(), "Steaming to sink " + oat::sinkText(sink) + ".\n") << oat::whoMessage(combiner->name(), "Press CTRL+C to exit.\n"); // Infinite loop until ctrl-c or server end-of-stream signal run(combiner); // Tell user std::cout << oat::whoMessage(combiner->name(), "Exiting.\n"); // Exit return 0; } catch (const cpptoml::parse_exception &ex) { std::cerr << oat::whoError(combiner->name(), "Failed to parse configuration file " + config_fk[0] + "\n") << oat::whoError(combiner->name(), ex.what()) << "\n"; } catch (const std::runtime_error &ex) { std::cerr << oat::whoError(combiner->name(), ex.what()) << "\n"; } catch (const cv::Exception &ex) { std::cerr << oat::whoError(combiner->name(), ex.what()) << "\n"; } catch (const boost::interprocess::interprocess_exception &ex) { std::cerr << oat::whoError(combiner->name(), ex.what()) << "\n"; } catch (...) { std::cerr << oat::whoError(combiner->name(), "Unknown exception.\n"); } // Exit failure return -1; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); // The image source to which the viewer will be attached std::vector<std::string> position_sources; std::string frame_source; std::string frame_sink; bool print_region = false; bool print_timestamp = false; bool print_sample_number = false; bool encode_sample_number = false; try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description configuration("CONFIGURATION"); configuration.add_options() ("position-sources,p", po::value< std::vector<std::string> >()->multitoken(), "The name of position SOURCE(s) used to draw object position markers.\n") ("timestamp,t", "Write the current date and time on each frame.\n") ("sample,s", "Write the frame sample number on each frame.\n") ("sample-code,S", "Write the binary encoded sample on the corner of each frame.\n") ("region,R", "Write region information on each frame " "if there is a position stream that contains it.\n") ; po::options_description hidden("POSITIONAL OPTIONS"); hidden.add_options() ("framesource", po::value<std::string>(&frame_source), "The name of the server that supplies images to decorate." "The server must be of type SMServer<SharedCVMatHeader>\n") ("framesink", po::value<std::string>(&frame_sink), "The name of the sink to which decorated images will be published." "The server must be of type SMServer<SharedCVMatHeader>\n") ; po::positional_options_description positional_options; // If not overridden by explicit --imagesource or --sink, // last positional arguments are imagesource and sink in that order positional_options.add("framesource", 1); positional_options.add("framesink", 1); po::options_description visible_options("OPTIONS"); visible_options.add(options).add(configuration); po::options_description all_options("ALL OPTIONS"); all_options.add(visible_options).add(hidden); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat Decorator, version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("framesource")) { printUsage(visible_options); std::cout << oat::Error("At least a single FRAME_SOURCE must be specified. \n"); return -1; } if (!variable_map.count("framesink")) { printUsage(visible_options); std::cout << oat::Error("At least a single FRAME_SINK must be specified.\n"); return -1; } if (variable_map.count("position-sources")) { position_sources = variable_map["position-sources"].as< std::vector<std::string> >(); } if (variable_map.count("timestamp")) { print_timestamp = true; } if (variable_map.count("sample")) { print_sample_number = true; } if (variable_map.count("sample-code")) { encode_sample_number = true; } if (variable_map.count("region")) { print_region = true; } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return -1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.\n"); return -1; } // Make the decorator auto decorator = std::make_shared<oat::Decorator>(position_sources, frame_source, frame_sink); decorator->set_print_timestamp(print_timestamp); decorator->set_print_sample_number(print_sample_number); decorator->set_encode_sample_number(encode_sample_number); decorator->set_print_region(print_region); // Tell user std::cout << oat::whoMessage(decorator->name(), "Listening to source " + oat::sourceText(frame_source) + ".\n") << oat::whoMessage(decorator->name(), "Steaming to sink " + oat::sinkText(frame_sink) + ".\n") << oat::whoMessage(decorator->name(), "Press CTRL+C to exit.\n"); try { // Infinite loop until ctrl-c or end of stream signal run(decorator); // Tell user std::cout << oat::whoMessage(decorator->name(), "Exiting.\n"); // Exit return 0; } catch (const std::runtime_error &ex) { std::cerr << oat::whoError(decorator->name(), ex.what()) << "\n"; } catch (const cv::Exception &ex) { std::cerr << oat::whoError(decorator->name(), ex.what()) << "\n"; } catch (const boost::interprocess::interprocess_exception &ex) { std::cerr << oat::whoError(decorator->name(), ex.what()) << "\n"; } catch (...) { std::cerr << oat::whoError(decorator->name(), "Unknown exception.\n"); } // Exit failure return -1; }
void generic_options::usage() const { std::cout << str(boost::format(_usage) % _progname) << std::endl << visible_options(); }
int main(int argc, char const * argv[]) { try { _note_c("dbg/main", "Begin of main()"); // TODO parse the debug options like set log level right here at start tools::sanitize_locale(); epee::string_tools::set_module_name_and_folder(argv[0]); // Build argument description po::options_description all_options("All"); po::options_description hidden_options("Hidden"); po::options_description visible_options("Options"); po::options_description core_settings("Settings"); po::positional_options_description positional_options; { bf::path default_data_dir = daemonizer::get_default_data_dir(); bf::path default_testnet_data_dir = {default_data_dir / "testnet"}; // Misc Options command_line::add_arg(visible_options, command_line::arg_help); command_line::add_arg(visible_options, command_line::arg_version); command_line::add_arg(visible_options, daemon_args::arg_os_version); bf::path default_conf = default_data_dir / std::string(CRYPTONOTE_NAME ".conf"); command_line::add_arg(visible_options, daemon_args::arg_config_file, default_conf.string()); command_line::add_arg(visible_options, command_line::arg_test_dbg_lock_sleep); cryptonote::core::init_options(core_settings); // Settings bf::path default_log = default_data_dir / std::string(CRYPTONOTE_NAME ".log"); command_line::add_arg(core_settings, daemon_args::arg_log_file, default_log.string()); command_line::add_arg(core_settings, daemon_args::arg_log_level); daemonizer::init_options(hidden_options, visible_options); daemonize::t_executor::init_options(core_settings); // Hidden options command_line::add_arg(hidden_options, daemon_args::arg_command); visible_options.add(core_settings); all_options.add(visible_options); all_options.add(hidden_options); // Positional positional_options.add(daemon_args::arg_command.name, -1); // -1 for unlimited arguments } // Do command line parsing po::variables_map vm; bool ok = command_line::handle_error_helper(visible_options, [&]() { boost::program_options::store( boost::program_options::command_line_parser(argc, argv) .options(all_options).positional(positional_options).run() , vm ); return true; }); if (!ok) return 1; if (command_line::get_arg(vm, command_line::arg_help)) { std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL; std::cout << "Usage: " + std::string{argv[0]} + " [options|settings] [daemon_command...]" << std::endl << std::endl; std::cout << visible_options << std::endl; return 0; } // Monero Version if (command_line::get_arg(vm, command_line::arg_version)) { std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL; return 0; } // OS if (command_line::get_arg(vm, daemon_args::arg_os_version)) { std::cout << "OS: " << tools::get_os_version_string() << ENDL; return 0; } epee::g_test_dbg_lock_sleep = command_line::get_arg(vm, command_line::arg_test_dbg_lock_sleep); std::string db_type = command_line::get_arg(vm, command_line::arg_db_type); // verify that blockchaindb type is valid if(cryptonote::blockchain_db_types.count(db_type) == 0) { std::cout << "Invalid database type (" << db_type << "), available types are:" << std::endl; for (const auto& type : cryptonote::blockchain_db_types) { std::cout << "\t" << type << std::endl; } return 0; } bool testnet_mode = command_line::get_arg(vm, command_line::arg_testnet_on); auto data_dir_arg = testnet_mode ? command_line::arg_testnet_data_dir : command_line::arg_data_dir; // data_dir // default: e.g. ~/.bitmonero/ or ~/.bitmonero/testnet // if data-dir argument given: // absolute path // relative path: relative to cwd // Create data dir if it doesn't exist boost::filesystem::path data_dir = boost::filesystem::absolute( command_line::get_arg(vm, data_dir_arg)); tools::create_directories_if_necessary(data_dir.string()); // FIXME: not sure on windows implementation default, needs further review //bf::path relative_path_base = daemonizer::get_relative_path_base(vm); bf::path relative_path_base = data_dir; std::string config = command_line::get_arg(vm, daemon_args::arg_config_file); boost::filesystem::path data_dir_path(data_dir); boost::filesystem::path config_path(config); if (!config_path.has_parent_path()) { config_path = data_dir / config_path; } boost::system::error_code ec; if (bf::exists(config_path, ec)) { po::store(po::parse_config_file<char>(config_path.string<std::string>().c_str(), core_settings), vm); } po::notify(vm); // If there are positional options, we're running a daemon command { auto command = command_line::get_arg(vm, daemon_args::arg_command); if (command.size()) { auto rpc_ip_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_rpc_bind_ip); auto rpc_port_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_rpc_bind_port); if (testnet_mode) { rpc_port_str = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_testnet_rpc_bind_port); } uint32_t rpc_ip; uint16_t rpc_port; if (!epee::string_tools::get_ip_int32_from_string(rpc_ip, rpc_ip_str)) { std::cerr << "Invalid IP: " << rpc_ip_str << std::endl; return 1; } if (!epee::string_tools::get_xtype_from_string(rpc_port, rpc_port_str)) { std::cerr << "Invalid port: " << rpc_port_str << std::endl; return 1; } daemonize::t_command_server rpc_commands{rpc_ip, rpc_port}; if (rpc_commands.process_command_vec(command)) { return 0; } else { std::cerr << "Unknown command" << std::endl; return 1; } } } // Start with log level 0 epee::log_space::get_set_log_detalisation_level(true, LOG_LEVEL_0); // Set log level { int new_log_level = command_line::get_arg(vm, daemon_args::arg_log_level); if(new_log_level < LOG_LEVEL_MIN || new_log_level > LOG_LEVEL_MAX) { LOG_PRINT_L0("Wrong log level value: " << new_log_level); } else if (epee::log_space::get_set_log_detalisation_level(false) != new_log_level) { epee::log_space::get_set_log_detalisation_level(true, new_log_level); int otshell_utils_log_level = 100 - (new_log_level * 20); gCurrentLogger.setDebugLevel(otshell_utils_log_level); LOG_PRINT_L0("LOG_LEVEL set to " << new_log_level); } } // log_file_path // default: <data_dir>/<CRYPTONOTE_NAME>.log // if log-file argument given: // absolute path // relative path: relative to data_dir // Set log file { bf::path log_file_path {data_dir / std::string(CRYPTONOTE_NAME ".log")}; if (! vm["log-file"].defaulted()) log_file_path = command_line::get_arg(vm, daemon_args::arg_log_file); log_file_path = bf::absolute(log_file_path, relative_path_base); epee::log_space::log_singletone::add_logger( LOGGER_FILE , log_file_path.filename().string().c_str() , log_file_path.parent_path().string().c_str() ); } _note_c("dbg/main", "Moving from main() into the daemonize now."); return daemonizer::daemonize(argc, argv, daemonize::t_executor{}, vm); } catch (std::exception const & ex) { LOG_ERROR("Exception in main! " << ex.what()); } catch (...) { LOG_ERROR("Exception in main!"); } return 1; }
int main(int argc, char *argv[]) { std::signal(SIGINT, sigHandler); // Switches and options std::string type; std::string source; std::string save_path; std::string homography_method {"robust"}; std::string camera_model {"pinhole"}; int chessboard_width {6}; int chessboard_height {9}; double square_length {1.0}; std::string config_file; std::string config_key; bool config_used {false}; // Visible program options po::options_description visible_options("OPTIONS"); // Component sub-type std::unordered_map<std::string, char> type_hash; type_hash["camera"] = 'a'; type_hash["homography"] = 'b'; // Homography estimation method std::unordered_map<std::string, HomographyGenerator::EstimationMethod> homo_meth_hash; homo_meth_hash["robust"] = HomographyGenerator::EstimationMethod::ROBUST; homo_meth_hash["regular"] = HomographyGenerator::EstimationMethod::REGULAR; homo_meth_hash["exact"] = HomographyGenerator::EstimationMethod::EXACT; // Camera calibration method std::unordered_map<std::string,CameraCalibrator::CameraModel> camera_model_hash; camera_model_hash["pinhole"] = CameraCalibrator::CameraModel::PINHOLE; camera_model_hash["fisheye"] = CameraCalibrator::CameraModel::FISHEYE; try { po::options_description options("INFO"); options.add_options() ("help", "Produce help message.") ("version,v", "Print version information.") ; po::options_description config("CONFIGURATION"); config.add_options() ("calibration-path,f", po::value<std::string>(&save_path), "The base configuration file location.\n" "The timestamp of the calibration will be prepended to th name." "If not provided, the calibration info will be printed to STDOUT.") ("homography-method", po::value<std::string>(&homography_method), "Homography estimation method.\n\n" "Values:\n" " robust (default): RANSAC-based robust estimation method (automatic outlier rejection).\n" " regular: Best-fit using all data points.\n" " exact: Compute the homography that fits four points. Useful when frames contain know fiducial marks.\n") ("camera-model", po::value<std::string>(&camera_model), "Model used for camera calibration.\n\n" "Values:\n" " pinhole (default): Pinhole camera model.\n" " fisheye: Fisheye camera model (ultra wide-angle lens with pronounced radial distortion.\n") ("chessboard-height,h", po::value<int>(&chessboard_height), "The number of vertical black squares in the chessboard used for calibration.\n") ("chessboard-width,w", po::value<int>(&chessboard_width), "The number of horizontal black squares in the chessboard used for calibration.\n") ("square-width,W", po::value<double>(&square_length), "The length/width of a single chessboard square in meters.\n") ("config-file,c", po::value<std::string>(&config_file), "Configuration file.") ("config-key,k", po::value<std::string>(&config_key), "Configuration key.") ; po::options_description hidden("HIDDEN OPTIONS"); hidden.add_options() ("type", po::value<std::string>(&type), "Type of frame calibrator to use.\n\n" "Values:\n" " camera: Generate calibration parameters (camera matrix and distortion coefficients).\n" " homography: Generate homography transform between pixels and world units.") ("source", po::value<std::string>(&source), "The name of the SOURCE that supplies images on which to perform background subtraction." "The server must be of type SMServer<SharedCVMatHeader>\n") ; po::positional_options_description positional_options; positional_options.add("type", 1); positional_options.add("source", 1); visible_options.add(options).add(config); po::options_description all_options("All options"); all_options.add(options).add(config).add(hidden); po::variables_map variable_map; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), variable_map); po::notify(variable_map); // Use the parsed options if (variable_map.count("help")) { printUsage(visible_options); return 0; } if (variable_map.count("version")) { std::cout << "Oat calibrator version " << Oat_VERSION_MAJOR << "." << Oat_VERSION_MINOR << "\n"; std::cout << "Written by Jonathan P. Newman in the MWL@MIT.\n"; std::cout << "Licensed under the GPL3.0.\n"; return 0; } if (!variable_map.count("type")) { printUsage(visible_options); std::cerr << oat::Error("A TYPE must be specified.\n"); return -1; } if (!variable_map.count("source")) { printUsage(visible_options); std::cerr << oat::Error("A SOURCE must be specified.\n"); return -1; } if (!variable_map.count("calibration-path")) { save_path = bfs::current_path().string(); } // Check to see that homography-method is valid if (homo_meth_hash.find(homography_method) == homo_meth_hash.end()) { printUsage(visible_options); std::cerr << oat::Error("Unrecognized homography-method.\n"); return -1; } // Check that chessboard height and width are valid if (type_hash[type] == 'a' && (chessboard_height < 2 || chessboard_width < 2)) { printUsage(visible_options); std::cerr << oat::Error("Camera calibration requires chessboard to be at least 2x2.\n"); return -1; } if ((variable_map.count("config-file") && !variable_map.count("config-key")) || (!variable_map.count("config-file") && variable_map.count("config-key"))) { printUsage(visible_options); std::cerr << oat::Error("A configuration file must be supplied with a corresponding config-key.\n"); return -1; } else if (variable_map.count("config-file")) { config_used = true; } } catch (std::exception& e) { std::cerr << oat::Error(e.what()) << "\n"; return -1; } catch (...) { std::cerr << oat::Error("Exception of unknown type.\n"); return -1; } // Create component std::shared_ptr<Calibrator> calibrator; // Refine component type switch (type_hash[type]) { case 'a': { auto chessboard_size = cv::Size(chessboard_height, chessboard_width); auto model =camera_model_hash.at(camera_model); calibrator = std::make_shared<CameraCalibrator>(source, model, chessboard_size, square_length); break; } case 'b': { auto meth = homo_meth_hash.at(homography_method); calibrator = std::make_shared<HomographyGenerator>(source, meth); break; } default: { printUsage(visible_options); std::cerr << oat::Error("Invalid TYPE specified.\n"); return -1; } } try{ if (config_used) calibrator->configure(config_file, config_key); // Generate the save path and check validity calibrator->generateSavePath(save_path); // Tell user std::cout << oat::whoMessage(calibrator->name(), "Listening to source " + oat::sourceText(source) + ".\n") << oat::whoMessage(calibrator->name(), "Press CTRL+C to exit.\n"); // Infinite loop until ctrl-c or end of stream signal run(calibrator); // Tell user std::cout << oat::whoMessage(calibrator->name(), "Exiting.\n"); // Exit success return 0; } catch (const cpptoml::parse_exception& ex) { std::cerr << oat::whoError(calibrator->name(), "Failed to parse configuration file " + config_file + "\n") << oat::whoError(calibrator->name(), ex.what()) << "\n"; } catch (const std::runtime_error& ex) { std::cerr << oat::whoError(calibrator->name(),ex.what()) << "\n"; } catch (const cv::Exception& ex) { std::cerr << oat::whoError(calibrator->name(), ex.what()) << "\n"; } catch (...) { std::cerr << oat::whoError(calibrator->name(), "Unknown exception.\n"); } // Exit failure return -1; }