From 0a32425c7f1c189aeccc200012d706890b0b9360 Mon Sep 17 00:00:00 2001 From: Bryan Biedenkapp Date: Sat, 21 Nov 2026 11:52:43 -0500 Subject: [PATCH] replace the greedy Trellis point fixers with Viterbi decoders; resolve tied confirmed data candidates by CRC-9; --- src/common/dmr/data/DataBlock.cpp | 79 ++++- src/common/dmr/data/DataBlock.h | 8 + src/common/edac/Trellis.cpp | 324 +++++++++++--------- src/common/edac/Trellis.h | 79 +++-- src/common/p25/data/DataBlock.cpp | 93 ++++-- src/common/p25/data/DataBlock.h | 10 +- tests/dmr/DataBlock_Tests.cpp | 78 ++++- tests/edac/Trellis_Tests.cpp | 190 +++++++++++- tests/p25/PDU_Confirmed_TrellisTie_Test.cpp | 77 +++++ 9 files changed, 704 insertions(+), 234 deletions(-) create mode 100644 tests/p25/PDU_Confirmed_TrellisTie_Test.cpp diff --git a/src/common/dmr/data/DataBlock.cpp b/src/common/dmr/data/DataBlock.cpp index 15839799..1cf59cd9 100644 --- a/src/common/dmr/data/DataBlock.cpp +++ b/src/common/dmr/data/DataBlock.cpp @@ -75,11 +75,41 @@ bool DataBlock::decode(const uint8_t* data, const DataHeader& header) if (m_DPF == DPF::CONFIRMED_DATA) { try { if (m_dataType == DataType::RATE_34_DATA) { - bool valid = m_trellis.decode34(data, buffer, true); - if (!valid) { + uint8_t candidates[edac::TRELLIS_34_MAX_LIST_PATHS * edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES]; + ::memset(candidates, 0x00U, sizeof(candidates)); + + bool truncated = false; + const uint32_t candidateCnt = m_trellis.decode34List(data, candidates, + edac::TRELLIS_34_MAX_LIST_PATHS, truncated, true); + if (candidateCnt == 0U) { LogError(LOG_DMR, "DataBlock::decode(), failed to decode Trellis 3/4 rate coding"); return false; } + + uint32_t selected = 0U; + bool valid = false; + for (uint32_t i = 0U; i < candidateCnt; i++) { + uint16_t candidateCRC = 0U; + uint16_t candidateCalc = 0U; + valid = checkConfirmedRate34CRC9(candidates + i * edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES, candidateCRC, candidateCalc); + if (valid) { + selected = i; + break; + } + } + + if (!valid && truncated) { + LogWarning(LOG_DMR, "DMR, dataType = $%02X, Trellis 3/4 rate candidate list truncated before CRC-9 match", + m_dataType); + } + + ::memcpy(buffer, candidates + selected * edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES, + edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES); + + if (valid && selected != 0U) { + LogDebug(LOG_DMR, "DMR, dataType = $%02X, Trellis 3/4 rate tie resolved by CRC-9, candidate %u of %u", + m_dataType, selected + 1U, candidateCnt); + } } else if (m_dataType == DataType::RATE_12_DATA) { m_bptc.decode(data, buffer); @@ -96,22 +126,9 @@ bool DataBlock::decode(const uint8_t* data, const DataHeader& header) Utils::dump(1U, "DMR, DataBlock::decode(), Confirmed PDU Data Block", buffer, DMR_PDU_UNCODED_LENGTH_BYTES); #endif - m_serialNo = (buffer[0] & 0xFEU) >> 1; // Confirmed Data Serial No. uint16_t crc = ((buffer[0] & 0x01U) << 8) + buffer[1]; // CRC-9 Check Sum crc ^= crcMask(m_dataType); - ::memset(m_data, 0x00U, DMR_PDU_UNCODED_LENGTH_BYTES); - if (m_dataType == DataType::RATE_34_DATA) - ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES); // Payload Data - else if (m_dataType == DataType::RATE_12_DATA) - ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_HR_DATA_LENGTH_BYTES); // Payload Data - else if (m_dataType == DataType::RATE_1_DATA) - ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_UNCODED_DATA_LENGTH_BYTES); // Payload Data - else { - LogError(LOG_DMR, "DataBlock::decode(), failed to decode block, invalid dataType = $%02X", m_dataType); - return false; - } - uint8_t crcBuffer[DMR_PDU_UNCODED_LENGTH_BYTES]; ::memset(crcBuffer, 0x00U, DMR_PDU_UNCODED_LENGTH_BYTES); @@ -157,6 +174,16 @@ bool DataBlock::decode(const uint8_t* data, const DataHeader& header) return false; } + m_serialNo = (buffer[0] & 0xFEU) >> 1; // Confirmed Data Serial No. + + ::memset(m_data, 0x00U, DMR_PDU_UNCODED_LENGTH_BYTES); + if (m_dataType == DataType::RATE_34_DATA) + ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES); // Payload Data + else if (m_dataType == DataType::RATE_12_DATA) + ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_HR_DATA_LENGTH_BYTES); // Payload Data + else + ::memcpy(m_data, buffer + 2U, DMR_PDU_CONFIRMED_UNCODED_DATA_LENGTH_BYTES); // Payload Data + #if DEBUG_DMR_PDU_DATA LogDebug(LOG_DMR, "DMR, dataType = $%02X, crc = $%04X, calculated = $%04X", m_dataType, crc, calculated); #endif @@ -479,6 +506,28 @@ uint16_t DataBlock::crcMask(const DataType::E dataType) const } } +/* Checks the CRC-9 of a decoded confirmed rate-3/4 data block. */ + +bool DataBlock::checkConfirmedRate34CRC9(const uint8_t* buffer, uint16_t& crc, uint16_t& calculated) const +{ + assert(buffer != nullptr); + + crc = (((buffer[0] & 0x01U) << 8) + buffer[1]) ^ crcMask(DataType::RATE_34_DATA); + + uint8_t crcBuffer[DMR_PDU_UNCODED_LENGTH_BYTES]; + ::memset(crcBuffer, 0x00U, sizeof(crcBuffer)); + ::memcpy(crcBuffer, buffer + 2U, DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES); + + // append the seven CRC bits from the first byte to the CRC input + for (uint32_t i = 0U; i < 7U; i++) { + const bool bit = READ_BIT(buffer, i) != 0U; + WRITE_BIT(crcBuffer, i + 128U, bit); + } + + calculated = ~edac::CRC::createCRC9(crcBuffer, 135U) & 0x1FFU; + return crc == calculated; +} + /* Decodes a rate 1 encoded data block. */ void DataBlock::decodeRate1(const uint8_t* data, uint8_t* payload) diff --git a/src/common/dmr/data/DataBlock.h b/src/common/dmr/data/DataBlock.h index 819af6ee..5cef97eb 100644 --- a/src/common/dmr/data/DataBlock.h +++ b/src/common/dmr/data/DataBlock.h @@ -129,6 +129,14 @@ namespace dmr * @returns uint16_t CRC mask. */ uint16_t crcMask(const defines::DataType::E dataType) const; + /** + * @brief Checks the CRC-9 of a decoded confirmed rate-3/4 data block. + * @param[in] buffer Decoded 18-byte rate-3/4 data block. + * @param[out] crc Unmasked CRC-9 carried in the block. + * @param[out] calculated CRC-9 computed over the block. + * @returns bool True if the carried and computed CRC-9 values match. + */ + bool checkConfirmedRate34CRC9(const uint8_t* buffer, uint16_t& crc, uint16_t& calculated) const; /** * @brief Decodes a rate 1 encoded data block. diff --git a/src/common/edac/Trellis.cpp b/src/common/edac/Trellis.cpp index 5bc69b82..505ef42b 100644 --- a/src/common/edac/Trellis.cpp +++ b/src/common/edac/Trellis.cpp @@ -5,7 +5,7 @@ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright (C) 2016,2018 Jonathan Naylor, G4KLX - * Copyright (C) 2023-2024 Bryan Biedenkapp, N2PLL + * Copyright (C) 2023-2026 Bryan Biedenkapp, N2PLL * */ #include "Defines.h" @@ -16,6 +16,8 @@ using namespace edac; #include +#include +#include // --------------------------------------------------------------------------- // Constants @@ -43,6 +45,14 @@ const uint8_t ENCODE_TABLE_12[] = { 13U, 2U, 1U, 14U, 9U, 6U, 5U, 10U }; +const int8_t POINT_DIBITS[16U][2U] = { + { +1, -1 }, { -1, -1 }, { +3, -3 }, { -3, -3 }, { -3, -1 }, { +3, -1 }, { -1, -3 }, { +1, -3 }, + { -3, +3 }, { +3, +3 }, { -1, +1 }, { +1, +1 }, { +1, +3 }, { -1, +3 }, { +3, +1 }, { -3, +1 } }; + +const uint32_t TRELLIS_STEPS = 49U; +const uint32_t TRELLIS_34_STATES = 8U; +const uint32_t TRELLIS_12_STATES = 4U; + // --------------------------------------------------------------------------- // Public Class Members // --------------------------------------------------------------------------- @@ -65,30 +75,34 @@ bool Trellis::decode34(const uint8_t* data, uint8_t* payload, bool skipSymbols) int8_t dibits[98U]; deinterleave(data, dibits, skipSymbols); - uint8_t points[49U]; - dibitsToPoints(dibits, points); + uint32_t metric = 0U; + bool truncated = false; + return viterbi34(dibits, payload, &metric, 1U, truncated) == 1U; +} - // Check the original code - uint8_t tribits[49U]; - uint32_t failPos = checkCode34(points, tribits); - if (failPos == 999U) { - tribitsToBits(tribits, payload); - return true; - } +/* Decodes 3/4 rate Trellis and returns a bounded list of best candidates. */ + +uint32_t Trellis::decode34List(const uint8_t* data, uint8_t* payloads, uint32_t maxPaths, bool& truncated, + bool skipSymbols) +{ + assert(data != nullptr); + assert(payloads != nullptr); - uint8_t savePoints[49U]; - for (uint32_t i = 0U; i < 49U; i++) - savePoints[i] = points[i]; + truncated = false; + if (maxPaths == 0U || maxPaths > TRELLIS_34_MAX_LIST_PATHS) + return 0U; - bool ret = fixCode34(points, failPos, payload); - if (ret) - return true; + int8_t dibits[98U]; + deinterleave(data, dibits, skipSymbols); - if (failPos == 0U) - return false; + uint32_t metrics[TRELLIS_34_MAX_LIST_PATHS]; + uint32_t count = viterbi34(dibits, payloads, metrics, maxPaths, truncated); + + uint32_t tied = 0U; + while (tied < count && metrics[tied] == metrics[0U]) + tied++; - // Backtrack one place for a last go - return fixCode34(savePoints, failPos - 1U, payload); + return tied; } /* Encodes 3/4 rate Trellis. */ @@ -128,30 +142,8 @@ bool Trellis::decode12(const uint8_t* data, uint8_t* payload) int8_t dibits[98U]; deinterleave(data, dibits); - uint8_t points[49U]; - dibitsToPoints(dibits, points); - - // Check the original code - uint8_t bits[49U]; - uint32_t failPos = checkCode12(points, bits); - if (failPos == 999U) { - dibitsToBits(bits, payload); - return true; - } - - uint8_t savePoints[49U]; - for (uint32_t i = 0U; i < 49U; i++) - savePoints[i] = points[i]; - - bool ret = fixCode12(points, failPos, payload); - if (ret) - return true; - - if (failPos == 0U) - return false; - - // Backtrack one place for a last go - return fixCode12(savePoints, failPos - 1U, payload); + uint32_t metric = 0U; + return viterbi12(dibits, payload, metric); } /* Encodes 1/2 rate Trellis. */ @@ -448,133 +440,171 @@ void Trellis::dibitsToBits(const uint8_t* dibits, uint8_t* payload) const } } -/* Helper to fix errors in Trellis coding. */ +/* Runs a bounded list Viterbi decode of the 3/4 rate Trellis. */ -bool Trellis::fixCode34(uint8_t* points, uint32_t failPos, uint8_t* payload) const +uint32_t Trellis::viterbi34(const int8_t* dibits, uint8_t* payloads, uint32_t* metrics, uint32_t maxPaths, + bool& truncated) const { -#if DEBUG_TRELLIS - ::LogDebugEx(LOG_HOST, "Trellis::fixCode34()", "failPos = %u, val = %01X", failPos, points[failPos]); -#endif - for (unsigned j = 0U; j < 20U; j++) { - uint32_t bestPos = 0U; - uint32_t bestVal = 0U; - - for (uint32_t i = 0U; i < 16U; i++) { - points[failPos] = i; - - uint8_t tribits[49U]; - uint32_t pos = checkCode34(points, tribits); - if (pos == 999U) { -#if DEBUG_TRELLIS - ::LogDebugEx(LOG_HOST, "Trellis::fixCode34()", "fixed, failPos = %u, pos = %u, val = %01X", failPos, bestPos, bestVal); -#endif - tribitsToBits(tribits, payload); - return true; + assert(dibits != nullptr); + assert(payloads != nullptr); + assert(metrics != nullptr); + assert(maxPaths >= 1U && maxPaths <= TRELLIS_34_MAX_LIST_PATHS); + + // keep the best maxPaths survivors per state, ordered by metric + struct Survivor { + uint16_t metric; + uint8_t prevState; + uint8_t prevRank; + bool truncated; + }; + + Survivor trace[TRELLIS_STEPS][TRELLIS_34_STATES][TRELLIS_34_MAX_LIST_PATHS]; + uint8_t traceCnt[TRELLIS_STEPS][TRELLIS_34_STATES]; + ::memset(traceCnt, 0x00U, sizeof(traceCnt)); + + Survivor current[TRELLIS_34_STATES][TRELLIS_34_MAX_LIST_PATHS]; + uint8_t currentCnt[TRELLIS_34_STATES]; + ::memset(currentCnt, 0x00U, sizeof(currentCnt)); + current[0U][0U] = { 0U, 0U, 0U, false }; + currentCnt[0U] = 1U; + + // for each step and destination state, retain the best maxPaths candidates across all predecessor states + for (uint32_t i = 0U; i < TRELLIS_STEPS; i++) { + const int8_t rx0 = dibits[i * 2U]; + const int8_t rx1 = dibits[i * 2U + 1U]; + + // for each destination state, merge candidates from all predecessor states in metric order + for (uint32_t next = 0U; next < TRELLIS_34_STATES; next++) { + Survivor* best = trace[i][next]; + uint32_t bestCnt = 0U; + + // compute the branch metric for each predecessor state and insert its survivors in sorted order + for (uint32_t state = 0U; state < TRELLIS_34_STATES; state++) { + const uint8_t point = ENCODE_TABLE_34[state * TRELLIS_34_STATES + next]; + const uint32_t branch = (uint32_t)((::abs(POINT_DIBITS[point][0U] - rx0) + ::abs(POINT_DIBITS[point][1U] - rx1)) / 2); + + // insert each predecessor survivor by metric, keeping only the best maxPaths candidates + for (uint32_t rank = 0U; rank < currentCnt[state]; rank++) { + const uint16_t metric = (uint16_t)(current[state][rank].metric + branch); + if (bestCnt == maxPaths && metric >= best[bestCnt - 1U].metric) { + if (metric == best[bestCnt - 1U].metric) { + for (uint32_t retained = 0U; retained < bestCnt; retained++) { + if (best[retained].metric == metric) + best[retained].truncated = true; + } + } + continue; + } + + // find the insertion point, shifting worse candidates right and dropping the last if full + uint32_t pos = (bestCnt < maxPaths) ? bestCnt++ : bestCnt - 1U; + while (pos > 0U && best[pos - 1U].metric > metric) { + best[pos] = best[pos - 1U]; + pos--; + } + + best[pos] = { metric, (uint8_t)state, (uint8_t)rank, current[state][rank].truncated }; + } } - if (pos > bestPos) { - bestPos = pos; - bestVal = i; - } + traceCnt[i][next] = (uint8_t)bestCnt; } - points[failPos] = bestVal; - failPos = bestPos; + // copy the retained survivors into the current path lists for the next trellis step + for (uint32_t state = 0U; state < TRELLIS_34_STATES; state++) { + currentCnt[state] = traceCnt[i][state]; + for (uint32_t rank = 0U; rank < currentCnt[state]; rank++) + current[state][rank] = trace[i][state][rank]; + } } - return false; -} - -/* Helper to detect errors in Trellis coding. */ - -uint32_t Trellis::checkCode34(const uint8_t* points, uint8_t* tribits) const -{ - uint8_t state = 0U; - - for (uint32_t i = 0U; i < 49U; i++) { - tribits[i] = 9U; - - for (uint32_t j = 0U; j < 8U; j++) { - if (points[i] == ENCODE_TABLE_34[state * 8U + j]) { - tribits[i] = j; - break; - } + // backtrack each retained path from the final state to recover its tribits and metric + const uint32_t count = traceCnt[TRELLIS_STEPS - 1U][0U]; + const uint16_t bestMetric = trace[TRELLIS_STEPS - 1U][0U][0U].metric; + for (uint32_t path = 0U; path < count; path++) { + uint8_t tribits[TRELLIS_STEPS]; + uint8_t state = 0U; + uint8_t rank = (uint8_t)path; + + metrics[path] = trace[TRELLIS_STEPS - 1U][0U][path].metric; + if (metrics[path] == bestMetric && trace[TRELLIS_STEPS - 1U][0U][path].truncated) + truncated = true; + + // follow predecessor state and rank links backward, recording each tribit + for (int32_t i = (int32_t)TRELLIS_STEPS - 1; i >= 0; i--) { + const Survivor& survivor = trace[i][state][rank]; + tribits[i] = state; + state = survivor.prevState; + rank = survivor.prevRank; } - if (tribits[i] == 9U) - return i; - - state = tribits[i]; + tribitsToBits(tribits, payloads + path * TRELLIS_34_PAYLOAD_LENGTH_BYTES); } - if (tribits[48U] != 0U) - return 48U; - - return 999U; + return count; } +/* Runs a Viterbi decode of the 1/2 rate Trellis. */ -/* Helper to fix errors in Trellis coding. */ - -bool Trellis::fixCode12(uint8_t* points, uint32_t failPos, uint8_t* payload) const +bool Trellis::viterbi12(const int8_t* dibits, uint8_t* payload, uint32_t& metric) const { -#if DEBUG_TRELLIS - ::LogDebugEx(LOG_HOST, "Trellis::fixCode12()", "failPos = %u, val = %01X", failPos, points[failPos]); -#endif - for (unsigned j = 0U; j < 20U; j++) { - uint32_t bestPos = 0U; - uint32_t bestVal = 0U; - - for (uint32_t i = 0U; i < 16U; i++) { - points[failPos] = i; - - uint8_t dibits[49U]; - uint32_t pos = checkCode12(points, dibits); - if (pos == 999U) { -#if DEBUG_TRELLIS - ::LogDebugEx(LOG_HOST, "Trellis::fixCode12()", "fixed, failPos = %u, pos = %u, val = %01X", failPos, bestPos, bestVal); -#endif - dibitsToBits(dibits, payload); - return true; - } + assert(dibits != nullptr); + assert(payload != nullptr); - if (pos > bestPos) { - bestPos = pos; - bestVal = i; + // keep the best path to each state at every step for traceback + struct Survivor { + uint16_t metric; + uint8_t prevState; + }; + + Survivor trace[TRELLIS_STEPS][TRELLIS_12_STATES]; + uint16_t currentMetric[TRELLIS_12_STATES] = { 0U, UINT16_MAX, UINT16_MAX, UINT16_MAX }; + + // start in state zero and update the best path metric for each destination state at every step + for (uint32_t i = 0U; i < TRELLIS_STEPS; i++) { + const int8_t rx0 = dibits[i * 2U]; + const int8_t rx1 = dibits[i * 2U + 1U]; + + // for each destination state, select the predecessor with the lowest accumulated path metric + for (uint32_t next = 0U; next < TRELLIS_12_STATES; next++) { + uint16_t bestMetric = UINT16_MAX; + uint8_t bestState = 0U; + + // skip unreachable states and compute the branch metric for each reachable predecessor + for (uint32_t state = 0U; state < TRELLIS_12_STATES; state++) { + if (currentMetric[state] == UINT16_MAX) + continue; + + const uint8_t point = ENCODE_TABLE_12[state * TRELLIS_12_STATES + next]; + const uint32_t branch = (uint32_t)((::abs(POINT_DIBITS[point][0U] - rx0) + + ::abs(POINT_DIBITS[point][1U] - rx1)) / 2); + const uint16_t candidate = (uint16_t)(currentMetric[state] + branch); + if (candidate < bestMetric) { + bestMetric = candidate; + bestState = (uint8_t)state; + } } + + trace[i][next] = { bestMetric, bestState }; } - points[failPos] = bestVal; - failPos = bestPos; + // carry the best metric for each state forward to the next trellis step + for (uint32_t state = 0U; state < TRELLIS_12_STATES; state++) + currentMetric[state] = trace[i][state].metric; } - return false; -} - -/* Helper to detect errors in Trellis coding. */ - -uint32_t Trellis::checkCode12(const uint8_t* points, uint8_t* dibits) const -{ + uint8_t decoded[TRELLIS_STEPS]; uint8_t state = 0U; + metric = trace[TRELLIS_STEPS - 1U][state].metric; + if (metric == UINT16_MAX) + return false; - for (uint32_t i = 0U; i < 49U; i++) { - dibits[i] = 5U; - - for (uint32_t j = 0U; j < 4U; j++) { - if (points[i] == ENCODE_TABLE_12[state * 4U + j]) { - dibits[i] = j; - break; - } - } - - if (dibits[i] == 5U) - return i; - - state = dibits[i]; + // trace back from the final state to recover the decoded dibits + for (int32_t i = (int32_t)TRELLIS_STEPS - 1; i >= 0; i--) { + decoded[i] = state; + state = trace[i][state].prevState; } - if (dibits[48U] != 0U) - return 48U; - - return 999U; + dibitsToBits(decoded, payload); + return true; } diff --git a/src/common/edac/Trellis.h b/src/common/edac/Trellis.h index c74762c8..138d4eed 100644 --- a/src/common/edac/Trellis.h +++ b/src/common/edac/Trellis.h @@ -5,7 +5,7 @@ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright (C) 2016,2018 Jonathan Naylor, G4KLX - * Copyright (C) 2023-2024 Bryan Biedenkapp, N2PLL + * Copyright (C) 2023-2026 Bryan Biedenkapp, N2PLL * */ /** @@ -21,6 +21,20 @@ namespace edac { + // --------------------------------------------------------------------------- + // Constants + // --------------------------------------------------------------------------- + + /** + * @addtogroup edac + * @{ + */ + + const uint32_t TRELLIS_34_MAX_LIST_PATHS = 8U; // Maximum number of candidate paths returned by the 3/4 rate Trellis list decoder. + const uint32_t TRELLIS_34_PAYLOAD_LENGTH_BYTES = 18U; // Length in bytes of one decoded 3/4 rate Trellis payload. + + /** @} */ + // --------------------------------------------------------------------------- // Class Declaration // --------------------------------------------------------------------------- @@ -42,12 +56,25 @@ namespace edac /** * @brief Decodes 3/4 rate Trellis. + * + * This performs a maximum-likelihood decode and always produces the closest retained + * codeword. The caller must use a CRC or another integrity check when one is available. * @param[in] data Trellis symbol bytes. - * @param[out] payload Output bytes. + * @param[out] payload Output buffer of TRELLIS_34_PAYLOAD_LENGTH_BYTES bytes. * @param skipSymbols Flag indicating symbols should be skipped (this is used for DMR). - * @returns bool True, if Trellis decoded, otherwise false. + * @returns bool True if a closest codeword was produced. */ bool decode34(const uint8_t* data, uint8_t* payload, bool skipSymbols = false); + /** + * @brief Decodes 3/4 rate Trellis and returns up to maxPaths candidates tied for the best metric. + * @param[in] data Trellis symbol bytes. + * @param[out] payloads Output buffer of maxPaths * TRELLIS_34_PAYLOAD_LENGTH_BYTES bytes. + * @param maxPaths Maximum number of candidates to return, from 1 through TRELLIS_34_MAX_LIST_PATHS. + * @param[out] truncated True if additional equally likely candidates were omitted; otherwise false. + * @param skipSymbols Flag indicating symbols should be skipped (this is used for DMR). + * @returns uint32_t Number of candidates written, or zero when maxPaths is invalid. + */ + uint32_t decode34List(const uint8_t* data, uint8_t* payloads, uint32_t maxPaths, bool& truncated, bool skipSymbols = false); /** * @brief Encodes 3/4 rate Trellis. * @param[in] payload Input bytes. @@ -58,9 +85,11 @@ namespace edac /** * @brief Decodes 1/2 rate Trellis. + * + * This performs a maximum-likelihood decode and always produces the closest codeword. * @param[in] data Trellis symbol bytes. * @param[out] payload Output bytes. - * @returns bool True, if Trellis decoded, otherwise false. + * @returns bool True if a closest codeword was produced. */ bool decode12(const uint8_t* data, uint8_t* payload); /** @@ -123,36 +152,24 @@ namespace edac void dibitsToBits(const uint8_t* dibits, uint8_t* payload) const; /** - * @brief Helper to fix errors in Trellis coding. - * @param points Trellis constellation points. - * @param failPos Failure position. - * @param payload Byte payload. - * @returns bool True, if error corrected, otherwise false. - */ - bool fixCode34(uint8_t* points, uint32_t failPos, uint8_t* payload) const; - /** - * @brief Helper to detect errors in Trellis coding. - * @param points Trellis constellation points. - * @param tribits Tribits. - * @returns uint32_t Position. - */ - uint32_t checkCode34(const uint8_t* points, uint8_t* tribits) const; - - /** - * @brief Helper to fix errors in Trellis coding. - * @param points Trelli constellation points. - * @param failPos Failure position. - * @param payload Byte payload. - * @returns bool True, if error corrected, otherwise false. + * @brief Runs a bounded list Viterbi decode of the 3/4 rate Trellis. + * @param[in] dibits Deinterleaved received dibits. + * @param[out] payloads Output buffer for maxPaths decoded payloads. + * @param[out] metrics Path metric for each returned candidate. + * @param maxPaths Number of survivors retained per state. + * @param[out] truncated True if an equal-metric survivor was discarded. + * @returns uint32_t Number of candidates written. */ - bool fixCode12(uint8_t* points, uint32_t failPos, uint8_t* payload) const; + uint32_t viterbi34(const int8_t* dibits, uint8_t* payloads, uint32_t* metrics, uint32_t maxPaths, + bool& truncated) const; /** - * @brief Helper to detect errors in Trellis coding. - * @param points Trelli constellation points. - * @param dibits Dibits. - * @returns uint32_t Position. + * @brief Runs a Viterbi decode of the 1/2 rate Trellis. + * @param[in] dibits Deinterleaved received dibits. + * @param[out] payload Decoded 12-byte payload. + * @param[out] metric Best path metric. + * @returns bool True if a path terminating in the flushing state was decoded. */ - uint32_t checkCode12(const uint8_t* points, uint8_t* dibits) const; + bool viterbi12(const int8_t* dibits, uint8_t* payload, uint32_t& metric) const; }; } // namespace edac diff --git a/src/common/p25/data/DataBlock.cpp b/src/common/p25/data/DataBlock.cpp index 1f787165..2ac119eb 100644 --- a/src/common/p25/data/DataBlock.cpp +++ b/src/common/p25/data/DataBlock.cpp @@ -4,7 +4,7 @@ * GPLv2 Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * Copyright (C) 2018-2025 Bryan Biedenkapp, N2PLL + * Copyright (C) 2018-2026 Bryan Biedenkapp, N2PLL * */ #include "Defines.h" @@ -75,48 +75,63 @@ bool DataBlock::decode(const uint8_t* data, const DataHeader& header, bool noTre if (m_fmt == PDUFormatType::CONFIRMED) { // decode 3/4 rate Trellis try { + uint8_t candidates[edac::TRELLIS_34_MAX_LIST_PATHS * P25_PDU_CONFIRMED_LENGTH_BYTES]; + ::memset(candidates, 0x00U, sizeof(candidates)); + + uint32_t candidateCnt = 1U; + bool truncated = false; if (!noTrellis) { - bool valid = m_trellis.decode34(data, buffer); - if (!valid) { + candidateCnt = m_trellis.decode34List(data, candidates, edac::TRELLIS_34_MAX_LIST_PATHS, truncated); + if (candidateCnt == 0U) { LogError(LOG_P25, "DataBlock::decode(), failed to decode Trellis 3/4 rate coding"); return false; } } else { - ::memcpy(buffer, data, P25_PDU_CONFIRMED_LENGTH_BYTES); + ::memcpy(candidates, data, P25_PDU_CONFIRMED_LENGTH_BYTES); + } + + uint16_t crc = 0U; + uint16_t calculated = 0U; + uint32_t selected = 0U; + bool valid = false; + for (uint32_t i = 0U; i < candidateCnt; i++) { + uint16_t candidateCRC = 0U; + uint16_t candidateCalc = 0U; + valid = checkConfirmedCRC9(candidates + i * P25_PDU_CONFIRMED_LENGTH_BYTES, candidateCRC, candidateCalc); + + if (i == 0U || valid) { + selected = i; + crc = candidateCRC; + calculated = candidateCalc; + } + + if (valid) + break; } + ::memcpy(buffer, candidates + selected * P25_PDU_CONFIRMED_LENGTH_BYTES, + P25_PDU_CONFIRMED_LENGTH_BYTES); + #if DEBUG_P25_PDU_DATA Utils::dump(1U, "P25, DataBlock::decode(), Confirmed PDU Data Block", buffer, P25_PDU_CONFIRMED_LENGTH_BYTES); #endif + if (!valid) { + if (truncated) { + LogWarning(LOG_P25, "PDU, fmt = $%02X, Trellis 3/4 rate candidate list truncated before CRC-9 match", m_fmt); + } + LogError(LOG_P25, "PDU, fmt = $%02X, invalid crc = $%04X != $%04X (computed)", m_fmt, crc, calculated); + return false; + } + m_serialNo = (buffer[0] & 0xFEU) >> 1; // Confirmed Data Serial No. - uint16_t crc = ((buffer[0] & 0x01U) << 8) + buffer[1]; // CRC-9 Check Sum ::memset(m_data, 0x00U, P25_PDU_CONFIRMED_DATA_LENGTH_BYTES); ::memcpy(m_data, buffer + 2U, P25_PDU_CONFIRMED_DATA_LENGTH_BYTES); // Payload Data - uint8_t crcBuffer[P25_PDU_CONFIRMED_LENGTH_BYTES]; - ::memset(crcBuffer, 0x00U, P25_PDU_CONFIRMED_LENGTH_BYTES); - - // generate CRC buffer - for (uint32_t i = 0U; i < 144U; i++) { - bool b = READ_BIT(buffer, i); - if (i < 7U) { - WRITE_BIT(crcBuffer, i, b); - } else if (i > 15U) { - WRITE_BIT(crcBuffer, i - 9U, b); - } - } - -#if DEBUG_P25_PDU_DATA - Utils::dump(2U, "P25, CRC Bit Buffer", crcBuffer, P25_PDU_CONFIRMED_LENGTH_BYTES); -#endif - - // compute CRC-9 for the packet - uint16_t calculated = edac::CRC::createCRC9(crcBuffer, 135U); - if ((crc ^ calculated) != 0) { - LogError(LOG_P25, "PDU, fmt = $%02X, invalid crc = $%04X != $%04X (computed)", m_fmt, crc, calculated); - return false; + if (selected != 0U) { + LogDebug(LOG_P25, "PDU, fmt = $%02X, Trellis 3/4 rate tie resolved by CRC-9, candidate %u of %u", + m_fmt, selected + 1U, candidateCnt); } #if DEBUG_P25_PDU_DATA @@ -303,3 +318,27 @@ void DataBlock::copy(const DataBlock& data) ::memcpy(m_data, data.m_data, P25_PDU_CONFIRMED_DATA_LENGTH_BYTES); } } + +/* Checks the CRC-9 of a decoded confirmed data block. */ + +bool DataBlock::checkConfirmedCRC9(const uint8_t* buffer, uint16_t& crc, uint16_t& calculated) +{ + assert(buffer != nullptr); + + crc = ((buffer[0] & 0x01U) << 8) + buffer[1]; + + uint8_t crcBuffer[P25_PDU_CONFIRMED_LENGTH_BYTES]; + ::memset(crcBuffer, 0x00U, sizeof(crcBuffer)); + + // append the seven CRC bits from the first byte to the CRC input + for (uint32_t i = 0U; i < 144U; i++) { + const bool bit = READ_BIT(buffer, i) != 0U; + if (i < 7U) + WRITE_BIT(crcBuffer, i, bit); + else if (i > 15U) + WRITE_BIT(crcBuffer, i - 9U, bit); + } + + calculated = edac::CRC::createCRC9(crcBuffer, 135U); + return crc == calculated; +} diff --git a/src/common/p25/data/DataBlock.h b/src/common/p25/data/DataBlock.h index a6ae99af..28866b18 100644 --- a/src/common/p25/data/DataBlock.h +++ b/src/common/p25/data/DataBlock.h @@ -4,7 +4,7 @@ * GPLv2 Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * Copyright (C) 2018-2025 Bryan Biedenkapp, N2PLL + * Copyright (C) 2018-2026 Bryan Biedenkapp, N2PLL * */ /** @@ -116,6 +116,14 @@ namespace p25 * @brief Internal helper to copy the class. */ void copy(const DataBlock& data); + /** + * @brief Checks the CRC-9 of a decoded confirmed data block. + * @param[in] buffer Decoded confirmed data block. + * @param[out] crc CRC-9 carried in the block. + * @param[out] calculated CRC-9 computed over the block. + * @returns bool True if the carried and computed CRC-9 values match. + */ + static bool checkConfirmedCRC9(const uint8_t* buffer, uint16_t& crc, uint16_t& calculated); }; } // namespace data } // namespace p25 diff --git a/tests/dmr/DataBlock_Tests.cpp b/tests/dmr/DataBlock_Tests.cpp index d587a535..ee289c28 100644 --- a/tests/dmr/DataBlock_Tests.cpp +++ b/tests/dmr/DataBlock_Tests.cpp @@ -4,13 +4,14 @@ * GPLv2 Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * Copyright (C) 2025 Bryan Biedenkapp, N2PLL + * Copyright (C) 2025,2026 Bryan Biedenkapp, N2PLL * */ #include #include #include +#include #include "common/Defines.h" #include "common/dmr/DMRDefines.h" @@ -86,6 +87,29 @@ namespace { ::memcpy(frame + 21U, block + 12U, 12U); } } + + /** Shifts one rate-3/4 symbol by one sliced 4FSK level in a DMR burst. */ + void shiftRate34Symbol(uint8_t* frame, uint32_t symbol, bool up) + { + uint32_t firstBit = symbol * 2U; + uint32_t secondBit = firstBit + 1U; + if (firstBit >= 98U) + firstBit += 68U; + if (secondBit >= 98U) + secondBit += 68U; + + const bool b1 = READ_BIT(frame, firstBit) != 0U; + const bool b2 = READ_BIT(frame, secondBit) != 0U; + int32_t level = (!b1 && b2) ? 3 : (!b1 && !b2) ? 1 : (b1 && !b2) ? -1 : -3; + level += up ? 2 : -2; + if (level > 3) + level = 1; + if (level < -3) + level = -1; + + WRITE_BIT(frame, firstBit, level < 0); + WRITE_BIT(frame, secondBit, level == 3 || level == -3); + } } TEST_CASE("DMR confirmed data blocks preserve DBSN, payload, and masked CRC-9", "[dmr][datablock]") @@ -167,6 +191,58 @@ TEST_CASE("DMR confirmed data blocks reject CRC-9 failures", "[dmr][datablock]") } } +TEST_CASE("DMR confirmed rate-3/4 resolves tied Trellis candidates by CRC-9", "[dmr][datablock][trellis]") +{ + std::array payload{}; + for (uint32_t i = 0U; i < DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES; i++) + payload[i] = (uint8_t)(i * 23U + 5U); + + DataBlock encoded; + encoded.setFormat(DPF::CONFIRMED_DATA); + encoded.setDataType(DataType::RATE_34_DATA); + encoded.setSerialNo(0x2AU); + encoded.setData(payload.data()); + + std::array cleanFrame{}; + encoded.encode(cleanFrame.data()); + std::array expectedRaw{}; + extractBlock(DataType::RATE_34_DATA, cleanFrame.data(), expectedRaw.data()); + + std::mt19937 rng(0x34D4U); + std::array tiedFrame{}; + bool found = false; + for (uint32_t trial = 0U; trial < 10000U && !found; trial++) { + tiedFrame = cleanFrame; + for (uint32_t error = 0U; error < 5U; error++) + shiftRate34Symbol(tiedFrame.data(), rng() % 98U, (rng() & 1U) != 0U); + + uint8_t candidates[edac::TRELLIS_34_MAX_LIST_PATHS * edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES]; + bool truncated = false; + const uint32_t count = edac::Trellis().decode34List(tiedFrame.data(), candidates, + edac::TRELLIS_34_MAX_LIST_PATHS, truncated, true); + for (uint32_t candidate = 1U; candidate < count; candidate++) { + if (::memcmp(candidates + candidate * edac::TRELLIS_34_PAYLOAD_LENGTH_BYTES, + expectedRaw.data(), expectedRaw.size()) == 0) { + found = true; + break; + } + } + } + + REQUIRE(found); + + DataHeader header; + header.setDPF(DPF::CONFIRMED_DATA); + DataBlock decoded; + decoded.setDataType(DataType::RATE_34_DATA); + REQUIRE(decoded.decode(tiedFrame.data(), header)); + REQUIRE(decoded.getSerialNo() == 0x2AU); + + std::array output{}; + REQUIRE(decoded.getData(output.data()) == DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES); + REQUIRE(::memcmp(output.data(), payload.data(), DMR_PDU_CONFIRMED_TQ_DATA_LENGTH_BYTES) == 0); +} + TEST_CASE("DMR unconfirmed Rate 1 maps all 24 payload octets around the burst centre", "[dmr][datablock]") { std::array payload{}; diff --git a/tests/edac/Trellis_Tests.cpp b/tests/edac/Trellis_Tests.cpp index d109a829..57462d4a 100644 --- a/tests/edac/Trellis_Tests.cpp +++ b/tests/edac/Trellis_Tests.cpp @@ -13,11 +13,41 @@ #include #include +#include #include "common/edac/Trellis.h" using namespace edac; +/** + * @brief Shifts one dibit by one sliced 4FSK level, optionally skipping the DMR sync and embedded signaling fields. + * @param data The burst data to modify. + * @param symbol The dibit index to shift. + * @param up Whether to shift the sliced level upward. + * @param skipSymbols Whether to skip the DMR sync and embedded signaling fields. + */ +static void shiftSymbol(uint8_t* data, uint32_t symbol, bool up, bool skipSymbols = false) +{ + uint32_t firstBit = symbol * 2U; + uint32_t secondBit = firstBit + 1U; + if (skipSymbols && firstBit >= 98U) + firstBit += 68U; + if (skipSymbols && secondBit >= 98U) + secondBit += 68U; + + const bool b1 = READ_BIT(data, firstBit) != 0U; + const bool b2 = READ_BIT(data, secondBit) != 0U; + int32_t level = (!b1 && b2) ? 3 : (!b1 && !b2) ? 1 : (b1 && !b2) ? -1 : -3; + level += up ? 2 : -2; + if (level > 3) + level = 1; + if (level < -3) + level = -1; + + WRITE_BIT(data, firstBit, level < 0); + WRITE_BIT(data, secondBit, level == 3 || level == -3); +} + TEST_CASE("Trellis 3/4 rate preserves all-zero payload", "[edac][trellis]") { uint8_t payload[18U]; ::memset(payload, 0x00U, sizeof(payload)); @@ -225,22 +255,15 @@ TEST_CASE("Trellis 1/2 rate corrects errors", "[edac][trellis]") { uint8_t encoded[25U]; ::memcpy(encoded, data, 25U); - // Test errors at various positions - const size_t errorPositions[] = {0, 8, 16, 24}; + const uint32_t errorSymbols[] = { 0U, 24U, 49U, 73U, 97U }; - for (auto pos : errorPositions) { + for (uint32_t symbol : errorSymbols) { ::memcpy(data, encoded, 25U); - - // Introduce errors - 1/2 rate has better error correction - data[pos] ^= 0x07U; + shiftSymbol(data, symbol, (symbol & 1U) != 0U); uint8_t decoded[12U]; - bool result = trellis.decode12(data, decoded); - - // 1/2 rate Trellis has stronger error correction - if (result) { - REQUIRE(::memcmp(decoded, original, 12U) == 0); - } + REQUIRE(trellis.decode12(data, decoded)); + REQUIRE(::memcmp(decoded, original, 12U) == 0); } } @@ -287,3 +310,146 @@ TEST_CASE("Trellis 3/4 rate handles random payloads", "[edac][trellis]") { REQUIRE(::memcmp(decoded, payload, 18U) == 0); } } + +TEST_CASE("Trellis Viterbi decoders correct every single-level symbol error", "[edac][trellis]") { + Trellis trellis; + + uint8_t payload34[18U]; + for (uint32_t i = 0U; i < sizeof(payload34); i++) + payload34[i] = (uint8_t)(i * 29U + 7U); + + uint8_t encoded34[25U] = { 0U }; + trellis.encode34(payload34, encoded34); + + uint8_t payload12[12U]; + for (uint32_t i = 0U; i < sizeof(payload12); i++) + payload12[i] = (uint8_t)(i * 31U + 11U); + + uint8_t encoded12[25U] = { 0U }; + trellis.encode12(payload12, encoded12); + + for (uint32_t symbol = 0U; symbol < 98U; symbol++) { + for (uint32_t direction = 0U; direction < 2U; direction++) { + uint8_t corrupted34[25U]; + ::memcpy(corrupted34, encoded34, sizeof(corrupted34)); + shiftSymbol(corrupted34, symbol, direction == 0U); + + uint8_t decoded34[18U] = { 0U }; + REQUIRE(trellis.decode34(corrupted34, decoded34)); + REQUIRE(::memcmp(decoded34, payload34, sizeof(payload34)) == 0); + + uint8_t corrupted12[25U]; + ::memcpy(corrupted12, encoded12, sizeof(corrupted12)); + shiftSymbol(corrupted12, symbol, direction == 0U); + + uint8_t decoded12[12U] = { 0U }; + REQUIRE(trellis.decode12(corrupted12, decoded12)); + REQUIRE(::memcmp(decoded12, payload12, sizeof(payload12)) == 0); + } + } +} + +TEST_CASE("Trellis 3/4 rate supports DMR symbol skipping with corruption", "[edac][trellis]") { + uint8_t payload[18U]; + for (uint32_t i = 0U; i < sizeof(payload); i++) + payload[i] = (uint8_t)(0xA5U ^ (i * 13U)); + + uint8_t encoded[33U] = { 0U }; + Trellis trellis; + trellis.encode34(payload, encoded, true); + + for (uint32_t symbol = 0U; symbol < 98U; symbol++) { + uint8_t corrupted[33U]; + ::memcpy(corrupted, encoded, sizeof(corrupted)); + shiftSymbol(corrupted, symbol, (symbol & 1U) != 0U, true); + + uint8_t decoded[18U] = { 0U }; + REQUIRE(trellis.decode34(corrupted, decoded, true)); + REQUIRE(::memcmp(decoded, payload, sizeof(payload)) == 0); + } +} + +TEST_CASE("Trellis Viterbi decoders handle deterministic scattered errors", "[edac][trellis]") { + std::mt19937 rng(0x251234U); + Trellis trellis; + + uint32_t corrected34 = 0U; + uint32_t corrected12 = 0U; + const uint32_t trials = 500U; + for (uint32_t trial = 0U; trial < trials; trial++) { + uint8_t payload34[18U]; + uint8_t payload12[12U]; + for (uint32_t i = 0U; i < sizeof(payload34); i++) + payload34[i] = (uint8_t)(rng() & 0xFFU); + for (uint32_t i = 0U; i < sizeof(payload12); i++) + payload12[i] = (uint8_t)(rng() & 0xFFU); + + uint8_t encoded34[25U] = { 0U }; + uint8_t encoded12[25U] = { 0U }; + trellis.encode34(payload34, encoded34); + trellis.encode12(payload12, encoded12); + + for (uint32_t error = 0U; error < 2U; error++) { + shiftSymbol(encoded34, rng() % 98U, (rng() & 1U) != 0U); + shiftSymbol(encoded12, rng() % 98U, (rng() & 1U) != 0U); + } + + uint8_t decoded34[18U] = { 0U }; + uint8_t decoded12[12U] = { 0U }; + REQUIRE(trellis.decode34(encoded34, decoded34)); + REQUIRE(trellis.decode12(encoded12, decoded12)); + if (::memcmp(decoded34, payload34, sizeof(payload34)) == 0) + corrected34++; + if (::memcmp(decoded12, payload12, sizeof(payload12)) == 0) + corrected12++; + } + + INFO("rate 3/4 corrected " << corrected34 << " of " << trials); + INFO("rate 1/2 corrected " << corrected12 << " of " << trials); + REQUIRE(corrected34 >= (trials * 90U) / 100U); + REQUIRE(corrected12 >= (trials * 95U) / 100U); +} + +TEST_CASE("Trellis 3/4 rate bounded list validates limits and ordering", "[edac][trellis]") { + uint8_t payload[18U]; + for (uint32_t i = 0U; i < sizeof(payload); i++) + payload[i] = (uint8_t)(i * 17U + 3U); + + uint8_t encoded[25U] = { 0U }; + Trellis trellis; + trellis.encode34(payload, encoded); + + uint8_t candidates[TRELLIS_34_MAX_LIST_PATHS * TRELLIS_34_PAYLOAD_LENGTH_BYTES]; + bool truncated = true; + REQUIRE(trellis.decode34List(encoded, candidates, TRELLIS_34_MAX_LIST_PATHS, truncated) == 1U); + REQUIRE_FALSE(truncated); + REQUIRE(::memcmp(candidates, payload, sizeof(payload)) == 0); + + truncated = true; + REQUIRE(trellis.decode34List(encoded, candidates, 0U, truncated) == 0U); + REQUIRE_FALSE(truncated); + truncated = true; + REQUIRE(trellis.decode34List(encoded, candidates, TRELLIS_34_MAX_LIST_PATHS + 1U, truncated) == 0U); + REQUIRE_FALSE(truncated); + + uint8_t single[18U] = { 0U }; + REQUIRE(trellis.decode34(encoded, single)); + truncated = false; + REQUIRE(trellis.decode34List(encoded, candidates, 1U, truncated) == 1U); + REQUIRE(::memcmp(candidates, single, sizeof(single)) == 0); + + bool foundTruncation = false; + for (uint32_t first = 0U; first < 98U && !foundTruncation; first++) { + for (uint32_t second = first + 1U; second < 98U && !foundTruncation; second++) { + uint8_t corrupted[25U]; + ::memcpy(corrupted, encoded, sizeof(corrupted)); + shiftSymbol(corrupted, first, false); + shiftSymbol(corrupted, second, true); + + truncated = false; + REQUIRE(trellis.decode34List(corrupted, candidates, 1U, truncated) == 1U); + foundTruncation = truncated; + } + } + REQUIRE(foundTruncation); +} diff --git a/tests/p25/PDU_Confirmed_TrellisTie_Test.cpp b/tests/p25/PDU_Confirmed_TrellisTie_Test.cpp new file mode 100644 index 00000000..83ae817f --- /dev/null +++ b/tests/p25/PDU_Confirmed_TrellisTie_Test.cpp @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Digital Voice Modem - Test Suite + * GPLv2 Open Source. Use is subject to license terms. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright (C) 2026 Bryan Biedenkapp, N2PLL + * + */ +#include "host/Defines.h" +#include "common/Log.h" +#include "common/edac/CRC.h" +#include "common/p25/P25Defines.h" +#include "common/p25/data/DataBlock.h" +#include "common/p25/data/DataHeader.h" + +using namespace p25; +using namespace p25::defines; +using namespace p25::data; + +#include +#include + +/** + * @brief Builds a confirmed user-data PDU header for decoding test blocks. + * @return A confirmed user-data PDU header. + */ +static DataHeader confirmedHeader() +{ + DataHeader header; + header.setFormat(PDUFormatType::CONFIRMED); + header.setSAP(PDUSAP::USER_DATA); + return header; +} + +TEST_CASE("P25 confirmed PDU resolves an over-the-air Trellis tie", "[p25][pdu][trellis]") { + g_logDisplayLevel = 1U; + + const uint8_t raw[4U][P25_PDU_FEC_LENGTH_BYTES] = { + { 0x2C, 0xE3, 0x23, 0xE2, 0xEE, 0x58, 0xE2, 0x92, 0xF2, 0x93, 0x2A, 0xB4, 0xA2, 0x72, 0xF2, 0x32, 0x22, 0x7F, 0x67, 0x57, 0x2E, 0x2F, 0x2D, 0xC7, 0xF0 }, + { 0x2C, 0x73, 0xF0, 0xE4, 0xEB, 0x38, 0xB2, 0xE6, 0x72, 0x53, 0x72, 0x6E, 0x6B, 0x25, 0x12, 0xE7, 0x22, 0x26, 0x01, 0xD7, 0x31, 0xC2, 0x0D, 0x5A, 0xD0 }, + { 0x2B, 0xA9, 0x05, 0x37, 0xE2, 0xF3, 0x2D, 0x7D, 0xCB, 0x61, 0x27, 0x23, 0xF8, 0xA1, 0x80, 0x81, 0xD3, 0x7E, 0x25, 0x34, 0x34, 0xAF, 0x1A, 0xC4, 0x20 }, + { 0x26, 0x22, 0x22, 0x22, 0x22, 0xD2, 0xAD, 0xF2, 0x22, 0x22, 0x22, 0xEB, 0xE2, 0xF2, 0x22, 0x22, 0x22, 0x56, 0x9B, 0x22, 0x22, 0x22, 0x22, 0xE7, 0xF0 } }; + + const uint8_t expectedBlock1[P25_PDU_CONFIRMED_DATA_LENGTH_BYTES] = { + 0x01, 0x48, 0xAC, 0x1C, 0x00, 0x37, 0xE3, 0x58, 0x0F, 0xA1, 0x00, 0x19, 0xA5, 0x09, 0x0B, 0x0F }; + + uint8_t userData[4U * P25_PDU_CONFIRMED_DATA_LENGTH_BYTES] = { 0U }; + const DataHeader header = confirmedHeader(); + for (uint32_t i = 0U; i < 4U; i++) { + DataBlock block; + INFO("block " << i); + REQUIRE(block.decode(raw[i], header)); + REQUIRE(block.getSerialNo() == i); + block.getData(userData + i * P25_PDU_CONFIRMED_DATA_LENGTH_BYTES); + } + + REQUIRE(::memcmp(userData + P25_PDU_CONFIRMED_DATA_LENGTH_BYTES, expectedBlock1, + P25_PDU_CONFIRMED_DATA_LENGTH_BYTES) == 0); + REQUIRE(edac::CRC::checkCRC32(userData, sizeof(userData))); +} + +TEST_CASE("P25 confirmed PDU rejects corruption without a CRC-valid best candidate", "[p25][pdu][trellis]") { + uint8_t payload[P25_PDU_CONFIRMED_DATA_LENGTH_BYTES] = { 0U }; + DataBlock encodedBlock; + encodedBlock.setFormat(PDUFormatType::CONFIRMED); + encodedBlock.setSerialNo(3U); + encodedBlock.setData(payload); + + uint8_t encoded[P25_PDU_FEC_LENGTH_BYTES] = { 0U }; + encodedBlock.encode(encoded); + for (uint32_t i = 0U; i < sizeof(encoded); i++) + encoded[i] ^= (uint8_t)(0x5AU + i * 17U); + + DataBlock decodedBlock; + REQUIRE_FALSE(decodedBlock.decode(encoded, confirmedHeader())); +}