32. Tags, Messages and Bursts in GNU Radio¶
PySDR’s SDR Frameworks chapter introduces the two things GNU Radio adds on top of streams of samples: stream tags, “small pieces of metadata attached to a specific sample, which travel through the flowgraph alongside the samples”, and messages, which “are asynchronous, not tied to any sample, and are used for control … or for passing around packets”. This chapter uses both to build the front end of a burst receiver. One block finds a known sync word and tags it, the way GNU Radio’s corr_est_cc does. A second block cuts each burst out of the stream, and GNU Radio’s tagged_stream_to_pdu turns each burst into a message.
The chapter follows one rule: a block’s output must depend only on its input stream, never on how the scheduler cuts that stream into work() calls. The scheduler chooses the call sizes from buffer space and thread timing, so a block that breaks the rule gives results that change from run to run on a live radio. Writing a GNU Radio Block in C++ showed that a filter with set_history() follows the rule without effort. A detector is harder, because a decision about one sample looks at its neighbours, and at a call boundary those neighbours are in another call.
The code is in code/include/cppsdr/burst.hpp (the detector, with no GNU Radio dependency), code/tests/test_burst.cpp, and in code/gnuradio_block/, the blocks sync_detect_cc and burst_gate_cc and the flowgraph test test_gr_bursts.cc. The test signal (code/tests/burst_scene.hpp) has 12 bursts. Each is a 64-sample sync word followed by a 192-sample payload, both band-limited like the signal in PySDR’s TDOA chapter. Each burst has a random fractional delay, carrier phase and gain (0.5 to 1.5), and the bursts sit in complex noise 10 dB below the burst power.
Where corr_est_cc Looks Outside Its Call¶
TDOA: Delays, Peaks and Positions found one place where corr_est_cc (gr-digital/lib/corr_est_cc_impl.cc, v3.10.12.0) depends on the call boundaries. When the correlation peak is the first output of a call, the sub-sample estimate reads d_corr_mag[i - 1] with i == 0. Its work() has more steps that look past the edges of the current call:
it climbs from the first sample above the threshold to the top of the peak, but stops at the last output of the call (
while ((i < (noutput_items - 1)) && ...)), and the next call then finds the same peak again;after a detection it skips
spssamples, a counter that starts again at zero in every call;amp_estis one over the largest input magnitude in the current call;the dynamic threshold (
THRESHOLD_DYNAMIC) is a multiple of the mean \(|c|^2\) over the current call.
The last one is the largest effect. Here is corr_est_cc with a dynamic threshold of 0.999 on the test signal, with the call size capped at multiples of the block’s output multiple (65 samples for a 64-sample word):
call size (samples) |
bursts tagged |
other tags |
|---|---|---|
65 |
0 of 12 |
1 |
130 |
10 of 12 |
1 |
195 |
12 of 12 |
2 |
650 |
11 of 12 |
0 |
1300 |
12 of 12 |
1 |
uncapped |
11 of 12 |
2 |
The eight call sizes the test tries give eight different sets of tags. With calls of 65 samples, a burst’s own correlation (its peak, its sidelobes and its payload) makes up most of the mean of the call it falls in, and that lifts the threshold above the peak. In this test the call sizes are reproducible because a vector_source writes its whole vector at once. With a live source, they follow the arrival of the samples.
The absolute threshold (THRESHOLD_ABSOLUTE) does not depend on the call, but it is a fraction of the word’s energy squared, not of the received energy. Strong bursts then cross it inside their payloads, 49 to 145 samples after the peak, while the weakest bursts stay below it. The test sweeps it from 0.10 to 0.80 in steps of 0.02, and no value tags all 12 bursts and nothing else: 0.30 finds all 12 plus 6 others, 0.50 finds 11 and nothing else.
Decisions With a Fixed Reach¶
The way out is to make the reach of every decision a fixed number of samples, and to hand the detector exactly that much context. cppsdr::burst::sync_detector decides that the word ending at sample \(n\) is present when two conditions hold:
the normalized correlation \(\rho^2(n) = |c(n)|^2 / (E_\text{word}\, E_x(n))\) reaches the threshold. \(E_x(n)\) is the energy of the received samples under the word. \(\rho^2\) is 1 for a perfect scaled copy of the word, whatever its gain, so a weak burst and a strong one pass the same threshold;
\(|c(n)|^2\) is the largest value within \(\pm G\) samples, the guard. Ties go to the earliest sample.
No counter or running mean carries over between calls. Each decision is a function of the \(L + 2G\) samples around it. The sub-sample offset comes from the parabola through \(|c|\) at the peak and its two neighbours, the three-point refiner with the smallest bias in TDOA: Delays, Peaks and Positions.
Two numbers follow from that reach. The tag belongs on the first sample of the word, but the peak is decided at its last sample plus \(G\). So the output is the input delayed by \(D = L - 1 + G\). The earliest sample a decision looks at is \(G\) before the word, so a call needs \(B = D + G\) samples before its first output:
std::size_t delay() const { return word_.size() - 1 + guard_; }
std::size_t look_behind() const { return delay() + guard_; } // GNU Radio's history() - 1
This is exactly what set_history() provides, so the GNU Radio block keeps no state of its own:
set_history(unsigned(det_.look_behind()) + 1);
declare_sample_delay(unsigned(det_.delay()));
...
int work(int noutput_items, ...) override
{
std::copy_n(in + (det_.look_behind() - det_.delay()), n, out); // the delayed output
det_.scan(std::span<const gr_complex>(in, n + det_.look_behind()), n, [&](auto const& d) {
const std::uint64_t at = nitems_written(0) + d.index;
add_item_tag(0, at, corr_start_, pmt::from_double(d.rho2), src_id_);
add_item_tag(0, at, time_est_, pmt::from_double(d.frac), src_id_);
...
});
return noutput_items;
}
The tags use corr_est_cc’s names (corr_start, time_est, phase_est, amp_est), so a flowgraph can swap one block for the other.
For the results to be bit-identical and not just close, every correlation value has to be the same float in every call. scan() computes each one as a dot product in a fixed order. The build does not use -ffast-math, so the compiler may not reorder the sums. An FFT correlator also works if its blocks are aligned to the stream rather than to the calls. That is why corr_est_cc sets its output multiple to the FFT filter’s block size.
test_burst.cpp checks the rule without GNU Radio. It models what a block with this history sees: the stream after \(B\) zeros, delivered in calls of given sizes. On the test signal, one call over the whole stream finds all 12 bursts and nothing else, with a sub-sample position error of 0.056 samples RMS (0.126 worst). Then:
two calls, split after each of the 5999 possible samples: all 5999 runs give bit-identical detections;
1000 random sequences of call sizes, 29 476 calls in all, 30 % of them 1 to 4 samples long: all bit-identical.
Tags That Travel With Their Samples¶
A block that delays its output also has to move the tags that arrive from upstream, or they end up on the wrong samples. declare_sample_delay(D) does that. GNU Radio’s buffer reader adds the declared delay to the offset of every tag it hands on (gnuradio-runtime/lib/buffer_reader.cc, t.offset += d_attr_delay). The flowgraph test puts a tag on input sample 500, as a source might mark a receive timestamp. It leaves the detector at offset 571 = 500 + 71, on the same sample. This is the behaviour PySDR describes: the tag “will come out of the far end of the chain still attached to the corresponding sample”.
Message Ports¶
The detector has two message ports. It publishes one PMT dictionary per detection on detections (offset, time_est, \(\rho^2\), phase), for a logger or a GUI that has no use for the samples themselves. It accepts a new threshold on threshold:
message_port_register_in(threshold_);
set_msg_handler(threshold_, [this](pmt::pmt_t const& m) {
if (pmt::is_number(m)) det_.set_threshold(float(pmt::to_double(m)));
});
The handler needs no lock. Writing a GNU Radio Block in C++’s Costas block had a setter called from another thread, which needs atomics. corr_est_cc locks a mutex in its setters and in work(). GNU Radio 3.10’s thread-per-block scheduler is different: it delivers queued messages in the block’s own thread, in the loop that calls work(), before each call (gnuradio-runtime/lib/tpb_thread_body.cc):
// handle any queued up messages
for (const auto& i : block->msg_queue) {
...
while ((msg = block->delete_head_nowait(i.first))) {
block->dispatch_msg(i.first, msg);
}
...
// run one iteration if we are a connected stream block
s = d_exec.run_one_iteration();
A new threshold therefore never takes effect in the middle of a call. The test queues the message 0.93 before the flowgraph starts, and only the 2 bursts with \(\rho^2 \geq 0.93\) come out.
A Block That Changes the Rate¶
burst_gate_cc passes 256 samples (word and payload) from each corr_start tag and drops everything between bursts. Its output is a tagged stream: each burst begins with a packet_len tag giving its length, which is what gr::pdu::tagged_stream_to_pdu needs to turn each burst into one PDU message.
A sync_block produces exactly as many samples as it consumes. The gate consumes everything and produces only the bursts, so it is a plain gr::block. It says separately how much it consumed and how much it produced:
void forecast(int noutput_items, gr_vector_int& ninput_items_required) override
{
ninput_items_required[0] = noutput_items; // at most one output per input
}
int general_work(int noutput_items, gr_vector_int& ninput_items, ...) override
{
...
while (i < nin && o < nout) {
if (left_ == 0) { // between bursts: jump to the next trigger
if (next == triggers_.end()) { i = nin; break; }
i = std::size_t(next->offset - r0);
++next;
left_ = length_;
add_item_tag(0, w0 + o, length_tag_, pmt::from_long(long(length_)));
... // and the trigger's own tags, moved to output w0 + o
}
const std::size_t k = std::min({left_, nin - i, nout - o});
std::copy_n(in + i, k, out + o);
i += k; o += k; left_ -= k;
}
consume_each(int(i));
return int(o);
}
The only state between calls is left_, the part of the current burst still to come, so a burst that spans calls continues where it stopped. Tags need care here. For a block whose output rate differs from its input rate, the scheduler places each propagated tag at the input offset times relative_rate() (propagate_tags in gnuradio-runtime/lib/block_executor.cc). That is right for a decimator, but meaningless for a gate whose rate depends on the signal. So the gate turns automatic propagation off (set_tag_propagation_policy(TPP_DONT)) and moves the trigger’s tags to the first sample of each burst itself.
The flowgraph test runs source, detector, gate, tagged_stream_to_pdu and two message_debug sinks, all in GNU Radio 3.10.12’s scheduler:
every detector tag equals the detector of
burst.hppcalled once on the whole stream, bit for bit, and there is onedetectionsmessage per detection;there are 12 PDUs, and each holds exactly the 256 input samples of its burst, with the burst’s
time_estin its metadata;with
work()capped at every size from 1 to 100 samples, and at 4096, all 101 runs give bit-identical tags, messages and PDUs.
Key Takeaways¶
A block’s output must depend only on its input stream, never on how the scheduler cuts it into calls. Test that directly: split the stream at every possible sample and cap the call size at 1, 2, 3, … samples.
Give every decision a fixed reach. A local maximum within \(\pm G\) samples replaces “climb to the top, then skip”, and a threshold on the normalized correlation \(\rho^2\) replaces a mean over the current call. The reach then sets the block’s delay and its
set_history().corr_est_cc’s dynamic threshold is a mean over the current call: on the test signal, eight call sizes gave eight different sets of tags, and calls of 65 samples tagged none of the 12 bursts. Its absolute threshold is relative to the word, not the received energy, and no value separated the weak bursts from the strong payloads.A block that delays its output must
declare_sample_delay(), or upstream tags end up on the wrong samples.Under the thread-per-block scheduler, message handlers run in the block’s own thread between
work()calls, so a message port is a lock-free way to change parameters.A rate-changing block is a
gr::blockwithforecast(),consume_each()and a return value that differ. Turn off automatic tag propagation and place the tags yourself.