diff options
Diffstat (limited to 'src/lib/netlist/prg')
-rw-r--r-- | src/lib/netlist/prg/nltool.cpp | 1357 | ||||
-rw-r--r-- | src/lib/netlist/prg/nlwav.cpp | 664 |
2 files changed, 1429 insertions, 592 deletions
diff --git a/src/lib/netlist/prg/nltool.cpp b/src/lib/netlist/prg/nltool.cpp index 1c5256654b1..85654e174ce 100644 --- a/src/lib/netlist/prg/nltool.cpp +++ b/src/lib/netlist/prg/nltool.cpp @@ -1,240 +1,322 @@ -// license:GPL-2.0+ +// license:BSD-3-Clause // copyright-holders:Couriersud -/*************************************************************************** - nltool.c - - Simple tool to debug netlists outside MAME. - -****************************************************************************/ - -#include "netlist/plib/pmain.h" -#include "netlist/devices/net_lib.h" -#include "netlist/nl_parser.h" -#include "netlist/nl_errstr.h" -#include "netlist/nl_setup.h" -#include "netlist/solver/nld_solver.h" -#include "netlist/tools/nl_convert.h" +// *************************************************************************** +// +// nltool.cpp +// +// Simple tool to debug netlists outside MAME. +// +// *************************************************************************** + +#include "plib/pdynlib.h" +#include "core/setup.h" +#include "devices/net_lib.h" +#include "nl_errstr.h" +#include "nl_parser.h" +#include "nl_setup.h" +#include "plib/pmain.h" +#include "plib/pstrutil.h" +#include "solver/nld_solver.h" +#include "tools/nl_convert.h" + +#include "plib/ptests.h" #include <cstdio> // scanf #include <iomanip> // scanf -#include <iostream> // scanf #include <ios> +#include <iostream> // scanf + +#ifndef NL_DISABLE_DYNAMIC_LOAD +#define NL_DISABLE_DYNAMIC_LOAD 0 +#endif + +// FIXME: "NamingConvention", "FunctionTable:", "Pinalias" need to be renamed here +// and in all source locations. +// spell-checker: words Pinalias, devsyn, csynopsis, subpage + +// +// Names +// spell-checker: words Woodbury, Raphson, +// +// FIXME: These are either defined in other parts or have more complex consequences +// spell-checker: words nlconst, rpad, pfmt, pexception, pbinary, dynlib, pstring, psplit,putf +// +// FIXME: nlconst -> nl_const +// +// Specific technical terms +// spell-checker: words rinf -#define NLTOOL_VERSION 20190420 +extern const plib::static_library::symbol nl_static_solver_syms[]; + +// Forward declarations + +class netlist_tool_t; class tool_app_t : public plib::app { public: tool_app_t() : plib::app(), + m_warnings(0), + m_errors(0), + opt_grp1(*this, "General options", "The following options apply to all commands."), - opt_cmd (*this, "c", "cmd", 0, std::vector<pstring>({"run","validate","convert","listdevices","static","header","docheader"}), "run|validate|convert|listdevices|static|header|docheader"), - opt_file(*this, "f", "file", "-", "file to process (default is stdin)"), + opt_cmd (*this, "c", "cmd", 0, std::vector<pstring>({"run","validate","convert","list-devices","list-models","static","header","doc-header","tests"}), "run|validate|convert|list-devices|list-models|static|header|doc-header|tests"), + opt_includes(*this, "I", "include", "Add the directory to the list of directories to be searched for header files. This option may be specified repeatedly."), opt_defines(*this, "D", "define", "predefine value as macro, e.g. -Dname=value. If '=value' is omitted predefine it as 1. This option may be specified repeatedly."), - opt_rfolders(*this, "r", "rom", "where to look for data files"), + opt_data_folders(*this, "d", "data", "where to look for data files"), opt_verb(*this, "v", "verbose", "be verbose - this produces lots of output"), opt_quiet(*this, "q", "quiet", "be quiet - no warnings"), + opt_pre_pro(*this, "", "prepro", "output preprocessor output to stderr"), + opt_progress(*this, "", "progress", "show progress bar on longer operations"), + + opt_files(*this, "files to process"), + opt_version(*this, "", "version", "display version and exit"), opt_help(*this, "h", "help", "display help and exit"), opt_grp2(*this, "Options for run and static commands", "These options apply to run and static commands."), opt_name(*this, "n", "name", "", "the netlist in file specified by ""-f"" option to run; default is first one"), - opt_grp3(*this, "Options for run command", "These options are only used by the run command."), - opt_ttr (*this, "t", "time_to_run", 1.0, "time to run the emulation (seconds)\n\n abc def\n\n xyz"), + opt_grp3(*this, "Options for static command", "These options apply to static command."), + opt_dir(*this, "d", "dir", "", "output directory for the generated files."), + opt_out(*this, "o", "output", "", "single output file for the generated code.\nEither --dir or --output can be specificied"), +// opt_static_include(*this, "", "static-include", "write static solvers to individual files\nincluded by file specified with --output.\n--dir must be path to \"generated/static\" path in netlist folder."), + opt_static_include(*this, "", "static-include", "write static solvers to individual files included by file specified with --output. --dir must be path to \"generated/static\" path in netlist folder."), + + opt_grp4(*this, "Options for run command", "These options are only used by the run command."), + opt_ttr (*this, "t", "time_to_run", 1, "time to run the emulation (seconds)"), + opt_boost_lib(*this, "", "boost-lib", "builtin", "generic: will use generic solvers.\nbuiltin: Use optimized solvers compiled in.\nsome_lib.so: Use library with precompiled solvers."), opt_stats(*this, "s", "statistics", "gather runtime statistics"), opt_logs(*this, "l", "log" , "define terminal to log. This option may be specified repeatedly."), opt_inp(*this, "i", "input", "", "input file to process (default is none)"), - opt_loadstate(*this,"", "loadstate", "", "load state from file and continue from there"), - opt_savestate(*this,"", "savestate", "", "save state to file at end of run"), + opt_load_state(*this,"", "load-state", "", "load state from file and continue from there"), + opt_save_state(*this,"", "save-state", "", "save state to file at end of run"), + opt_fp_error(*this, "", "fp-error", "raise exception on floating point errors. This is intended to be used during debugging."), - opt_grp4(*this, "Options for convert command", "These options are only used by the convert command."), - opt_type(*this, "y", "type", 0, std::vector<pstring>({"spice","eagle","rinf"}), "type of file to be converted: spice,eagle,rinf"), + opt_grp5(*this, "Options for convert command", "These options are only used by the convert command."), + opt_type(*this, "y", "type", 0, std::vector<pstring>({"spice","eagle","rinf"}), "type of file to be converted: spice,eagle,rinf"), - opt_grp5(*this, "Options for header command", "These options are only used by the header command."), - opt_tabwidth(*this, "", "tab-width", 4, "Tab width for output."), - opt_linewidth(*this,"", "line-width", 72, "Line width for output."), + opt_grp6(*this, "Options for validate command", "These options are only used by the validate command."), - opt_ex1(*this, "nltool -c run -t 3.5 -f nl_examples/cdelay.c -n cap_delay", + opt_grp7(*this, "Options for header command", "These options are only used by the header command."), + opt_tab_width(*this, "", "tab-width", 4, "Tab width for output."), + opt_line_width(*this,"", "line-width", 72, "Line width for output."), + opt_pattern(*this, "", "pattern", "Pattern to match against device names. If the device name contains pattern, the device will be included in the output. Multiple patterns can be specified, if none is given, all devices will be output."), + + opt_ex1(*this, "nltool -c run -t 3.5 -n cap_delay nl_examples/cdelay.c", "Run netlist \"cap_delay\" from file nl_examples/cdelay.c for 3.5 seconds"), - opt_ex2(*this, "nltool --cmd=listdevices", + opt_ex2(*this, "nltool --cmd=list-devices", "List all known devices."), opt_ex3(*this, "nltool --cmd=header --tab-width=8 --line-width=80", "Create the header file needed for including netlists as code."), - - m_warnings(0), - m_errors(0) + opt_ex4(*this, "nltool --cmd static --output src/lib/netlist/generated/static_solvers.cpp src/mame/audio/nl_*.cpp src/mame/machine/nl_*.cpp", + "Create static solvers for the MAME project using one single source file."), + opt_ex5(*this, "nltool --cmd static --output src/lib/netlist/generated/static_solvers.cpp --dir src/lib/netlist/generated/static --static_include src/mame/audio/nl_*.cpp src/mame/machine/nl_*.cpp", + "Create static solvers for the MAME project using a single source file which includes generated solvers written to --dir folder."), + opt_ex6(*this, "nltool --cmd tests", + "Run unit tests. In case the unit tests are not linked in, this will do nothing.") {} + int execute() override; + pstring usage() override; + + template<typename... ARGS> + void output_with_prefix(const pstring &prefix, const pstring &fmt, ARGS&&... args) + { + pstring res = plib::pfmt(fmt)(std::forward<ARGS>(args)...); + auto lines(plib::psplit(res, '\n', false)); + if (lines.empty()) + std_out(prefix + "\n"); + else + for (auto &l : lines) + std_out(prefix + l + "\n"); + } + + int m_warnings; + int m_errors; +private: plib::option_group opt_grp1; plib::option_str_limit<unsigned> opt_cmd; - plib::option_str opt_file; + plib::option_vec opt_includes; plib::option_vec opt_defines; - plib::option_vec opt_rfolders; + plib::option_vec opt_data_folders; plib::option_bool opt_verb; plib::option_bool opt_quiet; + plib::option_bool opt_pre_pro; + plib::option_bool opt_progress; + plib::option_args opt_files; plib::option_bool opt_version; plib::option_bool opt_help; + plib::option_group opt_grp2; plib::option_str opt_name; + plib::option_group opt_grp3; - plib::option_num<double> opt_ttr; + plib::option_str opt_dir; + plib::option_str opt_out; + plib::option_bool opt_static_include; + + plib::option_group opt_grp4; + plib::option_num<netlist::nl_fptype> opt_ttr; + plib::option_str opt_boost_lib; plib::option_bool opt_stats; plib::option_vec opt_logs; plib::option_str opt_inp; - plib::option_str opt_loadstate; - plib::option_str opt_savestate; - plib::option_group opt_grp4; - plib::option_str_limit<unsigned> opt_type; + plib::option_str opt_load_state; + plib::option_str opt_save_state; + plib::option_bool opt_fp_error; + plib::option_group opt_grp5; - plib::option_num<unsigned> opt_tabwidth; - plib::option_num<unsigned> opt_linewidth; + plib::option_str_limit<unsigned> opt_type; + + plib::option_group opt_grp6; + plib::option_group opt_grp7; + plib::option_num<unsigned> opt_tab_width; + plib::option_num<unsigned> opt_line_width; + plib::option_vec opt_pattern; plib::option_example opt_ex1; plib::option_example opt_ex2; plib::option_example opt_ex3; + plib::option_example opt_ex4; + plib::option_example opt_ex5; + plib::option_example opt_ex6; - int execute() override; - pstring usage() override; + struct compile_map_entry + { + compile_map_entry(const pstring &mod, const pstring &code) + : m_code(code) + { + m_modules.push_back(mod); + } + pstring m_code; + std::vector<pstring> m_modules; + }; + + using compile_map = std::map<pstring, compile_map_entry>; + + void logger(plib::plog_level l, const pstring &ls); + + void run_with_progress(netlist_tool_t &nt, netlist::netlist_time_ext start, netlist::netlist_time_ext duration); - int m_warnings; - int m_errors; -private: void run(); void validate(); void convert(); + + void compile_one_and_add_to_map(const pstring &file, + const pstring &name, netlist::solver::static_compile_target target, + compile_map &map); void static_compile(); - void mac_out(const pstring &s, const bool cont = true); + void mac_out(const pstring &s, bool cont = true); void header_entry(const netlist::factory::element_t *e); void mac(const netlist::factory::element_t *e); void create_header(); - void create_docheader(); + void create_doc_header(); - void listdevices(); + void list_models(); + void list_devices(); - std::vector<pstring> m_options; + std::vector<pstring> m_defines; }; static NETLIST_START(dummy) - /* Standard stuff */ - - CLOCK(clk, 1000) // 1000 Hz - SOLVER(Solver, 48000) - -NETLIST_END() +{ +} -/*************************************************************************** - CORE IMPLEMENTATION -***************************************************************************/ +// ************************************************************************** +// CORE IMPLEMENTATION +// ************************************************************************** -class netlist_data_folder_t : public netlist::source_t +class netlist_data_folder_t : public netlist::source_data_t { public: - netlist_data_folder_t(const pstring &folder) - : netlist::source_t(netlist::source_t::DATA) - , m_folder(folder) + explicit netlist_data_folder_t(const pstring &folder) + : m_folder(folder) { } - plib::unique_ptr<std::istream> stream(const pstring &file) override + plib::istream_uptr stream(const pstring &file) override { pstring name = m_folder + "/" + file; - auto strm(plib::make_unique<std::ifstream>(plib::filesystem::u8path(name))); + plib::istream_uptr strm(std::make_unique<plib::ifstream>(plib::filesystem::u8path(name)), plib::filesystem::u8path(name)); if (strm->fail()) - return plib::unique_ptr<std::istream>(nullptr); - else - { - strm->imbue(std::locale::classic()); - return std::move(strm); - } + return plib::istream_uptr(); + + strm->imbue(std::locale::classic()); + return strm; } private: pstring m_folder; }; -class netlist_tool_callbacks_t : public netlist::callbacks_t +class netlist_tool_t : public netlist::netlist_state_t { public: - netlist_tool_callbacks_t(tool_app_t &app) - : netlist::callbacks_t() - , m_app(app) - { } - - void vlog(const plib::plog_level &l, const pstring &ls) const override; -private: - tool_app_t &m_app; -}; - -class netlist_tool_t : public netlist::netlist_t -{ -public: - - netlist_tool_t(tool_app_t &app, const pstring &aname) - : netlist::netlist_t(aname, plib::make_unique<netlist_tool_callbacks_t>(app)) - { - } - - void init() + netlist_tool_t(plib::plog_delegate logger, const pstring &name, const pstring &boost_lib) + : netlist::netlist_state_t(name, logger) { + if (boost_lib == "builtin") + set_static_solver_lib(std::make_unique<plib::static_library>(nl_static_solver_syms)); + else if (boost_lib == "generic") + set_static_solver_lib(std::make_unique<plib::static_library>(nullptr)); + else if (NL_DISABLE_DYNAMIC_LOAD) + throw netlist::nl_exception("Dynamic library loading not supported due to project security concerns."); + else + //#pstring libpath = plib::util::environment("NL_BOOSTLIB", plib::util::buildpath({".", "nlboost.so"})); + set_static_solver_lib(std::make_unique<plib::dynamic_library>(boost_lib)); } - netlist::setup_t &setup() { return nlstate().setup(); } - void read_netlist(const pstring &filename, const pstring &name, const std::vector<pstring> &logs, const std::vector<pstring> &defines, - const std::vector<pstring> &roms) + const std::vector<pstring> &roms, + const std::vector<pstring> &includes) { // read the netlist ... - for (auto & d : defines) - setup().add_define(d); + for (const auto & d : defines) + parser().add_define(d); + + for (const auto & r : roms) + parser().register_source<netlist_data_folder_t>(r); - for (auto & r : roms) - setup().register_source(plib::make_unique<netlist_data_folder_t>(r)); + parser().add_include<netlist_data_folder_t>(plib::util::path(filename)); - setup().register_source(plib::make_unique<netlist::source_file_t>(filename)); - setup().include(name); - create_dynamic_logs(logs); + for (const auto & i : includes) + parser().add_include<netlist_data_folder_t>(i); + + parser().register_source<netlist::source_file_t>(filename); + parser().include(name); + parser().register_dynamic_log_devices(logs); // start devices setup().prepare_to_run(); } - void create_dynamic_logs(const std::vector<pstring> &logs) - { - log().debug("Creating dynamic logs ...\n"); - for (auto & log : logs) - { - pstring name = "log_" + log; - /*netlist_device_t *nc = */ setup().register_dev("LOG", name); - setup().register_link(name + ".I", log); - } - } - std::vector<char> save_state() { run_state_manager().pre_save(); std::size_t size = 0; for (auto const & s : run_state_manager().save_list()) - size += s->m_dt.size * s->m_count; + size += s->dt().size() * s->count(); std::vector<char> buf(size); char *p = buf.data(); for (auto const & s : run_state_manager().save_list()) { - std::size_t sz = s->m_dt.size * s->m_count; - if (s->m_dt.is_float || s->m_dt.is_integral) - std::copy(static_cast<char *>(s->m_ptr), - static_cast<char *>(s->m_ptr) + sz, p); + std::size_t sz = s->dt().size() * s->count(); + if (s->dt().is_float() || s->dt().is_integral()) + std::copy(static_cast<char *>(s->ptr()), + static_cast<char *>(s->ptr()) + sz, p); else - log().fatal("found unsupported save element {1}\n", s->m_name); + log().fatal("found unsupported save element {1}\n", s->name()); p += sz; } return buf; @@ -244,7 +326,7 @@ public: { std::size_t size = 0; for (auto const & s : run_state_manager().save_list()) - size += s->m_dt.size * s->m_count; + size += s->dt().size() * s->count(); if (buf.size() != size) throw netlist::nl_exception("Size different during load state."); @@ -253,15 +335,15 @@ public: for (auto const & s : run_state_manager().save_list()) { - std::size_t sz = s->m_dt.size * s->m_count; - if (s->m_dt.is_float || s->m_dt.is_integral) - std::copy(p, p + sz, static_cast<char *>(s->m_ptr)); + std::size_t sz = s->dt().size() * s->count(); + if (s->dt().is_float() || s->dt().is_integral()) + std::copy(p, p + sz, static_cast<char *>(s->ptr())); else - log().fatal("found unsupported save element {1}\n", s->m_name); + log().fatal("found unsupported save element {1}\n", s->name()); p += sz; } run_state_manager().post_load(); - nlstate().rebuild_lists(); + this->rebuild_lists(); } protected: @@ -269,74 +351,62 @@ protected: private: }; -void netlist_tool_callbacks_t::vlog(const plib::plog_level &l, const pstring &ls) const -{ - pstring err = plib::pfmt("{}: {}\n")(l.name())(ls.c_str()); - if (l == plib::plog_level::WARNING) - m_app.m_warnings++; - if (l == plib::plog_level::ERROR) - m_app.m_errors++; - if (l == plib::plog_level::FATAL) - { - m_app.m_errors++; - throw netlist::nl_exception(err); - } - else - m_app.pout("{}", err); -} struct input_t { - input_t(const netlist::setup_t &setup, const pstring &line) - : m_value(0.0) + input_t(const netlist::setup_t &setup, const putf8string &line) + : m_value(netlist::nlconst::zero()) { std::array<char, 400> buf; // NOLINT(cppcoreguidelines-pro-type-member-init) - double t; + double t(0); + double val(0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) - int e = std::sscanf(line.c_str(), "%lf,%[^,],%lf", &t, buf.data(), &m_value); + int e = std::sscanf(line.c_str(), "%lf,%[^,],%lf", &t, buf.data(), &val); if (e != 3) throw netlist::nl_exception(plib::pfmt("error {1} scanning line {2}\n")(e)(line)); - m_time = netlist::netlist_time::from_double(t); - m_param = setup.find_param(pstring(buf.data()), true); + m_value = static_cast<netlist::nl_fptype>(val); + m_time = netlist::netlist_time_ext::from_fp(t); + m_param = setup.find_param(pstring(buf.data())); } - void setparam() + void setparam() const { - switch (m_param->param_type()) + switch (m_param.param().param_type()) { case netlist::param_t::STRING: case netlist::param_t::POINTER: - throw netlist::nl_exception(plib::pfmt("param {1} is not numeric\n")(m_param->name())); + throw netlist::nl_exception(plib::pfmt("param {1} is not numeric\n")(m_param.param().name())); case netlist::param_t::DOUBLE: - static_cast<netlist::param_double_t*>(m_param)->setTo(m_value); + plib::downcast<netlist::param_fp_t &>(m_param.param()).set(m_value); break; case netlist::param_t::INTEGER: - static_cast<netlist::param_int_t*>(m_param)->setTo(static_cast<int>(m_value)); + plib::downcast<netlist::param_int_t &>(m_param.param()).set(static_cast<int>(m_value)); break; case netlist::param_t::LOGIC: - static_cast<netlist::param_logic_t*>(m_param)->setTo(static_cast<bool>(m_value)); + plib::downcast<netlist::param_logic_t &>(m_param.param()).set(static_cast<bool>(m_value)); break; } } - netlist::netlist_time m_time; - netlist::param_t *m_param; - double m_value; + netlist::netlist_time_ext m_time; + netlist::param_ref_t m_param; + netlist::nl_fptype m_value; }; static std::vector<input_t> read_input(const netlist::setup_t &setup, const pstring &fname) { std::vector<input_t> ret; - if (fname != "") + if (!fname.empty()) { - plib::putf8_reader r = plib::putf8_reader(std::ifstream(plib::filesystem::u8path(fname))); + plib::putf8_reader r = plib::putf8_reader(std::make_unique<plib::ifstream>(plib::filesystem::u8path(fname))); if (r.stream().fail()) throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(fname)); r.stream().imbue(std::locale::classic()); - pstring l; - while (r.readline(l)) + putf8string l; + while (r.read_line(l)) { - if (l != "") + if (!l.empty()) { input_t inp(setup, l); ret.push_back(inp); @@ -346,106 +416,154 @@ static std::vector<input_t> read_input(const netlist::setup_t &setup, const pstr return ret; } +void tool_app_t::run_with_progress(netlist_tool_t &nt, netlist::netlist_time_ext start, netlist::netlist_time_ext duration) +{ + if (!opt_progress()) + nt.exec().process_queue(duration); + else + { + auto now = nt.exec().time(); + auto end = now + duration; + // run to next_sec + while (now < end) + { + auto elapsed = now - start; + auto elapsed_sec = elapsed.in_sec() + 1; + + auto next_sec = start + netlist::netlist_time_ext::from_sec(elapsed_sec); + if (end < next_sec) + { + nt.exec().process_queue(end - now); + } + else + { + nt.exec().process_queue(next_sec - now); + std_out("progress {1:4}s : {2}\r", elapsed_sec, pstring(gsl::narrow_cast<std::size_t>(elapsed_sec), '*')); + std_out.flush(); + } + now = nt.exec().time(); + } + } +} + +void tool_app_t::logger(plib::plog_level l, const pstring &ls) +{ + pstring err = plib::pfmt("{}: {}\n")(l.name())(ls.c_str()); + if (l == plib::plog_level::WARNING) + m_warnings++; + if (l == plib::plog_level::ERROR) + m_errors++; + if (l == plib::plog_level::FATAL) + m_errors++; + std_out("{}", err); +} + void tool_app_t::run() { plib::chrono::timer<plib::chrono::system_ticks> t; - std::vector<input_t> inps; - netlist::netlist_time ttr; - netlist_tool_t nt(*this, "netlist"); + std::vector<input_t> inputs; + netlist::netlist_time_ext duration; - { - auto t_guard(t.guard()); - //plib::perftime_t<plib::exact_ticks> t; + if (opt_files().size() != 1) + throw netlist::nl_exception("nltool: run needs exactly one file"); - nt.enable_stats(opt_stats()); - nt.init(); + if (!plib::util::exists(opt_files()[0])) + throw netlist::nl_exception("nltool: file doesn't exists: {}", opt_files()[0]); - if (!opt_verb()) - nt.log().verbose.set_enabled(false); - if (opt_quiet()) - nt.log().info.set_enabled(false); + t.start(); - nt.read_netlist(opt_file(), opt_name(), - opt_logs(), - m_options, opt_rfolders()); + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); - nt.reset(); + nt.exec().enable_stats(opt_stats()); - inps = read_input(nt.setup(), opt_inp()); - ttr = netlist::netlist_time::from_double(opt_ttr()); - } + if (!opt_verb()) + nt.log().verbose.set_enabled(false); + if (opt_quiet()) + nt.log().info.set_enabled(false); + nt.read_netlist(opt_files()[0], opt_name(), + opt_logs(), + m_defines, opt_data_folders(), opt_includes()); - pout("startup time ==> {1:5.3f}\n", t.as_seconds() ); + // Inputs must be read before reset -> will clear setup and parser + inputs = read_input(nt.setup(), opt_inp()); + nt.free_setup_resources(); + nt.exec().reset(); - t.reset(); + duration = netlist::netlist_time_ext::from_fp(opt_ttr()); + t.stop(); + std_out("startup time ==> {1:5.3f}\n", t.as_seconds<netlist::nl_fptype>() ); - netlist::netlist_time nlt = nt.time(); + // FIXME: error handling + if (opt_load_state.was_specified()) { - auto t_guard(t.guard()); + plib::ifstream strm(plib::filesystem::u8path(opt_load_state())); + if (strm.fail()) + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(opt_load_state())); + strm.imbue(std::locale::classic()); + plib::pbinary_reader reader(strm); + std::vector<char> load_state; + reader.read(load_state); + nt.load_state(load_state); + std_out("Loaded state, run will continue at {1:.6f}\n", nt.exec().time().as_double()); + } - // FIXME: error handling - if (opt_loadstate.was_specified()) - { - std::ifstream strm(plib::filesystem::u8path(opt_loadstate())); - if (strm.fail()) - throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(opt_loadstate())); - strm.imbue(std::locale::classic()); - plib::pbinary_reader reader(strm); - std::vector<char> loadstate; - reader.read(loadstate); - nt.load_state(loadstate); - pout("Loaded state, run will continue at {1:.6f}\n", nt.time().as_double()); - } + t.reset(); + netlist::netlist_time_ext start = nt.exec().time(); + { + std_out("runnning ...\n"); unsigned pos = 0; + netlist::netlist_time_ext nlt = start; + auto t_guard(t.guard()); - - while (pos < inps.size() - && inps[pos].m_time < ttr - && inps[pos].m_time >= nlt) + while (pos < inputs.size() + && inputs[pos].m_time < duration + && inputs[pos].m_time >= nlt) { - nt.process_queue(inps[pos].m_time - nlt); - inps[pos].setparam(); - nlt = inps[pos].m_time; + run_with_progress(nt, start, inputs[pos].m_time - nlt); + inputs[pos].setparam(); + nlt = inputs[pos].m_time; pos++; } - pout("runnning ...\n"); - - if (ttr > nlt) - nt.process_queue(ttr - nlt); + if (duration > nlt) + run_with_progress(nt, start, duration - nlt); else { - pout("end time {1:.6f} less than saved time {2:.6f}\n", - ttr.as_double(), nlt.as_double()); - ttr = nlt; + std_out("end time {1:.6f} less than saved time {2:.6f}\n", + duration.as_double(), nlt.as_double()); + duration = nlt; } - - if (opt_savestate.was_specified()) - { - auto savestate = nt.save_state(); - std::ofstream strm(plib::filesystem::u8path(opt_savestate()), std::ios_base::binary); - if (strm.fail()) - throw plib::file_open_e(opt_savestate()); - strm.imbue(std::locale::classic()); - - plib::pbinary_writer writer(strm); - writer.write(savestate); - } - nt.stop(); } - double emutime = t.as_seconds(); - pout("{1:f} seconds emulation took {2:f} real time ==> {3:5.2f}%\n", - (ttr - nlt).as_double(), emutime, - (ttr - nlt).as_double() / emutime * 100.0); + if (opt_save_state.was_specified()) + { + auto save_state = nt.save_state(); + plib::ofstream strm(plib::filesystem::u8path(opt_save_state()), std::ios_base::binary); + if (strm.fail()) + throw plib::file_open_e(opt_save_state()); + strm.imbue(std::locale::classic()); + + plib::pbinary_writer writer(strm); + writer.write(save_state); + } + nt.exec().stop(); + + if (opt_progress()) + std_out("\n"); + auto emulation_time(t.as_seconds<netlist::nl_fptype>()); + std_out("{1:f} seconds emulation took {2:f} real time ==> {3:5.2f}%\n", + (duration - start).as_fp<netlist::nl_fptype>(), emulation_time, + (duration - start).as_fp<netlist::nl_fptype>() / emulation_time * netlist::nlconst::hundred()); } void tool_app_t::validate() { - std::vector<input_t> inps; - netlist_tool_t nt(*this, "netlist"); + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); + + if (opt_files().size() != 1) + throw netlist::nl_exception("nltool: validate needs exactly one file"); if (!opt_verb()) nt.log().verbose.set_enabled(false); @@ -455,23 +573,19 @@ void tool_app_t::validate() m_errors = 0; m_warnings = 0; - nt.setup().enable_validation(); - try { - nt.init(); - - nt.read_netlist(opt_file(), opt_name(), + nt.read_netlist(opt_files()[0], opt_name(), opt_logs(), - m_options, opt_rfolders()); + m_defines, opt_data_folders(), opt_includes()); } catch (netlist::nl_exception &e) { - pout("Netlist exception caught: {}\n", e.text()); + std_out("Netlist exception caught: {}\n", e.text()); } catch (plib::pexception &e) { - pout("plib exception caught: {}\n", e.text()); + std_out("plib exception caught: {}\n", e.text()); } //pout("Validation warnings: {}\n", m_warnings); @@ -482,32 +596,298 @@ void tool_app_t::validate() } +void tool_app_t::compile_one_and_add_to_map(const pstring &file, + const pstring &name, netlist::solver::static_compile_target target, + compile_map &map) +{ + try + { + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); + + nt.log().verbose.set_enabled(false); + nt.log().info.set_enabled(false); + nt.log().warning.set_enabled(false); + + nt.read_netlist(file, name, + opt_logs(), + m_defines, opt_data_folders(), opt_includes()); + + // need to reset ... + + nt.free_setup_resources(); + nt.exec().reset(); + + auto mp(nt.exec().solver()->create_solver_code(target)); + + for (auto &e : mp) + { + auto it = map.find(e.first); + if (it == map.end()) + map.insert({e.first, compile_map_entry(name, e.second)}); + else + { + if (it->second.m_code != e.second) + { + pstring msg = plib::pfmt("nltool: found hash conflict in {1}, netlist {2}")(file, name); + throw netlist::nl_exception(msg); + } + if (!plib::container::contains(it->second.m_modules, name)) + it->second.m_modules.push_back(name); + } + } + + nt.exec().stop(); + } + catch (netlist::nl_exception &e) + { + std_err("{} : Netlist exception : {}\n", file, e.text()); + } + catch (plib::pexception &e) + { + std_err("{} : Netlist exception : {}\n", file, e.text()); + } +} + void tool_app_t::static_compile() { - netlist_tool_t nt(*this, "netlist"); - nt.init(); + netlist::solver::static_compile_target target = netlist::solver::CXX_STATIC; - nt.log().verbose.set_enabled(false); - nt.log().info.set_enabled(false); + if (!opt_static_include() && ((opt_dir.was_specified() ^ opt_out.was_specified()) == 0)) + throw netlist::nl_exception("either --dir or --output option needed"); - nt.read_netlist(opt_file(), opt_name(), - opt_logs(), - m_options, opt_rfolders()); + if (opt_static_include() && (!opt_dir.was_specified() || !opt_out.was_specified())) + throw netlist::nl_exception("--split requires both --dir and --output option"); - // no reset needed ... + if (!opt_static_include() && opt_dir.was_specified()) + { + if (opt_files().size() != 1) + throw netlist::nl_exception("nltool: static_compile needs exactly one file"); - std::map<pstring, pstring> mp; + compile_map mp; - nt.solver()->create_solver_code(mp); + compile_one_and_add_to_map(opt_files()[0], opt_name(), target, mp); - for (auto &e : mp) + for (auto &e : mp) + { + plib::ofstream output_stream(opt_dir() + "/" + e.first + ".c" ); + output_stream << putf8string(e.second.m_code); + } + } + else { - pout.write(e.second); + compile_map map; + + for (const auto &f : opt_files()) + { + std::vector<pstring> names; + if (opt_name.was_specified()) + names.push_back(opt_name()); + else + { + plib::putf8_reader r = plib::putf8_reader(std::make_unique<plib::ifstream>(plib::filesystem::u8path(f))); + if (r.stream().fail()) + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(f)); + r.stream().imbue(std::locale::classic()); + putf8string line; + while (r.read_line(line)) + { + if (plib::startsWith(line, "//NL_CONTAINS ")) + { + auto sp = plib::psplit(pstring(plib::trim(line.substr(13))), ' ', true); + for (auto &e : sp) + names.push_back(e); + } + } + + if (names.empty()) + { + pstring name = plib::util::basename(f, ".cpp"); + if (plib::startsWith(name, "nl_")) + name = name.substr(3); + names.push_back(name); + } + + } + std::sort(names.begin(), names.end()); + for (auto &name : names) + { + if (!opt_quiet()) + std_out("Processing {}({}) ... \n", name, f); + + compile_one_and_add_to_map(f, name, target, map); + } + } + plib::ofstream output_stream(opt_out()); + if (output_stream.fail()) + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(opt_out())); + + output_stream << "// spell-checker: disable\n\n"; + output_stream << "#include \"plib/pdynlib.h\"\n\n"; + output_stream << "#if !defined(__EMSCRIPTEN__)\n\n"; + + std::vector<std::pair<pstring,pstring>> sort_map; + for (auto &e : map) + sort_map.emplace_back(e.second.m_modules[0], e.first); + + std::sort(sort_map.begin(), sort_map.end(), [](const auto &a, const auto &b) { + return a.first < b.first ? true : (a.first == b.first && a.second < b.second); + }); + + pstring last; + plib::ofstream output_splitted; + for (auto &se : sort_map) + { + const auto &e = map.find(se.second); + pstring mods; + for (auto &s : e->second.m_modules) + mods += s + ","; + mods = plib::left(mods, mods.length()-1); + if (opt_static_include()) + { + auto fname = pstring("sc_") + e->second.m_modules[0] + ".hpp"; + auto fpath(plib::util::build_path({opt_dir(), fname})); + if (last != fpath) + { + last = fpath; + if (output_splitted.is_open()) + output_splitted.close(); + output_splitted.open(fpath); + if (output_stream.fail()) + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(fpath)); + output_stream << "// spell-checker: disable\n\n"; + output_stream << "// " << putf8string(mods) << "\n"; + output_stream << "#include \"generated/static/" << fname << "\"\n"; + } + output_splitted << "// " << putf8string(mods) << "\n"; + output_splitted << putf8string(e->second.m_code); + } + else + { + output_stream << "// " << putf8string(mods) << "\n"; + output_stream << putf8string(e->second.m_code); + } + } + + output_stream << "#endif\n\n"; + output_stream << "extern const plib::static_library::symbol nl_static_solver_syms[];\n"; + output_stream << "const plib::static_library::symbol nl_static_solver_syms[] = {\n"; + output_stream << "#if !defined(__EMSCRIPTEN__)\n\n"; + for (auto &se : sort_map) + { + const auto &e = map.find(se.second); + pstring mods; + for (auto &s : e->second.m_modules) + mods += s + ","; + output_stream << "// " << putf8string(plib::left(mods, mods.length()-1)) << "\n"; + output_stream << "\t{\"" << putf8string(e->first) << "\", reinterpret_cast<void *>(&" << putf8string(e->first) << ")}, // NOLINT\n"; + } + output_stream << "#endif\n\n"; + output_stream << "{\"\", nullptr}\n"; + output_stream << "};\n"; + } +} + + - nt.stop(); +// "Description: The Swiss army knife for timing purposes\n" +// " which has a ton of applications.\n" +// "DipAlias: GND,TRIG,OUT,RESET,VCC,DISCH,THRES,CONT\n" +// "Package: DIP\n" +// "NamingConvention: Naming conventions follow Texas Instruments datasheet\n" +// "Limitations: Internal resistor network currently fixed to 5k\n" +// " more limitations\n" +// "FunctionTable:\n" +// +struct doc_ext +{ + pstring id; + pstring title; + pstring description; + std::vector<pstring> pin_alias; + pstring package; + std::vector<std::pair<pstring, pstring>> params; + pstring naming_conventions; + pstring limitations; + pstring function_table; + std::vector<pstring> example; +}; + +static doc_ext read_documentation_from_source(const pstring &fname, const pstring &id) +{ + plib::putf8_reader r = plib::putf8_reader(std::make_unique<plib::ifstream>(plib::filesystem::u8path(fname))); + if (r.stream().fail()) + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(fname)); + r.stream().imbue(std::locale::classic()); + doc_ext ret; + + putf8string l; + if (!r.read_line(l)) + return ret; + do + { + l = plib::trim(l); + if (plib::startsWith(l, "//-")) + { + l = plib::trim(l.substr(3)); + if (!l.empty()) + { + auto a(plib::psplit(pstring(l), ':', true)); + if (a.empty() || (a.size() > 2)) + throw netlist::nl_exception(pstring(l) + " size mismatch"); + pstring n(plib::trim(a[0])); + pstring v(a.size() < 2 ? "" : plib::trim(a[1])); + pstring v2(v); + if (n == "Identifier") + { + if (!r.read_line(l) || ret.id == id) + return (ret.id == id ? ret : doc_ext()); + ret = doc_ext(); + ret.id = v; + } + else + { + while (r.read_line(l)) + { + l = plib::ltrim(l); + if (!(plib::startsWith(l, "//- ") || plib::startsWith(l, "//-\t")) + && !(plib::rtrim(l) == "//-")) + break; + v = v + "\n" + pstring(l.substr(3)); + } + if (n == "Title") + ret.title = plib::trim(v); + else if (n == "Pinalias") + ret.pin_alias = plib::psplit(plib::trim(v),',',true); + else if (n == "Description") + ret.description = v; + else if (n == "Package") + ret.package = plib::trim(v); + else if (n == "NamingConvention") + ret.naming_conventions = v; + else if (n == "Limitations") + ret.limitations = v; + else if (n == "FunctionTable") + ret.function_table = v; + else if (n == "Param") + ret.params.emplace_back(v2, plib::trim(v.substr(v2.length()))); + else if (n == "Example") + { + ret.example = plib::psplit(plib::trim(v),',',true); + if (ret.example.size() != 2 && !ret.example.empty()) + throw netlist::nl_exception("Example requires 2 parameters, but found {1}", ret.example.size()); + } + else + throw netlist::nl_exception(n); + } + } + } + else if (!r.read_line(l)) + return (ret.id == id ? ret : doc_ext()); + } while (true); + //return ret; } void tool_app_t::mac_out(const pstring &s, const bool cont) @@ -520,8 +900,8 @@ void tool_app_t::mac_out(const pstring &s, const bool cont) { if (x == '\t') { - auto pos_mod_4 = pos % opt_tabwidth(); - auto tab_adj = opt_tabwidth() - pos_mod_4; + auto pos_mod_4 = pos % opt_tab_width(); + auto tab_adj = opt_tab_width() - pos_mod_4; r += plib::rpad(pstring(""), pstring(" "), tab_adj); pos += tab_adj; } @@ -531,186 +911,299 @@ void tool_app_t::mac_out(const pstring &s, const bool cont) pos++; } } - pout("{1}\\\n", plib::rpad(r, pstring(" "), opt_linewidth()-1)); + std_out("{1}\\\n", plib::rpad(r, pstring(" "), opt_line_width()-1)); } else - pout("{1}\n", s); + std_out("{1}\n", s); } void tool_app_t::header_entry(const netlist::factory::element_t *e) { - auto v = plib::psplit(e->param_desc(), ","); + auto v = plib::psplit(e->param_desc(), ','); pstring vs; + pstring avs; for (const auto &s : v) if (!plib::startsWith(s, "@")) vs += ", p" + plib::replace_all(plib::replace_all(s, "+", ""), ".", "_"); - mac_out("#define " + e->name() + "(name" + vs + ")"); - mac_out("\tNET_REGISTER_DEV(" + e->name() +", name)"); - - for (const auto &s : v) - { - pstring r(plib::replace_all(plib::replace_all(plib::replace_all(s, "+", ""), ".", "_"), "@","")); - if (plib::startsWith(s, "+")) - mac_out("\tNET_CONNECT(name, " + r + ", p" + r + ")"); - else if (plib::startsWith(s, "@")) - mac_out("\tNET_CONNECT(name, " + r + ", " + r + ")"); else - mac_out("\tNETDEV_PARAMI(name, " + r + ", p" + r + ")"); - } + avs += ", " + s.substr(1); + + mac_out("// usage : " + e->name() + "(name" + vs + ")", false); + if (!avs.empty()) + mac_out("// auto connect: " + avs.substr(2), false); + + mac_out("#define " + e->name() + "(...)"); + mac_out("\tNET_REGISTER_DEVEXT(" + e->name() +", __VA_ARGS__)", false); mac_out("", false); } void tool_app_t::mac(const netlist::factory::element_t *e) { - auto v = plib::psplit(e->param_desc(), ","); + auto v = plib::psplit(e->param_desc(), ','); pstring vs; for (const auto &s : v) if (!plib::startsWith(s, "@")) vs += ", " + plib::replace_all(plib::replace_all(s, "+", ""), ".", "_"); - pout("{1}(name{2})\n", e->name(), vs); - if (v.size() > 0) + std_out("{1}(name{2})\n", e->name(), vs); + if (!v.empty()) { - pout("/*\n"); + std_out("/*\n"); for (const auto &s : v) { pstring r(plib::replace_all(plib::replace_all(plib::replace_all(s, "+", ""), ".", "_"), "@","")); if (plib::startsWith(s, "+")) - pout("{1:10}: Terminal\n",r); + std_out("{1:10}: Terminal\n",r); else if (plib::startsWith(s, "@")) - pout("{1:10}: Power terminal - automatically connected\n", r); + std_out("{1:10}: Power terminal - automatically connected\n", r); else - pout("{1:10}: Parameter\n", r); + std_out("{1:10}: Parameter\n", r); } - pout("*/\n"); + std_out("*/\n"); } } void tool_app_t::create_header() { - netlist_tool_t nt(*this, "netlist"); + if (!opt_files().empty()) + throw netlist::nl_exception("Header doesn't support input files, but {1} where given", opt_files().size()); - nt.init(); + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); nt.log().verbose.set_enabled(false); nt.log().info.set_enabled(false); - nt.setup().register_source(plib::make_unique<netlist::source_proc_t>("dummy", &netlist_dummy)); - nt.setup().include("dummy"); - - pout("// license:GPL-2.0+\n"); - pout("// copyright-holders:Couriersud\n"); - pout("#ifndef NLD_DEVINC_H\n"); - pout("#define NLD_DEVINC_H\n"); - pout("\n"); - pout("#include \"nl_setup.h\"\n"); - pout("#ifndef __PLIB_PREPROCESSOR__\n"); - pout("\n"); - pout("/* ----------------------------------------------------------------------------\n"); - pout(" * Netlist Macros\n"); - pout(" * ---------------------------------------------------------------------------*/\n"); - pout("\n"); + nt.parser().register_source<netlist::source_proc_t>("dummy", &netlist_dummy); + nt.parser().include("dummy"); + + std_out("// license:BSD-3-Clause\n"); + std_out("// copyright-holders:Couriersud\n"); + std_out("#ifndef NLD_DEVINC_H\n"); + std_out("#define NLD_DEVINC_H\n"); + std_out("\n"); + std_out("#ifndef __PLIB_PREPROCESSOR__\n"); + std_out("\n"); + std_out("#include ""../nl_setup.h""\n"); + std_out("\n"); + + std_out("// ----------------------------------------------------------------------------\n"); + std_out("// Netlist Macros\n"); + std_out("// ---------------------------------------------------------------------------\n"); + std_out("\n"); pstring last_source(""); - for (auto &e : nt.setup().factory()) + for (auto &e : nt.parser().factory()) { - if (last_source != e->sourcefile()) + bool found(opt_pattern().empty()); + + for (const auto &p : opt_pattern()) + found |= (e->name().find(p) != pstring::npos); + + if (found) { - last_source = e->sourcefile(); - pout("{1}\n", plib::rpad(pstring("// "), pstring("-"), opt_linewidth())); - pout("{1}{2}\n", pstring("// Source: "), plib::replace_all(e->sourcefile(), "../", "")); - pout("{1}\n", plib::rpad(pstring("// "), pstring("-"), opt_linewidth())); + if (last_source != e->source().file_name()) + { + last_source = e->source().file_name(); + std_out("{1}\n", plib::rpad(pstring("// "), pstring("-"), opt_line_width())); + std_out("{1}{2}\n", "// Source: ", plib::replace_all(e->source().file_name(), "../", "")); + std_out("{1}\n", plib::rpad(pstring("// "), pstring("-"), opt_line_width())); + } + header_entry(e.get()); } - header_entry(e.get()); } - pout("#endif // __PLIB_PREPROCESSOR__\n"); - pout("#endif\n"); - nt.stop(); + std_out("#endif // __PLIB_PREPROCESSOR__\n"); + std_out("#endif\n"); + nt.exec().stop(); } -void tool_app_t::create_docheader() +void tool_app_t::create_doc_header() { - netlist_tool_t nt(*this, "netlist"); - - nt.init(); + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); nt.log().verbose.set_enabled(false); nt.log().info.set_enabled(false); - nt.setup().register_source(plib::make_unique<netlist::source_proc_t>("dummy", &netlist_dummy)); - nt.setup().include("dummy"); + nt.parser().register_source<netlist::source_proc_t>("dummy", &netlist_dummy); + nt.parser().include("dummy"); - std::vector<pstring> devs; - for (auto &e : nt.setup().factory()) - devs.push_back(e->name()); - std::sort(devs.begin(), devs.end(), [&](pstring &a, pstring &b) { return a < b; }); + std::vector<pstring> devices; + for (auto &e : nt.parser().factory()) + devices.push_back(e->name()); + std::sort(devices.begin(), devices.end(), [&](pstring &a, pstring &b) { return a < b; }); - pout("// license:GPL-2.0+\n"); - pout("// copyright-holders:Couriersud\n"); - pout("/* ----------------------------------------------------------------------------\n"); - pout(" * Automatically created file. DO NOT MODIFY.\n"); - pout(" * ---------------------------------------------------------------------------*/\n"); - pout("/*!\n"); - pout(" * \\page devices Devices\n"); - pout(" *\n"); - pout(" * Below is a list of all the devices currently known to the system ...\n"); - pout(" *\n"); + std_out("// license:BSD-3-Clause\n"); + std_out("// copyright-holders:Couriersud\n"); + std_out("\n"); + std_out("// ----------------------------------------------------------------------------\n"); + std_out("// Automatically created file. DO NOT MODIFY.\n"); + std_out("// ---------------------------------------------------------------------------\n"); + std_out("///\n"); + std_out("/// \\page devices Devices\n"); + std_out("///\n"); + std_out("/// Below is a list of all the devices currently known to the system ...\n"); + std_out("///\n"); - for (auto &s : devs) - pout(" * - \\subpage {1}\n", s); + for (auto &s : devices) + std_out("/// - @subpage {1}\n", s); - pout(" *\n"); + std_out("\n"); - for (auto &e : nt.setup().factory()) + std::vector<doc_ext> de_cache; + + for (auto &e : nt.parser().factory()) { - pout("//! [{1} csynopsis]\n", e->name()); - header_entry(e.get()); - pout("//! [{1} csynopsis]\n", e->name()); - pout("//! [{1} synopsis]\n", e->name()); - mac(e.get()); - pout("//! [{1} synopsis]\n", e->name()); + auto d(read_documentation_from_source(e->source().file_name(), e->name())); + + if (!d.id.empty()) + { + std_out("//! [{1} csynopsis]\n", e->name()); + header_entry(e.get()); + std_out("//! [{1} csynopsis]\n", e->name()); + std_out("//! [{1} synopsis]\n", e->name()); + mac(e.get()); + std_out("//! [{1} synopsis]\n", e->name()); + } + de_cache.push_back(std::move(d)); + } + + output_with_prefix("", ""); + output_with_prefix("///", ""); + //output_with_prefix("///", " @file "); + output_with_prefix("///", " @page ''"); // FIXME: snippets and pages need to be separate files + output_with_prefix("", ""); + + for (auto &d : de_cache) + { + //auto d(read_documentation_from_source(e->source().file_name(), e->name())); + + if (!d.id.empty()) + { + + output_with_prefix("///", ""); + //output_with_prefix("///", " @file {}", e->sourcefile()); + output_with_prefix("///", ""); + output_with_prefix("///", " @page {} {}", d.id, d.title); + output_with_prefix("///", ""); + output_with_prefix("///", " {}", d.description); + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_1 Synopsis", d.id); + output_with_prefix("///", ""); + output_with_prefix("///", " @snippet devsyn.dox.h {} synopsis", d.id); + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_11 C Synopsis", d.id); + output_with_prefix("///", ""); + output_with_prefix("///", " @snippet devsyn.dox.h {} csynopsis", d.id); + output_with_prefix("///", ""); + + output_with_prefix("///", " @section {}_2 Parameters", d.id); + output_with_prefix("///", ""); + if (!d.params.empty()) + { + output_with_prefix("///", " <table>"); + output_with_prefix("///", " <tr><th>Name</th><th>Description</th></tr>"); + for (auto &e : d.params) + output_with_prefix("///", " <tr><td>{1}</td><td>{2}</td></tr>", e.first, e.second); + output_with_prefix("///", " </table>"); + } + else + output_with_prefix("///", " This device has no parameters."); + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_3 Connection Diagram", d.id); + output_with_prefix("///", ""); + + if (!d.pin_alias.empty()) + { + output_with_prefix("///", " <pre>"); + if (d.package == "DIP") + { + auto & pins = d.pin_alias; + //const int w = 8; + output_with_prefix("///", " {1:10} +--------+", " "); + for (std::size_t i=0; i < pins.size() / 2; i++) + { + output_with_prefix("///", " {1:10} |{2:-2} {3:2}| {4:-10}", + pins[i], i+1, pins.size()-i, pins[pins.size()-i-1]); + } + output_with_prefix("///", " {1:10} +--------+", " "); + } + else if (d.package == "SIL") + { + auto & pins = d.pin_alias; + //const int w = 8; + output_with_prefix("///", " {1:10} +--------+", " "); + for (std::size_t i=0; i < pins.size(); i++) + { + output_with_prefix("///", " {1:10} |{2:-2} |", + pins[i], i+1); + } + output_with_prefix("///", " {1:10} +--------+", " "); + } + output_with_prefix("///", " </pre>"); + } + output_with_prefix("///", ""); + output_with_prefix("///", " {}", d.naming_conventions); + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_4 Function Table", d.id); + output_with_prefix("///", ""); + if (d.function_table.empty()) + output_with_prefix("///", " Please refer to the datasheet."); + else + output_with_prefix("///", " {}", d.function_table); + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_5 Limitations", d.id); + output_with_prefix("///", ""); + output_with_prefix("///", " {}", d.limitations); + if (!d.example.empty()) + { + output_with_prefix("///", ""); + output_with_prefix("///", " @section {}_6 Example", d.id); + output_with_prefix("///", " @snippet {1} {2}", d.example[0], d.example[1]); + output_with_prefix("///", ""); + output_with_prefix("", ""); + } + } } - nt.stop(); + nt.exec().stop(); } -/*------------------------------------------------- - listdevices - list all known devices --------------------------------------------------*/ +// ------------------------------------------------- +// list_devices - list all known devices +// ------------------------------------------------- -void tool_app_t::listdevices() +void tool_app_t::list_devices() { - netlist_tool_t nt(*this, "netlist"); - nt.init(); + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); nt.log().verbose.set_enabled(false); nt.log().info.set_enabled(false); nt.log().warning.set_enabled(false); - netlist::factory::list_t &list = nt.setup().factory(); - - nt.setup().register_source(plib::make_unique<netlist::source_proc_t>("dummy", &netlist_dummy)); - nt.setup().include("dummy"); - + netlist::factory::list_t &list = nt.parser().factory(); + nt.parser().register_source<netlist::source_proc_t>("dummy", &netlist_dummy); + nt.parser().include("dummy"); nt.setup().prepare_to_run(); - std::vector<netlist::pool_owned_ptr<netlist::core_device_t>> devs; + std::vector<netlist::device_arena::unique_ptr<netlist::core_device_t>> devices; - for (auto & f : list) + for (auto & fl : list) { - pstring out = plib::pfmt("{1:-20} {2}(<id>")(f->classname())(f->name()); + pstring out = plib::pfmt("{1:-20} {2}(<id>")(fl->name())(fl->name()); + + netlist::factory::element_t *f = nullptr; + nt.parser().register_dev(fl->name(), fl->name() + "_lc", + std::vector<pstring>(), &f); - f->macro_actions(nt.setup(), f->name() + "_lc"); - auto d = f->Create(nt.nlstate(), f->name() + "_lc"); + auto d = f->make_device(nt.pool(), nt, f->name() + "_lc"); // get the list of terminals ... std::vector<pstring> terms(nt.setup().get_terminals_for_device_name(d->name())); out += "," + f->param_desc(); - for (const auto &p : plib::psplit(f->param_desc(),",") ) + for (const auto &p : plib::psplit(f->param_desc(),',') ) { if (plib::startsWith(p, "+")) { @@ -718,67 +1211,114 @@ void tool_app_t::listdevices() } } out += ")"; - pout("{}\n", out); - if (terms.size() > 0) + std_out("{}\n", out); + if (!terms.empty()) { pstring t = ""; for (auto & j : terms) t += "," + j; - pout("\tTerminals: {}\n", t.substr(1)); + std_out("\tTerminals: {}\n", t.substr(1)); } - devs.emplace_back(std::move(d)); + devices.emplace_back(std::move(d)); } } -/*------------------------------------------------- - convert - convert spice et al to netlist --------------------------------------------------*/ +void tool_app_t::list_models() +{ + netlist_tool_t nt(plib::plog_delegate(&tool_app_t::logger, this), "netlist", opt_boost_lib()); + + nt.log().verbose.set_enabled(false); + nt.log().info.set_enabled(false); + nt.log().warning.set_enabled(false); + + nt.parser().register_source<netlist::source_proc_t>("dummy", &netlist_dummy); + nt.parser().include("dummy"); + nt.setup().prepare_to_run(); + + using string_pair = std::pair<pstring, pstring>; + + struct comp_s { + bool operator() (const string_pair &i, const string_pair &j) + { + if (i.first < j.first) + return true; + if (i.first == j.first) + return (i.second < j.second); + return false; + } + } comp; + + std::vector<string_pair> elems; + + for (auto & e : nt.setup().models().known_models()) + { + auto model = nt.setup().models().get_model(e); + + elems.emplace_back(model.type(), e); + } + + std::sort(elems.begin(), elems.end(), comp); + + for (auto & e : elems) + { + pstring out = plib::pfmt("{1:-15} {2}")(e.first, e.second); + std_out("{}\n", out); + } +} + +// ------------------------------------------------- +// convert - convert spice et al to netlist +// ------------------------------------------------- void tool_app_t::convert() { - pstring contents; - std::stringstream ostrm; - ostrm.imbue(std::locale::classic()); - if (opt_file() == "-") + std::stringstream out_stream; + out_stream.imbue(std::locale::classic()); + + if (opt_files().size() > 1) + throw netlist::nl_exception("nltool: convert needs exactly one file"); + + if (opt_files().empty() || opt_files()[0] == "-") { - plib::copystream(ostrm, std::cin); + plib::copy_stream(out_stream, std::cin); } else { - std::ifstream strm(plib::filesystem::u8path(opt_file())); + plib::ifstream strm(plib::filesystem::u8path(opt_files()[0])); if (strm.fail()) - throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(opt_file())); + throw netlist::nl_exception(netlist::MF_FILE_OPEN_ERROR(opt_files()[0])); strm.imbue(std::locale::classic()); - plib::copystream(ostrm, strm); + plib::copy_stream(out_stream, strm); } - contents = pstring(ostrm.str()); + + pstring contents(putf8string(out_stream.str())); pstring result; if (opt_type.as_string() == "spice") { - nl_convert_spice_t c; + netlist::convert::nl_convert_spice_t c; c.convert(contents); result = c.result(); } else if (opt_type.as_string() == "eagle") { - nl_convert_eagle_t c; + netlist::convert::nl_convert_eagle_t c; c.convert(contents); result = c.result(); } else if (opt_type.as_string() == "rinf") { - nl_convert_rinf_t c; + netlist::convert::nl_convert_rinf_t c; c.convert(contents); result = c.result(); } - /* present result */ - pout.write(result); + // present result + std_out.write(result); } -/*------------------------------------------------- - main - primary entry point --------------------------------------------------*/ +// ------------------------------------------------- +// main - primary entry point +// ------------------------------------------------- #if 0 static const pstring pmf_verbose[] = @@ -793,55 +1333,58 @@ static const pstring pmf_verbose[] = pstring tool_app_t::usage() { return help( - "nltool serves as the Swiss Army knife to run, test and convert netlists.", - "nltool [options]"); + "nltool serves as the Swiss Army knife to run, test and convert netlists.\n\n" + "Commands may accept one or more files depending on the functionality.\n" + "If no file is provided, standard input is used.", + "nltool [option]... [files]..."); } int tool_app_t::execute() { tool_app_t opts; - /* make SIGFPE actually deliver signals on supoorted platforms */ - plib::fpsignalenabler::global_enable(true); - plib::fpsignalenabler sigen(plib::FP_ALL & ~plib::FP_INEXACT & ~plib::FP_UNDERFLOW); - if (opt_help()) { - pout(plib::pfmt("{:10.3}\n").f(20.0)); - //pout(plib::pfmt("{10.3}\n").f(20)); - pout(usage()); + std_out(usage()); return 0; } if (opt_version()) { - pout( - "nltool (netlist) " PSTRINGIFY(NLTOOL_VERSION) "\n" - "Copyright (C) 2019 Couriersud\n" - "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.\n" + std_out( + "nltool (netlist) {1}\n" + "Copyright (C) 2021 Couriersud\n" + "License BSD-3-Clause\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n\n" - "Written by Couriersud.\n"); + "Written by Couriersud.\n", netlist::netlist_state_t::version()); if (opt_verb()) { std::vector<std::pair<pstring, pstring>> defs; netlist::netlist_state_t::compile_defines(defs); - pout("\nCompile defines:\n"); + std_out("\nCompile defines:\n"); for (auto &x : defs) - pout("{1:-30} = {2}\n", x.first, x.second); + std_out("{1:-30} = {2}\n", x.first, x.second); } return 0; } - m_options = opt_defines(); - m_options.emplace_back("NLTOOL_VERSION=" PSTRINGIFY(NLTOOL_VERSION)); + m_defines = opt_defines(); + m_defines.emplace_back("NLTOOL_VERSION=" + netlist::netlist_state_t::version()); + if (opt_pre_pro()) + m_defines.emplace_back("__PREPROCESSOR_DEBUG__=1"); try { + plib::fp_signal_enabler::global_enable(opt_fp_error()); + plib::fp_signal_enabler fp_protect(plib::FP_DIVBYZERO | plib::FP_UNDERFLOW | plib::FP_OVERFLOW | plib::FP_INVALID); + pstring cmd = opt_cmd.as_string(); - if (cmd == "listdevices") - listdevices(); + if (cmd == "list-devices") + list_devices(); + else if (cmd == "list-models") + list_models(); else if (cmd == "run") run(); else if (cmd == "validate") @@ -850,28 +1393,30 @@ int tool_app_t::execute() static_compile(); else if (cmd == "header") create_header(); - else if (cmd == "docheader") - create_docheader(); + else if (cmd == "doc-header") + create_doc_header(); else if (cmd == "convert") convert(); + else if (cmd == "tests") + { + return PRUN_ALL_TESTS(opt_verb() ? ::plib::testing::loglevel::INFO + : opt_quiet() ? ::plib::testing::loglevel::ERROR + : ::plib::testing::loglevel::WARNING); + } else { - perr("Unknown command {}\n", cmd.c_str()); + std_err("Unknown command {}\n", cmd.c_str()); //FIXME: usage_short - perr(usage()); + std_err(usage()); return 1; } } - catch (netlist::nl_exception &e) - { - perr("Netlist exception caught: {}\n", e.text()); - return 2; - } catch (plib::pexception &e) { - perr("plib exception caught: {}\n", e.text()); + std_err("Exception caught: {}\n", e.text()); return 2; } + #if 0 std::cout.imbue(std::locale("de_DE.utf8")); std::cout.imbue(std::locale("C.UTF-8")); diff --git a/src/lib/netlist/prg/nlwav.cpp b/src/lib/netlist/prg/nlwav.cpp index 3974dde1f3a..7c47b2a5ddc 100644 --- a/src/lib/netlist/prg/nlwav.cpp +++ b/src/lib/netlist/prg/nlwav.cpp @@ -1,34 +1,57 @@ -// license:GPL-2.0+ +// license:BSD-3-Clause // copyright-holders:Couriersud #include "plib/pstring.h" -#include "netlist/nl_setup.h" -#include "plib/plists.h" #include "plib/pmain.h" #include "plib/ppmf.h" #include "plib/pstream.h" +#include "plib/pstrutil.h" #include <cstdio> -/* From: https://ffmpeg.org/pipermail/ffmpeg-devel/2007-October/038122.html - * The most compatible way to make a wav header for unknown length is to put - * 0xffffffff in the header. 0 as the RIFF length and 0 as the data chunk length - * is a common agreement in serious recording applications while - * still recording the file. So a playback application can determine that the - * given file is still being recorded. As soon as the recording application - * finishes the ongoing recording, it writes the correct values for RIFF lenth - * and data chunk length to the file. - */ -/* http://de.wikipedia.org/wiki/RIFF_WAVE */ +// FIXME: These are either defined in other parts or have more complex consequences +// spell-checker: words nlconst, rpad, pfmt, pexception, pbinary, dynlib, pstring, psplit, putf, pmfp +// +// Specific technical terms +// spell-checker: words vcda, vcdd + +// FIXME: see below - this belongs somewhere else! +#ifdef _WIN32 +#include <stdio.h> +#include <fcntl.h> +#include <io.h> +#endif + +// From: https://ffmpeg.org/pipermail/ffmpeg-devel/2007-October/038122.html +// The most compatible way to make a wav header for unknown length is to put +// 0xffffffff in the header. 0 as the RIFF length and 0 as the data chunk length +// is a common agreement in serious recording applications while +// still recording the file. So a playback application can determine that the +// given file is still being recorded. As soon as the recording application +// finishes the ongoing recording, it writes the correct values for RIFF length +// and data chunk length to the file. +// +// http://de.wikipedia.org/wiki/RIFF_WAVE +// + +using arena = plib::aligned_arena<>; class wav_t { public: - // XXNOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) - wav_t(std::ostream &strm, bool is_seekable, std::size_t sr, std::size_t channels) + + enum format + { + s16, + s32, + f32 + }; + + wav_t(std::ostream &strm, bool is_seekable, format fmt, std::size_t sr, std::size_t channels) : m_f(strm) , m_stream_is_seekable(is_seekable) - /* force "play" to play and warn about eof instead of being silent */ - , m_fmt(static_cast<std::uint16_t>(channels), static_cast<std::uint32_t>(sr)) + , m_format(fmt) + // force "play" to play and warn about eof instead of being silent + , m_fmt(static_cast<std::uint16_t>(channels), static_cast<std::uint32_t>(sr), fmt) , m_data(is_seekable ? 0 : 0xffffffff) { @@ -37,13 +60,13 @@ public: write(m_data); } - COPYASSIGNMOVE(wav_t, delete) + PCOPYASSIGNMOVE(wav_t, delete) ~wav_t() { if (m_stream_is_seekable) { - m_fh.filelen = m_data.len + sizeof(m_data) + sizeof(m_fh) + sizeof(m_fmt) - 8; + m_fh.file_len = m_data.len + sizeof(m_data) + sizeof(m_fh) + sizeof(m_fmt) - 8; m_f.seekp(0); write(m_fh); write(m_fmt); @@ -53,62 +76,103 @@ public: } } - std::size_t channels() { return m_fmt.channels; } - std::size_t sample_rate() { return m_fmt.sample_rate; } + std::size_t channels() const { return m_fmt.channels; } + std::size_t sample_rate() const { return m_fmt.sample_rate; } template <typename T> void write(const T &val) { - m_f.write(reinterpret_cast<const std::ostream::char_type *>(&val), sizeof(T)); + plib::ostream_write(m_f, &val, 1); + } + + template <typename T> + void write_sample_int(double sample) + { + constexpr auto type_max(static_cast<double>(plib::numeric_limits<T>::max())); + constexpr auto type_min(static_cast<double>(plib::numeric_limits<T>::min())); + + sample *= type_max; + sample = std::max(type_min, sample); + sample = std::min(type_max, sample); + const T dest(static_cast<T>(sample)); + write(dest); } - void write_sample(int *sample) + // expects normalized samples between -1.0 to 1.0 for s16 and s32 + void write_samples(double *sample) { m_data.len += m_fmt.block_align; for (std::size_t i = 0; i < channels(); i++) { - auto ps = static_cast<int16_t>(sample[i]); /* 16 bit sample, FIXME: Endianess? */ - write(ps); + switch (m_format) + { + case s16: + write_sample_int<int16_t>(sample[i]); + break; + case s32: + write_sample_int<int32_t>(sample[i]); + break; + case f32: + const auto df32(static_cast<float>(sample[i])); + write(df32); + break; + } } } private: struct riff_chunk_t { - uint8_t group_id[4] = {'R','I','F','F'}; - uint32_t filelen = 0; - uint8_t rifftype[4] = {'W','A','V','E'}; + std::array<uint8_t, 4> group_id = {{'R','I','F','F'}}; + uint32_t file_len = 0; + std::array<uint8_t, 4> riff_type = {{'W','A','V','E'}}; }; struct riff_format_t { - riff_format_t(uint16_t achannels, uint32_t asample_rate) + riff_format_t(uint16_t num_channels, uint32_t a_sample_rate, format fm) { - channels = achannels; - sample_rate = asample_rate; + switch (fm) + { + case s16: + format_tag = 0x0001; // PCM + bits_sample = 16; + break; + case s32: + format_tag = 0x0001; // PCM + bits_sample = 32; + break; + case f32: + format_tag = 0x0003; // FLOAT + bits_sample = 32; + break; + } + channels = num_channels; + sample_rate = a_sample_rate; block_align = channels * ((bits_sample + 7) / 8); bytes_per_second = sample_rate * block_align; } - uint8_t signature[4] = {'f','m','t',' '}; + std::array<uint8_t, 4> signature = {{'f','m','t',' '}}; uint32_t fmt_length = 16; - uint16_t format_tag = 0x0001; // PCM + uint16_t format_tag; uint16_t channels; uint32_t sample_rate; uint32_t bytes_per_second; uint16_t block_align; - uint16_t bits_sample = 16; + uint16_t bits_sample; }; struct riff_data_t { - riff_data_t(uint32_t alen) : len(alen) {} - uint8_t signature[4] = {'d','a','t','a'}; + explicit riff_data_t(uint32_t alen) : len(alen) {} + std::array<uint8_t, 4> signature = {{'d','a','t','a'}}; uint32_t len; // data follows }; std::ostream &m_f; bool m_stream_is_seekable; + format m_format; riff_chunk_t m_fh; riff_format_t m_fmt; @@ -119,7 +183,7 @@ private: class log_processor { public: - using callback_type = plib::pmfp<void, std::size_t, double, double>; + using callback_type = plib::pmfp<void (std::size_t, double, double)>; struct elem { @@ -135,20 +199,21 @@ public: , m_e(channels) { } - bool readmore(std::vector<plib::putf8_reader> &r) + bool read_more(std::vector<plib::putf8_reader> &r) { bool success = false; for (std::size_t i = 0; i< r.size(); i++) { if (m_e[i].need_more) { - pstring line; - m_e[i].eof = !r[i].readline(line); + putf8string line; + m_e[i].eof = !r[i].read_line(line); if (!m_e[i].eof) { // sscanf is very fast ... // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) - std::sscanf(line.c_str(), "%lf %lf", &m_e[i].t, &m_e[i].v); + if (2 != std::sscanf(line.c_str(), "%lf %lf", &m_e[i].t, &m_e[i].v)) + fprintf(stderr, "arg: <%s>\n", line.c_str()); m_e[i].need_more = false; } } @@ -157,7 +222,7 @@ public: return success; } - void process(std::vector<plib::unique_ptr<std::istream>> &is) + void process(std::vector<std::unique_ptr<std::istream>> &is) { std::vector<plib::putf8_reader> readers; for (auto &i : is) @@ -167,7 +232,7 @@ public: } pstring line; - bool more = readmore(readers); + bool more = read_more(readers); while (more) { @@ -185,10 +250,11 @@ public: m_e[mini].need_more = true; m_cb(mini, mint, m_e[mini].v); - more = readmore(readers); + more = read_more(readers); } } + private: callback_type m_cb; std::vector<elem> m_e; @@ -196,7 +262,7 @@ private: struct aggregator { - using callback_type = plib::pmfp<void, std::size_t, double, double>; + using callback_type = plib::pmfp<void (std::size_t, double, double)>; aggregator(std::size_t channels, double quantum, callback_type cb) : m_channels(channels) @@ -204,27 +270,27 @@ struct aggregator , m_cb(cb) , ct(0.0) , lt(0.0) - , outsam(channels, 0.0) - , cursam(channels, 0.0) + , output_samples(channels, 0.0) + , current_samples(channels, 0.0) { } void process(std::size_t chan, double time, double val) { while (time >= ct + m_quantum) { + ct += m_quantum; for (std::size_t i=0; i< m_channels; i++) { - outsam[i] += (ct - lt) * cursam[i]; - outsam[i] = outsam[i] / m_quantum; - m_cb(i, ct, outsam[i]); - outsam[i] = 0.0; + output_samples[i] += (ct - lt) * current_samples[i]; + output_samples[i] = output_samples[i] / m_quantum; + m_cb(i, ct, output_samples[i]); + output_samples[i] = 0.0; } lt = ct; - ct += m_quantum; } for (std::size_t i=0; i< m_channels; i++) - outsam[i] += (time-lt)*cursam[i]; + output_samples[i] += (time-lt)*current_samples[i]; lt = time; - cursam[chan] = val; + current_samples[chan] = val; } private: @@ -233,60 +299,134 @@ private: callback_type m_cb; double ct; double lt; - std::vector<double> outsam; - std::vector<double> cursam; + std::vector<double> output_samples; + std::vector<double> current_samples; +}; + +struct filter_hp +{ + using callback_type = plib::pmfp<void (std::size_t, double, double)>; + + filter_hp(double freq, bool boost, std::size_t channels, callback_type cb) + : m_cb(cb) + , m_hp_omega(plib::constants<double>::two() * plib::constants<double>::pi() * freq) + , m_boost(boost) + , m_lt(channels, 0.0) + , m_in(channels, 0.0) + , m_cap(channels, 0.0) + { } + void process(std::size_t chan, double time, double val) + { + // based on CR filter + auto dt(time - m_lt[chan]); + + double omega = ((m_boost && (time < 1.0/m_hp_omega)) ? 1e12 : m_hp_omega); + auto m(1.0 - plib::exp(-dt * omega)); + m_cap[chan] += m * (m_in[chan] - m_cap[chan]); + // out = in - vcap + m_cb(chan, time, m_in[chan] - m_cap[chan]); + + m_in[chan] = val; + m_lt[chan] = time; + } + +private: + callback_type m_cb; + double m_hp_omega; + bool m_boost; + std::vector<double> m_lt; + std::vector<double> m_in; + std::vector<double> m_cap; +}; + +struct filter_lp +{ + using callback_type = plib::pmfp<void (std::size_t, double, double)>; + + filter_lp(double freq, std::size_t channels, callback_type cb) + : m_cb(cb) + , m_lp_omega(plib::constants<double>::two() * plib::constants<double>::pi() * freq) + , m_lt(channels, 0.0) + , m_in(channels, 0.0) // lp filter + , m_cap(channels, 0.0) // hp filter + { } + void process(std::size_t chan, double time, double val) + { + // based on RC filter + auto dt(time - m_lt[chan]); + + auto m(1.0 - plib::exp(-dt * m_lp_omega)); + + m_cap[chan] += m * (m_in[chan] - m_cap[chan]); + // out = vcap + m_cb(chan, time, m_cap[chan]); + + m_in[chan] = val; + m_lt[chan] = time; + } + +private: + callback_type m_cb; + double m_lp_omega; + std::vector<double> m_lt; + std::vector<double> m_in; + std::vector<double> m_cap; }; -class wavwriter +class wav_writer { public: - wavwriter(std::ostream &fo, bool is_seekable, std::size_t channels, std::size_t sample_rate, double ampa) - : mean(channels, 0.0) - , means(channels, 0.0) - , maxsam(channels, -1e9) - , minsam(channels, 1e9) + wav_writer(std::ostream &fo, bool is_seekable, wav_t::format fmt, + std::size_t channels, std::size_t sample_rate, double amplification) + : max_samples(channels, -1e9) + , min_samples(channels, 1e9) , m_n(channels, 0) , m_samples(channels, 0) , m_last_time(0) , m_fo(fo) - , m_amp(ampa) - , m_wo(m_fo, is_seekable, sample_rate, channels) + , m_amp(amplification <= 0.0 ? 1.0e6 : amplification) + , m_auto(amplification <= 0.0) + , m_wo(m_fo, is_seekable, fmt, sample_rate, channels) { } - void process(std::size_t chan, double time, double outsam) + void process(std::size_t chan, double time, double sample) { if (time > m_last_time) - m_wo.write_sample(m_samples.data()); + m_wo.write_samples(m_samples.data()); m_last_time = time; - means[chan] += outsam; - maxsam[chan] = std::max(maxsam[chan], outsam); - minsam[chan] = std::min(minsam[chan], outsam); + max_samples[chan] = std::max(max_samples[chan], sample); + min_samples[chan] = std::min(min_samples[chan], sample); m_n[chan]++; - //mean = means / (double) m_n; - mean[chan] += 5.0 / static_cast<double>(m_wo.sample_rate()) * (outsam - mean[chan]); - outsam = (outsam - mean[chan]) * m_amp; - outsam = std::max(-32000.0, outsam); - outsam = std::min(32000.0, outsam); - m_samples[chan] = static_cast<int>(outsam); + auto val(sample * m_amp); + if (m_auto && plib::abs(val) > 1.0) + { + do + { + m_amp /= 2.0; + val = sample * m_amp; + } while (plib::abs(val) > 1.0); + // FIXME: log this in state and provide on verbose output + //printf("dynamic amplification adjusted to %f at %f\n", m_amp, time); + } + m_samples[chan] = val; } - std::vector<double> mean; - std::vector<double> means; - std::vector<double> maxsam; - std::vector<double> minsam; + std::vector<double> max_samples; + std::vector<double> min_samples; std::vector<std::size_t> m_n; - std::vector<int> m_samples; + std::vector<double> m_samples; double m_last_time; private: std::ostream &m_fo; double m_amp; + bool m_auto; wav_t m_wo; }; -class vcdwriter +class vcd_writer { public: @@ -296,7 +436,7 @@ public: ANALOG }; - vcdwriter(std::ostream &fo, const std::vector<pstring> &channels, + vcd_writer(std::ostream &fo, const std::vector<pstring> &channels, format_e format, double high_level = 2.0, double low_level = 1.0) : m_channels(channels.size()) , m_last_time(0) @@ -318,9 +458,9 @@ public: { // $var real 64 N1X1 N1X1 $end if (format == ANALOG) - write(pstring("$var real 64 ") + m_ids[i++] + " " + ch + " $end\n"); + write("$var real 64 " + m_ids[i++] + " " + ch + " $end\n"); else if (format == DIGITAL) - write(pstring("$var wire 1 ") + m_ids[i++] + " " + ch + " $end\n"); + write("$var wire 1 " + m_ids[i++] + " " + ch + " $end\n"); } write("$enddefinitions $end\n"); if (format == ANALOG) @@ -328,36 +468,37 @@ public: write("$dumpvars\n"); //r0.0 N1X1 for (i = 0; i < channels.size(); i++) - write(pstring("r0.0 ") + m_ids[i] + "\n"); + write("r0.0 " + m_ids[i] + "\n"); write("$end\n"); } } - void process(std::size_t chan, double time, double outsam) + void process(std::size_t chan, double time, double sample) { if (time > m_last_time) { - write(pstring("#") + plib::to_string(static_cast<std::int64_t>(m_last_time * 1e9)) + " "); + write("#" + plib::to_string(static_cast<std::int64_t>(m_last_time * 1e9)) + " "); write(m_buf + "\n"); m_buf = ""; m_last_time = time; } if (m_format == ANALOG) - m_buf += "r" + plib::to_string(outsam)+ " " + m_ids[chan] + " "; + m_buf += "r" + plib::to_string(sample)+ " " + m_ids[chan] + " "; else { - if (outsam >= m_high_level) - m_buf += pstring("1") + m_ids[chan] + " "; - else if (outsam <= m_low_level) - m_buf += pstring("0") + m_ids[chan] + " "; + if (sample >= m_high_level) + m_buf += "1" + m_ids[chan] + " "; + else if (sample <= m_low_level) + m_buf += "0" + m_ids[chan] + " "; } } private: void write(const pstring &line) { - m_fo.write(line.c_str(), static_cast<std::streamsize>(plib::strlen(line.c_str()))); + const putf8string u8line(line); + m_fo.write(u8line.c_str(), static_cast<std::streamsize>(plib::strlen(u8line.c_str()))); } std::size_t m_channels; @@ -371,23 +512,99 @@ private: format_e m_format; }; +class tab_writer +{ +public: + + enum format_e + { + DIGITAL, + ANALOG + }; + + tab_writer(std::ostream &fo, const std::vector<pstring> &channels, + double start, double inc, std::size_t samples) + : m_last_time(0) + , m_next_time(start) + , m_fo(fo) + , m_inc(inc) + , m_samples(samples) + , m_buf(channels.size()) + , m_n(0) + { + } + + void process(std::size_t chan, double time, double sample) + { + if (time > m_last_time) + { + if (m_n < m_samples) + { + while (m_next_time < time && m_n < m_samples) + { + pstring o; + for (auto &e : m_buf) + { + o += pstring(",") + plib::to_string(e); // FIXME: locale!! + } + write(o.substr(1) + "\n"); + m_n++; + m_next_time += m_inc; + } + } + m_last_time = time; + } + m_buf[chan] = sample; + } + +private: + void write(const pstring &line) + { + const putf8string u8line(line); + m_fo.write(u8line.c_str(), static_cast<std::streamsize>(plib::strlen(u8line.c_str()))); + } + + double m_last_time; + double m_next_time; + + std::ostream &m_fo; + std::vector<pstring> m_ids; + double m_inc; + std::size_t m_samples; + std::vector<double> m_buf; + std::size_t m_n; +}; + class nlwav_app : public plib::app { public: nlwav_app() : plib::app(), - opt_fmt(*this, "f", "format", 0, std::vector<pstring>({"wav","vcda","vcdd"}), - "output format. Available options are wav|vcda|vcdd." - " wav : multichannel wav output" - " vcda : analog VCD output" - " vcdd : digital VCD output" + opt_fmt(*this, "f", "format", 0, std::vector<pstring>({"wav16s","wav32s","wav32f","vcda","vcdd", "tab"}), + "output format. Available options are wav16s|wav32s|wav32f|vcda|vcdd|tab.\n" + " wav16s : multichannel wav output 16 bit signed\n" + " wav32s : multichannel wav output 32 bit signed\n" + " wav32f : multichannel wav output 32 bit float\n" + " vcda : analog VCD output\n" + " vcdd : digital VCD output\n" + " tab : sampled output\n" " Digital signals are created using the --high and --low options" ), opt_out(*this, "o", "output", "-", "output file"), + opt_grp1(*this, "wav options", "These options apply to wav output only"), opt_rate(*this, "r", "rate", 48000, "sample rate of output file"), - opt_amp(*this, "a", "amp", 10000.0, "amplification after mean correction (wav only)"), - opt_high(*this, "u", "high", 2.0, "minimum input for high level (vcdd only)"), - opt_low(*this, "l", "low", 1.0, "maximum input for low level (vcdd only)"), + opt_amp(*this, "a", "amp", 10000.0, "amplification after mean correction"), + opt_lowpass(*this, "", "lowpass", 20000.0, "lowpass filter frequency.\nDefault {1:.0} Hz."), + opt_highpass(*this, "", "highpass", 20.0, "highpass filter frequency.\nDefault is {1:.0} Hz."), + opt_hp_boost(*this, "", "hp-boost", "enable highpass boost to filter out initial click."), + opt_grp2(*this, "vcdd options", "These options apply to vcdd output only"), + opt_high(*this, "u", "high", 2.0, "minimum input for high level"), + opt_low(*this, "l", "low", 1.0, "maximum input for low level"), + opt_grp3(*this, "tab options", "These options apply to sampled output only"), + opt_start(*this, "s", "start", 0.0, "time when sampling starts"), + opt_inc(*this, "i", "increment", 0.001, "time between samples"), + opt_samples(*this, "n", "samples", 1000000,"number of samples"), + opt_grp4(*this, "General options", "These options always apply"), opt_verb(*this, "v", "verbose", "be verbose - this produces lots of output"), opt_quiet(*this,"q", "quiet", "be quiet - no warnings"), opt_args(*this, "input file(s)"), @@ -395,24 +612,39 @@ public: opt_help(*this, "h", "help", "display help and exit"), opt_ex1(*this, "./nlwav -f vcdd -o x.vcd log_V*", "convert all files starting with \"log_V\" into a digital vcd file"), - opt_ex2(*this, "./nlwav -f wav -o x.wav log_V*", - "convert all files starting with \"log_V\" into a multichannel wav file"), - m_outstrm(nullptr) + opt_ex2(*this, "./nlwav -f wav16s -o x.wav log_V*", + "convert all files starting with \"log_V\" into a multichannel wav file (16bit, signed)"), + opt_ex3(*this, "./nlwav -f tab -o x.tab -s 0.0000005 -i 0.000001 -n 256 log_BLUE.log", + "convert file log_BLUE.log to sampled output. First sample at 500ns " + "followed by 255 samples every micro-second.") {} int execute() override; pstring usage() override; private: - void convert_wav(); - void convert_vcd(vcdwriter::format_e format); + void convert_wav(std::ostream &output, wav_t::format fmt); + void convert_vcd(std::ostream &output, vcd_writer::format_e format); + void convert_tab(std::ostream &output); + void convert(const pstring &output_file); plib::option_str_limit<unsigned> opt_fmt; plib::option_str opt_out; + plib::option_group opt_grp1; plib::option_num<std::size_t> opt_rate; plib::option_num<double> opt_amp; + plib::option_num<double> opt_lowpass; + plib::option_num<double> opt_highpass; + plib::option_bool opt_hp_boost; + plib::option_group opt_grp2; plib::option_num<double> opt_high; plib::option_num<double> opt_low; + plib::option_group opt_grp3; + plib::option_num<double> opt_start; + plib::option_num<double> opt_inc; + plib::option_num<std::size_t> opt_samples; + + plib::option_group opt_grp4; plib::option_bool opt_verb; plib::option_bool opt_quiet; plib::option_args opt_args; @@ -420,145 +652,205 @@ private: plib::option_bool opt_help; plib::option_example opt_ex1; plib::option_example opt_ex2; - std::vector<plib::unique_ptr<std::istream>> m_instrms; - std::ostream *m_outstrm; + plib::option_example opt_ex3; + std::vector<std::unique_ptr<std::istream>> m_in_streams; }; -void nlwav_app::convert_wav() +void nlwav_app::convert_wav(std::ostream &output, wav_t::format fmt) { - double dt = 1.0 / static_cast<double>(opt_rate()); + double dt = plib::reciprocal(static_cast<double>(opt_rate())); + auto num_channels = m_in_streams.size(); - plib::unique_ptr<wavwriter> wo = plib::make_unique<wavwriter>(*m_outstrm, opt_out() != "-", m_instrms.size(), opt_rate(), opt_amp()); - plib::unique_ptr<aggregator> ago = plib::make_unique<aggregator>(m_instrms.size(), dt, aggregator::callback_type(&wavwriter::process, wo.get())); - aggregator::callback_type agcb = log_processor::callback_type(&aggregator::process, ago.get()); + auto wo = plib::make_unique<wav_writer, arena>(output, opt_out() != "-", fmt, num_channels, opt_rate(), opt_amp()); + auto ago = plib::make_unique<aggregator, arena>(num_channels, dt, aggregator::callback_type(&wav_writer::process, wo.get())); + auto fgo_hp = plib::make_unique<filter_hp, arena>(opt_highpass(), opt_hp_boost(), num_channels, filter_hp::callback_type(&aggregator::process, ago.get())); + auto fgo_lp = plib::make_unique<filter_lp, arena>(opt_lowpass(), num_channels, filter_lp::callback_type(&filter_hp::process, fgo_hp.get())); - log_processor lp(m_instrms.size(), agcb); + auto top_cb = log_processor::callback_type(&filter_lp::process, fgo_lp.get()); - lp.process(m_instrms); + log_processor lp(num_channels, top_cb); + + lp.process(m_in_streams); if (!opt_quiet()) { #if 0 - perr("Mean (low freq filter): {}\n", wo->mean); - perr("Mean (static): {}\n", wo->means / static_cast<double>(wo->m_n)); - perr("Amp + {}\n", 32000.0 / (wo->maxsam - wo->mean)); - perr("Amp - {}\n", -32000.0 / (wo->minsam - wo->mean)); + std_err("Mean (low freq filter): {}\n", wo->mean); + std_err("Mean (static): {}\n", wo->means / static_cast<double>(wo->m_n)); + std_err("Amp + {}\n", 32000.0 / (wo->max_samples - wo->mean)); + std_err("Amp - {}\n", -32000.0 / (wo->min_samples - wo->mean)); #endif } } -void nlwav_app::convert_vcd(vcdwriter::format_e format) +void nlwav_app::convert_vcd(std::ostream &output, vcd_writer::format_e format) { - plib::unique_ptr<vcdwriter> wo = plib::make_unique<vcdwriter>(*m_outstrm, opt_args(), + arena::unique_ptr<vcd_writer> wo = plib::make_unique<vcd_writer, arena>(output, opt_args(), format, opt_high(), opt_low()); - log_processor::callback_type agcb = log_processor::callback_type(&vcdwriter::process, wo.get()); + log_processor::callback_type agcb = log_processor::callback_type(&vcd_writer::process, wo.get()); - log_processor lp(m_instrms.size(), agcb); + log_processor lp(m_in_streams.size(), agcb); - lp.process(m_instrms); + lp.process(m_in_streams); if (!opt_quiet()) { #if 0 - perr("Mean (low freq filter): {}\n", wo->mean); - perr("Mean (static): {}\n", wo->means / static_cast<double>(wo->m_n)); - perr("Amp + {}\n", 32000.0 / (wo->maxsam - wo->mean)); - perr("Amp - {}\n", -32000.0 / (wo->minsam - wo->mean)); + std_err("Mean (low freq filter): {}\n", wo->mean); + std_err("Mean (static): {}\n", wo->means / static_cast<double>(wo->m_n)); + std_err("Amp + {}\n", 32000.0 / (wo->max_samples - wo->mean)); + std_err("Amp - {}\n", -32000.0 / (wo->min_samples - wo->mean)); #endif } } +void nlwav_app::convert_tab(std::ostream &output) +{ + + auto wo = plib::make_unique<tab_writer, arena>(output, opt_args(), + opt_start(), opt_inc(), opt_samples()); + log_processor::callback_type agcb = log_processor::callback_type(&tab_writer::process, wo.get()); + + log_processor lp(m_in_streams.size(), agcb); + + lp.process(m_in_streams); + +} + + pstring nlwav_app::usage() { return help("Convert netlist log files into wav files.\n", "nlwav [OPTION] ... [FILE] ..."); } +template <typename F> +static void open_ostream_and_exec(const pstring &fname, bool binary, F func) +{ + if (fname != "-") + { + // FIXME: binary depends on format! + plib::ofstream output_stream(plib::filesystem::u8path(fname), + binary ? (std::ios::out | std::ios::binary) : std::ios::out); + if (output_stream.fail()) + throw plib::file_open_e(fname); + output_stream.imbue(std::locale::classic()); + func(output_stream); + } + else + { + std::cout.imbue(std::locale::classic()); + // FIXME: switch to binary on windows +#ifdef _WIN32 + _setmode(_fileno(stdout), _O_BINARY); +#endif + func(std::cout); + } +} + +void nlwav_app::convert(const pstring &output_file) +{ + switch (opt_fmt()) + { + case 0: + open_ostream_and_exec(output_file, true, [this](std::ostream &output) { convert_wav(output, wav_t::s16); }); + break; + case 1: + open_ostream_and_exec(output_file, true, [this](std::ostream &output) { convert_wav(output, wav_t::s32); }); + break; + case 2: + open_ostream_and_exec(output_file, true, [this](std::ostream &output) { convert_wav(output, wav_t::f32); }); + break; + case 3: + open_ostream_and_exec(output_file, false, [this](std::ostream &output) { convert_vcd(output, vcd_writer::ANALOG); }); + break; + case 4: + open_ostream_and_exec(output_file, false, [this](std::ostream &output) { convert_vcd(output, vcd_writer::DIGITAL); }); + break; + case 5: + open_ostream_and_exec(output_file, false, [this](std::ostream &output) { convert_tab(output); }); + break; + default: + // tease compiler - can't happen + break; + } +} int nlwav_app::execute() { - for (auto &i : opt_args()) - pout(pstring("Hello : ") + i + "\n"); if (opt_help()) { - pout(usage()); + std_out(usage()); return 0; } if (opt_version()) { - pout( + std_out( "nlwav (netlist) 0.1\n" - "Copyright (C) 2019 Couriersud\n" - "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.\n" + "Copyright (C) 2021 Couriersud\n" + "License BSD-3-Clause\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n\n" "Written by Couriersud.\n"); return 0; } - m_outstrm = (opt_out() == "-" ? &std::cout : plib::pnew<std::ofstream>(plib::filesystem::u8path(opt_out()))); - if (m_outstrm->fail()) - throw plib::file_open_e(opt_out()); - m_outstrm->imbue(std::locale::classic()); - - for (auto &oi: opt_args()) + try { - plib::unique_ptr<std::istream> fin; - - if (oi == "-") + for (const auto &oi: opt_args()) { - auto temp(plib::make_unique<std::stringstream>()); - plib::copystream(*temp, std::cin); - fin = std::move(temp); + std::unique_ptr<std::istream> fin; + if (oi == "-") + { + auto temp(std::make_unique<std::stringstream>()); + plib::copy_stream(*temp, std::cin); + fin = std::move(temp); + } + else + { + fin = std::make_unique<plib::ifstream>(plib::filesystem::u8path(oi), std::ios::in); + if (fin->fail()) + throw plib::file_open_e(oi); + } + fin->imbue(std::locale::classic()); + m_in_streams.push_back(std::move(fin)); } - else - fin = plib::make_unique<std::ifstream>(plib::filesystem::u8path(oi)); - fin->imbue(std::locale::classic()); - m_instrms.push_back(std::move(fin)); - } - switch (opt_fmt()) + convert(opt_out()); + } + catch (plib::pexception &e) { - case 0: - convert_wav(); break; - case 1: - convert_vcd(vcdwriter::ANALOG); break; - case 2: - convert_vcd(vcdwriter::DIGITAL); break; - default: - // tease compiler - can't happen - break; + std_err("Exception caught: {}\n", e.text()); + return 1; } - - if (opt_out() != "-") - plib::pdelete(m_outstrm); - return 0; } PMAIN(nlwav_app) -/* -Der Daten-Abschnitt enth??lt die Abtastwerte: -Offset L??nge Inhalt Beschreibung -36 (0x24) 4 'data' Header-Signatur -40 (0x28) 4 <length> L??nge des Datenblocks, max. <Dateigr????e>?????????44 - -0 (0x00) char 4 'RIFF' -4 (0x04) unsigned 4 <Dateigr????e>?????????8 -8 (0x08) char 4 'WAVE' - -Der fmt-Abschnitt (24 Byte) beschreibt das Format der einzelnen Abtastwerte: -Offset L??nge Inhalt Beschreibung -12 (0x0C) 4 'fmt ' Header-Signatur (folgendes Leerzeichen beachten) -16 (0x10) 4 <fmt length> L??nge des restlichen fmt-Headers (16 Bytes) -20 (0x14) 2 <format tag> Datenformat der Abtastwerte (siehe separate Tabelle weiter unten) -22 (0x16) 2 <channels> Anzahl der Kan??le: 1 = mono, 2 = stereo; mittlerweile sind auch mehr als 2 Kan??le (z. B. f??r Raumklang) m??glich.[2] -24 (0x18) 4 <sample rate> Samples pro Sekunde je Kanal (z. B. 44100) -28 (0x1C) 4 <bytes/second> Abtastrate????????Frame-Gr????e -32 (0x20) 2 <block align> Frame-Gr????e = <Anzahl der Kan??le>????????((<Bits/Sample (eines Kanals)>???+???7)???/???8) (Division ohne Rest) -34 (0x22) 2 <bits/sample> Anzahl der Datenbits pro Samplewert je Kanal (z. B. 12) -*/ +// spell-checker:disable +// +// Der Daten-Abschnitt enth??lt die Abtastwerte: +// Offset L??nge Inhalt Beschreibung +// 36 (0x24) 4 'data' Header-Signatur +// 40 (0x28) 4 <length> L??nge des Datenblocks, max. <Dateigr????e>?????????44 +// +// 0 (0x00) char 4 'RIFF' +// 4 (0x04) unsigned 4 <Dateigr????e>?????????8 +// 8 (0x08) char 4 'WAVE' +// +// Der fmt-Abschnitt (24 Byte) beschreibt das Format der einzelnen Abtastwerte: +// Offset L??nge Inhalt Beschreibung +// 12 (0x0C) 4 'fmt ' Header-Signatur (folgendes Leerzeichen beachten) +// 16 (0x10) 4 <fmt length> L??nge des restlichen fmt-Headers (16 Bytes) +// 20 (0x14) 2 <format tag> Datenformat der Abtastwerte (siehe separate Tabelle weiter unten) +// 22 (0x16) 2 <channels> Anzahl der Kan??le: 1 = mono, 2 = stereo; mittlerweile sind auch mehr als 2 Kan??le (z. B. f??r Raumklang) m??glich.[2] +// 24 (0x18) 4 <sample rate> Samples pro Sekunde je Kanal (z. B. 44100) +// 28 (0x1C) 4 <bytes/second> Abtastrate????????Frame-Gr????e +// 32 (0x20) 2 <block align> Frame-Gr????e = <Anzahl der Kan??le>????????((<Bits/Sample (eines Kanals)>???+???7)???/???8) (Division ohne Rest) +// 34 (0x22) 2 <bits/sample> Anzahl der Datenbits pro Samplewert je Kanal (z. B. 12) +// +// spell-checker:enable |