From 7c6dac7fa29ccd84da890aee7a0b1004dcd93d8b Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Sat, 4 Mar 2023 23:02:48 +0100 Subject: Align CIF Count and timestamp on startup --- src/DabMultiplexer.cpp | 73 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 21 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index fe7b156..a658262 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -99,25 +99,52 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - /* Ensure edi_time and TIST represent current time. Keep - * a granularity of 24ms, which corresponds to the - * duration of an ETI frame, to get nicer timestamps. + /* At startup, derive edi_time, TIST and CIF count such that there is + * a consistency across mux restarts. Ensure edi_time and TIST represent + * current time. + * + * Every 6s, FCT overflows. m_currentFrame overflows at 5000 every 120s. + * + * Keep a granularity of 24ms, which corresponds to the duration of an ETI + * frame, to get nicer timestamps. */ using Sec = chrono::seconds; const auto now = chrono::system_clock::now(); - m_edi_time = chrono::system_clock::to_time_t(chrono::time_point_cast(now)); - auto offset = now - chrono::time_point_cast(now); + const time_t t_now = chrono::system_clock::to_time_t(chrono::time_point_cast(now)); + + m_edi_time = t_now - (t_now % 6); + m_currentFrame = 0; + time_t edi_time_at_cif0 = t_now - (t_now % 120); + while (edi_time_at_cif0 < m_edi_time) { + edi_time_at_cif0 += 6; + m_currentFrame += 250; + } + + if (edi_time_at_cif0 != m_edi_time) { + throw std::logic_error("Invalid startup offset calculation for CIF!"); + } + + const auto offset = now - chrono::time_point_cast(now); if (offset >= chrono::seconds(1)) { throw std::logic_error("Invalid startup offset calculation for TIST! " + to_string(chrono::duration_cast(offset).count()) + " ms"); } + + int64_t offset_ms = chrono::duration_cast(offset).count(); + offset_ms += 1000 * (t_now - m_edi_time); + m_timestamp = 0; - while (offset >= chrono::milliseconds(24)) { + while (offset_ms >= 24) { increment_timestamp(); - offset -= chrono::milliseconds(24); + m_currentFrame++; + offset_ms -= 24; } + etiLog.log(info, "Startup CIF Count %i with timestamp: %d + %f", + m_currentFrame, m_edi_time, + (m_timestamp & 0xFFFFFF) / 16384000.0); + // Try to load offset once bool tist_enabled = m_pt.get("general.tist", false); @@ -415,8 +442,12 @@ void DabMultiplexer::mux_frame(std::vector >& outputs //****** Field FSYNC *****// // See ETS 300 799, 6.2.1.2 - sync ^= 0xffffff; - etiSync->FSYNC = sync; + if ((m_currentFrame & 1) == 0) { + etiSync->FSYNC = ETI_FSYNC1; + } + else { + etiSync->FSYNC = ETI_FSYNC1 ^ 0xffffff; + } /********************************************************************** *********** Section LIDATA of ETI(NI, G703) ********************** @@ -430,8 +461,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs //****** FCT ******// // Incremente for each frame, overflows at 249 - fc->FCT = currentFrame % 250; - edi_tagDETI.dlfc = currentFrame % 5000; + fc->FCT = m_currentFrame % 250; + edi_tagDETI.dlfc = m_currentFrame % 5000; //****** FICF ******// // Fast Information Channel Flag, 1 bit, =1 if FIC present @@ -448,7 +479,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs /* Frame Phase, 3 bit counter, tells the COFDM generator * when to insert the TII. Is also used by the MNSC. */ - fc->FP = edi_tagDETI.fp = currentFrame & 0x7; + fc->FP = edi_tagDETI.fp = m_currentFrame & 0x7; //****** MID ******// //Mode Identity, 2 bits, 01 ModeI, 10 modeII, 11 ModeIII, 00 ModeIV @@ -580,9 +611,9 @@ void DabMultiplexer::mux_frame(std::vector >& outputs edi_tagDETI.fic_length = FICL * 4; // Insert all FIBs - fig_carousel.update(currentFrame); + fig_carousel.update(m_currentFrame); const bool fib3_present = (ensemble->transmission_mode == TransmissionMode_e::TM_III); - index += fig_carousel.write_fibs(&etiFrame[index], currentFrame % 4, fib3_present); + index += fig_carousel.write_fibs(&etiFrame[index], m_currentFrame % 4, fib3_present); /********************************************************************** ****** Input Data Reading ******************************************* @@ -599,7 +630,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs if (result < 0) { etiLog.log(info, "Subchannel %d read failed at ETI frame number: %d", - subchannel->id, currentFrame); + subchannel->id, m_currentFrame); } // save pointer to Audio or Data Stream into correct TagESTn for EDI @@ -661,7 +692,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs output->setMetadata(md_edi_time); shared_ptr md_dlfc = - make_shared(currentFrame % 5000); + make_shared(m_currentFrame % 5000); output->setMetadata(md_dlfc); } } @@ -726,20 +757,20 @@ void DabMultiplexer::mux_frame(std::vector >& outputs /********************************************************************** *********** Output a small message ********************************* **********************************************************************/ - if (currentFrame % 100 == 0) { + if (m_currentFrame % 100 == 0) { if (enableTist) { etiLog.log(info, "ETI frame number %i Timestamp: %d + %f", - currentFrame, edi_time, + m_currentFrame, edi_time, (m_timestamp & 0xFFFFFF) / 16384000.0); } else { etiLog.log(info, "ETI frame number %i Time: %d, no TIST", - currentFrame, edi_time); + m_currentFrame, edi_time); } } #endif - currentFrame++; + m_currentFrame++; } void DabMultiplexer::print_info() @@ -775,7 +806,7 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co { stringstream ss; if (parameter == "frames") { - ss << currentFrame; + ss << m_currentFrame; } else if (parameter == "tist_offset") { ss << m_tist_offset; -- cgit v1.2.3 From 966a696e55f2112bb44d95b2b22a7e20423d1bad Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 3 May 2023 15:24:33 +0200 Subject: Ensure EDI inserts ESTn tags in the config file order Even though the spec says EDI decoders shall not assume any particular ordering, we've seen some that misbehave --- src/DabMultiplexer.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index a658262..fb5ec45 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -408,7 +408,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs // For EDI, save ETI(LI) Management data into a TAG Item DETI edi::TagDETI edi_tagDETI; edi::TagStarPTR edi_tagStarPtr("DETI"); - map edi_subchannelToTag; + vector edi_est_tags; // The above Tag Items will be assembled into a TAG Packet edi::TagPacket edi_tagpacket(edi_conf.tagpacket_alignment); @@ -541,7 +541,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs tag_ESTn.mst_data = nullptr; assert(subchannel->getSizeByte() % 8 == 0); - edi_subchannelToTag[subchannel.get()] = tag_ESTn; + edi_est_tags.push_back(std::move(tag_ESTn)); index += 4; } @@ -619,8 +619,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs ****** Input Data Reading ******************************************* **********************************************************************/ - for (auto subchannel : ensemble->subchannels) { - edi::TagESTn& tag = edi_subchannelToTag[subchannel.get()]; + for (size_t i = 0; i < ensemble->subchannels.size(); i++) { + auto& subchannel = ensemble->subchannels[i]; int sizeSubchannel = subchannel->getSizeByte(); // no need to check enableTist because we always increment the timestamp @@ -634,7 +634,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs } // save pointer to Audio or Data Stream into correct TagESTn for EDI - tag.mst_data = &etiFrame[index]; + edi_est_tags[i].mst_data = &etiFrame[index]; index += sizeSubchannel; } @@ -746,8 +746,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs edi_tagpacket.tag_items.push_back(&edi_tagStarPtr); edi_tagpacket.tag_items.push_back(&edi_tagDETI); - for (auto& tag : edi_subchannelToTag) { - edi_tagpacket.tag_items.push_back(&tag.second); + for (auto& tag : edi_est_tags) { + edi_tagpacket.tag_items.push_back(&tag); } edi_sender->write(edi_tagpacket); -- cgit v1.2.3 From 0b7d58968b37dc9d36a90d3fb439891a57b81a18 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 17 Jan 2024 09:48:56 +0100 Subject: Update ClockTAI and RemoteControl --- Makefile.am | 15 +- lib/ClockTAI.cpp | 422 ++++++++++++++++++++++++++++--------------- lib/ClockTAI.h | 61 +++++-- lib/Json.cpp | 122 +++++++++++++ lib/Json.h | 63 +++++++ lib/RemoteControl.cpp | 57 ++++-- lib/RemoteControl.h | 12 +- lib/charset/README | 2 +- lib/charset/utf8.h | 80 ++++---- lib/charset/utf8/checked.h | 176 ++++++++++-------- lib/charset/utf8/core.h | 275 ++++++++++++++++++++++------ lib/charset/utf8/cpp11.h | 70 +++++++ lib/charset/utf8/cpp17.h | 96 ++++++++++ lib/charset/utf8/cpp20.h | 124 +++++++++++++ lib/charset/utf8/unchecked.h | 163 +++++++++++------ src/DabMultiplexer.cpp | 10 +- src/DabMultiplexer.h | 4 +- src/MuxElements.cpp | 58 +++++- src/MuxElements.h | 10 +- src/input/Edi.cpp | 21 ++- src/input/Edi.h | 3 +- src/input/Zmq.cpp | 12 ++ src/input/Zmq.h | 1 + 23 files changed, 1458 insertions(+), 399 deletions(-) create mode 100644 lib/Json.cpp create mode 100644 lib/Json.h create mode 100644 lib/charset/utf8/cpp11.h create mode 100644 lib/charset/utf8/cpp17.h create mode 100644 lib/charset/utf8/cpp20.h (limited to 'src/DabMultiplexer.cpp') diff --git a/Makefile.am b/Makefile.am index f5e9c76..d512a16 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,7 +1,7 @@ # Copyright (C) 2008, 2009 Her Majesty the Queen in Right of Canada # (Communications Research Center Canada) # -# Copyright (C) 2018 Matthias P. Braendli +# Copyright (C) 2024 Matthias P. Braendli # http://opendigitalradio.org # This file is part of ODR-DabMux. @@ -49,6 +49,9 @@ lib_charset_sources = lib/charset/charset.cpp \ lib/charset/utf8/checked.h \ lib/charset/utf8/core.h \ lib/charset/utf8/unchecked.h \ + lib/charset/utf8/cpp11.h \ + lib/charset/utf8/cpp17.h \ + lib/charset/utf8/cpp20.h \ lib/charset/utf8.h odr_dabmux_CFLAGS =-Wall $(INCLUDE) $(PTHREAD_CFLAGS) $(GITVERSION_FLAGS) @@ -150,6 +153,8 @@ odr_dabmux_SOURCES =src/DabMux.cpp \ lib/Log.cpp \ lib/RemoteControl.cpp \ lib/RemoteControl.h \ + lib/Json.h \ + lib/Json.cpp \ lib/edi/STIDecoder.cpp \ lib/edi/STIDecoder.hpp \ lib/edi/STIWriter.cpp \ @@ -191,13 +196,15 @@ odr_zmq2farsync_SOURCES = src/zmq2farsync/zmq2farsync.cpp \ lib/Log.cpp \ lib/RemoteControl.cpp \ lib/RemoteControl.h \ + lib/Json.h \ + lib/Json.cpp \ lib/Socket.h \ lib/Socket.cpp \ lib/zmq.hpp odr_zmq2farsync_LDADD = $(ZMQ_LIBS) odr_zmq2farsync_CFLAGS = -Wall $(ZMQ_CPPFLAGS) $(PTHREAD_CFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) -odr_zmq2farsync_CXXFLAGS = -Wall -std=c++11 $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) $(ZMQ_CPPFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) +odr_zmq2farsync_CXXFLAGS = -Wall $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) $(ZMQ_CPPFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) odr_zmq2edi_SOURCES = src/zmq2edi/zmq2edi.cpp \ src/zmq2edi/EDISender.h \ @@ -221,6 +228,8 @@ odr_zmq2edi_SOURCES = src/zmq2edi/zmq2edi.cpp \ lib/Log.cpp \ lib/RemoteControl.cpp \ lib/RemoteControl.h \ + lib/Json.h \ + lib/Json.cpp \ lib/crc.h \ lib/crc.c \ lib/ReedSolomon.h \ @@ -233,7 +242,7 @@ odr_zmq2edi_SOURCES = src/zmq2edi/zmq2edi.cpp \ odr_zmq2edi_LDADD = $(ZMQ_LIBS) $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) $(BOOST_SYSTEM_LIB) odr_zmq2edi_CFLAGS = -Wall $(ZMQ_CPPFLAGS) $(PTHREAD_CFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) -odr_zmq2edi_CXXFLAGS = -Wall -std=c++11 $(PTHREAD_LIBS) $(ZMQ_CPPFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) +odr_zmq2edi_CXXFLAGS = -Wall $(PTHREAD_LIBS) $(ZMQ_CPPFLAGS) $(GITVERSION_FLAGS) $(INCLUDE) man_MANS = man/odr-dabmux.1 \ man/odr-zmq2edi.1 diff --git a/lib/ClockTAI.cpp b/lib/ClockTAI.cpp index a244aba..c32c58d 100644 --- a/lib/ClockTAI.cpp +++ b/lib/ClockTAI.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -33,6 +33,7 @@ * ClockTAI.cpp Log.cpp RemoteControl.cpp -lboost_system -o taitest && ./taitest */ +#include #ifdef HAVE_CONFIG_H # include "config.h" #endif @@ -61,22 +62,15 @@ using namespace std; -#ifdef DOWNLOADED_IN_THE_PAST_TEST -static bool wait_longer = true; -#endif - constexpr int refresh_retry_interval_hours = 1; // Offset between NTP time and POSIX time: // timestamp_unix = timestamp_ntp - NTP_UNIX_OFFSET constexpr int64_t NTP_UNIX_OFFSET = 2208988800L; -constexpr int64_t MONTH = 3600 * 24 * 30; - -// leap seconds insertion bulletin is available from the IETF and in the TZ -// distribution -static array default_tai_urls = { - "https://www.ietf.org/timezones/data/leap-seconds.list", +// leap seconds insertion bulletin was previously available from the IETF and in the TZ +// distribution, but in late 2023 IETF stopped serving the file. +static array default_tai_urls = { "https://raw.githubusercontent.com/eggert/tz/master/leap-seconds.list", }; @@ -84,6 +78,32 @@ static array default_tai_urls = { // /var/tmp "must not be deleted when the system is booted." static const char *tai_cache_location = "/var/tmp/odr-leap-seconds.cache"; +static string join_string_with_pipe(const vector& vec) +{ + stringstream ss; + for (auto it = vec.cbegin(); it != vec.cend(); ++it) { + ss << *it; + if (it + 1 != vec.cend()) { + ss << "|"; + } + } + return ss.str(); +} + +static vector split_pipe_separated_string(const string& s) +{ + stringstream ss; + ss << s; + + string elem; + vector components; + while (getline(ss, elem, '|')) { + components.push_back(elem); + } + return components; +} + + // read TAI offset from a valid bulletin in IETF format static int parse_ietf_bulletin(const std::string& bulletin) { @@ -146,20 +166,31 @@ static int parse_ietf_bulletin(const std::string& bulletin) throw runtime_error("No data in TAI bulletin"); } + // With the current evolution of the offset, we're probably going + // to reach 500 long after DAB gets replaced by another standard. + // Or maybe leap seconds get abolished first... + if (tai_utc_offset < 0 or tai_utc_offset > 500) { + throw runtime_error("Unreasonable TAI-UTC offset calculated"); + } + return tai_utc_offset; } +int64_t BulletinState::expires_in() const { + time_t now = time(nullptr); + return expires_at - now; +} -struct bulletin_state { - bool valid = false; - int64_t expiry = 0; - int offset = 0; +bool BulletinState::usable() const { + return valid and expires_in() > 0; +} - bool usable() const { return valid and expiry > 0; } - bool expires_soon() const { return usable() and expiry < 1 * MONTH; } -}; +bool BulletinState::expires_soon() const { + constexpr int64_t MONTH = 3600 * 24 * 30; + return usable() and expires_in() < 1 * MONTH; +} -static bulletin_state parse_bulletin(const string& bulletin) +BulletinState Bulletin::state() const { // The bulletin contains one line that specifies an expiration date // in NTP time. If that point in time is in the future, we consider @@ -168,11 +199,22 @@ static bulletin_state parse_bulletin(const string& bulletin) // The entry looks like this: //#@ 3707596800 - bulletin_state ret; + BulletinState ret; - std::regex regex_expiration(R"(#@\s+([0-9]+))"); + if (std::holds_alternative(bulletin_or_override)) { + const auto& od = std::get(bulletin_or_override); + ret.offset = od.offset; + ret.expires_at = od.expires_at; + ret.valid = true; +#ifdef TAI_TEST + etiLog.level(debug) << "state() from Override!"; +#endif + return ret; + } - time_t now = time(nullptr); + const auto& bulletin = std::get(bulletin_or_override); + + std::regex regex_expiration(R"(#@\s+([0-9]+))"); stringstream ss(bulletin); @@ -190,20 +232,29 @@ static bulletin_state parse_bulletin(const string& bulletin) const int64_t expiry_unix = std::stoll(expiry_data_str) - NTP_UNIX_OFFSET; #ifdef TAI_TEST - etiLog.level(info) << "Bulletin expires in " << expiry_unix - now; + { + // Do not use `now` for anything else but debugging, otherwise it + // breaks the cache. + time_t now = time(nullptr); + etiLog.level(debug) << "Bulletin " << + get_source() << " expires in " << expiry_unix - now; + } #endif - ret.expiry = expiry_unix - now; + ret.expires_at = expiry_unix; ret.offset = parse_ietf_bulletin(bulletin); ret.valid = true; } catch (const invalid_argument& e) { - etiLog.level(warn) << "Could not parse bulletin: " << e.what(); + etiLog.level(warn) << "Could not parse bulletin from " << + get_source() << ": " << e.what(); } catch (const out_of_range&) { - etiLog.level(warn) << "Parse bulletin: conversion is out of range"; + etiLog.level(warn) << "Parse bulletin from " << + get_source() << ": conversion is out of range"; } catch (const runtime_error& e) { - etiLog.level(warn) << "Parse bulletin: " << e.what(); + etiLog.level(warn) << "Parse bulletin from " << + get_source() << ": " << e.what(); } break; } @@ -224,9 +275,9 @@ static size_t fill_bulletin(char *ptr, size_t size, size_t nmemb, void *ctx) return len; } -static string download_tai_utc_bulletin(const char* url) +Bulletin Bulletin::download_from_url(const char* url) { - stringstream bulletin; + stringstream bulletin_data; #ifdef HAVE_CURL CURL *curl; @@ -238,7 +289,7 @@ static string download_tai_utc_bulletin(const char* url) /* Tell libcurl to follow redirection */ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fill_bulletin); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bulletin); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bulletin_data); res = curl_easy_perform(curl); /* always cleanup ! */ @@ -249,19 +300,39 @@ static string download_tai_utc_bulletin(const char* url) string(curl_easy_strerror(res))); } } - return bulletin.str(); + Bulletin bulletin; + bulletin.source = url; + bulletin.bulletin_or_override = bulletin_data.str(); + return bulletin; #else throw runtime_error("Cannot download TAI Clock information without cURL"); #endif // HAVE_CURL } -static string load_bulletin_from_file(const char* cache_filename) +Bulletin Bulletin::create_with_fixed_offset(int offset) { + Bulletin bulletin; + bulletin.source = "manual override"; + + OverrideData od; + od.offset = offset; + time_t now = time(nullptr); + // 10 years is probably equivalent to infinity in this case... + od.expires_at = now + 10L * 365 * 24 * 3600; + bulletin.bulletin_or_override = od; + return bulletin; +} + +Bulletin Bulletin::load_from_file(const char* cache_filename) +{ + Bulletin bulletin; + bulletin.source = cache_filename; + int fd = open(cache_filename, O_RDWR); // lockf requires O_RDWR if (fd == -1) { etiLog.level(error) << "TAI-UTC bulletin open cache for reading: " << strerror(errno); - return ""; + return bulletin; } lseek(fd, 0, SEEK_SET); @@ -280,7 +351,7 @@ static string load_bulletin_from_file(const char* cache_filename) close(fd); etiLog.level(error) << "TAI-UTC bulletin read cache: " << strerror(errno); - return ""; + return bulletin; } copy(buf.data(), buf.data() + ret, back_inserter(new_bulletin_data)); @@ -288,7 +359,7 @@ static string load_bulletin_from_file(const char* cache_filename) close(fd); - return string{new_bulletin_data.data(), new_bulletin_data.size()}; + bulletin.bulletin_or_override = string{new_bulletin_data.data(), new_bulletin_data.size()}; } else { etiLog.level(error) << @@ -296,13 +367,25 @@ static string load_bulletin_from_file(const char* cache_filename) strerror(errno); close(fd); } - return ""; + return bulletin; +} + +void Bulletin::clear_expiry_if_overridden() +{ + if (std::holds_alternative(bulletin_or_override)) { + auto& od = std::get(bulletin_or_override); + time_t now = time(nullptr); + od.expires_at = now; + } } ClockTAI::ClockTAI(const std::vector& bulletin_urls) : RemoteControllable("clocktai") { + RC_ADD_PARAMETER(tai_utc_offset, "TAI-UTC offset"); RC_ADD_PARAMETER(expiry, "Number of seconds until TAI Bulletin expires"); + RC_ADD_PARAMETER(expires_at, "UNIX timestamp when TAI Bulletin expires"); + RC_ADD_PARAMETER(url, "URLs used to fetch the bulletin, separated by pipes"); if (bulletin_urls.empty()) { etiLog.level(debug) << "Initialising default TAI Bulletin URLs"; @@ -315,138 +398,119 @@ ClockTAI::ClockTAI(const std::vector& bulletin_urls) : m_bulletin_urls = bulletin_urls; } - for (const auto& url : m_bulletin_urls) { - etiLog.level(info) << "TAI Bulletin URL: '" << url << "'"; - } + etiLog.level(debug) << "ClockTAI uses bulletin URL: '" << join_string_with_pipe(m_bulletin_urls) << "'"; } -int ClockTAI::get_valid_offset() +BulletinState ClockTAI::get_valid_offset() { - int offset = 0; - bool offset_valid = false; - bool refresh_m_bulletin = false; - std::unique_lock lock(m_data_mutex); - const auto state = parse_bulletin(m_bulletin); - if (state.usable()) { + const auto state = m_bulletin.state(); #if TAI_TEST - etiLog.level(info) << "Bulletin already valid"; + etiLog.level(info) << "TAI get_valid_offset STEP 1 "; + etiLog.level(info) << " " << m_bulletin.get_source() << " " << + state.valid << " " << state.usable() << " " << state.expires_in(); #endif - offset = state.offset; - offset_valid = true; - - refresh_m_bulletin = state.expires_soon(); - } - else { - refresh_m_bulletin = true; + if (state.usable()) { + return state; } - if (refresh_m_bulletin) { - const auto cache_bulletin = load_bulletin_from_file(tai_cache_location); #if TAI_TEST - etiLog.level(info) << "Loaded cache bulletin with " << - std::count_if(cache_bulletin.cbegin(), cache_bulletin.cend(), - [](const char c){ return c == '\n'; }) << " lines"; + etiLog.level(info) << "TAI get_valid_offset STEP 2"; #endif - const auto cache_state = parse_bulletin(cache_bulletin); + const auto cache_bulletin = Bulletin::load_from_file(tai_cache_location); + const auto cache_state = cache_bulletin.state(); + if (cache_state.usable()) { + m_bulletin = cache_bulletin; +#if TAI_TEST + etiLog.level(info) << "TAI get_valid_offset STEP 2 take cache"; +#endif + return cache_state; + } - if (cache_state.usable() and not cache_state.expires_soon()) { - m_bulletin = cache_bulletin; - offset = cache_state.offset; - offset_valid = true; #if TAI_TEST - etiLog.level(info) << "Bulletin from cache valid with offset=" << offset; + etiLog.level(info) << "TAI get_valid_offset STEP 3"; #endif - } - else { - for (const auto& url : m_bulletin_urls) { - try { + + vector bulletins({m_bulletin, cache_bulletin}); + + for (const auto& url : m_bulletin_urls) { + try { #if TAI_TEST - etiLog.level(info) << "Load bulletin from " << url; + etiLog.level(info) << "Load bulletin from " << url; #endif - const auto new_bulletin = download_tai_utc_bulletin(url.c_str()); - const auto new_state = parse_bulletin(new_bulletin); - if (new_state.usable()) { - m_bulletin = new_bulletin; - offset = new_state.offset; - offset_valid = true; - - etiLog.level(debug) << "Loaded valid TAI Bulletin from " << - url << " giving offset=" << offset; - } - else { - etiLog.level(debug) << "Skipping invalid TAI bulletin from " - << url; - } - } - catch (const runtime_error& e) { - etiLog.level(warn) << - "TAI-UTC offset could not be retrieved from " << - url << " : " << e.what(); - } + const auto new_bulletin = Bulletin::download_from_url(url.c_str()); + bulletins.push_back(new_bulletin); - if (offset_valid) { - update_cache(tai_cache_location); - break; - } + const auto new_state = new_bulletin.state(); + if (new_state.usable()) { + m_bulletin = new_bulletin; + new_bulletin.store_to_cache(tai_cache_location); + + etiLog.level(debug) << "Loaded valid TAI Bulletin from " << + url << " giving offset=" << new_state.offset; + return new_state; + } + else { + etiLog.level(debug) << "Skipping invalid TAI bulletin from " + << url; } } + catch (const runtime_error& e) { + etiLog.level(warn) << + "TAI-UTC offset could not be retrieved from " << + url << " : " << e.what(); + } } - if (offset_valid) { - // With the current evolution of the offset, we're probably going - // to reach 500 long after DAB gets replaced by another standard. - if (offset < 0 or offset > 500) { - stringstream ss; - ss << "TAI offset " << offset << " out of range"; - throw range_error(ss.str()); - } +#if TAI_TEST + etiLog.level(info) << "TAI get_valid_offset STEP 4"; +#endif - return offset; - } - else { - // Try again later - throw download_failed(); + // Maybe we have a valid but expired bulletin available. + // Place bulletins with largest expiry first + std::sort(bulletins.begin(), bulletins.end(), + [](const Bulletin& a, const Bulletin& b) { + return a.state().expires_at > b.state().expires_at; }); + + for (const auto& bulletin : bulletins) { + const auto& state = bulletin.state(); + if (state.valid) { + etiLog.level(warn) << "Taking TAI-UTC offset from expired bulletin from " << + bulletin.get_source() << " : " << state.offset << "s expired " << + state.expires_in() << "s ago"; + m_bulletin = bulletin; + return state; + } } + + throw download_failed(); } int ClockTAI::get_offset() { using namespace std::chrono; - const auto time_now = system_clock::now(); + const auto time_now = steady_clock::now(); std::unique_lock lock(m_data_mutex); - if (not m_offset_valid) { -#ifdef DOWNLOADED_IN_THE_PAST_TEST - // Assume we've downloaded it in the past: - - m_offset = 37; // Valid in early 2017 - m_offset_valid = true; - - // Simulate requiring a new download - m_bulletin_refresh_time = time_now - hours(24 * 40); -#else + if (not m_state.has_value()) { // First time we run we must block until we know // the offset lock.unlock(); try { - m_offset = get_valid_offset(); + m_state = get_valid_offset(); } catch (const download_failed&) { throw runtime_error("Unable to download TAI bulletin"); } lock.lock(); - m_offset_valid = true; - m_bulletin_refresh_time = time_now; -#endif - etiLog.level(info) << - "Initialised TAI-UTC offset to " << m_offset << "s."; + m_state_last_updated = time_now; + etiLog.level(info) << "Initialised TAI-UTC offset to " << m_state->offset << "s."; } - if (m_bulletin_refresh_time + hours(1) < time_now) { + if (m_state_last_updated + hours(1) < time_now) { // Once per hour, parse the bulletin again, and // if necessary trigger a download. // Leap seconds are announced several months in advance @@ -457,23 +521,23 @@ int ClockTAI::get_offset() switch (state) { case future_status::ready: try { - m_offset = m_offset_future.get(); - m_offset_valid = true; - m_bulletin_refresh_time = time_now; + m_state = m_offset_future.get(); + m_state_last_updated = time_now; etiLog.level(info) << - "Updated TAI-UTC offset to " << m_offset << "s."; + "Updated TAI-UTC offset to " << m_state->offset << "s."; } catch (const download_failed&) { etiLog.level(warn) << "TAI-UTC download failed, will retry in " << refresh_retry_interval_hours << " hour(s)"; - m_bulletin_refresh_time += hours(refresh_retry_interval_hours); - } -#ifdef DOWNLOADED_IN_THE_PAST_TEST - wait_longer = false; +#if TAI_TEST + m_state_last_updated += seconds(11); +#else + m_state_last_updated += hours(refresh_retry_interval_hours); #endif + } break; case future_status::deferred: @@ -493,7 +557,10 @@ int ClockTAI::get_offset() } } - return m_offset; + if (m_state) { + return m_state->offset; + } + throw std::logic_error("ClockTAI: No valid m_state at end of get_offset()"); } #if SUPPORT_SETTING_CLOCK_TAI @@ -514,8 +581,13 @@ int ClockTAI::update_local_tai_clock(int offset) } #endif -void ClockTAI::update_cache(const char* cache_filename) +void Bulletin::store_to_cache(const char* cache_filename) const { + if (not std::holds_alternative(bulletin_or_override)) { + etiLog.level(error) << "ClockTAI: Cannot store an artificial bulletin to cache!"; + } + const auto& bulletin = std::get(bulletin_or_override); + int fd = open(cache_filename, O_RDWR | O_CREAT, 00664); if (fd == -1) { etiLog.level(error) << @@ -529,8 +601,8 @@ void ClockTAI::update_cache(const char* cache_filename) ssize_t ret = lockf(fd, F_LOCK, 0); if (ret == 0) { // exclusive lock acquired - const char *data = m_bulletin.data(); - size_t remaining = m_bulletin.size(); + const char *data = bulletin.data(); + size_t remaining = bulletin.size(); while (remaining > 0) { ret = write(fd, data, remaining); @@ -557,13 +629,35 @@ void ClockTAI::update_cache(const char* cache_filename) } } - void ClockTAI::set_parameter(const string& parameter, const string& value) { - if (parameter == "expiry") { + if (parameter == "expiry" or parameter == "expires_at") { throw ParameterError("Parameter '" + parameter + "' is read-only in controllable " + get_rc_name()); } + else if (parameter == "tai_utc_offset") { + const auto offset = std::stoi(value); + auto b = Bulletin::create_with_fixed_offset(offset); + + etiLog.level(warn) << "ClockTAI: manually overriding UTC-TAI offset to " << offset; + + std::unique_lock lock(m_data_mutex); + m_bulletin = b; + m_state = b.state(); + m_state_last_updated = chrono::steady_clock::now(); + } + else if (parameter == "url") { + { + std::unique_lock lock(m_data_mutex); + m_bulletin_urls = split_pipe_separated_string(value); + m_state_last_updated = chrono::steady_clock::time_point::min(); + + // Setting URL expires the bulletin, if it was manually overridden, + // so that the selection logic doesn't prefer it + m_bulletin.clear_expiry_if_overridden(); + } + etiLog.level(info) << "ClockTAI: triggering a reload from URLs..."; + } else { throw ParameterError("Parameter '" + parameter + "' is not exported by controllable " + get_rc_name()); @@ -574,13 +668,22 @@ const string ClockTAI::get_parameter(const string& parameter) const { if (parameter == "expiry") { std::unique_lock lock(m_data_mutex); - const int64_t expiry = parse_bulletin(m_bulletin).expiry; - if (expiry > 0) { - return to_string(expiry); - } - else { - return "Bulletin expired or invalid!"; + return to_string(m_bulletin.state().expires_in()); + } + else if (parameter == "expires_at") { + std::unique_lock lock(m_data_mutex); + return to_string(m_bulletin.state().expires_at); + } + else if (parameter == "tai_utc_offset") { + std::unique_lock lock(m_data_mutex); + if (m_state) { + return to_string(m_state->offset); } + throw ParameterError("Parameter '" + parameter + + "' has no current value" + get_rc_name()); + } + else if (parameter == "url") { + return join_string_with_pipe(m_bulletin_urls);; } else { throw ParameterError("Parameter '" + parameter + @@ -588,6 +691,35 @@ const string ClockTAI::get_parameter(const string& parameter) const } } +const json::map_t ClockTAI::get_all_values() const +{ + json::map_t stat; + std::unique_lock lock(m_data_mutex); + + const auto& state = m_bulletin.state(); + +#if CLOCK_TAI + etiLog.level(debug) << "CALC FROM m_bulletin: " << state.valid << " " << + state.offset << " " << state.expires_at << " -> " << state.expires_in(); + etiLog.level(debug) << "CACHED IN m_state: " << m_state->valid << " " << + m_state->offset << " " << m_state->expires_at << " -> " << m_state->expires_in(); +#endif + + stat["tai_utc_offset"].v = state.offset; + + stat["expiry"].v = state.expires_in(); // Might be negative when expired or 0 when invalid + if (state.valid) { + stat["expires_at"].v = state.expires_at; + } + else { + stat["expires_at"].v = nullopt; + } + + stat["url"].v = join_string_with_pipe(m_bulletin_urls); + + return stat; +} + #if 0 // Example testing code void debug_tai_clk() diff --git a/lib/ClockTAI.h b/lib/ClockTAI.h index 743cf68..8cd00e5 100644 --- a/lib/ClockTAI.h +++ b/lib/ClockTAI.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -42,12 +42,49 @@ #include #include #include +#include +#include #include "RemoteControl.h" // EDI needs to know UTC-TAI, but doesn't need the CLOCK_TAI to be set. // We can keep this code, maybe for future use #define SUPPORT_SETTING_CLOCK_TAI 0 +struct BulletinState { + bool valid = false; + int64_t expires_at = 0; + int offset = 0; + + int64_t expires_in() const; + bool usable() const; + bool expires_soon() const; +}; + +class Bulletin { + public: + static Bulletin download_from_url(const char *url); + static Bulletin create_with_fixed_offset(int offset); + static Bulletin load_from_file(const char *cache_filename); + + void clear_expiry_if_overridden(); + + void store_to_cache(const char* cache_filename) const; + + std::string get_source() const { return source; } + BulletinState state() const; + private: + // URL or file path from which the bulletin has been/will be loaded + std::string source; + + struct OverrideData { + int offset = 0; + int expires_at = 0; + }; + // string: A cache of the bulletin, or empty string if not loaded + // int: A manually overridden offset + std::variant bulletin_or_override; +}; + /* Loads, parses and represents TAI-UTC offset information from the IETF bulletin */ class ClockTAI : public RemoteControllable { public: @@ -71,33 +108,31 @@ class ClockTAI : public RemoteControllable { // download it, and calculate the TAI-UTC offset. // Returns the offset or throws download_failed or a range_error // if the offset is out of bounds. - int get_valid_offset(void); + BulletinState get_valid_offset(void); // Download of new bulletin is done asynchronously - std::future m_offset_future; + std::future m_offset_future; // Protect all data members, as RC functions are in another thread mutable std::mutex m_data_mutex; - // The currently used TAI-UTC offset, extracted from m_bulletin and cached here - // to avoid having to parse the bulletin all the time - int m_offset = 0; - int m_offset_valid = false; - std::vector m_bulletin_urls; - std::string m_bulletin; - std::chrono::system_clock::time_point m_bulletin_refresh_time; - - // Update the cache file with the current m_bulletin - void update_cache(const char* cache_filename); + Bulletin m_bulletin; + // The currently used TAI-UTC offset, extracted the bulletin and cached + // here to avoid having to parse the bulletin all the time + std::optional m_state; + std::chrono::steady_clock::time_point m_state_last_updated; + public: /* Remote control */ virtual void set_parameter(const std::string& parameter, const std::string& value); /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + + virtual const json::map_t get_all_values() const; }; diff --git a/lib/Json.cpp b/lib/Json.cpp new file mode 100644 index 0000000..4dc2f25 --- /dev/null +++ b/lib/Json.cpp @@ -0,0 +1,122 @@ +/* + Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 + Her Majesty the Queen in Right of Canada (Communications Research + Center Canada) + + Copyright (C) 2023 + Matthias P. Braendli, matthias.braendli@mpb.li + + http://www.opendigitalradio.org + */ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ +#include +#include +#include +#include +#include +#include + +#include "Json.h" + +namespace json { + static std::string escape_json(const std::string &s) { + std::ostringstream o; + for (auto c = s.cbegin(); c != s.cend(); c++) { + switch (*c) { + case '"': o << "\\\""; break; + case '\\': o << "\\\\"; break; + case '\b': o << "\\b"; break; + case '\f': o << "\\f"; break; + case '\n': o << "\\n"; break; + case '\r': o << "\\r"; break; + case '\t': o << "\\t"; break; + default: + if ('\x00' <= *c && *c <= '\x1f') { + o << "\\u" + << std::hex << std::setw(4) << std::setfill('0') << static_cast(*c); + } else { + o << *c; + } + } + } + return o.str(); + } + + std::string map_to_json(const map_t& values) { + std::ostringstream ss; + ss << "{ "; + size_t ix = 0; + for (const auto& element : values) { + if (ix > 0) { + ss << ","; + } + + ss << "\"" << escape_json(element.first) << "\": "; + ss << value_to_json(element.second); + + ix++; + } + ss << " }"; + + return ss.str(); + } + + std::string value_to_json(const value_t& value) + { + std::ostringstream ss; + + if (std::holds_alternative(value.v)) { + ss << "\"" << escape_json(std::get(value.v)) << "\""; + } + else if (std::holds_alternative(value.v)) { + ss << std::fixed << std::get(value.v); + } + else if (std::holds_alternative(value.v)) { + ss << std::get(value.v); + } + else if (std::holds_alternative(value.v)) { + ss << std::get(value.v); + } + else if (std::holds_alternative(value.v)) { + ss << (std::get(value.v) ? "true" : "false"); + } + else if (std::holds_alternative(value.v)) { + ss << "null"; + } + else if (std::holds_alternative >(value.v)) { + const auto& vec = std::get >(value.v); + ss << "[ "; + size_t list_ix = 0; + for (const auto& list_element : vec) { + if (list_ix > 0) { + ss << ","; + } + ss << value_to_json(list_element); + list_ix++; + } + ss << "]"; + } + else if (std::holds_alternative >(value.v)) { + const map_t& v = *std::get >(value.v); + ss << map_to_json(v); + } + else { + throw std::logic_error("variant alternative not handled"); + } + + return ss.str(); + } +} diff --git a/lib/Json.h b/lib/Json.h new file mode 100644 index 0000000..65aa668 --- /dev/null +++ b/lib/Json.h @@ -0,0 +1,63 @@ +/* + Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 + Her Majesty the Queen in Right of Canada (Communications Research + Center Canada) + + Copyright (C) 2023 + Matthias P. Braendli, matthias.braendli@mpb.li + + http://www.opendigitalradio.org + + This module adds remote-control capability to some of the dabmux/dabmod modules. + */ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +#pragma once + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace json { + + // STL containers are not required to support incomplete types, + // hence the shared_ptr + + struct value_t { + std::variant< + std::shared_ptr>, + std::vector, + std::string, + double, + size_t, + ssize_t, + bool, + std::nullopt_t> v; + }; + + using map_t = std::unordered_map; + + std::string map_to_json(const map_t& values); + std::string value_to_json(const value_t& value); +} diff --git a/lib/RemoteControl.cpp b/lib/RemoteControl.cpp index 30dcb60..dca3373 100644 --- a/lib/RemoteControl.cpp +++ b/lib/RemoteControl.cpp @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include @@ -102,6 +104,18 @@ std::list< std::vector > RemoteControllers::get_param_list_values(c return allparams; } + + +std::string RemoteControllers::get_showjson() { + json::map_t root; + for (auto &controllable : rcs.controllables) { + root[controllable->get_rc_name()].v = + std::make_shared(controllable->get_all_values()); + } + + return json::map_to_json(root); +} + std::string RemoteControllers::get_param(const std::string& name, const std::string& param) { RemoteControllable* controllable = get_controllable_(name); return controllable->get_parameter(param); @@ -123,7 +137,7 @@ RemoteControllable* RemoteControllers::get_controllable_(const std::string& name [&](RemoteControllable* r) { return r->get_rc_name() == name; }); if (rc == controllables.end()) { - throw ParameterError("Module name unknown"); + throw ParameterError(string{"Module name '"} + name + "' unknown"); } else { return *rc; @@ -427,10 +441,15 @@ void RemoteControllerZmq::recv_all(zmq::socket_t& pSocket, std::vector 0) ? zmq::send_flags::sndmore : zmq::send_flags::none); } } + else if (msg.size() == 1 && command == "showjson") { + try { + std::string json = rcs.get_showjson(); + + zmq::message_t zmsg(json.size()); + memcpy(zmsg.data(), json.data(), json.size()); + + repSocket.send(zmsg, zmq::send_flags::none); + } + catch (const ParameterError &err) { + send_fail_reply(repSocket, err.what()); + } + } else if (msg.size() == 2 && command == "show") { - std::string module((char*) msg[1].data(), msg[1].size()); + const std::string module((char*) msg[1].data(), msg[1].size()); try { list< vector > r = rcs.get_param_list_values(module); size_t r_size = r.size(); @@ -533,8 +566,8 @@ void RemoteControllerZmq::process() } } else if (msg.size() == 3 && command == "get") { - std::string module((char*) msg[1].data(), msg[1].size()); - std::string parameter((char*) msg[2].data(), msg[2].size()); + const std::string module((char*) msg[1].data(), msg[1].size()); + const std::string parameter((char*) msg[2].data(), msg[2].size()); try { std::string value = rcs.get_param(module, parameter); @@ -547,9 +580,9 @@ void RemoteControllerZmq::process() } } else if (msg.size() == 4 && command == "set") { - std::string module((char*) msg[1].data(), msg[1].size()); - std::string parameter((char*) msg[2].data(), msg[2].size()); - std::string value((char*) msg[3].data(), msg[3].size()); + const std::string module((char*) msg[1].data(), msg[1].size()); + const std::string parameter((char*) msg[2].data(), msg[2].size()); + const std::string value((char*) msg[3].data(), msg[3].size()); try { rcs.set_param(module, parameter, value); @@ -561,7 +594,7 @@ void RemoteControllerZmq::process() } else { send_fail_reply(repSocket, - "Unsupported command. commands: list, show, get, set"); + "Unsupported command. commands: list, show, get, set, showjson"); } } } diff --git a/lib/RemoteControl.h b/lib/RemoteControl.h index 2358b3a..26f30d9 100644 --- a/lib/RemoteControl.h +++ b/lib/RemoteControl.h @@ -3,7 +3,7 @@ Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2023 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -36,6 +36,8 @@ #endif #include +#include +#include #include #include #include @@ -46,6 +48,7 @@ #include "Log.h" #include "Socket.h" +#include "Json.h" #define RC_ADD_PARAMETER(p, desc) { \ std::vector p; \ @@ -113,13 +116,13 @@ class RemoteControllable { } /* Base function to set parameters. */ - virtual void set_parameter( - const std::string& parameter, - const std::string& value) = 0; + virtual void set_parameter(const std::string& parameter, const std::string& value) = 0; /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const = 0; + virtual const json::map_t get_all_values() const = 0; + protected: std::string m_rc_name; std::list< std::vector > m_parameters; @@ -135,6 +138,7 @@ class RemoteControllers { void check_faults(); std::list< std::vector > get_param_list_values(const std::string& name); std::string get_param(const std::string& name, const std::string& param); + std::string get_showjson(); void set_param( const std::string& name, diff --git a/lib/charset/README b/lib/charset/README index b20f76b..3217b87 100644 --- a/lib/charset/README +++ b/lib/charset/README @@ -1,2 +1,2 @@ This UTF-8 to EBU charset (defined in ETSI TS 101 756v1.8.1) was copied from -ODR-PadEnc. +ODR-PadEnc, with utf8 library v4.0.5 from https://github.com/nemtrif/utfcpp/tree/master/source/utf8 diff --git a/lib/charset/utf8.h b/lib/charset/utf8.h index 4e44514..b513530 100644 --- a/lib/charset/utf8.h +++ b/lib/charset/utf8.h @@ -1,34 +1,46 @@ -// Copyright 2006 Nemanja Trifunovic - -/* -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -*/ - - -#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 -#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 - -#include "utf8/checked.h" -#include "utf8/unchecked.h" - -#endif // header guard +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 +#define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 + +/* +To control the C++ language version used by the library, you can define UTF_CPP_CPLUSPLUS macro +and set it to one of the values used by the __cplusplus predefined macro. + +For instance, + #define UTF_CPP_CPLUSPLUS 199711L +will cause the UTF-8 CPP library to use only types and language features available in the C++ 98 standard. +Some library features will be disabled. + +If you leave UTF_CPP_CPLUSPLUS undefined, it will be internally assigned to __cplusplus. +*/ + +#include "utf8/checked.h" +#include "utf8/unchecked.h" + +#endif // header guard diff --git a/lib/charset/utf8/checked.h b/lib/charset/utf8/checked.h index 1331155..98949f8 100644 --- a/lib/charset/utf8/checked.h +++ b/lib/charset/utf8/checked.h @@ -1,4 +1,4 @@ -// Copyright 2006 Nemanja Trifunovic +// Copyright 2006-2016 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization @@ -39,64 +39,62 @@ namespace utf8 // Exceptions that may be thrown from the library functions. class invalid_code_point : public exception { - uint32_t cp; + utfchar32_t cp; public: - invalid_code_point(uint32_t cp) : cp(cp) {} - virtual const char* what() const throw() { return "Invalid code point"; } - uint32_t code_point() const {return cp;} + invalid_code_point(utfchar32_t codepoint) : cp(codepoint) {} + virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid code point"; } + utfchar32_t code_point() const {return cp;} }; class invalid_utf8 : public exception { - uint8_t u8; + utfchar8_t u8; public: - invalid_utf8 (uint8_t u) : u8(u) {} - virtual const char* what() const throw() { return "Invalid UTF-8"; } - uint8_t utf8_octet() const {return u8;} + invalid_utf8 (utfchar8_t u) : u8(u) {} + invalid_utf8 (char c) : u8(static_cast(c)) {} + virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid UTF-8"; } + utfchar8_t utf8_octet() const {return u8;} }; class invalid_utf16 : public exception { - uint16_t u16; + utfchar16_t u16; public: - invalid_utf16 (uint16_t u) : u16(u) {} - virtual const char* what() const throw() { return "Invalid UTF-16"; } - uint16_t utf16_word() const {return u16;} + invalid_utf16 (utfchar16_t u) : u16(u) {} + virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Invalid UTF-16"; } + utfchar16_t utf16_word() const {return u16;} }; class not_enough_room : public exception { public: - virtual const char* what() const throw() { return "Not enough space"; } + virtual const char* what() const UTF_CPP_NOEXCEPT UTF_CPP_OVERRIDE { return "Not enough space"; } }; /// The library API - functions intended to be called by the users template - octet_iterator append(uint32_t cp, octet_iterator result) + octet_iterator append(utfchar32_t cp, octet_iterator result) { if (!utf8::internal::is_code_point_valid(cp)) throw invalid_code_point(cp); - if (cp < 0x80) // one octet - *(result++) = static_cast(cp); - else if (cp < 0x800) { // two octets - *(result++) = static_cast((cp >> 6) | 0xc0); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else if (cp < 0x10000) { // three octets - *(result++) = static_cast((cp >> 12) | 0xe0); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else { // four octets - *(result++) = static_cast((cp >> 18) | 0xf0); - *(result++) = static_cast(((cp >> 12) & 0x3f) | 0x80); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - return result; + return internal::append(cp, result); + } + + inline void append(utfchar32_t cp, std::string& s) + { + append(cp, std::back_inserter(s)); + } + + template + word_iterator append16(utfchar32_t cp, word_iterator result) + { + if (!utf8::internal::is_code_point_valid(cp)) + throw invalid_code_point(cp); + + return internal::append16(cp, result); } template - output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) + output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, utfchar32_t replacement) { while (start != end) { octet_iterator sequence_start = start; @@ -107,7 +105,9 @@ namespace utf8 *out++ = *it; break; case internal::NOT_ENOUGH_ROOM: - throw not_enough_room(); + out = utf8::append (replacement, out); + start = end; + break; case internal::INVALID_LEAD: out = utf8::append (replacement, out); ++start; @@ -129,14 +129,28 @@ namespace utf8 template inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) { - static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); + static const utfchar32_t replacement_marker = utf8::internal::mask16(0xfffd); return utf8::replace_invalid(start, end, out, replacement_marker); } + inline std::string replace_invalid(const std::string& s, utfchar32_t replacement) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); + return result; + } + + inline std::string replace_invalid(const std::string& s) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + template - uint32_t next(octet_iterator& it, octet_iterator end) + utfchar32_t next(octet_iterator& it, octet_iterator end) { - uint32_t cp = 0; + utfchar32_t cp = 0; internal::utf_error err_code = utf8::internal::validate_next(it, end, cp); switch (err_code) { case internal::UTF8_OK : @@ -146,21 +160,31 @@ namespace utf8 case internal::INVALID_LEAD : case internal::INCOMPLETE_SEQUENCE : case internal::OVERLONG_SEQUENCE : - throw invalid_utf8(*it); + throw invalid_utf8(static_cast(*it)); case internal::INVALID_CODE_POINT : throw invalid_code_point(cp); } return cp; } + template + utfchar32_t next16(word_iterator& it, word_iterator end) + { + utfchar32_t cp = 0; + internal::utf_error err_code = utf8::internal::validate_next16(it, end, cp); + if (err_code == internal::NOT_ENOUGH_ROOM) + throw not_enough_room(); + return cp; + } + template - uint32_t peek_next(octet_iterator it, octet_iterator end) + utfchar32_t peek_next(octet_iterator it, octet_iterator end) { return utf8::next(it, end); } template - uint32_t prior(octet_iterator& it, octet_iterator start) + utfchar32_t prior(octet_iterator& it, octet_iterator start) { // can't do much if it == start if (it == start) @@ -174,23 +198,19 @@ namespace utf8 return utf8::peek_next(it, end); } - /// Deprecated in versions that include "prior" - template - uint32_t previous(octet_iterator& it, octet_iterator pass_start) - { - octet_iterator end = it; - while (utf8::internal::is_trail(*(--it))) - if (it == pass_start) - throw invalid_utf8(*it); // error - no lead byte in the sequence - octet_iterator temp = it; - return utf8::next(temp, end); - } - template void advance (octet_iterator& it, distance_type n, octet_iterator end) { - for (distance_type i = 0; i < n; ++i) - utf8::next(it, end); + const distance_type zero(0); + if (n < zero) { + // backward + for (distance_type i = n; i < zero; ++i) + utf8::prior(it, end); + } else { + // forward + for (distance_type i = zero; i < n; ++i) + utf8::next(it, end); + } } template @@ -207,23 +227,23 @@ namespace utf8 octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { - uint32_t cp = utf8::internal::mask16(*start++); + utfchar32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first if (utf8::internal::is_lead_surrogate(cp)) { if (start != end) { - uint32_t trail_surrogate = utf8::internal::mask16(*start++); + const utfchar32_t trail_surrogate = utf8::internal::mask16(*start++); if (utf8::internal::is_trail_surrogate(trail_surrogate)) cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; else - throw invalid_utf16(static_cast(trail_surrogate)); + throw invalid_utf16(static_cast(trail_surrogate)); } else - throw invalid_utf16(static_cast(cp)); + throw invalid_utf16(static_cast(cp)); } // Lone trail surrogate else if (utf8::internal::is_trail_surrogate(cp)) - throw invalid_utf16(static_cast(cp)); + throw invalid_utf16(static_cast(cp)); result = utf8::append(cp, result); } @@ -233,14 +253,14 @@ namespace utf8 template u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { - while (start != end) { - uint32_t cp = utf8::next(start, end); + while (start < end) { + const utfchar32_t cp = utf8::next(start, end); if (cp > 0xffff) { //make a surrogate pair - *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); - *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); } else - *result++ = static_cast(cp); + *result++ = static_cast(cp); } return result; } @@ -257,7 +277,7 @@ namespace utf8 template u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { - while (start != end) + while (start < end) (*result++) = utf8::next(start, end); return result; @@ -265,23 +285,28 @@ namespace utf8 // The iterator class template - class iterator : public std::iterator { + class iterator { octet_iterator it; octet_iterator range_start; octet_iterator range_end; public: + typedef utfchar32_t value_type; + typedef utfchar32_t* pointer; + typedef utfchar32_t& reference; + typedef std::ptrdiff_t difference_type; + typedef std::bidirectional_iterator_tag iterator_category; iterator () {} explicit iterator (const octet_iterator& octet_it, - const octet_iterator& range_start, - const octet_iterator& range_end) : - it(octet_it), range_start(range_start), range_end(range_end) + const octet_iterator& rangestart, + const octet_iterator& rangeend) : + it(octet_it), range_start(rangestart), range_end(rangeend) { if (it < range_start || it > range_end) throw std::out_of_range("Invalid utf-8 iterator position"); } // the default "big three" are OK octet_iterator base () const { return it; } - uint32_t operator * () const + utfchar32_t operator * () const { octet_iterator temp = it; return utf8::next(temp, range_end); @@ -322,6 +347,13 @@ namespace utf8 } // namespace utf8 -#endif //header guard +#if UTF_CPP_CPLUSPLUS >= 202002L // C++ 20 or later +#include "cpp20.h" +#elif UTF_CPP_CPLUSPLUS >= 201703L // C++ 17 or later +#include "cpp17.h" +#elif UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later +#include "cpp11.h" +#endif // C++ 11 or later +#endif //header guard diff --git a/lib/charset/utf8/core.h b/lib/charset/utf8/core.h index 693d388..4494c53 100644 --- a/lib/charset/utf8/core.h +++ b/lib/charset/utf8/core.h @@ -29,15 +29,42 @@ DEALINGS IN THE SOFTWARE. #define UTF8_FOR_CPP_CORE_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #include +#include +#include + +// Determine the C++ standard version. +// If the user defines UTF_CPP_CPLUSPLUS, use that. +// Otherwise, trust the unreliable predefined macro __cplusplus + +#if !defined UTF_CPP_CPLUSPLUS + #define UTF_CPP_CPLUSPLUS __cplusplus +#endif + +#if UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later + #define UTF_CPP_OVERRIDE override + #define UTF_CPP_NOEXCEPT noexcept +#else // C++ 98/03 + #define UTF_CPP_OVERRIDE + #define UTF_CPP_NOEXCEPT throw() +#endif // C++ 11 or later + namespace utf8 { - // The typedefs for 8-bit, 16-bit and 32-bit unsigned integers - // You may need to change them to match your system. - // These typedefs have the same names as ones from cstdint, or boost/cstdint - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; +// The typedefs for 8-bit, 16-bit and 32-bit code units +#if UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later + #if UTF_CPP_CPLUSPLUS >= 202002L // C++ 20 or later + typedef char8_t utfchar8_t; + #else // C++ 11/14/17 + typedef unsigned char utfchar8_t; + #endif + typedef char16_t utfchar16_t; + typedef char32_t utfchar32_t; +#else // C++ 98/03 + typedef unsigned char utfchar8_t; + typedef unsigned short utfchar16_t; + typedef unsigned int utfchar32_t; +#endif // C++ 11 or later // Helper code - not intended to be directly called by the library users. May be changed at any time namespace internal @@ -45,61 +72,62 @@ namespace internal // Unicode constants // Leading (high) surrogates: 0xd800 - 0xdbff // Trailing (low) surrogates: 0xdc00 - 0xdfff - const uint16_t LEAD_SURROGATE_MIN = 0xd800u; - const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; - const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; - const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; - const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); - const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; + const utfchar16_t LEAD_SURROGATE_MIN = 0xd800u; + const utfchar16_t LEAD_SURROGATE_MAX = 0xdbffu; + const utfchar16_t TRAIL_SURROGATE_MIN = 0xdc00u; + const utfchar16_t TRAIL_SURROGATE_MAX = 0xdfffu; + const utfchar16_t LEAD_OFFSET = 0xd7c0u; // LEAD_SURROGATE_MIN - (0x10000 >> 10) + const utfchar32_t SURROGATE_OFFSET = 0xfca02400u; // 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN // Maximum valid value for a Unicode code point - const uint32_t CODE_POINT_MAX = 0x0010ffffu; + const utfchar32_t CODE_POINT_MAX = 0x0010ffffu; template - inline uint8_t mask8(octet_type oc) + inline utfchar8_t mask8(octet_type oc) { - return static_cast(0xff & oc); + return static_cast(0xff & oc); } template - inline uint16_t mask16(u16_type oc) + inline utfchar16_t mask16(u16_type oc) { - return static_cast(0xffff & oc); + return static_cast(0xffff & oc); } + template inline bool is_trail(octet_type oc) { return ((utf8::internal::mask8(oc) >> 6) == 0x2); } - template - inline bool is_lead_surrogate(u16 cp) + inline bool is_lead_surrogate(utfchar32_t cp) { return (cp >= LEAD_SURROGATE_MIN && cp <= LEAD_SURROGATE_MAX); } - template - inline bool is_trail_surrogate(u16 cp) + inline bool is_trail_surrogate(utfchar32_t cp) { return (cp >= TRAIL_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); } - template - inline bool is_surrogate(u16 cp) + inline bool is_surrogate(utfchar32_t cp) { return (cp >= LEAD_SURROGATE_MIN && cp <= TRAIL_SURROGATE_MAX); } - template - inline bool is_code_point_valid(u32 cp) + inline bool is_code_point_valid(utfchar32_t cp) { return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp)); } + inline bool is_in_bmp(utfchar32_t cp) + { + return cp < utfchar32_t(0x10000); + } + template - inline typename std::iterator_traits::difference_type - sequence_length(octet_iterator lead_it) + int sequence_length(octet_iterator lead_it) { - uint8_t lead = utf8::internal::mask8(*lead_it); + const utfchar8_t lead = utf8::internal::mask8(*lead_it); if (lead < 0x80) return 1; else if ((lead >> 5) == 0x6) @@ -112,8 +140,7 @@ namespace internal return 0; } - template - inline bool is_overlong_sequence(uint32_t cp, octet_difference_type length) + inline bool is_overlong_sequence(utfchar32_t cp, int length) { if (cp < 0x80) { if (length != 1) @@ -127,7 +154,6 @@ namespace internal if (length != 3) return true; } - return false; } @@ -135,22 +161,22 @@ namespace internal /// Helper for get_sequence_x template - utf_error increase_safely(octet_iterator& it, octet_iterator end) + utf_error increase_safely(octet_iterator& it, const octet_iterator end) { if (++it == end) return NOT_ENOUGH_ROOM; if (!utf8::internal::is_trail(*it)) return INCOMPLETE_SEQUENCE; - + return UTF8_OK; } - #define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;} + #define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;} /// get_sequence_x functions decode utf-8 sequences of the length x template - utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t& code_point) + utf_error get_sequence_1(octet_iterator& it, octet_iterator end, utfchar32_t& code_point) { if (it == end) return NOT_ENOUGH_ROOM; @@ -161,11 +187,11 @@ namespace internal } template - utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t& code_point) + utf_error get_sequence_2(octet_iterator& it, octet_iterator end, utfchar32_t& code_point) { if (it == end) return NOT_ENOUGH_ROOM; - + code_point = utf8::internal::mask8(*it); UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) @@ -176,7 +202,7 @@ namespace internal } template - utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t& code_point) + utf_error get_sequence_3(octet_iterator& it, octet_iterator end, utfchar32_t& code_point) { if (it == end) return NOT_ENOUGH_ROOM; @@ -195,7 +221,7 @@ namespace internal } template - utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t& code_point) + utf_error get_sequence_4(octet_iterator& it, octet_iterator end, utfchar32_t& code_point) { if (it == end) return NOT_ENOUGH_ROOM; @@ -220,21 +246,23 @@ namespace internal #undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR template - utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point) + utf_error validate_next(octet_iterator& it, octet_iterator end, utfchar32_t& code_point) { + if (it == end) + return NOT_ENOUGH_ROOM; + // Save the original value of it so we can go back in case of failure // Of course, it does not make much sense with i.e. stream iterators octet_iterator original_it = it; - uint32_t cp = 0; + utfchar32_t cp = 0; // Determine the sequence length based on the lead octet - typedef typename std::iterator_traits::difference_type octet_difference_type; - const octet_difference_type length = utf8::internal::sequence_length(it); + const int length = utf8::internal::sequence_length(it); // Get trail octets and calculate the code point utf_error err = UTF8_OK; switch (length) { - case 0: + case 0: return INVALID_LEAD; case 1: err = utf8::internal::get_sequence_1(it, end, cp); @@ -273,16 +301,133 @@ namespace internal template inline utf_error validate_next(octet_iterator& it, octet_iterator end) { - uint32_t ignored; + utfchar32_t ignored; return utf8::internal::validate_next(it, end, ignored); } + template + utf_error validate_next16(word_iterator& it, word_iterator end, utfchar32_t& code_point) + { + if (it == end) + return NOT_ENOUGH_ROOM; + // Save the original value of it so we can go back in case of failure + // Of course, it does not make much sense with i.e. stream iterators + word_iterator original_it = it; + + utf_error err = UTF8_OK; + + const utfchar16_t first_word = *it++; + if (!is_surrogate(first_word)) { + code_point = first_word; + return UTF8_OK; + } + else { + if (it == end) + err = NOT_ENOUGH_ROOM; + else if (is_lead_surrogate(first_word)) { + const utfchar16_t second_word = *it++; + if (is_trail_surrogate(second_word)) { + code_point = (first_word << 10) + second_word + SURROGATE_OFFSET; + return UTF8_OK; + } else + err = INCOMPLETE_SEQUENCE; + + } else { + err = INVALID_LEAD; + } + } + // error branch + it = original_it; + return err; + } + + // Internal implementation of both checked and unchecked append() function + // This function will be invoked by the overloads below, as they will know + // the octet_type. + template + octet_iterator append(utfchar32_t cp, octet_iterator result) { + if (cp < 0x80) // one octet + *(result++) = static_cast(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast((cp >> 6) | 0xc0); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast((cp >> 12) | 0xe0); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast((cp >> 18) | 0xf0); + *(result++) = static_cast(((cp >> 12) & 0x3f)| 0x80); + *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast((cp & 0x3f) | 0x80); + } + return result; + } + + // One of the following overloads will be invoked from the API calls + + // A simple (but dangerous) case: the caller appends byte(s) to a char array + inline char* append(utfchar32_t cp, char* result) { + return append(cp, result); + } + + // Hopefully, most common case: the caller uses back_inserter + // i.e. append(cp, std::back_inserter(str)); + template + std::back_insert_iterator append + (utfchar32_t cp, std::back_insert_iterator result) { + return append, + typename container_type::value_type>(cp, result); + } + + // The caller uses some other kind of output operator - not covered above + // Note that in this case we are not able to determine octet_type + // so we assume it's utfchar8_t; that can cause a conversion warning if we are wrong. + template + octet_iterator append(utfchar32_t cp, octet_iterator result) { + return append(cp, result); + } + + // Internal implementation of both checked and unchecked append16() function + // This function will be invoked by the overloads below, as they will know + // the word_type. + template + word_iterator append16(utfchar32_t cp, word_iterator result) { + if (is_in_bmp(cp)) + *(result++) = static_cast(cp); + else { + // Code points from the supplementary planes are encoded via surrogate pairs + *(result++) = static_cast(LEAD_OFFSET + (cp >> 10)); + *(result++) = static_cast(TRAIL_SURROGATE_MIN + (cp & 0x3FF)); + } + return result; + } + + // Hopefully, most common case: the caller uses back_inserter + // i.e. append16(cp, std::back_inserter(str)); + template + std::back_insert_iterator append16 + (utfchar32_t cp, std::back_insert_iterator result) { + return append16, + typename container_type::value_type>(cp, result); + } + + // The caller uses some other kind of output operator - not covered above + // Note that in this case we are not able to determine word_type + // so we assume it's utfchar16_t; that can cause a conversion warning if we are wrong. + template + word_iterator append16(utfchar32_t cp, word_iterator result) { + return append16(cp, result); + } + } // namespace internal /// The library API - functions intended to be called by the users // Byte order mark - const uint8_t bom[] = {0xef, 0xbb, 0xbf}; + const utfchar8_t bom[] = {0xef, 0xbb, 0xbf}; template octet_iterator find_invalid(octet_iterator start, octet_iterator end) @@ -296,12 +441,36 @@ namespace internal return result; } + inline const char* find_invalid(const char* str) + { + const char* end = str + std::strlen(str); + return find_invalid(str, end); + } + + inline std::size_t find_invalid(const std::string& s) + { + std::string::const_iterator invalid = find_invalid(s.begin(), s.end()); + return (invalid == s.end()) ? std::string::npos : static_cast(invalid - s.begin()); + } + template inline bool is_valid(octet_iterator start, octet_iterator end) { return (utf8::find_invalid(start, end) == end); } + inline bool is_valid(const char* str) + { + return (*(utf8::find_invalid(str)) == '\0'); + } + + inline bool is_valid(const std::string& s) + { + return is_valid(s.begin(), s.end()); + } + + + template inline bool starts_with_bom (octet_iterator it, octet_iterator end) { @@ -311,17 +480,11 @@ namespace internal ((it != end) && (utf8::internal::mask8(*it)) == bom[2]) ); } - - //Deprecated in release 2.3 - template - inline bool is_bom (octet_iterator it) + + inline bool starts_with_bom(const std::string& s) { - return ( - (utf8::internal::mask8(*it++)) == bom[0] && - (utf8::internal::mask8(*it++)) == bom[1] && - (utf8::internal::mask8(*it)) == bom[2] - ); - } + return starts_with_bom(s.begin(), s.end()); + } } // namespace utf8 #endif // header guard diff --git a/lib/charset/utf8/cpp11.h b/lib/charset/utf8/cpp11.h new file mode 100644 index 0000000..691633c --- /dev/null +++ b/lib/charset/utf8/cpp11.h @@ -0,0 +1,70 @@ +// Copyright 2018 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 +#define UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 + +#include "checked.h" + +namespace utf8 +{ + inline void append16(utfchar32_t cp, std::u16string& s) + { + append16(cp, std::back_inserter(s)); + } + + inline std::string utf16to8(const std::u16string& s) + { + std::string result; + utf16to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u16string utf8to16(const std::string& s) + { + std::u16string result; + utf8to16(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::string utf32to8(const std::u32string& s) + { + std::string result; + utf32to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u32string utf8to32(const std::string& s) + { + std::u32string result; + utf8to32(s.begin(), s.end(), std::back_inserter(result)); + return result; + } +} // namespace utf8 + +#endif // header guard + diff --git a/lib/charset/utf8/cpp17.h b/lib/charset/utf8/cpp17.h new file mode 100644 index 0000000..6e2fcc2 --- /dev/null +++ b/lib/charset/utf8/cpp17.h @@ -0,0 +1,96 @@ +// Copyright 2018 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_7e906c01_03a3_4daf_b420_ea7ea952b3c9 +#define UTF8_FOR_CPP_7e906c01_03a3_4daf_b420_ea7ea952b3c9 + +#include "cpp11.h" + +namespace utf8 +{ + inline std::string utf16to8(std::u16string_view s) + { + std::string result; + utf16to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u16string utf8to16(std::string_view s) + { + std::u16string result; + utf8to16(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::string utf32to8(std::u32string_view s) + { + std::string result; + utf32to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u32string utf8to32(std::string_view s) + { + std::u32string result; + utf8to32(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::size_t find_invalid(std::string_view s) + { + std::string_view::const_iterator invalid = find_invalid(s.begin(), s.end()); + return (invalid == s.end()) ? std::string_view::npos : static_cast(invalid - s.begin()); + } + + inline bool is_valid(std::string_view s) + { + return is_valid(s.begin(), s.end()); + } + + inline std::string replace_invalid(std::string_view s, char32_t replacement) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); + return result; + } + + inline std::string replace_invalid(std::string_view s) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline bool starts_with_bom(std::string_view s) + { + return starts_with_bom(s.begin(), s.end()); + } + +} // namespace utf8 + +#endif // header guard + diff --git a/lib/charset/utf8/cpp20.h b/lib/charset/utf8/cpp20.h new file mode 100644 index 0000000..07b61d0 --- /dev/null +++ b/lib/charset/utf8/cpp20.h @@ -0,0 +1,124 @@ +// Copyright 2022 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_207e906c01_03a3_4daf_b420_ea7ea952b3c9 +#define UTF8_FOR_CPP_207e906c01_03a3_4daf_b420_ea7ea952b3c9 + +#include "cpp17.h" + +namespace utf8 +{ + inline std::u8string utf16tou8(const std::u16string& s) + { + std::u8string result; + utf16to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u8string utf16tou8(std::u16string_view s) + { + std::u8string result; + utf16to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u16string utf8to16(const std::u8string& s) + { + std::u16string result; + utf8to16(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u16string utf8to16(const std::u8string_view& s) + { + std::u16string result; + utf8to16(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u8string utf32tou8(const std::u32string& s) + { + std::u8string result; + utf32to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u8string utf32tou8(const std::u32string_view& s) + { + std::u8string result; + utf32to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u32string utf8to32(const std::u8string& s) + { + std::u32string result; + utf8to32(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u32string utf8to32(const std::u8string_view& s) + { + std::u32string result; + utf8to32(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::size_t find_invalid(const std::u8string& s) + { + std::u8string::const_iterator invalid = find_invalid(s.begin(), s.end()); + return (invalid == s.end()) ? std::string_view::npos : static_cast(invalid - s.begin()); + } + + inline bool is_valid(const std::u8string& s) + { + return is_valid(s.begin(), s.end()); + } + + inline std::u8string replace_invalid(const std::u8string& s, char32_t replacement) + { + std::u8string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); + return result; + } + + inline std::u8string replace_invalid(const std::u8string& s) + { + std::u8string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline bool starts_with_bom(const std::u8string& s) + { + return starts_with_bom(s.begin(), s.end()); + } + +} // namespace utf8 + +#endif // header guard + diff --git a/lib/charset/utf8/unchecked.h b/lib/charset/utf8/unchecked.h index cb24271..65d4948 100644 --- a/lib/charset/utf8/unchecked.h +++ b/lib/charset/utf8/unchecked.h @@ -32,37 +32,79 @@ DEALINGS IN THE SOFTWARE. namespace utf8 { - namespace unchecked + namespace unchecked { template - octet_iterator append(uint32_t cp, octet_iterator result) + octet_iterator append(utfchar32_t cp, octet_iterator result) { - if (cp < 0x80) // one octet - *(result++) = static_cast(cp); - else if (cp < 0x800) { // two octets - *(result++) = static_cast((cp >> 6) | 0xc0); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else if (cp < 0x10000) { // three octets - *(result++) = static_cast((cp >> 12) | 0xe0); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); - } - else { // four octets - *(result++) = static_cast((cp >> 18) | 0xf0); - *(result++) = static_cast(((cp >> 12) & 0x3f)| 0x80); - *(result++) = static_cast(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast((cp & 0x3f) | 0x80); + return internal::append(cp, result); + } + + template + word_iterator append16(utfchar32_t cp, word_iterator result) + { + return internal::append16(cp, result); + } + + template + output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, utfchar32_t replacement) + { + while (start != end) { + octet_iterator sequence_start = start; + internal::utf_error err_code = utf8::internal::validate_next(start, end); + switch (err_code) { + case internal::UTF8_OK : + for (octet_iterator it = sequence_start; it != start; ++it) + *out++ = *it; + break; + case internal::NOT_ENOUGH_ROOM: + out = utf8::unchecked::append(replacement, out); + start = end; + break; + case internal::INVALID_LEAD: + out = utf8::unchecked::append(replacement, out); + ++start; + break; + case internal::INCOMPLETE_SEQUENCE: + case internal::OVERLONG_SEQUENCE: + case internal::INVALID_CODE_POINT: + out = utf8::unchecked::append(replacement, out); + ++start; + // just one replacement mark for the sequence + while (start != end && utf8::internal::is_trail(*start)) + ++start; + break; + } } + return out; + } + + template + inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) + { + static const utfchar32_t replacement_marker = utf8::internal::mask16(0xfffd); + return utf8::unchecked::replace_invalid(start, end, out, replacement_marker); + } + + inline std::string replace_invalid(const std::string& s, utfchar32_t replacement) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); + return result; + } + + inline std::string replace_invalid(const std::string& s) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result)); return result; } template - uint32_t next(octet_iterator& it) + utfchar32_t next(octet_iterator& it) { - uint32_t cp = utf8::internal::mask8(*it); - typename std::iterator_traits::difference_type length = utf8::internal::sequence_length(it); - switch (length) { + utfchar32_t cp = utf8::internal::mask8(*it); + switch (utf8::internal::sequence_length(it)) { case 1: break; case 2: @@ -85,40 +127,50 @@ namespace utf8 break; } ++it; - return cp; + return cp; } template - uint32_t peek_next(octet_iterator it) + utfchar32_t peek_next(octet_iterator it) { - return utf8::unchecked::next(it); + return utf8::unchecked::next(it); } - template - uint32_t prior(octet_iterator& it) + template + utfchar32_t next16(word_iterator& it) { - while (utf8::internal::is_trail(*(--it))) ; - octet_iterator temp = it; - return utf8::unchecked::next(temp); + utfchar32_t cp = utf8::internal::mask16(*it++); + if (utf8::internal::is_lead_surrogate(cp)) + return (cp << 10) + *it++ + utf8::internal::SURROGATE_OFFSET; + return cp; } - // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) template - inline uint32_t previous(octet_iterator& it) + utfchar32_t prior(octet_iterator& it) { - return utf8::unchecked::prior(it); + while (utf8::internal::is_trail(*(--it))) ; + octet_iterator temp = it; + return utf8::unchecked::next(temp); } template - void advance (octet_iterator& it, distance_type n) + void advance(octet_iterator& it, distance_type n) { - for (distance_type i = 0; i < n; ++i) - utf8::unchecked::next(it); + const distance_type zero(0); + if (n < zero) { + // backward + for (distance_type i = n; i < zero; ++i) + utf8::unchecked::prior(it); + } else { + // forward + for (distance_type i = zero; i < n; ++i) + utf8::unchecked::next(it); + } } template typename std::iterator_traits::difference_type - distance (octet_iterator first, octet_iterator last) + distance(octet_iterator first, octet_iterator last) { typename std::iterator_traits::difference_type dist; for (dist = 0; first < last; ++dist) @@ -127,37 +179,39 @@ namespace utf8 } template - octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) - { + octet_iterator utf16to8(u16bit_iterator start, u16bit_iterator end, octet_iterator result) + { while (start != end) { - uint32_t cp = utf8::internal::mask16(*start++); - // Take care of surrogate pairs first + utfchar32_t cp = utf8::internal::mask16(*start++); + // Take care of surrogate pairs first if (utf8::internal::is_lead_surrogate(cp)) { - uint32_t trail_surrogate = utf8::internal::mask16(*start++); + if (start == end) + return result; + utfchar32_t trail_surrogate = utf8::internal::mask16(*start++); cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; } result = utf8::unchecked::append(cp, result); } - return result; + return result; } template - u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) + u16bit_iterator utf8to16(octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start < end) { - uint32_t cp = utf8::unchecked::next(start); + utfchar32_t cp = utf8::unchecked::next(start); if (cp > 0xffff) { //make a surrogate pair - *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); - *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); + *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); + *result++ = static_cast((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); } else - *result++ = static_cast(cp); + *result++ = static_cast(cp); } return result; } template - octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) + octet_iterator utf32to8(u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) result = utf8::unchecked::append(*(start++), result); @@ -166,7 +220,7 @@ namespace utf8 } template - u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) + u32bit_iterator utf8to32(octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start < end) (*result++) = utf8::unchecked::next(start); @@ -176,14 +230,19 @@ namespace utf8 // The iterator class template - class iterator : public std::iterator { + class iterator { octet_iterator it; public: + typedef utfchar32_t value_type; + typedef utfchar32_t* pointer; + typedef utfchar32_t& reference; + typedef std::ptrdiff_t difference_type; + typedef std::bidirectional_iterator_tag iterator_category; iterator () {} explicit iterator (const octet_iterator& octet_it): it(octet_it) {} // the default "big three" are OK octet_iterator base () const { return it; } - uint32_t operator * () const + utfchar32_t operator * () const { octet_iterator temp = it; return utf8::unchecked::next(temp); diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index fb5ec45..908caf9 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2020 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -820,3 +820,11 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co } +const json::map_t DabMultiplexer::get_all_values() const +{ + json::map_t map; + map["frames"].v = m_currentFrame; + map["tist_offset"].v = m_tist_offset; + return map; +} + diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 3b521ff..90e5767 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -76,6 +76,8 @@ class DabMultiplexer : public RemoteControllable { /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + virtual const json::map_t get_all_values() const; + private: void prepare_subchannels(void); void prepare_services_components(void); diff --git a/src/MuxElements.cpp b/src/MuxElements.cpp index 215a56d..d17b283 100644 --- a/src/MuxElements.cpp +++ b/src/MuxElements.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2020 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -180,6 +180,34 @@ const string AnnouncementCluster::get_parameter(const string& parameter) const return ss.str(); } +const json::map_t AnnouncementCluster::get_all_values() const +{ + json::map_t map; + + lock_guard lock(m_active_mutex); + map["active"].v = m_active; + + using namespace std::chrono; + + if (m_deferred_start_time) { + const auto diff = *m_deferred_start_time - steady_clock::now(); + map["start_in"].v = duration_cast(diff).count(); + } + else { + map["start_in"].v = nullopt; + } + + if (m_deferred_stop_time) { + const auto diff = *m_deferred_stop_time - steady_clock::now(); + map["stop_in"].v = duration_cast(diff).count(); + } + else { + map["stop_in"].v = nullopt; + } + + return map; +} + int DabLabel::setLabel(const std::string& label) { @@ -512,6 +540,16 @@ const string DabComponent::get_parameter(const string& parameter) const } +const json::map_t DabComponent::get_all_values() const +{ + json::map_t map; + // It's cleaner to have it separate in JSON, but we + // need the comma separated variant for setting + map["label"].v = label.long_label(); + map["shortlabel"].v = label.short_label(); + return map; +} + subchannel_type_t DabService::getType( const std::shared_ptr ensemble) const { @@ -638,6 +676,16 @@ const string DabService::get_parameter(const string& parameter) const return ss.str(); } +const json::map_t DabService::get_all_values() const +{ + json::map_t map; + map["label"].v = label.long_label(); + map["shortlabel"].v = label.short_label(); + map["pty"].v = (int)pty_settings.pty; + map["ptysd"].v = (pty_settings.dynamic_no_static ? "dynamic" : "static"); + return map; +} + void dabEnsemble::set_parameter(const string& parameter, const string& value) { if (parameter == "localtimeoffset") { @@ -687,6 +735,14 @@ const string dabEnsemble::get_parameter(const string& parameter) const return ss.str(); } +const json::map_t dabEnsemble::get_all_values() const +{ + json::map_t map; + map["localtimeoffset_auto"].v = lto_auto; + map["localtimeoffset"].v = lto; + return map; +} + bool dabEnsemble::validate_linkage_sets() { for (const auto& ls : linkagesets) { diff --git a/src/MuxElements.h b/src/MuxElements.h index 9990415..d118df9 100644 --- a/src/MuxElements.h +++ b/src/MuxElements.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2022 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -163,6 +163,8 @@ class AnnouncementCluster : public RemoteControllable { /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + + virtual const json::map_t get_all_values() const; }; struct dabOutput { @@ -310,6 +312,8 @@ class dabEnsemble : public RemoteControllable { /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + virtual const json::map_t get_all_values() const; + /* Check if the Linkage Sets are valid */ bool validate_linkage_sets(void); @@ -483,6 +487,8 @@ class DabComponent : public RemoteControllable /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + + virtual const json::map_t get_all_values() const; }; class DabService : public RemoteControllable @@ -536,6 +542,8 @@ class DabService : public RemoteControllable /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + + virtual const json::map_t get_all_values() const; }; /* Represent an entry for FIG0/24 */ diff --git a/src/input/Edi.cpp b/src/input/Edi.cpp index 692ecb3..3838541 100644 --- a/src/input/Edi.cpp +++ b/src/input/Edi.cpp @@ -2,7 +2,7 @@ Copyright (C) 2009 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -470,7 +470,7 @@ const std::string Edi::get_parameter(const std::string& parameter) const ss << "prebuffering"; break; case Inputs::BufferManagement::Timestamped: - ss << "Timestamped"; + ss << "timestamped"; break; } } @@ -483,4 +483,21 @@ const std::string Edi::get_parameter(const std::string& parameter) const return ss.str(); } +const json::map_t Edi::get_all_values() const +{ + json::map_t map; + map["buffer"].v = m_max_frames_overrun; + map["prebuffering"].v = m_num_frames_prebuffering; + switch (getBufferManagement()) { + case Inputs::BufferManagement::Prebuffering: + map["buffermanagement"].v = "prebuffering"; + break; + case Inputs::BufferManagement::Timestamped: + map["buffermanagement"].v = "timestamped"; + break; + } + map["tistdelay"].v = m_tist_delay.count(); + return map; +} + } diff --git a/src/input/Edi.h b/src/input/Edi.h index cf4c576..3de17a7 100644 --- a/src/input/Edi.h +++ b/src/input/Edi.h @@ -2,7 +2,7 @@ Copyright (C) 2009 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2019 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -78,6 +78,7 @@ class Edi : public InputBase, public RemoteControllable { /* Remote control */ virtual void set_parameter(const std::string& parameter, const std::string& value); virtual const std::string get_parameter(const std::string& parameter) const; + virtual const json::map_t get_all_values() const; protected: void m_run(); diff --git a/src/input/Zmq.cpp b/src/input/Zmq.cpp index be3fd1f..d5e722e 100644 --- a/src/input/Zmq.cpp +++ b/src/input/Zmq.cpp @@ -614,7 +614,19 @@ const string ZmqBase::get_parameter(const string& parameter) const throw ParameterError(ss.str()); } return ss.str(); +} +const json::map_t ZmqBase::get_all_values() const +{ + json::map_t map; + map["buffer"].v = m_config.buffer_size; + map["prebuffering"].v = m_config.prebuffering; + map["enable"].v = m_enable_input; + map["encryption"].v = m_config.enable_encryption; + map["secretkey"].v = m_config.curve_secret_keyfile; + map["publickey"].v = m_config.curve_public_keyfile; + map["encoderkey"].v = m_config.curve_encoder_keyfile; + return map; } }; diff --git a/src/input/Zmq.h b/src/input/Zmq.h index c101da0..72fccbd 100644 --- a/src/input/Zmq.h +++ b/src/input/Zmq.h @@ -194,6 +194,7 @@ class ZmqBase : public InputBase, public RemoteControllable { /* Getting a parameter always returns a string. */ virtual const std::string get_parameter(const std::string& parameter) const; + virtual const json::map_t get_all_values() const; protected: virtual int readFromSocket(size_t framesize) = 0; -- cgit v1.2.3 From c4d841b4901563e38f705f62860d6214da53a689 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 8 Apr 2024 15:26:06 +0200 Subject: Clean up FIG carousel a bit --- src/DabMultiplexer.cpp | 6 ++-- src/DabMultiplexer.h | 4 +-- src/fig/FIG.cpp | 2 +- src/fig/FIG.h | 7 ++--- src/fig/FIG0_1.cpp | 9 +++--- src/fig/FIG0_1.h | 6 ++-- src/fig/FIG0_10.h | 2 +- src/fig/FIG0_13.h | 1 + src/fig/FIG0_17.h | 2 +- src/fig/FIG0_2.h | 1 + src/fig/FIG0_8.h | 1 + src/fig/FIG0_9.h | 2 +- src/fig/FIG0structs.h | 2 -- src/fig/FIGCarousel.cpp | 82 +++++++++++++++++++++++++++---------------------- src/fig/FIGCarousel.h | 8 ++--- 15 files changed, 70 insertions(+), 65 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 908caf9..b1f2c75 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -103,7 +103,8 @@ void DabMultiplexer::prepare(bool require_tai_clock) * a consistency across mux restarts. Ensure edi_time and TIST represent * current time. * - * Every 6s, FCT overflows. m_currentFrame overflows at 5000 every 120s. + * FCT and DLFC are directly derived from m_currentFrame. + * Every 6s, FCT overflows. DLFC overflows at 5000 every 120s. * * Keep a granularity of 24ms, which corresponds to the duration of an ETI * frame, to get nicer timestamps. @@ -611,9 +612,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs edi_tagDETI.fic_length = FICL * 4; // Insert all FIBs - fig_carousel.update(m_currentFrame); const bool fib3_present = (ensemble->transmission_mode == TransmissionMode_e::TM_III); - index += fig_carousel.write_fibs(&etiFrame[index], m_currentFrame % 4, fib3_present); + index += fig_carousel.write_fibs(&etiFrame[index], m_currentFrame, fib3_present); /********************************************************************** ****** Input Data Reading ******************************************* diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 90e5767..44155dc 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -61,7 +61,7 @@ class DabMultiplexer : public RemoteControllable { void prepare(bool require_tai_clock); - unsigned long getCurrentFrame() { return m_currentFrame; } + uint64_t getCurrentFrame() const { return m_currentFrame; } void mux_frame(std::vector >& outputs); @@ -93,7 +93,7 @@ class DabMultiplexer : public RemoteControllable { edi::configuration_t edi_conf; std::shared_ptr edi_sender; - unsigned long m_currentFrame = 0; + uint64_t m_currentFrame = 0; std::shared_ptr ensemble; diff --git a/src/fig/FIG.cpp b/src/fig/FIG.cpp index e064a33..ed79cf3 100644 --- a/src/fig/FIG.cpp +++ b/src/fig/FIG.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ diff --git a/src/fig/FIG.h b/src/fig/FIG.h index 116ac8b..9752245 100644 --- a/src/fig/FIG.h +++ b/src/fig/FIG.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ @@ -24,8 +24,7 @@ along with ODR-DabMux. If not, see . */ -#ifndef __FIG_H_ -#define __FIG_H_ +#pragma once #include #include "MuxElements.h" @@ -106,5 +105,3 @@ class IFIG } // namespace FIC -#endif // __FIG_H_ - diff --git a/src/fig/FIG0_1.cpp b/src/fig/FIG0_1.cpp index 60704f2..d72b301 100644 --- a/src/fig/FIG0_1.cpp +++ b/src/fig/FIG0_1.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -23,9 +23,7 @@ along with ODR-DabMux. If not, see . */ -#include "fig/FIG0structs.h" #include "fig/FIG0_1.h" -#include "utils.h" namespace FIC { @@ -101,7 +99,7 @@ FillStatus FIG0_1::fill(uint8_t *buf, size_t max_size) size_t remaining = max_size; etiLog.level(FIG0_1_TRACE) << "FIG0_1::fill initialised=" << - (m_initialised ? 1 : 0); + (m_initialised ? 1 : 0) << " max_size=" << max_size; const int watermark_bit = (m_watermarkData[m_watermarkPos >> 3] >> (7 - (m_watermarkPos & 0x07))) & 1; @@ -130,7 +128,8 @@ FillStatus FIG0_1::fill(uint8_t *buf, size_t max_size) for (; subchannelFIG0_1 != subchannels.end(); ++subchannelFIG0_1 ) { size_t subch_iter_ix = std::distance(subchannels.begin(), subchannelFIG0_1); - etiLog.level(FIG0_1_TRACE) << "FIG0_1::fill loop ix=" << subch_iter_ix; + etiLog.level(FIG0_1_TRACE) << "FIG0_1::fill loop ix=" << subch_iter_ix << + " of " << subchannels.size(); dabProtection* protection = &(*subchannelFIG0_1)->protection; diff --git a/src/fig/FIG0_1.h b/src/fig/FIG0_1.h index 4fc70ea..2bb898f 100644 --- a/src/fig/FIG0_1.h +++ b/src/fig/FIG0_1.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -26,11 +26,11 @@ #pragma once #include -#include +#include "fig/FIG.h" namespace FIC { -// FIG type 0/1, MIC, Sub-Channel Organization, +// FIG type 0/1, MCI, Sub-Channel Organization, // one instance of the part for each subchannel class FIG0_1 : public IFIG { diff --git a/src/fig/FIG0_10.h b/src/fig/FIG0_10.h index bc4a84b..69ba342 100644 --- a/src/fig/FIG0_10.h +++ b/src/fig/FIG0_10.h @@ -26,7 +26,7 @@ #pragma once #include -#include +#include "fig/FIG.h" namespace FIC { diff --git a/src/fig/FIG0_13.h b/src/fig/FIG0_13.h index 18159f0..00b5137 100644 --- a/src/fig/FIG0_13.h +++ b/src/fig/FIG0_13.h @@ -27,6 +27,7 @@ #include #include +#include "fig/FIG.h" namespace FIC { diff --git a/src/fig/FIG0_17.h b/src/fig/FIG0_17.h index d796f43..8d478c0 100644 --- a/src/fig/FIG0_17.h +++ b/src/fig/FIG0_17.h @@ -26,7 +26,7 @@ #pragma once #include -#include +#include "fig/FIG.h" namespace FIC { diff --git a/src/fig/FIG0_2.h b/src/fig/FIG0_2.h index 6cfca24..a96f189 100644 --- a/src/fig/FIG0_2.h +++ b/src/fig/FIG0_2.h @@ -27,6 +27,7 @@ #include #include +#include "fig/FIG.h" namespace FIC { // FIG type 0/2, MCI, Service Organization, one instance of diff --git a/src/fig/FIG0_8.h b/src/fig/FIG0_8.h index 64ca8d2..aef86c5 100644 --- a/src/fig/FIG0_8.h +++ b/src/fig/FIG0_8.h @@ -27,6 +27,7 @@ #include #include +#include "fig/FIG.h" namespace FIC { diff --git a/src/fig/FIG0_9.h b/src/fig/FIG0_9.h index f0ae2ea..ae9b7d1 100644 --- a/src/fig/FIG0_9.h +++ b/src/fig/FIG0_9.h @@ -26,8 +26,8 @@ #pragma once #include -#include #include +#include "fig/FIG.h" namespace FIC { diff --git a/src/fig/FIG0structs.h b/src/fig/FIG0structs.h index eb77df4..5f514b3 100644 --- a/src/fig/FIG0structs.h +++ b/src/fig/FIG0structs.h @@ -26,8 +26,6 @@ #pragma once #include -#include -#include #include "fig/FIG.h" diff --git a/src/fig/FIGCarousel.cpp b/src/fig/FIGCarousel.cpp index 4c5c04c..9748dbf 100644 --- a/src/fig/FIGCarousel.cpp +++ b/src/fig/FIGCarousel.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2020 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li Implementation of the FIG carousel to schedule the FIGs into the @@ -148,11 +148,14 @@ void FIGCarousel::load_and_allocate(IFIG& fig, FIBAllocation fib) m_fibs[fib].push_back(el); } -void FIGCarousel::update(unsigned long currentFrame) +size_t FIGCarousel::write_fibs( + uint8_t *buf, + uint64_t current_frame, + bool fib3_present) { - m_rti.currentFrame = currentFrame; + m_rti.currentFrame = current_frame; - if ((currentFrame % 250) == 0 and m_missed_deadlines.size() > 0) { + if ((current_frame % 250) == 0 and m_missed_deadlines.size() > 0) { std::stringstream ss; for (const auto& fig_missed_count : m_missed_deadlines) { ss << " " << fig_missed_count; @@ -161,21 +164,7 @@ void FIGCarousel::update(unsigned long currentFrame) etiLog.level(info) << "Could not respect repetition rates for FIGs:" << ss.str(); } -} - -void dumpfib(const uint8_t *buf, size_t bufsize) { - std::cerr << "FIB "; - for (size_t i = 0; i < bufsize; i++) { - std::cerr << boost::format("%02x ") % (unsigned int)buf[i]; - } - std::cerr << std::endl; -} -size_t FIGCarousel::write_fibs( - uint8_t *buf, - int framephase, - bool fib3_present) -{ /* Decrement all deadlines of all figs */ for (auto& fib_fig : m_fibs) { auto& fig = fib_fig.second; @@ -183,6 +172,9 @@ size_t FIGCarousel::write_fibs( fig_el.reduce_deadline(); if (fig_el.deadline < 0) { +#if CAROUSELDEBUG + etiLog.level(warn) << " FIG" << fig_el.fig->name() << " LATE"; +#endif m_missed_deadlines.insert(fig_el.fig->name()); } } @@ -192,7 +184,7 @@ size_t FIGCarousel::write_fibs( for (int fib = 0; fib < fibCount; fib++) { memset(buf, 0x00, 30); - size_t figSize = carousel(fib, buf, 30, framephase); + size_t figSize = carousel(fib, buf, 30, current_frame); if (figSize < 30) { buf[figSize] = 0xff; // end marker @@ -219,8 +211,10 @@ size_t FIGCarousel::carousel( int fib, uint8_t *buf, const size_t bufsize, - int framephase) + uint64_t current_frame) { + const int framephase = current_frame % 4; + uint8_t *pbuf = buf; FIBAllocation fibix; @@ -253,9 +247,10 @@ size_t FIGCarousel::carousel( for (auto& fig : sorted_figs) { if (fig->check_deadline()) { #if CAROUSELDEBUG - std::cerr << " FIG" << fig->fig->figtype() << "/" << - fig->fig->figextension() << " deadline changed" << - std::endl; + etiLog.level(debug) << + "FRAME " << current_frame << + " FIG" << fig->fig->figtype() << "/" << + fig->fig->figextension() << " deadline changed"; #endif } } @@ -267,12 +262,18 @@ size_t FIGCarousel::carousel( return left->deadline < right->deadline; }); -#if CAROUSELDEBUG - std::cerr << " ************** FIGs" << std::endl; - for (auto& f : sorted_figs) { - std::cerr << " FIG" << f->fig->figtype() << "/" << - f->fig->figextension() << " deadline " << - f->deadline << std::endl; +#if 0 + { + std::stringstream ss; + ss << "FRAME " << current_frame + << " sorted FIGs "; + + for (auto& f : sorted_figs) { + ss << f->fig->figtype() << "/" << + f->fig->figextension() << "(" << + f->deadline << ") "; + } + etiLog.level(debug) << ss.str(); } #endif @@ -301,8 +302,9 @@ size_t FIGCarousel::carousel( pbuf += written; #if CAROUSELDEBUG - std::cerr << " ****** FIG0/0(special) wrote\t" << written << " bytes" - << std::endl; + etiLog.level(debug) << + "FRAME " << current_frame << + " *** FIG0/0(special) wrote\t" << written << " bytes"; #endif } else { @@ -325,8 +327,9 @@ size_t FIGCarousel::carousel( pbuf += written; #if CAROUSELDEBUG - std::cerr << " ****** FIG0/7(special) wrote\t" << written << " bytes" - << std::endl; + etiLog.level(debug) << + "FRAME " << current_frame << + " ****** FIG0/7(special) wrote\t" << written << " bytes"; #endif } @@ -376,13 +379,14 @@ size_t FIGCarousel::carousel( } #if CAROUSELDEBUG if (written) { - std::cerr << + etiLog.level(debug) << + " FRAME " << current_frame << " ** FIB" << fib << " FIG" << fig_el->fig->figtype() << "/" << fig_el->fig->figextension() << " wrote\t" << written << " bytes" << (status.complete_fig_transmitted ? ", complete" : ", incomplete") << - std::endl; + ", margin " << fig_el->deadline; } #endif @@ -393,7 +397,13 @@ size_t FIGCarousel::carousel( sorted_figs.pop_front(); } - //dumpfib(buf, bufsize); +#if 0 + std::cerr << "FIB "; + for (size_t i = 0; i < bufsize; i++) { + std::cerr << boost::format("%02x ") % (unsigned int)buf[i]; + } + std::cerr << std::endl; +#endif return bufsize - available_size; } diff --git a/src/fig/FIGCarousel.h b/src/fig/FIGCarousel.h index 00b6d18..1e33577 100644 --- a/src/fig/FIGCarousel.h +++ b/src/fig/FIGCarousel.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2020 + Copyright (C) 2024 Matthias P. Braendli, matthias.braendli@mpb.li Implementation of the FIG carousel to schedule the FIGs into the @@ -69,8 +69,6 @@ class FIGCarousel { public: FIGCarousel(std::shared_ptr ensemble); - void update(unsigned long currentFrame); - /* Write all FIBs to the buffer, including correct padding and crc. * Returns number of bytes written. * @@ -79,11 +77,11 @@ class FIGCarousel { */ size_t write_fibs( uint8_t *buf, - int framephase, + uint64_t current_frame, bool fib3_present); private: - size_t carousel(int fib, uint8_t *buf, size_t bufsize, int framephase); + size_t carousel(int fib, uint8_t *buf, size_t bufsize, uint64_t current_frame); void load_and_allocate(IFIG& fig, FIBAllocation fib); -- cgit v1.2.3 From 5b35713111c38108f3560595a0a428836ec6e749 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Sun, 9 Jun 2024 12:06:48 +0200 Subject: Make MNSC compatible with Easydabv2 again --- src/DabMultiplexer.cpp | 21 ++++++++++++++------- src/DabMultiplexer.h | 14 +++++++++++++- 2 files changed, 27 insertions(+), 8 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index b1f2c75..c402d84 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -142,6 +142,9 @@ void DabMultiplexer::prepare(bool require_tai_clock) offset_ms -= 24; } + mnsc_increment_time = false; + mnsc_time = m_edi_time; + etiLog.log(info, "Startup CIF Count %i with timestamp: %d + %f", m_currentFrame, m_edi_time, (m_timestamp & 0xFFFFFF) / 16384000.0); @@ -393,6 +396,9 @@ void DabMultiplexer::increment_timestamp() if (m_timestamp > 0xf9FFff) { m_timestamp -= 0xfa0000; // Substract 16384000, corresponding to one second m_edi_time += 1; + + // Also update MNSC time for next time FP==0 + mnsc_increment_time = true; } } @@ -554,14 +560,9 @@ void DabMultiplexer::mux_frame(std::vector >& outputs eoh->MNSC = 0; - if (fc->FP == 0) { - // update the latched time only when FP==0 to ensure MNSC encodes - // a consistent time - m_edi_time_latched_for_mnsc = edi_time; - } - struct tm time_tm; - gmtime_r(&m_edi_time_latched_for_mnsc, &time_tm); + gmtime_r(&mnsc_time, &time_tm); + switch (fc->FP & 0x3) { case 0: { @@ -571,6 +572,12 @@ void DabMultiplexer::mux_frame(std::vector >& outputs mnsc->identifier = 0; mnsc->rfa = 0; } + + if (mnsc_increment_time) + { + mnsc_increment_time = false; + mnsc_time += 1; + } break; case 1: { diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 44155dc..89d547e 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -88,7 +88,19 @@ class DabMultiplexer : public RemoteControllable { uint32_t m_timestamp = 0; std::time_t m_edi_time = 0; - std::time_t m_edi_time_latched_for_mnsc = 0; + + /* Pre v3 odr-dabmux did the MNSC calculation differently, + * which works with the easydabv2. The rework in odr-dabmux, + * deriving MNSC time from EDI time broke this. + * + * That's why we're now tracking MNSC time in separate variables, + * to get the same behaviour back. + * + * I'm not aware of any devices using MNSC time besides the + * easydab. ODR-DabMod now considers EDI seconds or ZMQ metadata. + */ + bool mnsc_increment_time = false; + std::time_t mnsc_time = 0; edi::configuration_t edi_conf; std::shared_ptr edi_sender; -- cgit v1.2.3 From 4b6590c5fa5b7a7a4cc5b62da4db21e9a1247b61 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Tue, 11 Jun 2024 15:29:07 +0200 Subject: Apply tist_offset to MNSC time too --- src/DabMultiplexer.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index c402d84..bd1c909 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -143,7 +143,11 @@ void DabMultiplexer::prepare(bool require_tai_clock) } mnsc_increment_time = false; - mnsc_time = m_edi_time; + + bool tist_enabled = m_pt.get("general.tist", false); + m_tist_offset = m_pt.get("general.tist_offset", 0); + + mnsc_time = m_edi_time + m_tist_offset; etiLog.log(info, "Startup CIF Count %i with timestamp: %d + %f", m_currentFrame, m_edi_time, @@ -151,9 +155,6 @@ void DabMultiplexer::prepare(bool require_tai_clock) // Try to load offset once - bool tist_enabled = m_pt.get("general.tist", false); - m_tist_offset = m_pt.get("general.tist_offset", 0); - m_tai_clock_required = (tist_enabled and edi_conf.enabled()) or require_tai_clock; if (m_tai_clock_required) { -- cgit v1.2.3 From 9566a524f87d9de68d7fd16660e9c467a588559e Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 6 Jan 2025 21:56:49 +0100 Subject: Support 24ms granularity in tist_offset --- doc/example.mux | 6 +- src/DabMultiplexer.cpp | 204 ++++++++++++++++++++++++++++--------------------- src/DabMultiplexer.h | 66 ++++++++-------- 3 files changed, 151 insertions(+), 125 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/doc/example.mux b/doc/example.mux index d53b789..34cd2ee 100644 --- a/doc/example.mux +++ b/doc/example.mux @@ -57,9 +57,9 @@ general { tist false ; On startup, the timestamp is initialised to system time. If you want - ; to add an offset, uncomment the following line and give a number - ; in seconds. - ; tist_offset 0 + ; to add an offset, uncomment the following line and give a positive + ; number in seconds. Granularity: 24ms + ; tist_offset 0.480 ; The URLs used to fetch the TAI bulletin can be overridden if needed. ; URLs are given as a pipe-separated list, and the default value is: diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index bd1c909..87cccd4 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -23,11 +23,13 @@ along with ODR-DabMux. If not, see . */ +#include #include #include #include "DabMultiplexer.h" #include "ConfigParser.h" -#include "fig/FIG.h" +#include "crc.h" +#include "utils.h" using namespace std; @@ -44,8 +46,84 @@ static vector split_pipe_separated_string(const std::string& s) return components; } -DabMultiplexer::DabMultiplexer( - boost::property_tree::ptree pt) : +uint64_t MuxTime::init() +{ + /* At startup, derive edi_time, TIST and CIF count such that there is + * a consistency across mux restarts. Ensure edi_time and TIST represent + * current time. + * + * FCT and DLFC are directly derived from m_currentFrame. + * Every 6s, FCT overflows. DLFC overflows at 5000 every 120s. + * + * Keep a granularity of 24ms, which corresponds to the duration of an ETI + * frame, to get nicer timestamps. + */ + using Sec = chrono::seconds; + const auto now = chrono::system_clock::now(); + const auto offset = now - chrono::time_point_cast(now); + if (offset >= chrono::seconds(1)) { + throw std::logic_error("Invalid startup offset calculation for TIST! " + + to_string(chrono::duration_cast(offset).count()) + + " ms"); + } + const time_t t_now = chrono::system_clock::to_time_t(chrono::time_point_cast(now)); + + m_edi_time = t_now - (t_now % 6); + uint64_t currentFrame = 0; + time_t edi_time_at_cif0 = t_now - (t_now % 120); + while (edi_time_at_cif0 < m_edi_time) { + edi_time_at_cif0 += 6; + currentFrame += 250; + } + + if (edi_time_at_cif0 != m_edi_time) { + throw std::logic_error("Invalid startup offset calculation for CIF!"); + } + + int64_t offset_ms = chrono::duration_cast(offset).count(); + offset_ms += 1000 * (t_now - m_edi_time); + + m_timestamp = 0; + while (offset_ms >= 24) { + increment_timestamp(); + currentFrame++; + offset_ms -= 24; + } + return currentFrame; +} + +void MuxTime::increment_timestamp() +{ + m_timestamp += 24 << 14; // Shift 24ms by 14 to Timestamp level 2 + if (m_timestamp > 0xf9FFff) { + m_timestamp -= 0xfa0000; // Subtract 16384000, corresponding to one second + m_edi_time += 1; + + // Also update MNSC time for next time FP==0 + mnsc_increment_time = true; + } +} + +std::pair MuxTime::get_time() +{ + // negative tist_offset not supported, because the calculation is annoying + if (tist_offset < 0) return {m_timestamp, m_edi_time}; + + double fractional_part = tist_offset - std::floor(tist_offset); + const size_t steps = std::lround(std::floor(fractional_part / 24e-3)); + uint32_t timestamp = m_timestamp + (24 << 14) * steps; + + std::time_t edi_time = m_edi_time + std::lround(std::floor(tist_offset)); + + if (timestamp > 0xf9FFff) { + edi_time += 1; + } + + return {timestamp % 0xfa0000, edi_time}; +} + + +DabMultiplexer::DabMultiplexer(boost::property_tree::ptree pt) : RemoteControllable("mux"), m_pt(pt), ensemble(std::make_shared()), @@ -53,7 +131,7 @@ DabMultiplexer::DabMultiplexer( fig_carousel(ensemble) { RC_ADD_PARAMETER(frames, "Show number of frames generated [read-only]"); - RC_ADD_PARAMETER(tist_offset, "Timestamp offset in integral number of seconds"); + RC_ADD_PARAMETER(tist_offset, "Timestamp offset in fractional number of seconds"); rcs.enrol(&m_clock_tai); } @@ -99,59 +177,20 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - /* At startup, derive edi_time, TIST and CIF count such that there is - * a consistency across mux restarts. Ensure edi_time and TIST represent - * current time. - * - * FCT and DLFC are directly derived from m_currentFrame. - * Every 6s, FCT overflows. DLFC overflows at 5000 every 120s. - * - * Keep a granularity of 24ms, which corresponds to the duration of an ETI - * frame, to get nicer timestamps. - */ - using Sec = chrono::seconds; - const auto now = chrono::system_clock::now(); - const time_t t_now = chrono::system_clock::to_time_t(chrono::time_point_cast(now)); - - m_edi_time = t_now - (t_now % 6); - m_currentFrame = 0; - time_t edi_time_at_cif0 = t_now - (t_now % 120); - while (edi_time_at_cif0 < m_edi_time) { - edi_time_at_cif0 += 6; - m_currentFrame += 250; - } - - if (edi_time_at_cif0 != m_edi_time) { - throw std::logic_error("Invalid startup offset calculation for CIF!"); - } - - const auto offset = now - chrono::time_point_cast(now); - if (offset >= chrono::seconds(1)) { - throw std::logic_error("Invalid startup offset calculation for TIST! " + - to_string(chrono::duration_cast(offset).count()) + - " ms"); - } - - int64_t offset_ms = chrono::duration_cast(offset).count(); - offset_ms += 1000 * (t_now - m_edi_time); - - m_timestamp = 0; - while (offset_ms >= 24) { - increment_timestamp(); - m_currentFrame++; - offset_ms -= 24; - } - - mnsc_increment_time = false; + m_time.init(); + m_time.mnsc_increment_time = false; bool tist_enabled = m_pt.get("general.tist", false); - m_tist_offset = m_pt.get("general.tist_offset", 0); + m_time.tist_offset = m_pt.get("general.tist_offset", 0.0); - mnsc_time = m_edi_time + m_tist_offset; + auto tist_edi_time = m_time.get_time(); + const auto timestamp = tist_edi_time.first; + const auto edi_time = tist_edi_time.second; + m_time.mnsc_time = edi_time; etiLog.log(info, "Startup CIF Count %i with timestamp: %d + %f", - m_currentFrame, m_edi_time, - (m_timestamp & 0xFFFFFF) / 16384000.0); + currentFrame, edi_time, + (timestamp & 0xFFFFFF) / 16384000.0); // Try to load offset once @@ -391,17 +430,6 @@ void DabMultiplexer::prepare_data_inputs() } } -void DabMultiplexer::increment_timestamp() -{ - m_timestamp += 24 << 14; // Shift 24ms by 14 to Timestamp level 2 - if (m_timestamp > 0xf9FFff) { - m_timestamp -= 0xfa0000; // Substract 16384000, corresponding to one second - m_edi_time += 1; - - // Also update MNSC time for next time FP==0 - mnsc_increment_time = true; - } -} /* Each call creates one ETI frame */ void DabMultiplexer::mux_frame(std::vector >& outputs) @@ -434,7 +462,9 @@ void DabMultiplexer::mux_frame(std::vector >& outputs } update_dab_time(); - const auto edi_time = m_edi_time + m_tist_offset; + auto tist_edi_time = m_time.get_time(); + const auto timestamp = tist_edi_time.first; + const auto edi_time = tist_edi_time.second; // Initialise the ETI frame memset(etiFrame, 0, 6144); @@ -450,7 +480,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs //****** Field FSYNC *****// // See ETS 300 799, 6.2.1.2 - if ((m_currentFrame & 1) == 0) { + if ((currentFrame & 1) == 0) { etiSync->FSYNC = ETI_FSYNC1; } else { @@ -469,8 +499,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs //****** FCT ******// // Incremente for each frame, overflows at 249 - fc->FCT = m_currentFrame % 250; - edi_tagDETI.dlfc = m_currentFrame % 5000; + fc->FCT = currentFrame % 250; + edi_tagDETI.dlfc = currentFrame % 5000; //****** FICF ******// // Fast Information Channel Flag, 1 bit, =1 if FIC present @@ -487,7 +517,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs /* Frame Phase, 3 bit counter, tells the COFDM generator * when to insert the TII. Is also used by the MNSC. */ - fc->FP = edi_tagDETI.fp = m_currentFrame & 0x7; + fc->FP = edi_tagDETI.fp = currentFrame & 0x7; //****** MID ******// //Mode Identity, 2 bits, 01 ModeI, 10 modeII, 11 ModeIII, 00 ModeIV @@ -562,7 +592,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs eoh->MNSC = 0; struct tm time_tm; - gmtime_r(&mnsc_time, &time_tm); + gmtime_r(&m_time.mnsc_time, &time_tm); switch (fc->FP & 0x3) { case 0: @@ -574,10 +604,10 @@ void DabMultiplexer::mux_frame(std::vector >& outputs mnsc->rfa = 0; } - if (mnsc_increment_time) + if (m_time.mnsc_increment_time) { - mnsc_increment_time = false; - mnsc_time += 1; + m_time.mnsc_increment_time = false; + m_time.mnsc_time += 1; } break; case 1: @@ -621,7 +651,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs // Insert all FIBs const bool fib3_present = (ensemble->transmission_mode == TransmissionMode_e::TM_III); - index += fig_carousel.write_fibs(&etiFrame[index], m_currentFrame, fib3_present); + index += fig_carousel.write_fibs(&etiFrame[index], currentFrame, fib3_present); /********************************************************************** ****** Input Data Reading ******************************************* @@ -633,12 +663,13 @@ void DabMultiplexer::mux_frame(std::vector >& outputs int sizeSubchannel = subchannel->getSizeByte(); // no need to check enableTist because we always increment the timestamp int result = subchannel->readFrame(&etiFrame[index], - sizeSubchannel, edi_time, tai_utc_offset, m_timestamp); + sizeSubchannel, + edi_time, tai_utc_offset, timestamp); if (result < 0) { etiLog.log(info, "Subchannel %d read failed at ETI frame number: %d", - subchannel->id, m_currentFrame); + subchannel->id, currentFrame); } // save pointer to Audio or Data Stream into correct TagESTn for EDI @@ -678,8 +709,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs bool enableTist = m_pt.get("general.tist", false); if (enableTist) { - tist->TIST = htonl(m_timestamp) | 0xff; - edi_tagDETI.tsta = m_timestamp & 0xffffff; + tist->TIST = htonl(timestamp) | 0xff; + edi_tagDETI.tsta = timestamp & 0xffffff; } else { tist->TIST = htonl(0xffffff) | 0xff; @@ -700,7 +731,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs output->setMetadata(md_edi_time); shared_ptr md_dlfc = - make_shared(m_currentFrame % 5000); + make_shared(currentFrame % 5000); output->setMetadata(md_dlfc); } } @@ -716,8 +747,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs Approximate 8 ms 1 ms 3,91 us 488 ns 61 ns time resolution */ - - increment_timestamp(); + m_time.increment_timestamp(); /********************************************************************** *********** Section FRPD ***************************************** @@ -769,7 +799,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs if (enableTist) { etiLog.log(info, "ETI frame number %i Timestamp: %d + %f", m_currentFrame, edi_time, - (m_timestamp & 0xFFFFFF) / 16384000.0); + (timestamp & 0xFFFFFF) / 16384000.0); } else { etiLog.log(info, "ETI frame number %i Time: %d, no TIST", @@ -778,7 +808,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs } #endif - m_currentFrame++; + currentFrame++; } void DabMultiplexer::print_info() @@ -799,7 +829,7 @@ void DabMultiplexer::set_parameter(const std::string& parameter, throw ParameterError(ss.str()); } else if (parameter == "tist_offset") { - m_tist_offset = std::stoi(value); + m_time.tist_offset = std::stod(value); } else { stringstream ss; @@ -814,10 +844,10 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co { stringstream ss; if (parameter == "frames") { - ss << m_currentFrame; + ss << currentFrame; } else if (parameter == "tist_offset") { - ss << m_tist_offset; + ss << m_time.tist_offset; } else { ss << "Parameter '" << parameter << @@ -831,8 +861,8 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co const json::map_t DabMultiplexer::get_all_values() const { json::map_t map; - map["frames"].v = m_currentFrame; - map["tist_offset"].v = m_tist_offset; + map["frames"].v = currentFrame; + map["tist_offset"].v = m_time.tist_offset; return map; } diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 89d547e..d3cdb75 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -30,21 +30,12 @@ #endif #include "dabOutput/dabOutput.h" -#include "edioutput/TagItems.h" -#include "edioutput/TagPacket.h" -#include "edioutput/AFPacket.h" #include "edioutput/Transport.h" #include "fig/FIGCarousel.h" -#include "crc.h" -#include "utils.h" -#include "Socket.h" -#include "PcDebug.h" #include "MuxElements.h" #include "RemoteControl.h" -#include "Eti.h" #include "ClockTAI.h" #include -#include #include #include #include @@ -52,6 +43,34 @@ constexpr uint32_t ETI_FSYNC1 = 0x49C5F8; +class MuxTime { + private: + uint32_t m_timestamp = 0; + std::time_t m_edi_time = 0; + + public: + std::pair get_time(); + + double tist_offset = 0; + + /* Pre v3 odr-dabmux did the MNSC calculation differently, + * which works with the easydabv2. The rework in odr-dabmux, + * deriving MNSC time from EDI time broke this. + * + * That's why we're now tracking MNSC time in separate variables, + * to get the same behaviour back. + * + * I'm not aware of any devices using MNSC time besides the + * easydab. ODR-DabMod now considers EDI seconds or ZMQ metadata. + */ + bool mnsc_increment_time = false; + std::time_t mnsc_time = 0; + + /* Setup the time and return the initial currentFrame counter value */ + uint64_t init(); + void increment_timestamp(); +}; + class DabMultiplexer : public RemoteControllable { public: DabMultiplexer(boost::property_tree::ptree pt); @@ -61,7 +80,7 @@ class DabMultiplexer : public RemoteControllable { void prepare(bool require_tai_clock); - uint64_t getCurrentFrame() const { return m_currentFrame; } + uint64_t getCurrentFrame() const { return currentFrame; } void mux_frame(std::vector >& outputs); @@ -82,34 +101,17 @@ class DabMultiplexer : public RemoteControllable { void prepare_subchannels(void); void prepare_services_components(void); void prepare_data_inputs(void); - void increment_timestamp(void); boost::property_tree::ptree m_pt; - uint32_t m_timestamp = 0; - std::time_t m_edi_time = 0; - - /* Pre v3 odr-dabmux did the MNSC calculation differently, - * which works with the easydabv2. The rework in odr-dabmux, - * deriving MNSC time from EDI time broke this. - * - * That's why we're now tracking MNSC time in separate variables, - * to get the same behaviour back. - * - * I'm not aware of any devices using MNSC time besides the - * easydab. ODR-DabMod now considers EDI seconds or ZMQ metadata. - */ - bool mnsc_increment_time = false; - std::time_t mnsc_time = 0; + MuxTime m_time; + uint64_t currentFrame = 0; edi::configuration_t edi_conf; std::shared_ptr edi_sender; - uint64_t m_currentFrame = 0; - std::shared_ptr ensemble; - int m_tist_offset = 0; bool m_tai_clock_required = false; ClockTAI m_clock_tai; @@ -117,12 +119,6 @@ class DabMultiplexer : public RemoteControllable { FIC::FIGCarousel fig_carousel; }; -// DAB Mode -#define DEFAULT_DAB_MODE 1 - -// Taille de la trame de donnee, sous-canal 3, nb de paquets de 64bits, -// STL3 * 8 = x kbytes par trame ETI - // Data bitrate in kbits/s. Must be 64 kb/s multiple. #define DEFAULT_DATA_BITRATE 384 #define DEFAULT_PACKET_BITRATE 32 -- cgit v1.2.3 From 409ec7f6899693fb7f1c141945f83fe6cfa41827 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 6 Jan 2025 22:11:12 +0100 Subject: Move some constants around --- src/ConfigParser.cpp | 11 +++++++---- src/DabMultiplexer.cpp | 2 +- src/DabMultiplexer.h | 19 +------------------ src/fig/FIG0structs.h | 18 ++++++++---------- src/utils.cpp | 1 - 5 files changed, 17 insertions(+), 34 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/ConfigParser.cpp b/src/ConfigParser.cpp index 74e627b..7d166b6 100644 --- a/src/ConfigParser.cpp +++ b/src/ConfigParser.cpp @@ -36,16 +36,13 @@ # include "config.h" #endif -#include "dabOutput/dabOutput.h" #include "utils.h" -#include "DabMux.h" -#include "ManagementServer.h" #include "input/Edi.h" #include "input/Prbs.h" #include "input/Zmq.h" #include "input/File.h" #include "input/Udp.h" -#include "Eti.h" +#include "fig/FIG0structs.h" #include #include #include @@ -63,6 +60,12 @@ using namespace std; using boost::property_tree::ptree; using boost::property_tree::ptree_error; +constexpr uint16_t DEFAULT_DATA_BITRATE = 384; +constexpr uint16_t DEFAULT_PACKET_BITRATE = 32; + +constexpr uint32_t DEFAULT_SERVICE_ID = 50; + + static void setup_subchannel_from_ptree(shared_ptr& subchan, const ptree &pt, std::shared_ptr ensemble, diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 87cccd4..e84bfbf 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2024 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li */ /* diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index d3cdb75..92fa2c0 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2024 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -118,20 +118,3 @@ class DabMultiplexer : public RemoteControllable { /* New FIG Carousel */ FIC::FIGCarousel fig_carousel; }; - -// Data bitrate in kbits/s. Must be 64 kb/s multiple. -#define DEFAULT_DATA_BITRATE 384 -#define DEFAULT_PACKET_BITRATE 32 - -/* default ensemble parameters. Label must be max 16 chars, short label - * a subset of the label, max 8 chars - */ -#define DEFAULT_ENSEMBLE_LABEL "ODR Dab Mux" -#define DEFAULT_ENSEMBLE_SHORT_LABEL "ODRMux" -#define DEFAULT_ENSEMBLE_ID 0xc000 -#define DEFAULT_ENSEMBLE_ECC 0xa1 - -// start value for default service IDs (if not overridden by configuration) -#define DEFAULT_SERVICE_ID 50 -#define DEFAULT_PACKET_ADDRESS 0 - diff --git a/src/fig/FIG0structs.h b/src/fig/FIG0structs.h index 5f514b3..2e107e8 100644 --- a/src/fig/FIG0structs.h +++ b/src/fig/FIG0structs.h @@ -24,19 +24,17 @@ */ #pragma once - #include - #include "fig/FIG.h" -#define FIG0_13_APPTYPE_SLIDESHOW 0x2 -#define FIG0_13_APPTYPE_WEBSITE 0x3 -#define FIG0_13_APPTYPE_TPEG 0x4 -#define FIG0_13_APPTYPE_DGPS 0x5 -#define FIG0_13_APPTYPE_TMC 0x6 -#define FIG0_13_APPTYPE_SPI 0x7 -#define FIG0_13_APPTYPE_DABJAVA 0x8 -#define FIG0_13_APPTYPE_JOURNALINE 0x44a +constexpr uint16_t FIG0_13_APPTYPE_SLIDESHOW = 0x2; +constexpr uint16_t FIG0_13_APPTYPE_WEBSITE = 0x3; +constexpr uint16_t FIG0_13_APPTYPE_TPEG = 0x4; +constexpr uint16_t FIG0_13_APPTYPE_DGPS = 0x5; +constexpr uint16_t FIG0_13_APPTYPE_TMC = 0x6; +constexpr uint16_t FIG0_13_APPTYPE_SPI = 0x7; +constexpr uint16_t FIG0_13_APPTYPE_DABJAVA = 0x8; +constexpr uint16_t FIG0_13_APPTYPE_JOURNALINE = 0x44a; struct FIGtype0 { diff --git a/src/utils.cpp b/src/utils.cpp index e7ef224..1a13caf 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -29,7 +29,6 @@ #include #include #include -#include "DabMux.h" #include "utils.h" #include "fig/FIG0structs.h" -- cgit v1.2.3 From 02dce785b1861e4c017b48b2a76fef346bb1259a Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 17 Feb 2025 07:48:55 +0100 Subject: Fix initial setting of DFLC and FCT --- src/DabMultiplexer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index e84bfbf..095a835 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -177,7 +177,7 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - m_time.init(); + currentFrame = m_time.init(); m_time.mnsc_increment_time = false; bool tist_enabled = m_pt.get("general.tist", false); -- cgit v1.2.3 From 9c5b00e8cd05d3e484d6bbfbee351845598cd2ec Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 17 Feb 2025 08:05:36 +0100 Subject: Add tist_at_fct0 configuration --- doc/advanced.mux | 3 +++ src/DabMultiplexer.cpp | 12 +++++++++--- src/DabMultiplexer.h | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/doc/advanced.mux b/doc/advanced.mux index 246f981..618a6b6 100644 --- a/doc/advanced.mux +++ b/doc/advanced.mux @@ -36,6 +36,9 @@ general { ; in seconds. ; tist_offset 0 + ; Specify the TIST value for the frame with FCT==0, in microseconds + ; tist_at_fct0 768000 + ; The management server is a simple TCP server that can present ; statistics data (buffers, overruns, underruns, etc) ; which can then be graphed a tool like Munin diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 095a835..a68f09a 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -46,7 +46,7 @@ static vector split_pipe_separated_string(const std::string& s) return components; } -uint64_t MuxTime::init() +uint64_t MuxTime::init(uint32_t tist_at_fct0_us) { /* At startup, derive edi_time, TIST and CIF count such that there is * a consistency across mux restarts. Ensure edi_time and TIST represent @@ -83,7 +83,12 @@ uint64_t MuxTime::init() int64_t offset_ms = chrono::duration_cast(offset).count(); offset_ms += 1000 * (t_now - m_edi_time); - m_timestamp = 0; + if (tist_at_fct0_us >= 1000000) { + etiLog.level(error) << "tist_at_fct0 may not be larger than 1s"; + throw MuxInitException(); + } + + m_timestamp = (uint64_t)tist_at_fct0_us * 16384 / 1000; while (offset_ms >= 24) { increment_timestamp(); currentFrame++; @@ -177,7 +182,8 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - currentFrame = m_time.init(); + const uint32_t tist_at_fct0_us = m_pt.get("general.tist_at_fct0", 0); + currentFrame = m_time.init(tist_at_fct0_us); m_time.mnsc_increment_time = false; bool tist_enabled = m_pt.get("general.tist", false); diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 92fa2c0..aa6adfb 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -67,7 +67,7 @@ class MuxTime { std::time_t mnsc_time = 0; /* Setup the time and return the initial currentFrame counter value */ - uint64_t init(); + uint64_t init(uint32_t tist_at_fct0_us); void increment_timestamp(); }; -- cgit v1.2.3 From 6517cc3078eba96ea96e085d033a4b8a96eb7151 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Tue, 11 Mar 2025 16:35:08 +0100 Subject: Add EDI/TCP number of active connections statistics --- doc/STATS.md | 7 +++-- doc/show_dabmux_stats.py | 22 +++++++++++++ lib/Socket.cpp | 22 +++++++++++++ lib/Socket.h | 10 ++++++ lib/ThreadsafeQueue.h | 38 +++++++++++++++-------- lib/edioutput/Transport.cpp | 16 +++++++++- lib/edioutput/Transport.h | 11 +++++-- src/DabMultiplexer.cpp | 7 +++++ src/ManagementServer.cpp | 75 ++++++++++++++++++++++++++++++++------------- src/ManagementServer.h | 20 ++++++++---- 10 files changed, 181 insertions(+), 47 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/doc/STATS.md b/doc/STATS.md index 385d41e..435a92e 100644 --- a/doc/STATS.md +++ b/doc/STATS.md @@ -4,12 +4,13 @@ Stats available through Management Server Interface --------- -The management server makes statistics about the inputs available through a ZMQ request/reply socket. +The management server makes statistics about the inputs and EDI/TCP outputs +available through a ZMQ request/reply socket. The `show_dabmux_stats.py` illustrates how to access this information. -Meaning of values ------------------ +Meaning of values for inputs +---------------------------- `max` and `min` indicate input buffer fullness in bytes. diff --git a/doc/show_dabmux_stats.py b/doc/show_dabmux_stats.py index 7ea60f7..3b6d869 100755 --- a/doc/show_dabmux_stats.py +++ b/doc/show_dabmux_stats.py @@ -46,6 +46,7 @@ if len(sys.argv) == 1: data = sock.recv().decode("utf-8") values = json.loads(data)['values'] + print("## INPUT STATS") tmpl = "{ident:20}{maxfill:>8}{minfill:>8}{under:>8}{over:>8}{audioleft:>8}{audioright:>8}{peakleft:>8}{peakright:>8}{state:>16}{version:>48}{uptime:>8}{offset:>8}" print(tmpl.format( ident="id", @@ -89,6 +90,27 @@ if len(sys.argv) == 1: uptime=v['uptime'], offset=v['last_tist_offset'])) + sock.send(b"output_values") + + poller = zmq.Poller() + poller.register(sock, zmq.POLLIN) + + socks = dict(poller.poll(1000)) + if socks: + if socks.get(sock) == zmq.POLLIN: + print() + print("## OUTPUT STATS") + data = sock.recv().decode("utf-8") + values = json.loads(data)['output_values'] + for identifier in values: + if identifier.startswith("edi_tcp_"): + listen_port = identifier.rsplit("_", 1)[-1] + num_connections = values[identifier]["num_connections"] + print(f"EDI TCP on port {listen_port}: {num_connections} connections") + else: + print(f"Unknown output type: {identifier}") + + elif len(sys.argv) == 2 and sys.argv[1] == "config": sock = connect() diff --git a/lib/Socket.cpp b/lib/Socket.cpp index 938b573..5c920d7 100644 --- a/lib/Socket.cpp +++ b/lib/Socket.cpp @@ -24,6 +24,7 @@ #include "Socket.h" +#include #include #include #include @@ -1063,6 +1064,17 @@ void TCPConnection::process() #endif } +TCPConnection::stats_t TCPConnection::get_stats() const +{ + TCPConnection::stats_t s; + const vector buffer_sizes = queue.map( + [](const vector& vec) { return vec.size(); } + ); + + s.buffer_fullness = std::accumulate(buffer_sizes.cbegin(), buffer_sizes.cend(), 0); + s.remote_address = m_sock.get_remote_address(); + return s; +} TCPDataDispatcher::TCPDataDispatcher(size_t max_queue_size, size_t buffers_to_preroll) : m_max_queue_size(max_queue_size), @@ -1136,6 +1148,16 @@ void TCPDataDispatcher::process() } } + +std::vector TCPDataDispatcher::get_stats() const +{ + std::vector s; + for (const auto& conn : m_connections) { + s.push_back(conn.get_stats()); + } + return s; +} + TCPReceiveServer::TCPReceiveServer(size_t blocksize) : m_blocksize(blocksize) { diff --git a/lib/Socket.h b/lib/Socket.h index 7709145..29b618a 100644 --- a/lib/Socket.h +++ b/lib/Socket.h @@ -213,6 +213,8 @@ class TCPSocket { SOCKET get_sockfd() const { return m_sock; } + InetAddress get_remote_address() const { return m_remote_address; } + private: explicit TCPSocket(int sockfd); explicit TCPSocket(int sockfd, InetAddress remote_address); @@ -254,6 +256,12 @@ class TCPConnection ThreadsafeQueue > queue; + struct stats_t { + size_t buffer_fullness = 0; + InetAddress remote_address; + }; + stats_t get_stats() const; + private: std::atomic m_running; std::thread m_sender_thread; @@ -276,6 +284,8 @@ class TCPDataDispatcher void start(int port, const std::string& address); void write(const std::vector& data); + std::vector get_stats() const; + private: void process(); diff --git a/lib/ThreadsafeQueue.h b/lib/ThreadsafeQueue.h index 8b385d6..13bc19e 100644 --- a/lib/ThreadsafeQueue.h +++ b/lib/ThreadsafeQueue.h @@ -2,7 +2,7 @@ Copyright (C) 2007, 2008, 2009, 2010, 2011 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2023 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li An implementation for a threadsafe queue, depends on C++11 @@ -28,6 +28,7 @@ #pragma once +#include #include #include #include @@ -63,10 +64,10 @@ public: std::unique_lock lock(the_mutex); size_t queue_size_before = the_queue.size(); if (max_size == 0) { - the_queue.push(val); + the_queue.push_back(val); } else if (queue_size_before < max_size) { - the_queue.push(val); + the_queue.push_back(val); } size_t queue_size = the_queue.size(); lock.unlock(); @@ -80,10 +81,10 @@ public: std::unique_lock lock(the_mutex); size_t queue_size_before = the_queue.size(); if (max_size == 0) { - the_queue.emplace(std::move(val)); + the_queue.emplace_back(std::move(val)); } else if (queue_size_before < max_size) { - the_queue.emplace(std::move(val)); + the_queue.emplace_back(std::move(val)); } size_t queue_size = the_queue.size(); lock.unlock(); @@ -110,9 +111,9 @@ public: bool overflow = false; while (the_queue.size() >= max_size) { overflow = true; - the_queue.pop(); + the_queue.pop_front(); } - the_queue.push(val); + the_queue.push_back(val); const size_t queue_size = the_queue.size(); lock.unlock(); @@ -129,9 +130,9 @@ public: bool overflow = false; while (the_queue.size() >= max_size) { overflow = true; - the_queue.pop(); + the_queue.pop_front(); } - the_queue.emplace(std::move(val)); + the_queue.emplace_back(std::move(val)); const size_t queue_size = the_queue.size(); lock.unlock(); @@ -152,7 +153,7 @@ public: while (the_queue.size() >= threshold) { the_tx_notification.wait(lock); } - the_queue.push(val); + the_queue.push_back(val); size_t queue_size = the_queue.size(); lock.unlock(); @@ -198,7 +199,7 @@ public: } popped_value = the_queue.front(); - the_queue.pop(); + the_queue.pop_front(); lock.unlock(); the_tx_notification.notify_one(); @@ -220,15 +221,26 @@ public: } else { std::swap(popped_value, the_queue.front()); - the_queue.pop(); + the_queue.pop_front(); lock.unlock(); the_tx_notification.notify_one(); } } + template + std::vector map(std::function func) const + { + std::vector result; + std::unique_lock lock(the_mutex); + for (const T& elem : the_queue) { + result.push_back(func(elem)); + } + return result; + } + private: - std::queue the_queue; + std::deque the_queue; mutable std::mutex the_mutex; std::condition_variable the_rx_notification; std::condition_variable the_tx_notification; diff --git a/lib/edioutput/Transport.cpp b/lib/edioutput/Transport.cpp index 4979e93..a5e0bc3 100644 --- a/lib/edioutput/Transport.cpp +++ b/lib/edioutput/Transport.cpp @@ -1,5 +1,5 @@ /* - Copyright (C) 2022 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -220,6 +220,20 @@ void Sender::override_pft_sequence(uint16_t pseq) edi_pft.OverridePSeq(pseq); } +std::vector Sender::get_tcp_server_stats() const +{ + std::vector stats; + + for (auto& el : tcp_dispatchers) { + Sender::stats_t s; + s.listen_port = el.first->listen_port; + s.stats = el.second->get_stats(); + stats.push_back(s); + } + + return stats; +} + void Sender::run() { while (m_running) { diff --git a/lib/edioutput/Transport.h b/lib/edioutput/Transport.h index c62545c..2ca638e 100644 --- a/lib/edioutput/Transport.h +++ b/lib/edioutput/Transport.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2022 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -38,10 +38,11 @@ #include #include #include +#include namespace edi { -/** STI sender for EDI output */ +/** ETI/STI sender for EDI output */ class Sender { public: @@ -64,6 +65,12 @@ class Sender { void override_af_sequence(uint16_t seq); void override_pft_sequence(uint16_t pseq); + struct stats_t { + uint16_t listen_port; + std::vector stats; + }; + std::vector get_tcp_server_stats() const; + private: void run(); diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index a68f09a..b9575fc 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -28,6 +28,7 @@ #include #include "DabMultiplexer.h" #include "ConfigParser.h" +#include "ManagementServer.h" #include "crc.h" #include "utils.h" @@ -795,6 +796,12 @@ void DabMultiplexer::mux_frame(std::vector >& outputs } edi_sender->write(edi_tagpacket); + + for (const auto& stat : edi_sender->get_tcp_server_stats()) { + get_mgmt_server().update_edi_tcp_output_stat( + stat.listen_port, + stat.stats.size()); + } } #if _DEBUG diff --git a/src/ManagementServer.cpp b/src/ManagementServer.cpp index 568e80e..dff093a 100644 --- a/src/ManagementServer.cpp +++ b/src/ManagementServer.cpp @@ -2,7 +2,7 @@ Copyright (C) 2009 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2018 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -28,13 +28,12 @@ along with ODR-DabMux. If not, see . */ -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include #include #include "ManagementServer.h" #include "Log.h" @@ -127,37 +126,42 @@ ManagementServer& get_mgmt_server() */ } -void ManagementServer::registerInput(InputStat* is) +void ManagementServer::register_input(InputStat* is) { unique_lock lock(m_statsmutex); std::string id(is->get_name()); - if (m_inputStats.count(id) == 1) { + if (m_input_stats.count(id) == 1) { etiLog.level(error) << "Double registration in MGMT Server with id '" << id << "'"; return; } - m_inputStats[id] = is; + m_input_stats[id] = is; } -void ManagementServer::unregisterInput(std::string id) +void ManagementServer::unregister_input(std::string id) { unique_lock lock(m_statsmutex); - if (m_inputStats.count(id) == 1) { - m_inputStats.erase(id); + if (m_input_stats.count(id) == 1) { + m_input_stats.erase(id); } } +// outputs will never disappear, no need to have a "remove" logic +void ManagementServer::update_edi_tcp_output_stat(uint16_t listen_port, size_t num_connections) +{ + m_output_stats[listen_port] = num_connections; +} bool ManagementServer::isInputRegistered(std::string& id) { unique_lock lock(m_statsmutex); - if (m_inputStats.count(id) == 0) { + if (m_input_stats.count(id) == 0) { etiLog.level(error) << "Management Server: id '" << id << "' does was not registered"; @@ -166,7 +170,7 @@ bool ManagementServer::isInputRegistered(std::string& id) return true; } -std::string ManagementServer::getStatConfigJSON() +std::string ManagementServer::get_input_config_json() { unique_lock lock(m_statsmutex); @@ -175,7 +179,7 @@ std::string ManagementServer::getStatConfigJSON() std::map::iterator iter; int i = 0; - for(iter = m_inputStats.begin(); iter != m_inputStats.end(); + for (iter = m_input_stats.begin(); iter != m_input_stats.end(); ++iter, i++) { std::string id = iter->first; @@ -192,16 +196,15 @@ std::string ManagementServer::getStatConfigJSON() return ss.str(); } -std::string ManagementServer::getValuesJSON() +std::string ManagementServer::get_input_values_json() { unique_lock lock(m_statsmutex); std::ostringstream ss; ss << "{ \"values\" : {\n"; - std::map::iterator iter; int i = 0; - for(iter = m_inputStats.begin(); iter != m_inputStats.end(); + for (auto iter = m_input_stats.begin(); iter != m_input_stats.end(); ++iter, i++) { const std::string& id = iter->first; @@ -220,6 +223,31 @@ std::string ManagementServer::getValuesJSON() return ss.str(); } +std::string ManagementServer::get_output_values_json() +{ + unique_lock lock(m_statsmutex); + + std::ostringstream ss; + ss << "{ \"output_values\" : {\n"; + + int i = 0; + for (auto iter = m_output_stats.begin(); iter != m_output_stats.end(); + ++iter, i++) + { + auto listen_port = iter->first; + auto num_connections = iter->second; + if (i > 0) { + ss << " ,\n"; + } + ss << " \"edi_tcp_" << listen_port << "\" : { \"num_connections\": " << + num_connections << "} "; + } + + ss << "}\n}\n"; + + return ss.str(); +} + ManagementServer::ManagementServer() : m_zmq_context(), m_zmq_sock(m_zmq_context, ZMQ_REP), @@ -323,10 +351,13 @@ void ManagementServer::handle_message(zmq::message_t& zmq_message) << "}\n"; } else if (data == "config") { - answer << getStatConfigJSON(); + answer << get_input_config_json(); } else if (data == "values") { - answer << getValuesJSON(); + answer << get_input_values_json(); + } + else if (data == "output_values") { + answer << get_output_values_json(); } else if (data == "getptree") { unique_lock lock(m_configmutex); @@ -366,12 +397,12 @@ InputStat::InputStat(const std::string& name) : InputStat::~InputStat() { - get_mgmt_server().unregisterInput(m_name); + get_mgmt_server().unregister_input(m_name); } void InputStat::registerAtServer() { - get_mgmt_server().registerInput(this); + get_mgmt_server().register_input(this); } void InputStat::notifyBuffer(long bufsize) diff --git a/src/ManagementServer.h b/src/ManagementServer.h index 6e39922..c7a4222 100644 --- a/src/ManagementServer.h +++ b/src/ManagementServer.h @@ -2,7 +2,7 @@ Copyright (C) 2009 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2018 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -50,6 +50,7 @@ # include "config.h" #endif +#include "Socket.h" #include "zmq.hpp" #include #include @@ -167,8 +168,10 @@ class ManagementServer void open(int listenport); /* Un-/Register a statistics data source */ - void registerInput(InputStat* is); - void unregisterInput(std::string id); + void register_input(InputStat* is); + void unregister_input(std::string id); + + void update_edi_tcp_output_stat(uint16_t listen_port, size_t num_connections); /* Load a ptree given by the management server. * @@ -205,20 +208,25 @@ class ManagementServer std::thread m_restarter_thread; /******* Statistics Data ********/ - std::map m_inputStats; + std::map m_input_stats; + + // Holds information about EDI/TCP outputs + std::map m_output_stats; /* Return a description of the configuration that will * allow to define what graphs to be created * * returns: a JSON encoded configuration */ - std::string getStatConfigJSON(); + std::string get_input_config_json(); /* Return the values for the statistics as defined in the configuration * * returns: JSON encoded statistics */ - std::string getValuesJSON(); + std::string get_input_values_json(); + + std::string get_output_values_json(); // mutex for accessing the map std::mutex m_statsmutex; -- cgit v1.2.3 From 397905cb5079205e2a4bb64cca35517e60c01a58 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Sun, 13 Apr 2025 20:11:34 +0200 Subject: Compensate for tist_at_fct0 in tist_offset --- src/DabMultiplexer.cpp | 13 ++++++++++--- src/DabMultiplexer.h | 1 + 2 files changed, 11 insertions(+), 3 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index b9575fc..58e0f9b 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -49,6 +49,8 @@ static vector split_pipe_separated_string(const std::string& s) uint64_t MuxTime::init(uint32_t tist_at_fct0_us) { + m_tist_at_fct0_us = tist_at_fct0_us; + /* At startup, derive edi_time, TIST and CIF count such that there is * a consistency across mux restarts. Ensure edi_time and TIST represent * current time. @@ -112,14 +114,19 @@ void MuxTime::increment_timestamp() std::pair MuxTime::get_time() { + // The user-visible configuration tist_offset is the effective + // offset, but since we implicityle add the tist_at_fct0 to it, + // we must compensate. + double corrected_tist_offset = tist_offset - (m_tist_at_fct0_us / 1e6); + // negative tist_offset not supported, because the calculation is annoying - if (tist_offset < 0) return {m_timestamp, m_edi_time}; + if (corrected_tist_offset < 0) return {m_timestamp, m_edi_time}; - double fractional_part = tist_offset - std::floor(tist_offset); + double fractional_part = corrected_tist_offset - std::floor(corrected_tist_offset); const size_t steps = std::lround(std::floor(fractional_part / 24e-3)); uint32_t timestamp = m_timestamp + (24 << 14) * steps; - std::time_t edi_time = m_edi_time + std::lround(std::floor(tist_offset)); + std::time_t edi_time = m_edi_time + std::lround(std::floor(corrected_tist_offset)); if (timestamp > 0xf9FFff) { edi_time += 1; diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index aa6adfb..bbb4bde 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -47,6 +47,7 @@ class MuxTime { private: uint32_t m_timestamp = 0; std::time_t m_edi_time = 0; + uint32_t m_tist_at_fct0_us = 0; public: std::pair get_time(); -- cgit v1.2.3 From 103841bc578888a828d176eddfdd9fa345549f03 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 23 Apr 2025 11:18:08 +0200 Subject: Rework FIG0/10 DAB time indication to match EDI time --- src/DabMultiplexer.cpp | 24 ++++++++++++++++-------- src/DabMultiplexer.h | 6 ++---- src/fig/FIG.h | 10 +++++++++- src/fig/FIG0_10.cpp | 11 +++++------ src/fig/FIGCarousel.cpp | 7 +++++-- src/fig/FIGCarousel.h | 4 +++- src/utils.cpp | 24 +----------------------- src/utils.h | 6 +----- 8 files changed, 42 insertions(+), 50 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 58e0f9b..e6e6782 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -100,9 +100,11 @@ uint64_t MuxTime::init(uint32_t tist_at_fct0_us) return currentFrame; } +constexpr int TIMESTAMP_LEVEL_2_SHIFT = 14; + void MuxTime::increment_timestamp() { - m_timestamp += 24 << 14; // Shift 24ms by 14 to Timestamp level 2 + m_timestamp += 24 << TIMESTAMP_LEVEL_2_SHIFT; // Shift 24ms by 14 to Timestamp level 2 if (m_timestamp > 0xf9FFff) { m_timestamp -= 0xfa0000; // Subtract 16384000, corresponding to one second m_edi_time += 1; @@ -112,10 +114,10 @@ void MuxTime::increment_timestamp() } } -std::pair MuxTime::get_time() +std::pair MuxTime::get_tist_seconds() { // The user-visible configuration tist_offset is the effective - // offset, but since we implicityle add the tist_at_fct0 to it, + // offset, but since we implicitly add the tist_at_fct0 to it, // we must compensate. double corrected_tist_offset = tist_offset - (m_tist_at_fct0_us / 1e6); @@ -124,7 +126,7 @@ std::pair MuxTime::get_time() double fractional_part = corrected_tist_offset - std::floor(corrected_tist_offset); const size_t steps = std::lround(std::floor(fractional_part / 24e-3)); - uint32_t timestamp = m_timestamp + (24 << 14) * steps; + uint32_t timestamp = m_timestamp + (24 << TIMESTAMP_LEVEL_2_SHIFT) * steps; std::time_t edi_time = m_edi_time + std::lround(std::floor(corrected_tist_offset)); @@ -135,13 +137,20 @@ std::pair MuxTime::get_time() return {timestamp % 0xfa0000, edi_time}; } +std::pair MuxTime::get_milliseconds_seconds() +{ + auto tist_seconds = get_tist_seconds(); + return {tist_seconds.first >> TIMESTAMP_LEVEL_2_SHIFT, tist_seconds.second}; +} + DabMultiplexer::DabMultiplexer(boost::property_tree::ptree pt) : RemoteControllable("mux"), m_pt(pt), + m_time(), ensemble(std::make_shared()), m_clock_tai(split_pipe_separated_string(pt.get("general.tai_clock_bulletins", ""))), - fig_carousel(ensemble) + fig_carousel(ensemble, [&]() { return m_time.get_milliseconds_seconds(); }) { RC_ADD_PARAMETER(frames, "Show number of frames generated [read-only]"); RC_ADD_PARAMETER(tist_offset, "Timestamp offset in fractional number of seconds"); @@ -197,7 +206,7 @@ void DabMultiplexer::prepare(bool require_tai_clock) bool tist_enabled = m_pt.get("general.tist", false); m_time.tist_offset = m_pt.get("general.tist_offset", 0.0); - auto tist_edi_time = m_time.get_time(); + auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; const auto edi_time = tist_edi_time.second; m_time.mnsc_time = edi_time; @@ -474,9 +483,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs etiLog.level(error) << "Could not get UTC-TAI offset for EDI timestamp"; } } - update_dab_time(); - auto tist_edi_time = m_time.get_time(); + auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; const auto edi_time = tist_edi_time.second; diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index bbb4bde..5a0d906 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -50,7 +50,8 @@ class MuxTime { uint32_t m_tist_at_fct0_us = 0; public: - std::pair get_time(); + std::pair get_tist_seconds(); + std::pair get_milliseconds_seconds(); double tist_offset = 0; @@ -81,8 +82,6 @@ class DabMultiplexer : public RemoteControllable { void prepare(bool require_tai_clock); - uint64_t getCurrentFrame() const { return currentFrame; } - void mux_frame(std::vector >& outputs); void print_info(void); @@ -116,6 +115,5 @@ class DabMultiplexer : public RemoteControllable { bool m_tai_clock_required = false; ClockTAI m_clock_tai; - /* New FIG Carousel */ FIC::FIGCarousel fig_carousel; }; diff --git a/src/fig/FIG.h b/src/fig/FIG.h index 9752245..eda4671 100644 --- a/src/fig/FIG.h +++ b/src/fig/FIG.h @@ -35,11 +35,19 @@ namespace FIC { class FIGRuntimeInformation { public: - FIGRuntimeInformation(std::shared_ptr& e) : + + using dab_time_t = std::pair; + using get_time_func_t = std::function; + + FIGRuntimeInformation( + std::shared_ptr& e, + get_time_func_t getTimeFunc) : + getTimeFunc(getTimeFunc), currentFrame(0), ensemble(e), factumAnalyzer(false) {} + get_time_func_t getTimeFunc; unsigned long currentFrame; std::shared_ptr ensemble; bool factumAnalyzer; diff --git a/src/fig/FIG0_10.cpp b/src/fig/FIG0_10.cpp index 56ce9fb..240aa19 100644 --- a/src/fig/FIG0_10.cpp +++ b/src/fig/FIG0_10.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li */ /* @@ -23,7 +23,6 @@ along with ODR-DabMux. If not, see . */ -#include "fig/FIG0structs.h" #include "fig/FIG0_10.h" #include "utils.h" @@ -89,7 +88,7 @@ FillStatus FIG0_10::fill(uint8_t *buf, size_t max_size) return fs; } - //Time and country identifier + // Time and country identifier auto fig0_10 = (FIGtype0_10_LongForm*)buf; fig0_10->FIGtypeNumber = 0; @@ -102,9 +101,9 @@ FillStatus FIG0_10::fill(uint8_t *buf, size_t max_size) remaining -= 2; struct tm timeData; - time_t dab_time_seconds = 0; - uint32_t dab_time_millis = 0; - get_dab_time(&dab_time_seconds, &dab_time_millis); + const auto dab_time = m_rti->getTimeFunc(); + time_t dab_time_seconds = dab_time.second; + uint32_t dab_time_millis = dab_time.first; gmtime_r(&dab_time_seconds, &timeData); fig0_10->RFU = 0; diff --git a/src/fig/FIGCarousel.cpp b/src/fig/FIGCarousel.cpp index 9748dbf..ceda275 100644 --- a/src/fig/FIGCarousel.cpp +++ b/src/fig/FIGCarousel.cpp @@ -68,8 +68,11 @@ bool FIGCarouselElement::check_deadline() /**************** FIGCarousel *****************/ -FIGCarousel::FIGCarousel(std::shared_ptr ensemble) : - m_rti(ensemble), +FIGCarousel::FIGCarousel( + std::shared_ptr ensemble, + FIGRuntimeInformation::get_time_func_t getTimeFunc + ) : + m_rti(ensemble, getTimeFunc), m_fig0_0(&m_rti), m_fig0_1(&m_rti), m_fig0_2(&m_rti), diff --git a/src/fig/FIGCarousel.h b/src/fig/FIGCarousel.h index 1e33577..a2a8022 100644 --- a/src/fig/FIGCarousel.h +++ b/src/fig/FIGCarousel.h @@ -67,7 +67,9 @@ enum class FIBAllocation { class FIGCarousel { public: - FIGCarousel(std::shared_ptr ensemble); + FIGCarousel( + std::shared_ptr ensemble, + FIGRuntimeInformation::get_time_func_t getTimeFunc); /* Write all FIBs to the buffer, including correct padding and crc. * Returns number of bytes written. diff --git a/src/utils.cpp b/src/utils.cpp index 1a13caf..7ea6293 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2021 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -34,30 +34,8 @@ using namespace std; -static time_t dab_time_seconds = 0; -static int dab_time_millis = 0; - static void printServices(const vector >& services); -void update_dab_time() -{ - if (dab_time_seconds == 0) { - dab_time_seconds = time(nullptr); - } else { - dab_time_millis+= 24; - if (dab_time_millis >= 1000) { - dab_time_millis -= 1000; - ++dab_time_seconds; - } - } -} - -void get_dab_time(time_t *time, uint32_t *millis) -{ - *time = dab_time_seconds; - *millis = dab_time_millis; -} - uint32_t gregorian2mjd(int year, int month, int day) { diff --git a/src/utils.h b/src/utils.h index 331a0b2..d037bb3 100644 --- a/src/utils.h +++ b/src/utils.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2020 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li This file contains a set of utility functions that are used to show @@ -34,10 +34,6 @@ #include #include "MuxElements.h" -/* Must be called once per ETI frame to update the time */ -void update_dab_time(void); -void get_dab_time(time_t *time, uint32_t *millis); - /* Convert a date and time into the modified Julian date * used in FIG 0/10 * -- cgit v1.2.3 From 4205ff220c5f7dc71fedb93bce38bddc18aa5b5c Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 11 Jun 2025 17:07:04 +0200 Subject: Rework counter and TIST initialisation to ensure TIST@FCT0 works correctly This loses the continuity-across-restarts of the counter, but most destinations already see a counter discontinuity now. So it's not a big loss --- src/DabMultiplexer.cpp | 118 ++++++------- src/DabMultiplexer.h | 9 +- src/zmq2edi/EDISender.cpp | 390 ++++++++++++++++++++++++++++++++++++++++++ src/zmq2edi/EDISender.h | 91 ++++++++++ src/zmq2edi/zmq2edi.cpp | 419 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 957 insertions(+), 70 deletions(-) create mode 100644 src/zmq2edi/EDISender.cpp create mode 100644 src/zmq2edi/EDISender.h create mode 100644 src/zmq2edi/zmq2edi.cpp (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index e6e6782..31b12bb 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -47,22 +47,21 @@ static vector split_pipe_separated_string(const std::string& s) return components; } -uint64_t MuxTime::init(uint32_t tist_at_fct0_us) +uint64_t MuxTime::init(uint32_t tist_at_fct0_us, double tist_offset) { - m_tist_at_fct0_us = tist_at_fct0_us; - - /* At startup, derive edi_time, TIST and CIF count such that there is - * a consistency across mux restarts. Ensure edi_time and TIST represent - * current time. - * - * FCT and DLFC are directly derived from m_currentFrame. - * Every 6s, FCT overflows. DLFC overflows at 5000 every 120s. - * - * Keep a granularity of 24ms, which corresponds to the duration of an ETI - * frame, to get nicer timestamps. - */ + // Things we must guarantee, up to granularity of 24ms: + // Difference between current time and EDI time = tist_offset + // TIST of frame 0 = tist_at_fct0_us + // In order to achieve the second, we calculate the initial + // counter value so that FCT0 corresponds to the desired TIST. + // + // Changing the tist_offset at runtime will throw off the TIST@FCT0 value + m_tist_offset_ms = std::lround(tist_offset * 1000); + using Sec = chrono::seconds; - const auto now = chrono::system_clock::now(); + const auto now = chrono::system_clock::now() + + chrono::milliseconds(std::lround(tist_offset * 1000.0)); + const auto offset = now - chrono::time_point_cast(now); if (offset >= chrono::seconds(1)) { throw std::logic_error("Invalid startup offset calculation for TIST! " + @@ -70,43 +69,26 @@ uint64_t MuxTime::init(uint32_t tist_at_fct0_us) " ms"); } const time_t t_now = chrono::system_clock::to_time_t(chrono::time_point_cast(now)); + const auto offset_ms = chrono::duration_cast(offset).count(); - m_edi_time = t_now - (t_now % 6); - uint64_t currentFrame = 0; - time_t edi_time_at_cif0 = t_now - (t_now % 120); - while (edi_time_at_cif0 < m_edi_time) { - edi_time_at_cif0 += 6; - currentFrame += 250; - } + m_edi_time = t_now; + m_pps_offset_ms = std::lround(offset_ms / 24.0) * 24; - if (edi_time_at_cif0 != m_edi_time) { - throw std::logic_error("Invalid startup offset calculation for CIF!"); - } + const auto counter_offset = tist_at_fct0_us / 24; + const auto offset_as_count = m_pps_offset_ms / 24; - int64_t offset_ms = chrono::duration_cast(offset).count(); - offset_ms += 1000 * (t_now - m_edi_time); + etiLog.level(debug) << "Init " << counter_offset << " " << offset_as_count; - if (tist_at_fct0_us >= 1000000) { - etiLog.level(error) << "tist_at_fct0 may not be larger than 1s"; - throw MuxInitException(); - } - - m_timestamp = (uint64_t)tist_at_fct0_us * 16384 / 1000; - while (offset_ms >= 24) { - increment_timestamp(); - currentFrame++; - offset_ms -= 24; - } - return currentFrame; + return (250 - counter_offset + offset_as_count) % 250; } constexpr int TIMESTAMP_LEVEL_2_SHIFT = 14; void MuxTime::increment_timestamp() { - m_timestamp += 24 << TIMESTAMP_LEVEL_2_SHIFT; // Shift 24ms by 14 to Timestamp level 2 - if (m_timestamp > 0xf9FFff) { - m_timestamp -= 0xfa0000; // Subtract 16384000, corresponding to one second + m_pps_offset_ms += 24; + if (m_pps_offset_ms >= 1000) { + m_pps_offset_ms -= 1000; m_edi_time += 1; // Also update MNSC time for next time FP==0 @@ -114,27 +96,32 @@ void MuxTime::increment_timestamp() } } -std::pair MuxTime::get_tist_seconds() +void MuxTime::set_tist_offset(double new_tist_offset) { - // The user-visible configuration tist_offset is the effective - // offset, but since we implicitly add the tist_at_fct0 to it, - // we must compensate. - double corrected_tist_offset = tist_offset - (m_tist_at_fct0_us / 1e6); - - // negative tist_offset not supported, because the calculation is annoying - if (corrected_tist_offset < 0) return {m_timestamp, m_edi_time}; - - double fractional_part = corrected_tist_offset - std::floor(corrected_tist_offset); - const size_t steps = std::lround(std::floor(fractional_part / 24e-3)); - uint32_t timestamp = m_timestamp + (24 << TIMESTAMP_LEVEL_2_SHIFT) * steps; - - std::time_t edi_time = m_edi_time + std::lround(std::floor(corrected_tist_offset)); - - if (timestamp > 0xf9FFff) { - edi_time += 1; + int32_t new_tist_offset_ms = std::lround(new_tist_offset * 1000.0); + if (new_tist_offset_ms > 0) { + while (new_tist_offset_ms > 0) { + increment_timestamp(); + new_tist_offset_ms -= 24; + } + } + else if (new_tist_offset_ms < 0) { + while (new_tist_offset_ms < 0) { + m_edi_time -= 1; + new_tist_offset_ms += 1000; + } + // compensate the we subtracted too much + while (new_tist_offset_ms > 0) { + increment_timestamp(); + new_tist_offset_ms -= 24; + } } +} - return {timestamp % 0xfa0000, edi_time}; +std::pair MuxTime::get_tist_seconds() +{ + auto timestamp = m_pps_offset_ms * 16384; + return {timestamp % 0xfa0000, m_edi_time}; } std::pair MuxTime::get_milliseconds_seconds() @@ -153,7 +140,6 @@ DabMultiplexer::DabMultiplexer(boost::property_tree::ptree pt) : fig_carousel(ensemble, [&]() { return m_time.get_milliseconds_seconds(); }) { RC_ADD_PARAMETER(frames, "Show number of frames generated [read-only]"); - RC_ADD_PARAMETER(tist_offset, "Timestamp offset in fractional number of seconds"); rcs.enrol(&m_clock_tai); } @@ -200,11 +186,10 @@ void DabMultiplexer::prepare(bool require_tai_clock) } const uint32_t tist_at_fct0_us = m_pt.get("general.tist_at_fct0", 0); - currentFrame = m_time.init(tist_at_fct0_us); + currentFrame = m_time.init(tist_at_fct0_us, m_pt.get("general.tist_offset", 0.0)); m_time.mnsc_increment_time = false; bool tist_enabled = m_pt.get("general.tist", false); - m_time.tist_offset = m_pt.get("general.tist_offset", 0.0); auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; @@ -487,6 +472,8 @@ void DabMultiplexer::mux_frame(std::vector >& outputs auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; const auto edi_time = tist_edi_time.second; + etiLog.level(debug) << "Frame " << currentFrame << " " << edi_time << + " + " << (timestamp >> TIMESTAMP_LEVEL_2_SHIFT); // Initialise the ETI frame memset(etiFrame, 0, 6144); @@ -520,7 +507,6 @@ void DabMultiplexer::mux_frame(std::vector >& outputs eti_FC *fc = (eti_FC *) &etiFrame[4]; //****** FCT ******// - // Incremente for each frame, overflows at 249 fc->FCT = currentFrame % 250; edi_tagDETI.dlfc = currentFrame % 5000; @@ -857,7 +843,7 @@ void DabMultiplexer::set_parameter(const std::string& parameter, throw ParameterError(ss.str()); } else if (parameter == "tist_offset") { - m_time.tist_offset = std::stod(value); + m_time.set_tist_offset(std::stod(value)); } else { stringstream ss; @@ -875,7 +861,7 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co ss << currentFrame; } else if (parameter == "tist_offset") { - ss << m_time.tist_offset; + ss << m_time.tist_offset(); } else { ss << "Parameter '" << parameter << @@ -890,7 +876,7 @@ const json::map_t DabMultiplexer::get_all_values() const { json::map_t map; map["frames"].v = currentFrame; - map["tist_offset"].v = m_time.tist_offset; + map["tist_offset"].v = m_time.tist_offset(); return map; } diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 5a0d906..07b42a1 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -45,15 +45,14 @@ constexpr uint32_t ETI_FSYNC1 = 0x49C5F8; class MuxTime { private: - uint32_t m_timestamp = 0; std::time_t m_edi_time = 0; - uint32_t m_tist_at_fct0_us = 0; + uint32_t m_pps_offset_ms = 0; + int64_t m_tist_offset_ms = 0; public: std::pair get_tist_seconds(); std::pair get_milliseconds_seconds(); - double tist_offset = 0; /* Pre v3 odr-dabmux did the MNSC calculation differently, * which works with the easydabv2. The rework in odr-dabmux, @@ -69,8 +68,10 @@ class MuxTime { std::time_t mnsc_time = 0; /* Setup the time and return the initial currentFrame counter value */ - uint64_t init(uint32_t tist_at_fct0_us); + uint64_t init(uint32_t tist_at_fct0_us, double tist_offset); void increment_timestamp(); + double tist_offset() const { return m_tist_offset_ms * 1000.0; } + void set_tist_offset(double new_tist_offset); }; class DabMultiplexer : public RemoteControllable { diff --git a/src/zmq2edi/EDISender.cpp b/src/zmq2edi/EDISender.cpp new file mode 100644 index 0000000..06b7420 --- /dev/null +++ b/src/zmq2edi/EDISender.cpp @@ -0,0 +1,390 @@ +/* + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, + 2011, 2012 Her Majesty the Queen in Right of Canada (Communications + Research Center Canada) + + Copyright (C) 2018 + Matthias P. Braendli, matthias.braendli@mpb.li + + http://www.opendigitalradio.org + */ +/* + This file is part of ODR-DabMux. + + ODR-DabMux is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + ODR-DabMux is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with ODR-DabMux. If not, see . +*/ + +#include "EDISender.h" +#include "Log.h" +#include +#include +#include +#include + +using namespace std; + +EDISender::~EDISender() +{ + if (running.load()) { + running.store(false); + + // Unblock thread + frame_t emptyframe; + frames.push(emptyframe); + + process_thread.join(); + } +} + +void EDISender::start(const edi_configuration_t& conf, + int delay_ms, int max_delay_ms) +{ + edi_conf = conf; + tist_delay_ms = delay_ms; + tist_max_delay_ms = max_delay_ms; + + if (edi_conf.verbose) { + etiLog.log(info, "Setup EDI"); + } + + if (edi_conf.dump) { + edi_debug_file.open("./edi.debug"); + } + + if (edi_conf.enabled()) { + for (auto& edi_destination : edi_conf.destinations) { + auto edi_output = make_shared(edi_destination.source_port); + + if (not edi_destination.source_addr.empty()) { + int err = edi_output->setMulticastSource(edi_destination.source_addr.c_str()); + if (err) { + throw runtime_error("EDI socket set source failed!"); + } + err = edi_output->setMulticastTTL(edi_destination.ttl); + if (err) { + throw runtime_error("EDI socket set TTL failed!"); + } + } + + edi_destination.socket = edi_output; + } + } + + if (edi_conf.verbose) { + etiLog.log(info, "EDI set up"); + } + + // The AF Packet will be protected with reed-solomon and split in fragments + edi::PFT pft(edi_conf); + edi_pft = pft; + + if (edi_conf.interleaver_enabled()) { + edi_interleaver.SetLatency(edi_conf.latency_frames); + } + + startTime = std::chrono::steady_clock::now(); + running.store(true); + process_thread = thread(&EDISender::process, this); +} + +void EDISender::push_frame(const frame_t& frame) +{ + frames.push(frame); +} + +void EDISender::print_configuration() +{ + if (edi_conf.enabled()) { + etiLog.level(info) << "EDI"; + etiLog.level(info) << " verbose " << edi_conf.verbose; + for (auto& edi_dest : edi_conf.destinations) { + etiLog.level(info) << " to " << edi_dest.dest_addr << ":" << edi_conf.dest_port; + if (not edi_dest.source_addr.empty()) { + etiLog.level(info) << " source " << edi_dest.source_addr; + etiLog.level(info) << " ttl " << edi_dest.ttl; + } + etiLog.level(info) << " source port " << edi_dest.source_port; + } + if (edi_conf.interleaver_enabled()) { + etiLog.level(info) << " interleave " << edi_conf.latency_frames * 24 << " ms"; + } + } + else { + etiLog.level(info) << "EDI disabled"; + } +} + +void EDISender::send_eti_frame(uint8_t* p, metadata_t metadata) +{ + edi::TagDETI edi_tagDETI; + edi::TagStarPTR edi_tagStarPtr; + map edi_subchannelToTag; + // The above Tag Items will be assembled into a TAG Packet + edi::TagPacket edi_tagpacket(edi_conf.tagpacket_alignment); + + // SYNC + edi_tagDETI.stat = p[0]; + + // LIDATA FCT + edi_tagDETI.dlfc = metadata.dlfc; + + const int fct = p[4]; + if (metadata.dlfc % 250 != fct) { + etiLog.level(warn) << "Frame FCT=" << fct << + " does not correspond to DLFC=" << metadata.dlfc; + } + + bool ficf = (p[5] & 0x80) >> 7; + edi_tagDETI.ficf = ficf; + + const int nst = p[5] & 0x7F; + + edi_tagDETI.fp = (p[6] & 0xE0) >> 5; + const int mid = (p[6] & 0x18) >> 3; + edi_tagDETI.mid = mid; + //const int fl = (p[6] & 0x07) * 256 + p[7]; + + int ficl = 0; + if (ficf == 0) { + etiLog.level(warn) << "Not FIC in data stream!"; + return; + } + else if (mid == 3) { + ficl = 32; + } + else { + ficl = 24; + } + + vector sad(nst); + vector stl(nst); + // Loop over STC subchannels: + for (int i=0; i < nst; i++) { + // EDI stream index is 1-indexed + const int edi_stream_id = i + 1; + + uint32_t scid = (p[8 + 4*i] & 0xFC) >> 2; + sad[i] = (p[8+4*i] & 0x03) * 256 + p[9+4*i]; + uint32_t tpl = (p[10+4*i] & 0xFC) >> 2; + stl[i] = (p[10+4*i] & 0x03) * 256 + \ + p[11+4*i]; + + edi::TagESTn tag_ESTn; + tag_ESTn.id = edi_stream_id; + tag_ESTn.scid = scid; + tag_ESTn.sad = sad[i]; + tag_ESTn.tpl = tpl; + tag_ESTn.rfa = 0; // two bits + tag_ESTn.mst_length = stl[i]; + tag_ESTn.mst_data = nullptr; + + edi_subchannelToTag[i] = tag_ESTn; + } + + const uint16_t mnsc = p[8 + 4*nst] * 256 + \ + p[8 + 4*nst + 1]; + edi_tagDETI.mnsc = mnsc; + + /*const uint16_t crc1 = p[8 + 4*nst + 2]*256 + \ + p[8 + 4*nst + 3]; */ + + edi_tagDETI.fic_data = p + 12 + 4*nst; + edi_tagDETI.fic_length = ficl * 4; + + // loop over MSC subchannels + int offset = 0; + for (int i=0; i < nst; i++) { + edi::TagESTn& tag = edi_subchannelToTag[i]; + tag.mst_data = (p + 12 + 4*nst + ficf*ficl*4 + offset); + + offset += stl[i] * 8; + } + + /* + const uint16_t crc2 = p[12 + 4*nst + ficf*ficl*4 + offset] * 256 + \ + p[12 + 4*nst + ficf*ficl*4 + offset + 1]; */ + + // TIST + const size_t tist_ix = 12 + 4*nst + ficf*ficl*4 + offset + 4; + uint32_t tist = (uint32_t)(p[tist_ix]) << 24 | + (uint32_t)(p[tist_ix+1]) << 16 | + (uint32_t)(p[tist_ix+2]) << 8 | + (uint32_t)(p[tist_ix+3]); + + std::time_t posix_timestamp_1_jan_2000 = 946684800; + + // Wait until our time is tist_delay after the TIST before + // we release that frame + + using namespace std::chrono; + + const auto seconds = metadata.edi_time; + const auto pps_offset = milliseconds(std::lrint((tist & 0xFFFFFF) / 16384.0)); + const auto t_frame = system_clock::from_time_t( + seconds + posix_timestamp_1_jan_2000) + pps_offset; + + const auto t_release = t_frame + milliseconds(tist_delay_ms); + const auto t_now = system_clock::now(); + + /* + etiLog.level(debug) << "seconds " << seconds + posix_timestamp_1_jan_2000; + etiLog.level(debug) << "now " << system_clock::to_time_t(t_now); + etiLog.level(debug) << "wait " << wait_time.count(); + */ + + const auto wait_time = t_release - t_now; + wait_times.push_back(duration_cast(wait_time).count()); + + if (tist_max_delay_ms > 0) { + const auto t_latest_release = t_frame + milliseconds(tist_max_delay_ms); + + if (t_now > t_latest_release) { + // drop frame + num_dropped.fetch_add(1); + return; + } + } + + if (t_release > t_now) { + std::this_thread::sleep_for(wait_time); + } + + edi_tagDETI.tsta = tist; + edi_tagDETI.atstf = 1; + edi_tagDETI.utco = metadata.utc_offset; + edi_tagDETI.seconds = metadata.edi_time; + + if (edi_conf.enabled()) { + // put tags *ptr, DETI and all subchannels into one TagPacket + edi_tagpacket.tag_items.push_back(&edi_tagStarPtr); + edi_tagpacket.tag_items.push_back(&edi_tagDETI); + + for (auto& tag : edi_subchannelToTag) { + edi_tagpacket.tag_items.push_back(&tag.second); + } + + // Assemble into one AF Packet + edi::AFPacket edi_afpacket = edi_afPacketiser.Assemble(edi_tagpacket); + + if (edi_conf.enable_pft) { + // Apply PFT layer to AF Packet (Reed Solomon FEC and Fragmentation) + vector edi_fragments = edi_pft.Assemble(edi_afpacket); + + if (edi_conf.verbose) { + fprintf(stderr, "EDI number of PFT fragment before interleaver %zu\n", + edi_fragments.size()); + } + + if (edi_conf.interleaver_enabled()) { + edi_fragments = edi_interleaver.Interleave(edi_fragments); + } + + // Send over ethernet + for (const auto& edi_frag : edi_fragments) { + for (auto& dest : edi_conf.destinations) { + InetAddress addr; + addr.setAddress(dest.dest_addr.c_str()); + addr.setPort(edi_conf.dest_port); + + dest.socket->send(edi_frag, addr); + } + + if (edi_conf.dump) { + std::ostream_iterator debug_iterator(edi_debug_file); + std::copy(edi_frag.begin(), edi_frag.end(), debug_iterator); + } + } + + if (edi_conf.verbose) { + fprintf(stderr, "EDI number of PFT fragments %zu\n", + edi_fragments.size()); + } + } + else { + // Send over ethernet + for (auto& dest : edi_conf.destinations) { + InetAddress addr; + addr.setAddress(dest.dest_addr.c_str()); + addr.setPort(edi_conf.dest_port); + + dest.socket->send(edi_afpacket, addr); + } + + if (edi_conf.dump) { + std::ostream_iterator debug_iterator(edi_debug_file); + std::copy(edi_afpacket.begin(), edi_afpacket.end(), debug_iterator); + } + } + } +} + +void EDISender::process() +{ + while (running.load()) { + frame_t frame; + frames.wait_and_pop(frame); + + if (not running.load() or frame.first.empty()) { + break; + } + + if (frame.first.size() == 6144) { + send_eti_frame(frame.first.data(), frame.second); + } + else { + etiLog.level(warn) << "Ignoring short ETI frame, " + "DFLC=" << frame.second.dlfc << ", len=" << + frame.first.size(); + } + + if (wait_times.size() == 250) { // every six seconds + const double n = wait_times.size(); + + double sum = accumulate(wait_times.begin(), wait_times.end(), 0); + size_t num_late = std::count_if(wait_times.begin(), wait_times.end(), + [](double v){ return v < 0; }); + double mean = sum / n; + + double sq_sum = 0; + for (const auto t : wait_times) { + sq_sum += (t-mean) * (t-mean); + } + double stdev = sqrt(sq_sum / n); + auto min_max = minmax_element(wait_times.begin(), wait_times.end()); + + /* Debug code + stringstream ss; + ss << "times:"; + for (const auto t : wait_times) { + ss << " " << t; + } + etiLog.level(debug) << ss.str(); + */ + + const size_t dropped = num_dropped.exchange(0); + + etiLog.level(info) << "Wait time statistics [microseconds]:" + " min: " << *min_max.first << + " max: " << *min_max.second << + " mean: " << mean << + " stdev: " << stdev << + " late: " << + num_late << " of " << wait_times.size() << " (" << + num_late * 100.0 / n << "%)" << + " dropped: " << dropped; + + wait_times.clear(); + } + } +} diff --git a/src/zmq2edi/EDISender.h b/src/zmq2edi/EDISender.h new file mode 100644 index 0000000..44502c1 --- /dev/null +++ b/src/zmq2edi/EDISender.h @@ -0,0 +1,91 @@ +/* + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, + 2011, 2012 Her Majesty the Queen in Right of Canada (Communications + Research Center Canada) + + Copyright (C) 2018 + Matthias P. Braendli, matthias.braendli@mpb.li + + http://www.opendigitalradio.org + */ +/* + This file is part of ODR-DabMux. + + ODR-DabMux is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + ODR-DabMux is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with ODR-DabMux. If not, see . +*/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include "ThreadsafeQueue.h" +#include "dabOutput/dabOutput.h" +#include "dabOutput/edi/TagItems.h" +#include "dabOutput/edi/TagPacket.h" +#include "dabOutput/edi/AFPacket.h" +#include "dabOutput/edi/PFT.h" +#include "dabOutput/edi/Interleaver.h" + +// This metadata gets transmitted in the zmq stream +struct metadata_t { + uint32_t edi_time = 0; + int16_t utc_offset = 0; + uint16_t dlfc = 0; +}; + +using frame_t = std::pair, metadata_t>; + +class EDISender { + public: + EDISender() = default; + EDISender(const EDISender& other) = delete; + EDISender& operator=(const EDISender& other) = delete; + ~EDISender(); + void start(const edi_configuration_t& conf, int delay_ms, int max_delay_ms); + void push_frame(const frame_t& frame); + void print_configuration(void); + + private: + void send_eti_frame(uint8_t* p, metadata_t metadata); + void process(void); + + int tist_delay_ms = 0; + int tist_max_delay_ms = 0; + std::atomic running = ATOMIC_VAR_INIT(false); + std::thread process_thread; + edi_configuration_t edi_conf; + std::chrono::steady_clock::time_point startTime; + ThreadsafeQueue frames; + std::ofstream edi_debug_file; + + // The TagPacket will then be placed into an AFPacket + edi::AFPacketiser edi_afPacketiser; + + // The AF Packet will be protected with reed-solomon and split in fragments + edi::PFT edi_pft; + + // To mitigate for burst packet loss, PFT fragments can be sent out-of-order + edi::Interleaver edi_interleaver; + + // For statistics about wait time before we transmit packets, + // in microseconds + std::vector wait_times; + + // Number of frames dropped because their TIST was larger than max_delay + std::atomic num_dropped = ATOMIC_VAR_INIT(0); + +}; diff --git a/src/zmq2edi/zmq2edi.cpp b/src/zmq2edi/zmq2edi.cpp new file mode 100644 index 0000000..63c3228 --- /dev/null +++ b/src/zmq2edi/zmq2edi.cpp @@ -0,0 +1,419 @@ +/* + Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, + 2011, 2012 Her Majesty the Queen in Right of Canada (Communications + Research Center Canada) + + Copyright (C) 2018 + Matthias P. Braendli, matthias.braendli@mpb.li + + http://www.opendigitalradio.org + */ +/* + This file is part of ODR-DabMux. + + ODR-DabMux is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + ODR-DabMux is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with ODR-DabMux. If not, see . +*/ + +#include "Log.h" +#include "zmq.hpp" +#include +#include +#include +#include +#include +#include + +#include "EDISender.h" +#include "dabOutput/dabOutput.h" + +constexpr size_t MAX_ERROR_COUNT = 10; +constexpr long ZMQ_TIMEOUT_MS = 1000; + +static edi_configuration_t edi_conf; + +static EDISender edisender; + +void usage(void) +{ + using namespace std; + + cerr << "Usage:" << endl; + cerr << "odr-zmq2edi [options] " << endl << endl; + + cerr << "Options:" << endl; + cerr << "The following options can be given only once:" << endl; + cerr << " is a ZMQ URL that points to a ODR-DabMux ZMQ output." << endl; + cerr << " -w Keep every ETI frame until TIST is milliseconds after current system time." << endl; + cerr << " -W Drop ETI frames if TIST is later than current system time." << endl; + cerr << " -p sets the destination port." << endl; + cerr << " -P Disable PFT and send AFPackets." << endl; + cerr << " -f sets the FEC." << endl; + cerr << " -i enables the interleaved with this latency." << endl; + cerr << " -D dumps the EDI to edi.debug file." << endl; + cerr << " -v Enables verbose mode." << endl; + cerr << " -a sets the alignment of the TAG Packet (default 8)." << endl << endl; + + cerr << "The following options can be given several times, when more than once destination is addressed:" << endl; + cerr << " -d sets the destination ip." << endl; + cerr << " -s sets the source port." << endl; + cerr << " -S select the source IP in case we want to use multicast." << endl; + cerr << " -t set the packet's TTL." << endl << endl; + + cerr << "odr-zmq2edi will quit if it does not receive data for " << + (int)(MAX_ERROR_COUNT * ZMQ_TIMEOUT_MS / 1000.0) << " seconds." << endl; + cerr << "It is best practice to run this tool under a process supervisor that will restart it automatically." << endl; +} + +static metadata_t get_md_one_frame(uint8_t *buf, size_t size, size_t *consumed_bytes) +{ + size_t remaining = size; + if (remaining < 3) { + etiLog.level(warn) << "Insufficient data to parse metadata"; + throw std::runtime_error("Insufficient data"); + } + + metadata_t md; + bool utc_offset_received = false; + bool edi_time_received = false; + bool dlfc_received = false; + + while (remaining) { + uint8_t id = buf[0]; + uint16_t len = (((uint16_t)buf[1]) << 8) + buf[2]; + + if (id == static_cast(output_metadata_id_e::separation_marker)) { + if (len != 0) { + etiLog.level(warn) << "Invalid length " << len << " for metadata: separation_marker"; + } + + if (not utc_offset_received or not edi_time_received or not dlfc_received) { + throw std::runtime_error("Incomplete metadata received"); + } + + remaining -= 3; + *consumed_bytes = size - remaining; + return md; + } + else if (id == static_cast(output_metadata_id_e::utc_offset)) { + if (len != 2) { + etiLog.level(warn) << "Invalid length " << len << " for metadata: utc_offset"; + } + if (remaining < 2) { + throw std::runtime_error("Insufficient data for utc_offset"); + } + uint16_t utco; + std::memcpy(&utco, buf + 3, sizeof(utco)); + md.utc_offset = ntohs(utco); + utc_offset_received = true; + remaining -= 5; + buf += 5; + } + else if (id == static_cast(output_metadata_id_e::edi_time)) { + if (len != 4) { + etiLog.level(warn) << "Invalid length " << len << " for metadata: edi_time"; + } + if (remaining < 4) { + throw std::runtime_error("Insufficient data for edi_time"); + } + uint32_t edi_time; + std::memcpy(&edi_time, buf + 3, sizeof(edi_time)); + md.edi_time = ntohl(edi_time); + edi_time_received = true; + remaining -= 7; + buf += 7; + } + else if (id == static_cast(output_metadata_id_e::dlfc)) { + if (len != 2) { + etiLog.level(warn) << "Invalid length " << len << " for metadata: dlfc"; + } + if (remaining < 2) { + throw std::runtime_error("Insufficient data for dlfc"); + } + uint16_t dlfc; + std::memcpy(&dlfc, buf + 3, sizeof(dlfc)); + md.dlfc = ntohs(dlfc); + dlfc_received = true; + remaining -= 5; + buf += 5; + } + } + + throw std::runtime_error("Insufficient data"); +} + +/* There is some state inside the parsing of destination arguments, + * because several destinations can be given. */ + +static edi_destination_t edi_destination; +static bool source_port_set = false; +static bool source_addr_set = false; +static bool ttl_set = false; +static bool dest_addr_set = false; + +static void add_edi_destination(void) +{ + if (not dest_addr_set) { + throw std::runtime_error("Destination address not specified for destination number " + + std::to_string(edi_conf.destinations.size() + 1)); + } + + edi_conf.destinations.push_back(edi_destination); + edi_destination_t newdest; + edi_destination = newdest; + + source_port_set = false; + source_addr_set = false; + ttl_set = false; + dest_addr_set = false; +} + +static void parse_destination_args(char option) +{ + switch (option) { + case 's': + if (source_port_set) { + add_edi_destination(); + } + edi_destination.source_port = std::stoi(optarg); + source_port_set = true; + break; + case 'S': + if (source_addr_set) { + add_edi_destination(); + } + edi_destination.source_addr = optarg; + source_addr_set = true; + break; + case 't': + if (ttl_set) { + add_edi_destination(); + } + edi_destination.ttl = std::stoi(optarg); + ttl_set = true; + break; + case 'd': + if (dest_addr_set) { + add_edi_destination(); + } + edi_destination.dest_addr = optarg; + dest_addr_set = true; + break; + default: + throw std::logic_error("parse_destination_args invalid"); + } +} + +int start(int argc, char **argv) +{ + edi_conf.enable_pft = true; + + if (argc == 0) { + usage(); + return 1; + } + + int delay_ms = 500; + int max_delay_ms = 0; // no max delay + + int ch = 0; + while (ch != -1) { + ch = getopt(argc, argv, "d:p:s:S:t:Pf:i:Dva:w:W:"); + switch (ch) { + case -1: + break; + case 'd': + case 's': + case 'S': + case 't': + parse_destination_args(ch); + break; + case 'p': + edi_conf.dest_port = std::stoi(optarg); + break; + case 'P': + edi_conf.enable_pft = false; + break; + case 'f': + edi_conf.fec = std::stoi(optarg); + break; + case 'i': + { + double interleave_ms = std::stod(optarg); + if (interleave_ms != 0.0) { + if (interleave_ms < 0) { + throw std::runtime_error("EDI output: negative interleave value is invalid."); + } + + auto latency_rounded = lround(interleave_ms / 24.0); + if (latency_rounded * 24 > 30000) { + throw std::runtime_error("EDI output: interleaving set for more than 30 seconds!"); + } + + edi_conf.latency_frames = latency_rounded; + } + } + break; + case 'D': + edi_conf.dump = true; + break; + case 'v': + edi_conf.verbose = true; + break; + case 'a': + edi_conf.tagpacket_alignment = std::stoi(optarg); + break; + case 'w': + delay_ms = std::stoi(optarg); + break; + case 'W': + max_delay_ms = std::stoi(optarg); + break; + case 'h': + default: + usage(); + return 1; + } + } + + add_edi_destination(); + + if (optind >= argc) { + etiLog.level(error) << "source option is missing"; + return 1; + } + + if (edi_conf.dest_port == 0) { + etiLog.level(error) << "No EDI destination port defined"; + return 1; + } + + if (edi_conf.destinations.empty()) { + etiLog.level(error) << "No EDI destinations set"; + return 1; + } + + if (max_delay_ms > 0) { + etiLog.level(info) << "Setting up EDI Sender with delay " << delay_ms << " ms and max delay " << max_delay_ms << " ms"; + } + else { + etiLog.level(info) << "Setting up EDI Sender with delay " << delay_ms << " ms"; + } + edisender.start(edi_conf, delay_ms, max_delay_ms); + edisender.print_configuration(); + + const char* source_url = argv[optind]; + + + size_t frame_count = 0; + size_t error_count = 0; + + etiLog.level(info) << "Opening ZMQ input: " << source_url; + + zmq::context_t zmq_ctx(1); + zmq::socket_t zmq_sock(zmq_ctx, ZMQ_SUB); + zmq_sock.connect(source_url); + zmq_sock.setsockopt(ZMQ_SUBSCRIBE, NULL, 0); // subscribe to all messages + + while (error_count < MAX_ERROR_COUNT) { + zmq::message_t incoming; + zmq::pollitem_t items[1]; + items[0].socket = zmq_sock; + items[0].events = ZMQ_POLLIN; + const int num_events = zmq::poll(items, 1, ZMQ_TIMEOUT_MS); + if (num_events == 0) { // timeout + error_count++; + } + else { + // Event received: recv will not block + zmq_sock.recv(&incoming); + + zmq_dab_message_t* dab_msg = (zmq_dab_message_t*)incoming.data(); + + if (dab_msg->version != 1) { + etiLog.level(error) << "ZeroMQ wrong packet version " << dab_msg->version; + error_count++; + } + + int offset = sizeof(dab_msg->version) + + NUM_FRAMES_PER_ZMQ_MESSAGE * sizeof(*dab_msg->buflen); + + std::list, metadata_t> > all_frames; + + for (int i = 0; i < NUM_FRAMES_PER_ZMQ_MESSAGE; i++) { + if (dab_msg->buflen[i] <= 0 or dab_msg->buflen[i] > 6144) { + etiLog.level(error) << "ZeroMQ buffer " << i << + " has invalid length " << dab_msg->buflen[i]; + error_count++; + } + else { + std::vector buf(6144, 0x55); + + const int framesize = dab_msg->buflen[i]; + + memcpy(&buf.front(), + ((uint8_t*)incoming.data()) + offset, + framesize); + + all_frames.emplace_back( + std::piecewise_construct, + std::make_tuple(std::move(buf)), + std::make_tuple()); + + offset += framesize; + } + } + + for (auto &f : all_frames) { + size_t consumed_bytes = 0; + + f.second = get_md_one_frame( + static_cast(incoming.data()) + offset, + incoming.size() - offset, + &consumed_bytes); + + offset += consumed_bytes; + } + + for (auto &f : all_frames) { + edisender.push_frame(f); + frame_count++; + } + } + } + + etiLog.level(info) << "Quitting after " << frame_count << " frames transferred"; + + return 0; +} + +int main(int argc, char **argv) +{ + etiLog.level(info) << "ZMQ2EDI converter from " << + PACKAGE_NAME << " " << +#if defined(GITVERSION) + GITVERSION << +#else + PACKAGE_VERSION << +#endif + " starting up"; + + try { + return start(argc, argv); + } + catch (std::runtime_error &e) { + etiLog.level(error) << "Error: " << e.what(); + } + + return 1; +} -- cgit v1.2.3 From 6d90eb23c4a86906b5157feb34e1698bdbf58dd5 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 11 Jun 2025 20:43:40 +0200 Subject: RC: Fix set tist_offset --- src/DabMultiplexer.cpp | 22 +++++++++++++--------- src/DabMultiplexer.h | 2 +- 2 files changed, 14 insertions(+), 10 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 31b12bb..f0ffa16 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -98,24 +98,26 @@ void MuxTime::increment_timestamp() void MuxTime::set_tist_offset(double new_tist_offset) { - int32_t new_tist_offset_ms = std::lround(new_tist_offset * 1000.0); - if (new_tist_offset_ms > 0) { - while (new_tist_offset_ms > 0) { + const int32_t new_tist_offset_ms = std::lround(new_tist_offset * 1000.0); + int32_t delta = m_tist_offset_ms - new_tist_offset_ms; + if (delta > 0) { + while (delta > 0) { increment_timestamp(); - new_tist_offset_ms -= 24; + delta -= 24; } } - else if (new_tist_offset_ms < 0) { - while (new_tist_offset_ms < 0) { + else if (delta < 0) { + while (delta < 0) { m_edi_time -= 1; - new_tist_offset_ms += 1000; + delta += 1000; } // compensate the we subtracted too much - while (new_tist_offset_ms > 0) { + while (delta > 0) { increment_timestamp(); - new_tist_offset_ms -= 24; + delta -= 24; } } + m_tist_offset_ms = new_tist_offset_ms; } std::pair MuxTime::get_tist_seconds() @@ -472,8 +474,10 @@ void DabMultiplexer::mux_frame(std::vector >& outputs auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; const auto edi_time = tist_edi_time.second; + /* etiLog.level(debug) << "Frame " << currentFrame << " " << edi_time << " + " << (timestamp >> TIMESTAMP_LEVEL_2_SHIFT); + */ // Initialise the ETI frame memset(etiFrame, 0, 6144); diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 07b42a1..c38d4dc 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -70,7 +70,7 @@ class MuxTime { /* Setup the time and return the initial currentFrame counter value */ uint64_t init(uint32_t tist_at_fct0_us, double tist_offset); void increment_timestamp(); - double tist_offset() const { return m_tist_offset_ms * 1000.0; } + double tist_offset() const { return m_tist_offset_ms / 1000.0; } void set_tist_offset(double new_tist_offset); }; -- cgit v1.2.3 From 203f5adec61b2bfeb6b97eed242ff185da071c0d Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Tue, 24 Jun 2025 13:10:24 +0200 Subject: Rename tist_at_fct0_us to -tist_at_fct0_ms --- src/DabMultiplexer.cpp | 10 +++++----- src/DabMultiplexer.h | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index f0ffa16..52f053a 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -47,11 +47,11 @@ static vector split_pipe_separated_string(const std::string& s) return components; } -uint64_t MuxTime::init(uint32_t tist_at_fct0_us, double tist_offset) +uint64_t MuxTime::init(uint32_t tist_at_fct0_ms, double tist_offset) { // Things we must guarantee, up to granularity of 24ms: // Difference between current time and EDI time = tist_offset - // TIST of frame 0 = tist_at_fct0_us + // TIST of frame 0 = tist_at_fct0_ms // In order to achieve the second, we calculate the initial // counter value so that FCT0 corresponds to the desired TIST. // @@ -74,7 +74,7 @@ uint64_t MuxTime::init(uint32_t tist_at_fct0_us, double tist_offset) m_edi_time = t_now; m_pps_offset_ms = std::lround(offset_ms / 24.0) * 24; - const auto counter_offset = tist_at_fct0_us / 24; + const auto counter_offset = tist_at_fct0_ms / 24; const auto offset_as_count = m_pps_offset_ms / 24; etiLog.level(debug) << "Init " << counter_offset << " " << offset_as_count; @@ -187,8 +187,8 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - const uint32_t tist_at_fct0_us = m_pt.get("general.tist_at_fct0", 0); - currentFrame = m_time.init(tist_at_fct0_us, m_pt.get("general.tist_offset", 0.0)); + const uint32_t tist_at_fct0_ms = m_pt.get("general.tist_at_fct0", 0); + currentFrame = m_time.init(tist_at_fct0_ms, m_pt.get("general.tist_offset", 0.0)); m_time.mnsc_increment_time = false; bool tist_enabled = m_pt.get("general.tist", false); diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index c38d4dc..9306eed 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -68,7 +68,7 @@ class MuxTime { std::time_t mnsc_time = 0; /* Setup the time and return the initial currentFrame counter value */ - uint64_t init(uint32_t tist_at_fct0_us, double tist_offset); + uint64_t init(uint32_t tist_at_fct0_ms, double tist_offset); void increment_timestamp(); double tist_offset() const { return m_tist_offset_ms / 1000.0; } void set_tist_offset(double new_tist_offset); -- cgit v1.2.3 From fd5e9b49e8fe0fc74088c39d4511e0e6ba6c7a12 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Mon, 7 Jul 2025 15:10:03 +0200 Subject: Remove debugging Init print on startup --- src/DabMultiplexer.cpp | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index 52f053a..bea82c2 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -77,8 +77,6 @@ uint64_t MuxTime::init(uint32_t tist_at_fct0_ms, double tist_offset) const auto counter_offset = tist_at_fct0_ms / 24; const auto offset_as_count = m_pps_offset_ms / 24; - etiLog.level(debug) << "Init " << counter_offset << " " << offset_as_count; - return (250 - counter_offset + offset_as_count) % 250; } -- cgit v1.2.3 From 90e9f058450cfb8bc2f06b02c60ba8cb533c2738 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 10 Sep 2025 12:03:24 +0200 Subject: Remove some old _WIN32 ifdefs, restructure includes --- Makefile.am | 1 - src/DabMultiplexer.cpp | 1 + src/DabMux.cpp | 80 +++--------------------------------------------- src/DabMux.h | 45 --------------------------- src/Eti.cpp | 17 +++------- src/Eti.h | 18 ++--------- src/Interleaver.cpp | 5 --- src/ManagementServer.cpp | 11 +------ src/ManagementServer.h | 2 -- src/MuxElements.cpp | 9 +++++- src/MuxElements.h | 8 ++--- src/PcDebug.h | 62 ++++++++++++------------------------- src/fig/FIG0_6.h | 2 -- src/fig/FIG1.h | 13 +------- src/fig/FIG2.h | 14 +-------- src/input/File.cpp | 18 +++-------- src/mpeg.h | 15 ++------- 17 files changed, 54 insertions(+), 267 deletions(-) delete mode 100644 src/DabMux.h (limited to 'src/DabMultiplexer.cpp') diff --git a/Makefile.am b/Makefile.am index be2eed3..455a3a0 100644 --- a/Makefile.am +++ b/Makefile.am @@ -60,7 +60,6 @@ odr_dabmux_LDADD =$(ZMQ_LIBS) $(BOOST_LDFLAGS) \ $(PTHREAD_CFLAGS) $(PTHREAD_LIBS) $(BOOST_SYSTEM_LIB) odr_dabmux_SOURCES =src/DabMux.cpp \ - src/DabMux.h \ src/DabMultiplexer.cpp \ src/DabMultiplexer.h \ src/input/inputs.h \ diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index bea82c2..c665f2c 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -31,6 +31,7 @@ #include "ManagementServer.h" #include "crc.h" #include "utils.h" +#include "Eti.h" using namespace std; diff --git a/src/DabMux.cpp b/src/DabMux.cpp index 4b9352f..0066629 100644 --- a/src/DabMux.cpp +++ b/src/DabMux.cpp @@ -29,83 +29,27 @@ # include "config.h" #endif -#include #include #include #include #include +#include +#include #include -#include -#include -#include #include +#include #include -#include -#include -#include #include #include -// for basename -#include - -#include #include -#include #include -#include -#include -#include - -#ifdef _WIN32 -# include -# include -# include -# include -# include // For types... -typedef u_char uint8_t; -typedef WORD uint16_t; -typedef DWORD32 uint32_t; - -# ifndef __MINGW32__ -# include "xgetopt.h" -# endif -# define read _read -# define snprintf _snprintf -# define sleep(a) Sleep((a) * 1000) -#else -# include -# include -# include -# include -# include -# include -# include -# include - -#endif - -#include - -#ifdef _WIN32 -# pragma warning ( disable : 4103 ) -# include "Eti.h" -# pragma warning ( default : 4103 ) -#else -# include "Eti.h" -#endif -#include "input/Prbs.h" -#include "input/Zmq.h" +#include "DabMultiplexer.h" #include "dabOutput/dabOutput.h" -#include "crc.h" -#include "Socket.h" -#include "PcDebug.h" -#include "DabMux.h" #include "MuxElements.h" #include "utils.h" -#include "ConfigParser.h" #include "ManagementServer.h" #include "Log.h" #include "RemoteControl.h" @@ -120,14 +64,10 @@ volatile sig_atomic_t running = 1; */ void signalHandler(int signum) { -#ifdef _WIN32 - fprintf(stderr, "\npid: %i\n", _getpid()); -#else fprintf(stderr, "\npid: %i, ppid: %i\n", getpid(), getppid()); -#endif + #define SIG_MSG "Signal received: " switch (signum) { -#ifndef _WIN32 case SIGHUP: fprintf(stderr, SIG_MSG "SIGHUP\n"); break; @@ -138,7 +78,6 @@ void signalHandler(int signum) fprintf(stderr, SIG_MSG "SIGPIPE\n"); return; break; -#endif case SIGINT: fprintf(stderr, SIG_MSG "SIGINT\n"); break; @@ -150,9 +89,7 @@ void signalHandler(int signum) default: fprintf(stderr, SIG_MSG "number %i\n", signum); } -#ifndef _WIN32 killpg(0, SIGPIPE); -#endif running = 0; } @@ -185,12 +122,6 @@ int main(int argc, char *argv[]) } } -#ifdef _WIN32 - if (SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) == 0) { - etiLog.log(warn, "Can't increase priority: %s\n", - strerror(errno)); - } -#else // Use the lowest real-time priority for this thread, and switch to real-time scheduling const int policy = SCHED_RR; sched_param sp; @@ -199,7 +130,6 @@ int main(int argc, char *argv[]) if (thread_prio_ret != 0) { etiLog.level(error) << "Could not set real-time priority for thread:" << thread_prio_ret; } -#endif int returnCode = 0; ptree pt; diff --git a/src/DabMux.h b/src/DabMux.h deleted file mode 100644 index 80b4881..0000000 --- a/src/DabMux.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, - 2011 Her Majesty the Queen in Right of Canada (Communications - Research Center Canada) - - Copyright (C) 2014 - Matthias P. Braendli, matthias.braendli@mpb.li - - This file declares several structures used in the multiplexer, - and defines default values for some parameters. - */ -/* - This file is part of ODR-DabMux. - - ODR-DabMux is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - ODR-DabMux is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with ODR-DabMux. If not, see . -*/ -#pragma once - -#include -#include -#include -#include "DabMultiplexer.h" -#include "RemoteControl.h" -#include "dabOutput/dabOutput.h" -#include "input/inputs.h" -#include "Eti.h" -#include "MuxElements.h" - -#ifdef _WIN32 -# include -#else -# include -#endif - diff --git a/src/Eti.cpp b/src/Eti.cpp index e1b51fb..2f26f2d 100644 --- a/src/Eti.cpp +++ b/src/Eti.cpp @@ -22,19 +22,10 @@ along with ODR-DabMux. If not, see . */ -#ifdef _WIN32 -# pragma warning ( disable : 4103 ) -# include "Eti.h" -# pragma warning ( default : 4103 ) -#else -# include "Eti.h" -# include -#endif - +#include "Eti.h" //definitions des structures des champs du ETI(NI, G703) - unsigned short eti_FC::getFrameLength() { return (unsigned short)((FL_high << 8) | FL_low); @@ -80,7 +71,7 @@ void eti_MNSC_TIME_1::setFromTime(struct tm *time_tm) { second_unit = time_tm->tm_sec % 10; second_tens = time_tm->tm_sec / 10; - + minute_unit = time_tm->tm_min % 10; minute_tens = time_tm->tm_min / 10; } @@ -89,7 +80,7 @@ void eti_MNSC_TIME_2::setFromTime(struct tm *time_tm) { hour_unit = time_tm->tm_hour % 10; hour_tens = time_tm->tm_hour / 10; - + day_unit = time_tm->tm_mday % 10; day_tens = time_tm->tm_mday / 10; } @@ -98,7 +89,7 @@ void eti_MNSC_TIME_3::setFromTime(struct tm *time_tm) { month_unit = (time_tm->tm_mon + 1) % 10; month_tens = (time_tm->tm_mon + 1) / 10; - + // They didn't see the y2k bug coming, did they ? year_unit = (time_tm->tm_year - 100) % 10; year_tens = (time_tm->tm_year - 100) / 10; diff --git a/src/Eti.h b/src/Eti.h index 88055c3..0d7aea5 100644 --- a/src/Eti.h +++ b/src/Eti.h @@ -29,24 +29,12 @@ # include #endif -#ifdef _WIN32 -# include // For types... -typedef WORD uint16_t; -typedef DWORD32 uint32_t; - -# define PACKED -# pragma pack(push, 1) -#else -# include -# include - -# define PACKED __attribute__ ((packed)) -#endif - +#include +#include +#define PACKED __attribute__ ((packed)) //definitions des structures des champs du ETI(NI, G703) - struct eti_SYNC { uint32_t ERR:8; uint32_t FSYNC:24; diff --git a/src/Interleaver.cpp b/src/Interleaver.cpp index cf0d235..1786d08 100644 --- a/src/Interleaver.cpp +++ b/src/Interleaver.cpp @@ -23,11 +23,6 @@ #include -#ifdef _WIN32 -# define bzero(a, b) memset((a), 0, (b)) -#endif // _WIN32 - - Interleaver::Interleaver(unsigned short I, unsigned short M, bool reverse) : I(I), M(M), diff --git a/src/ManagementServer.cpp b/src/ManagementServer.cpp index dff093a..2c25a7a 100644 --- a/src/ManagementServer.cpp +++ b/src/ManagementServer.cpp @@ -95,11 +95,6 @@ INPUT_COUNTER_RESET_TIME = std::chrono::minutes(30); static constexpr int INPUT_UNSTABLE_THRESHOLD = 3; -/* For how long the input buffers must be empty before we move an input to the - * NoData state. */ -static constexpr auto -INPUT_NODATA_TIMEOUT = std::chrono::seconds(30); - /* Keep 30s of min/max buffer fill information so that we can catch meaningful * values even if we have a slow poller */ static constexpr auto @@ -643,11 +638,7 @@ input_state_t InputStat::determineState() // STATE CALCULATION - /* If the buffer has been empty for more than - * INPUT_NODATA_TIMEOUT, we go to the NoData state. - * - * Consider an empty deque to be NoData too. - */ + /* Consider an empty deque to be NoData. */ if (std::all_of( m_buffer_fill_stats.begin(), m_buffer_fill_stats.end(), [](const fill_stat_t& fs) { return fs.bufsize == 0; }) ) { diff --git a/src/ManagementServer.h b/src/ManagementServer.h index c7a4222..d328f88 100644 --- a/src/ManagementServer.h +++ b/src/ManagementServer.h @@ -50,7 +50,6 @@ # include "config.h" #endif -#include "Socket.h" #include "zmq.hpp" #include #include @@ -65,7 +64,6 @@ #include #include -#include /*** State handing ***/ /* An input can be in one of the following three states: diff --git a/src/MuxElements.cpp b/src/MuxElements.cpp index d17b283..1f02a6d 100644 --- a/src/MuxElements.cpp +++ b/src/MuxElements.cpp @@ -743,7 +743,14 @@ const json::map_t dabEnsemble::get_all_values() const return map; } -bool dabEnsemble::validate_linkage_sets() +bool dabEnsemble::validate_linkage_sets() const +{ + return validate_linkage_sets(services, linkagesets); +} + +bool dabEnsemble::validate_linkage_sets( + const vec_sp_service& services, + std::vector > linkagesets) { for (const auto& ls : linkagesets) { const std::string keyserviceuid = ls->keyservice; diff --git a/src/MuxElements.h b/src/MuxElements.h index d118df9..0266671 100644 --- a/src/MuxElements.h +++ b/src/MuxElements.h @@ -33,16 +33,13 @@ #include #include #include -#include #include -#include #include #include #include #include "dabOutput/dabOutput.h" #include "input/inputs.h" #include "RemoteControl.h" -#include "Eti.h" // Protection levels and bitrates for UEP. const unsigned char ProtectionLevelTable[64] = { @@ -315,7 +312,10 @@ class dabEnsemble : public RemoteControllable { virtual const json::map_t get_all_values() const; /* Check if the Linkage Sets are valid */ - bool validate_linkage_sets(void); + bool validate_linkage_sets() const; + static bool validate_linkage_sets( + const vec_sp_service& services, + std::vector > linkagesets); /* all fields are public, since this was a struct before */ uint16_t id = 0; diff --git a/src/PcDebug.h b/src/PcDebug.h index d0b2b2c..68fceb8 100644 --- a/src/PcDebug.h +++ b/src/PcDebug.h @@ -19,8 +19,7 @@ along with ODR-DabMux. If not, see . */ -#ifndef PC_DEBUG_ -#define PC_DEBUG_ +#pragma once #ifdef HAVE_CONFIG_H # include "config.h" @@ -31,49 +30,28 @@ #include -#define LOG stderr +#define LOG stderr -#if !defined(_WIN32) || defined(__MINGW32__) -# ifndef PDEBUG -# ifdef DEBUG -# define PDEBUG(fmt, args...) fprintf (LOG, fmt , ## args) -# else -# define PDEBUG(fmt, args...) -# endif -# endif +#ifndef PDEBUG # ifdef DEBUG -# define PDEBUG_VERBOSE(level, verbosity, fmt, args...) if (level <= verbosity) { fprintf(LOG, fmt, ## args); fflush(LOG); } -# define PDEBUG0_VERBOSE(level, verbosity, txt) if (level <= verbosity) { fprintf(LOG, txt); fflush(LOG); } -# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) if (level <= verbosity) { fprintf(LOG, txt, arg0); fflush(LOG); } -# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1); fflush(LOG); } -# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2); fflush(LOG); } -# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2, arg3); fflush(LOG); } -# else -# define PDEBUG_VERBOSE(level, verbosity, fmt, args...) -# define PDEBUG0_VERBOSE(level, verbosity, txt) -# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) -# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) -# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) -# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) -# endif // DEBUG -#else // _WIN32 -# ifdef _DEBUG -# define PDEBUG -# define PDEBUG_VERBOSE -# define PDEBUG0_VERBOSE(level, verbosity, txt) if (level <= verbosity) { fprintf(LOG, txt); fflush(LOG); } -# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) if (level <= verbosity) { fprintf(LOG, txt, arg0); fflush(LOG); } -# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1); fflush(LOG); } -# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2); fflush(LOG); } -# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2, arg3); fflush(LOG); } +# define PDEBUG(fmt, args...) fprintf (LOG, fmt , ## args) # else -# define PDEBUG -# define PDEBUG_VERBOSE -# define PDEBUG0_VERBOSE(level, verbosity, txt) -# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) -# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) -# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) -# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) +# define PDEBUG(fmt, args...) # endif #endif +#ifdef DEBUG +# define PDEBUG_VERBOSE(level, verbosity, fmt, args...) if (level <= verbosity) { fprintf(LOG, fmt, ## args); fflush(LOG); } +# define PDEBUG0_VERBOSE(level, verbosity, txt) if (level <= verbosity) { fprintf(LOG, txt); fflush(LOG); } +# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) if (level <= verbosity) { fprintf(LOG, txt, arg0); fflush(LOG); } +# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1); fflush(LOG); } +# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2); fflush(LOG); } +# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) if (level <= verbosity) { fprintf(LOG, txt, arg0, arg1, arg2, arg3); fflush(LOG); } +#else +# define PDEBUG_VERBOSE(level, verbosity, fmt, args...) +# define PDEBUG0_VERBOSE(level, verbosity, txt) +# define PDEBUG1_VERBOSE(level, verbosity, txt, arg0) +# define PDEBUG2_VERBOSE(level, verbosity, txt, arg0, arg1) +# define PDEBUG3_VERBOSE(level, verbosity, txt, arg0, arg1, arg2) +# define PDEBUG4_VERBOSE(level, verbosity, txt, arg0, arg1, arg2, arg3) +#endif // DEBUG -#endif // PC_DEBUG_ diff --git a/src/fig/FIG0_6.h b/src/fig/FIG0_6.h index 770c4d5..96464d2 100644 --- a/src/fig/FIG0_6.h +++ b/src/fig/FIG0_6.h @@ -26,8 +26,6 @@ #pragma once #include -#include -#include namespace FIC { diff --git a/src/fig/FIG1.h b/src/fig/FIG1.h index 0fedffe..fe36717 100644 --- a/src/fig/FIG1.h +++ b/src/fig/FIG1.h @@ -23,8 +23,7 @@ along with ODR-DabMux. If not, see . */ -#ifndef __FIG1_H_ -#define __FIG1_H_ +#pragma once #include @@ -103,10 +102,6 @@ class FIG1_5 : public IFIG vec_sp_service::iterator service; }; -#ifdef _WIN32 -# pragma pack(push) -#endif - struct FIGtype1_0 { uint8_t Length:5; uint8_t FIGtypeNumber:3; @@ -165,11 +160,5 @@ struct FIGtype1_4_data { } PACKED; -#ifdef _WIN32 -# pragma pack(pop) -#endif - } // namespace FIC -#endif // __FIG1_H_ - diff --git a/src/fig/FIG2.h b/src/fig/FIG2.h index ee3fed9..e69c5db 100644 --- a/src/fig/FIG2.h +++ b/src/fig/FIG2.h @@ -22,9 +22,7 @@ You should have received a copy of the GNU General Public License along with ODR-DabMux. If not, see . */ - -#ifndef __FIG2_H_ -#define __FIG2_H_ +#pragma once #include #include @@ -117,10 +115,6 @@ class FIG2_4 : public IFIG std::map, FIG2_Segments> segment_per_component; }; -#ifdef _WIN32 -# pragma pack(push) -#endif - struct FIGtype2 { uint8_t Length:5; uint8_t FIGtypeNumber:3; @@ -159,11 +153,5 @@ struct FIG2_Extended_Label_WithTextControl { uint8_t EncodingFlag:1; } PACKED; -#ifdef _WIN32 -# pragma pack(pop) -#endif - } // namespace FIC -#endif // __FIG2_H_ - diff --git a/src/input/File.cpp b/src/input/File.cpp index d9fe02a..c70feee 100644 --- a/src/input/File.cpp +++ b/src/input/File.cpp @@ -28,9 +28,6 @@ #include #include #include -#ifndef _WIN32 -# define O_BINARY 0 -#endif #include "input/File.h" #include "mpeg.h" #include "ReedSolomon.h" @@ -39,9 +36,6 @@ using namespace std; namespace Inputs { -#ifdef _WIN32 -# pragma pack(push, 1) -#endif struct packetHeader { unsigned char addressHigh:2; unsigned char last:1; @@ -52,11 +46,7 @@ struct packetHeader { unsigned char dataLength:7; unsigned char command; } -#ifdef _WIN32 -# pragma pack(pop) -#else __attribute((packed)) -#endif ; @@ -68,7 +58,7 @@ void FileBase::open(const std::string& name) load_entire_file(); } else { - int flags = O_RDONLY | O_BINARY; + int flags = O_RDONLY; if (m_nonblock) { flags |= O_NONBLOCK; } @@ -140,13 +130,13 @@ ssize_t FileBase::load_entire_file() { // Clear the buffer if the file open fails, this allows user to stop transmission // of the current data. - vector old_file_contents = move(m_file_contents); + vector old_file_contents = std::move(m_file_contents); m_file_contents.clear(); m_file_contents_offset = 0; // Read entire file in chunks of 4MiB constexpr size_t blocksize = 4 * 1024 * 1024; - constexpr int flags = O_RDONLY | O_BINARY; + constexpr int flags = O_RDONLY; m_fd = ::open(m_filename.c_str(), flags); if (m_fd == -1) { if (not m_file_open_alert_shown) { @@ -225,7 +215,7 @@ ssize_t FileBase::readFromFile(uint8_t *buffer, size_t size) vector remaining_buf; copy(m_nonblock_buffer.begin() + size, m_nonblock_buffer.end(), back_inserter(remaining_buf)); - m_nonblock_buffer = move(remaining_buf); + m_nonblock_buffer = std::move(remaining_buf); return size; } diff --git a/src/mpeg.h b/src/mpeg.h index 15b9b80..29b3655 100644 --- a/src/mpeg.h +++ b/src/mpeg.h @@ -18,23 +18,13 @@ You should have received a copy of the GNU General Public License along with ODR-DabMux. If not, see . */ - -#ifndef _MPEG -#define _MPEG +#pragma once #ifdef HAVE_CONFIG_H # include "config.h" #endif -#ifdef _WIN32 -# include -# include -# include - -# define ssize_t SSIZE_T -#else -# include -#endif +#include #ifdef __cplusplus extern "C" { @@ -86,4 +76,3 @@ int checkDabMpegFrame(void* data); } #endif -#endif // _MPEG -- cgit v1.2.3 From c84727c8ec0f99d66d1ad7d4716de79b6235d4d1 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Thu, 11 Sep 2025 15:37:32 +0200 Subject: Add runtime linkage-set reload --- src/ConfigParser.cpp | 15 +++++----- src/ConfigParser.h | 8 +++-- src/DabMultiplexer.cpp | 75 ++++++++++++++++++++++++++++++++++++++++------ src/DabMultiplexer.h | 78 ++++++++++++++++++++++++++++-------------------- src/DabMux.cpp | 44 ++++++++++----------------- src/ManagementServer.cpp | 4 +-- src/ManagementServer.h | 16 +++++----- src/MuxElements.h | 18 +++++------ 8 files changed, 161 insertions(+), 97 deletions(-) (limited to 'src/DabMultiplexer.cpp') diff --git a/src/ConfigParser.cpp b/src/ConfigParser.cpp index 7d166b6..2d500b3 100644 --- a/src/ConfigParser.cpp +++ b/src/ConfigParser.cpp @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2022 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org @@ -110,10 +110,10 @@ static void parse_fig2_label(ptree& pt, DabLabel& label) { } // Parse the linkage section -static void parse_linkage(ptree& pt, - std::shared_ptr ensemble) +void parse_linkage( + const boost::optional pt_linking, + std::vector >& linkageSets) { - auto pt_linking = pt.get_child_optional("linking"); if (pt_linking) { for (const auto& it : *pt_linking) { const string setuid = it.first; @@ -132,7 +132,7 @@ static void parse_linkage(ptree& pt, string service_uid = pt_set.get("keyservice", ""); auto linkageset = make_shared(setuid, lsn, active, hard, international); - linkageset->keyservice = service_uid; // TODO check if it exists + linkageset->keyservice = service_uid; // existence check is done in validate_linkage_sets() auto pt_list = pt_set.get_child_optional("list"); @@ -189,7 +189,7 @@ static void parse_linkage(ptree& pt, linkageset->id_list.push_back(link); } } - ensemble->linkagesets.push_back(linkageset); + linkageSets.push_back(linkageset); } } } @@ -910,7 +910,8 @@ void parse_ptree( } - parse_linkage(pt, ensemble); + const auto pt_linking = pt.get_child_optional("linking"); + parse_linkage(pt_linking, ensemble->linkagesets); parse_freq_info(pt, ensemble); parse_other_service_linking(pt, ensemble); } diff --git a/src/ConfigParser.h b/src/ConfigParser.h index 9ca6c81..038247b 100644 --- a/src/ConfigParser.h +++ b/src/ConfigParser.h @@ -3,7 +3,7 @@ 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) - Copyright (C) 2016 + Copyright (C) 2025 Matthias P. Braendli, matthias.braendli@mpb.li The Configuration parser sets up the ensemble according @@ -34,6 +34,10 @@ #include #include -void parse_ptree(boost::property_tree::ptree& pt, +void parse_ptree( + boost::property_tree::ptree& pt, std::shared_ptr ensemble); +void parse_linkage( + const boost::optional pt_linking, + std::vector >& linkageSets); diff --git a/src/DabMultiplexer.cpp b/src/DabMultiplexer.cpp index c665f2c..7a8ac97 100644 --- a/src/DabMultiplexer.cpp +++ b/src/DabMultiplexer.cpp @@ -26,6 +26,9 @@ #include #include #include +#include +#include + #include "DabMultiplexer.h" #include "ConfigParser.h" #include "ManagementServer.h" @@ -132,15 +135,35 @@ std::pair MuxTime::get_milliseconds_seconds() } -DabMultiplexer::DabMultiplexer(boost::property_tree::ptree pt) : +void DabMultiplexerConfig::read(const std::string& filename) +{ + m_config_file = ""; + try { + if (stringEndsWith(filename, ".json")) { + read_json(filename, pt); + } + else { + read_info(filename, pt); + } + m_config_file = filename; + } + catch (const boost::property_tree::file_parser_error& e) + { + etiLog.level(warn) << "Failed to read " << filename; + } +} + +DabMultiplexer::DabMultiplexer(DabMultiplexerConfig& config) : RemoteControllable("mux"), - m_pt(pt), + m_config(config), m_time(), ensemble(std::make_shared()), - m_clock_tai(split_pipe_separated_string(pt.get("general.tai_clock_bulletins", ""))), + m_clock_tai(split_pipe_separated_string(m_config.pt.get("general.tai_clock_bulletins", ""))), fig_carousel(ensemble, [&]() { return m_time.get_milliseconds_seconds(); }) { RC_ADD_PARAMETER(frames, "Show number of frames generated [read-only]"); + RC_ADD_PARAMETER(tist_offset, "Configured tist-offset"); + RC_ADD_PARAMETER(reload_linkagesets, "Write 1 to this parameter to trigger a reload of the linkage sets from the config [write-only]"); rcs.enrol(&m_clock_tai); } @@ -160,7 +183,7 @@ void DabMultiplexer::set_edi_config(const edi::configuration_t& new_edi_conf) // Run a set of checks on the configuration void DabMultiplexer::prepare(bool require_tai_clock) { - parse_ptree(m_pt, ensemble); + parse_ptree(m_config.pt, ensemble); rcs.enrol(this); rcs.enrol(ensemble.get()); @@ -186,11 +209,11 @@ void DabMultiplexer::prepare(bool require_tai_clock) throw MuxInitException(); } - const uint32_t tist_at_fct0_ms = m_pt.get("general.tist_at_fct0", 0); - currentFrame = m_time.init(tist_at_fct0_ms, m_pt.get("general.tist_offset", 0.0)); + const uint32_t tist_at_fct0_ms = m_config.pt.get("general.tist_at_fct0", 0); + currentFrame = m_time.init(tist_at_fct0_ms, m_config.pt.get("general.tist_offset", 0.0)); m_time.mnsc_increment_time = false; - bool tist_enabled = m_pt.get("general.tist", false); + bool tist_enabled = m_config.pt.get("general.tist", false); auto tist_edi_time = m_time.get_tist_seconds(); const auto timestamp = tist_edi_time.first; @@ -439,6 +462,32 @@ void DabMultiplexer::prepare_data_inputs() } } +void DabMultiplexer::reload_linkagesets() +{ + try { + DabMultiplexerConfig new_conf; + new_conf.read(m_config.config_file()); + if (new_conf.valid()) { + const auto pt_linking = new_conf.pt.get_child_optional("linking"); + std::vector > linkagesets; + parse_linkage(pt_linking, linkagesets); + + etiLog.level(info) << "Validating " << linkagesets.size() << " new linkage sets."; + + if (ensemble->validate_linkage_sets(ensemble->services, linkagesets)) { + ensemble->linkagesets = linkagesets; + etiLog.level(info) << "Loaded new linkage sets."; + } + else { + etiLog.level(warn) << "New linkage set validation failed"; + } + } + } + catch (const std::exception& e) + { + etiLog.level(warn) << "Failed to update linkage sets: " << e.what(); + } +} /* Each call creates one ETI frame */ void DabMultiplexer::mux_frame(std::vector >& outputs) @@ -458,7 +507,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs // The above Tag Items will be assembled into a TAG Packet edi::TagPacket edi_tagpacket(edi_conf.tagpacket_alignment); - const bool tist_enabled = m_pt.get("general.tist", false); + const bool tist_enabled = m_config.pt.get("general.tist", false); int tai_utc_offset = 0; if (tist_enabled and m_tai_clock_required) { @@ -718,7 +767,7 @@ void DabMultiplexer::mux_frame(std::vector >& outputs index = (FLtmp + 2 + 1) * 4; eti_TIST *tist = (eti_TIST *) & etiFrame[index]; - bool enableTist = m_pt.get("general.tist", false); + bool enableTist = m_config.pt.get("general.tist", false); if (enableTist) { tist->TIST = htonl(timestamp) | 0xff; edi_tagDETI.tsta = timestamp & 0xffffff; @@ -848,6 +897,9 @@ void DabMultiplexer::set_parameter(const std::string& parameter, else if (parameter == "tist_offset") { m_time.set_tist_offset(std::stod(value)); } + else if (parameter == "reload_linkagesets") { + reload_linkagesets(); + } else { stringstream ss; ss << "Parameter '" << parameter << @@ -866,6 +918,11 @@ const std::string DabMultiplexer::get_parameter(const std::string& parameter) co else if (parameter == "tist_offset") { ss << m_time.tist_offset(); } + else if (parameter == "reload_linkagesets") { + ss << "Parameter '" << parameter << + "' is not write-only in controllable " << get_rc_name(); + throw ParameterError(ss.str()); + } else { ss << "Parameter '" << parameter << "' is not exported by controllable " << get_rc_name(); diff --git a/src/DabMultiplexer.h b/src/DabMultiplexer.h index 9306eed..620e65d 100644 --- a/src/DabMultiplexer.h +++ b/src/DabMultiplexer.h @@ -45,47 +45,59 @@ constexpr uint32_t ETI_FSYNC1 = 0x49C5F8; class MuxTime { private: - std::time_t m_edi_time = 0; - uint32_t m_pps_offset_ms = 0; - int64_t m_tist_offset_ms = 0; + std::time_t m_edi_time = 0; + uint32_t m_pps_offset_ms = 0; + int64_t m_tist_offset_ms = 0; public: - std::pair get_tist_seconds(); - std::pair get_milliseconds_seconds(); - - - /* Pre v3 odr-dabmux did the MNSC calculation differently, - * which works with the easydabv2. The rework in odr-dabmux, - * deriving MNSC time from EDI time broke this. - * - * That's why we're now tracking MNSC time in separate variables, - * to get the same behaviour back. - * - * I'm not aware of any devices using MNSC time besides the - * easydab. ODR-DabMod now considers EDI seconds or ZMQ metadata. - */ - bool mnsc_increment_time = false; - std::time_t mnsc_time = 0; - - /* Setup the time and return the initial currentFrame counter value */ - uint64_t init(uint32_t tist_at_fct0_ms, double tist_offset); - void increment_timestamp(); - double tist_offset() const { return m_tist_offset_ms / 1000.0; } - void set_tist_offset(double new_tist_offset); + std::pair get_tist_seconds(); + std::pair get_milliseconds_seconds(); + + + /* Pre v3 odr-dabmux did the MNSC calculation differently, + * which works with the easydabv2. The rework in odr-dabmux, + * deriving MNSC time from EDI time broke this. + * + * That's why we're now tracking MNSC time in separate variables, + * to get the same behaviour back. + * + * I'm not aware of any devices using MNSC time besides the + * easydab. ODR-DabMod now considers EDI seconds or ZMQ metadata. + */ + bool mnsc_increment_time = false; + std::time_t mnsc_time = 0; + + /* Setup the time and return the initial currentFrame counter value */ + uint64_t init(uint32_t tist_at_fct0_ms, double tist_offset); + void increment_timestamp(); + double tist_offset() const { return m_tist_offset_ms / 1000.0; } + void set_tist_offset(double new_tist_offset); +}; + +class DabMultiplexerConfig { + public: + boost::property_tree::ptree pt; + + void read(const std::string& filename); + bool valid() const { return m_config_file != ""; } + std::string config_file() const { return m_config_file; } + + private: + std::string m_config_file; }; class DabMultiplexer : public RemoteControllable { public: - DabMultiplexer(boost::property_tree::ptree pt); + DabMultiplexer(DabMultiplexerConfig& config); DabMultiplexer(const DabMultiplexer& other) = delete; DabMultiplexer& operator=(const DabMultiplexer& other) = delete; - ~DabMultiplexer(); + virtual ~DabMultiplexer(); void prepare(bool require_tai_clock); void mux_frame(std::vector >& outputs); - void print_info(void); + void print_info(); void set_edi_config(const edi::configuration_t& new_edi_conf); @@ -99,11 +111,13 @@ class DabMultiplexer : public RemoteControllable { virtual const json::map_t get_all_values() const; private: - void prepare_subchannels(void); - void prepare_services_components(void); - void prepare_data_inputs(void); + void prepare_subchannels(); + void prepare_services_components(); + void prepare_data_inputs(); + + void reload_linkagesets(); - boost::property_tree::ptree m_pt; + DabMultiplexerConfig& m_config; MuxTime m_time; uint64_t currentFrame = 0; diff --git a/src/DabMux.cpp b/src/DabMux.cpp index 0066629..7b5f5d6 100644 --- a/src/DabMux.cpp +++ b/src/DabMux.cpp @@ -31,8 +31,6 @@ #include #include -#include -#include #include #include #include @@ -132,12 +130,13 @@ int main(int argc, char *argv[]) } int returnCode = 0; - ptree pt; std::vector > outputs; try { string conf_file = ""; + DabMultiplexerConfig mux_conf; + if (argc == 2) { // Assume the only argument is a config file conf_file = argv[1]; @@ -154,8 +153,7 @@ int main(int argc, char *argv[]) } conf_file = argv[2]; - - read_info(conf_file, pt); + mux_conf.read(conf_file); } catch (runtime_error &e) { throw MuxInitException(e.what()); @@ -168,23 +166,18 @@ int main(int argc, char *argv[]) } try { - if (stringEndsWith(conf_file, ".json")) { - read_json(conf_file, pt); - } - else { - read_info(conf_file, pt); - } + mux_conf.read(conf_file); } catch (runtime_error &e) { throw MuxInitException(e.what()); } /* Enable Logging to syslog conditionally */ - if (pt.get("general.syslog", false)) { + if (mux_conf.pt.get("general.syslog", false)) { etiLog.register_backend(std::make_shared()); } - const auto startupcheck = pt.get("general.startupcheck", ""); + const auto startupcheck = mux_conf.pt.get("general.startupcheck", ""); if (not startupcheck.empty()) { etiLog.level(info) << "Running startup check '" << startupcheck << "'"; int wstatus = system(startupcheck.c_str()); @@ -204,26 +197,26 @@ int main(int argc, char *argv[]) } } - int mgmtserverport = pt.get("general.managementport", - pt.get("general.statsserverport", 0) ); + int mgmtserverport = mux_conf.pt.get("general.managementport", + mux_conf.pt.get("general.statsserverport", 0) ); /* Management: stats and config server */ get_mgmt_server().open(mgmtserverport); /************** READ REMOTE CONTROL PARAMETERS *************/ - int telnetport = pt.get("remotecontrol.telnetport", 0); + int telnetport = mux_conf.pt.get("remotecontrol.telnetport", 0); if (telnetport != 0) { auto rc = std::make_shared(telnetport); rcs.add_controller(rc); } - auto zmqendpoint = pt.get("remotecontrol.zmqendpoint", ""); + auto zmqendpoint = mux_conf.pt.get("remotecontrol.zmqendpoint", ""); if (not zmqendpoint.empty()) { auto rc = std::make_shared(zmqendpoint); rcs.add_controller(rc); } - DabMultiplexer mux(pt); + DabMultiplexer mux(mux_conf); etiLog.level(info) << PACKAGE_NAME << " " << @@ -240,7 +233,7 @@ int main(int argc, char *argv[]) /******************** READ OUTPUT PARAMETERS ***************/ set all_output_names; bool output_require_tai_clock = false; - ptree pt_outputs = pt.get_child("outputs"); + ptree pt_outputs = mux_conf.pt.get_child("outputs"); for (auto ptree_pair : pt_outputs) { string outputuid = ptree_pair.first; @@ -444,7 +437,6 @@ int main(int argc, char *argv[]) } outputs.push_back(output); - } } @@ -464,7 +456,7 @@ int main(int argc, char *argv[]) edi_conf.print(); } - size_t limit = pt.get("general.nbframes", 0); + const size_t limit = mux_conf.pt.get("general.nbframes", 0); etiLog.level(info) << "Start loop"; /* Each iteration of the main loop creates one ETI frame */ @@ -473,6 +465,7 @@ int main(int argc, char *argv[]) mux.mux_frame(outputs); if (limit && currentFrame >= limit) { + etiLog.level(info) << "Max number of ETI frames reached: " << currentFrame; break; } @@ -491,17 +484,12 @@ int main(int argc, char *argv[]) mgmt_server.restart(); } - mgmt_server.update_ptree(pt); + mgmt_server.update_ptree(mux_conf.pt); } } - - if (limit) { - etiLog.level(info) << "Max number of ETI frames reached: " << currentFrame; - } } catch (const MuxInitException& except) { - etiLog.level(error) << "Multiplex initialisation aborted: " << - except.what(); + etiLog.level(error) << "Multiplex initialisation aborted: " << except.what(); returnCode = 1; } catch (const std::invalid_argument& except) { diff --git a/src/ManagementServer.cpp b/src/ManagementServer.cpp index 2c25a7a..7344b8b 100644 --- a/src/ManagementServer.cpp +++ b/src/ManagementServer.cpp @@ -473,7 +473,7 @@ void InputStat::notifyPeakLevels(int peak_left, int peak_right) } } -void InputStat::notifyUnderrun(void) +void InputStat::notifyUnderrun() { unique_lock lock(m_mutex); @@ -492,7 +492,7 @@ void InputStat::notifyUnderrun(void) } } -void InputStat::notifyOverrun(void) +void InputStat::notifyOverrun() { unique_lock lock(m_mutex); diff --git a/src/ManagementServer.h b/src/ManagementServer.h index d328f88..93ad28c 100644 --- a/src/ManagementServer.h +++ b/src/ManagementServer.h @@ -93,20 +93,20 @@ class InputStat InputStat(const InputStat& other) = delete; InputStat& operator=(const InputStat& other) = delete; ~InputStat(); - void registerAtServer(void); + void registerAtServer(); - std::string get_name(void) const { return m_name; } + std::string get_name() const { return m_name; } /* This function is called for every frame read by * the multiplexer */ void notifyBuffer(long bufsize); void notifyTimestampOffset(double offset); void notifyPeakLevels(int peak_left, int peak_right); - void notifyUnderrun(void); - void notifyOverrun(void); + void notifyUnderrun(); + void notifyOverrun(); void notifyVersion(const std::string& version, uint32_t uptime_s); - std::string encodeValuesJSON(void); - input_state_t determineState(void); + std::string encodeValuesJSON(); + input_state_t determineState(); private: std::string m_name; @@ -183,7 +183,7 @@ class ManagementServer void update_ptree(const boost::property_tree::ptree& pt); bool fault_detected() const { return m_fault; } - void restart(void); + void restart(); private: void restart_thread(long); @@ -192,7 +192,7 @@ class ManagementServer zmq::context_t m_zmq_context; zmq::socket_t m_zmq_sock; - void serverThread(void); + void serverThread(); void handle_message(zmq::message_t& zmq_message); bool isInputRegistered(std::string& id); diff --git a/src/MuxElements.h b/src/MuxElements.h index 0266671..dfc4380 100644 --- a/src/MuxElements.h +++ b/src/MuxElements.h @@ -84,7 +84,7 @@ class MuxInitException : public std::exception MuxInitException(const std::string m = "ODR-DabMux initialisation error") throw() : msg(m) {} - ~MuxInitException(void) throw() {} + ~MuxInitException() throw() {} const char* what() const throw() { return msg.c_str(); } private: std::string msg; @@ -137,12 +137,12 @@ class AnnouncementCluster : public RemoteControllable { uint16_t flags = 0; std::string subchanneluid; - std::string tostring(void) const; + std::string tostring() const; /* Check if the activation/deactivation timeout occurred, * and return of if the Announcement is active */ - bool is_active(void); + bool is_active(); private: mutable std::mutex m_active_mutex; @@ -372,7 +372,7 @@ struct dabProtectionEEP { // select EEP profile A and B. // Other values are for future use, see // EN 300 401 Clause 6.2.1 "Basic sub-channel organisation" - uint8_t GetOption(void) const { + uint8_t GetOption() const { return (this->profile == EEP_A) ? 0 : 1; } }; @@ -402,16 +402,16 @@ public: protection() { } // Calculate subchannel size in number of CU - unsigned short getSizeCu(void) const; + unsigned short getSizeCu() const; // Calculate subchannel size in number of bytes - unsigned short getSizeByte(void) const; + unsigned short getSizeByte() const; // Calculate subchannel size in number of uint32_t - unsigned short getSizeWord(void) const; + unsigned short getSizeWord() const; // Calculate subchannel size in number of uint64_t - unsigned short getSizeDWord(void) const; + unsigned short getSizeDWord() const; // Read from the input, using the correct buffer management size_t readFrame(uint8_t *buffer, size_t size, std::time_t seconds, int utco, uint32_t tsta); @@ -574,7 +574,7 @@ class LinkageSet { bool hard, bool international); - std::string get_name(void) const { return m_name; } + std::string get_name() const { return m_name; } std::list id_list; -- cgit v1.2.3