]> sigrok.org Git - pulseview.git/blame_incremental - pv/data/decodesignal.cpp
Begin PD multisegment support
[pulseview.git] / pv / data / decodesignal.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2017 Soeren Apel <soeren@apelpie.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <limits>
21
22#include <QDebug>
23
24#include "logic.hpp"
25#include "logicsegment.hpp"
26#include "decodesignal.hpp"
27#include "signaldata.hpp"
28
29#include <pv/binding/decoder.hpp>
30#include <pv/data/decode/decoder.hpp>
31#include <pv/data/decode/row.hpp>
32#include <pv/globalsettings.hpp>
33#include <pv/session.hpp>
34
35using std::lock_guard;
36using std::make_pair;
37using std::make_shared;
38using std::min;
39using std::out_of_range;
40using std::shared_ptr;
41using std::unique_lock;
42using pv::data::decode::Annotation;
43using pv::data::decode::Decoder;
44using pv::data::decode::Row;
45
46namespace pv {
47namespace data {
48
49const double DecodeSignal::DecodeMargin = 1.0;
50const double DecodeSignal::DecodeThreshold = 0.2;
51const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
52
53
54DecodeSignal::DecodeSignal(pv::Session &session) :
55 SignalBase(nullptr, SignalBase::DecodeChannel),
56 session_(session),
57 srd_session_(nullptr),
58 logic_mux_data_invalid_(false),
59 start_time_(0),
60 samplerate_(0),
61 samples_decoded_(0),
62 frame_complete_(false)
63{
64 connect(&session_, SIGNAL(capture_state_changed(int)),
65 this, SLOT(on_capture_state_changed(int)));
66}
67
68DecodeSignal::~DecodeSignal()
69{
70 reset_decode();
71}
72
73const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
74{
75 return stack_;
76}
77
78void DecodeSignal::stack_decoder(const srd_decoder *decoder)
79{
80 assert(decoder);
81 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
82
83 stack_.push_back(dec);
84
85 // Set name if this decoder is the first in the list
86 if (stack_.size() == 1)
87 set_name(QString::fromUtf8(decoder->name));
88
89 // Include the newly created decode channels in the channel lists
90 update_channel_list();
91
92 auto_assign_signals(dec);
93 commit_decoder_channels();
94 begin_decode();
95}
96
97void DecodeSignal::remove_decoder(int index)
98{
99 assert(index >= 0);
100 assert(index < (int)stack_.size());
101
102 // Find the decoder in the stack
103 auto iter = stack_.begin();
104 for (int i = 0; i < index; i++, iter++)
105 assert(iter != stack_.end());
106
107 // Delete the element
108 stack_.erase(iter);
109
110 // Update channels and decoded data
111 update_channel_list();
112 begin_decode();
113}
114
115bool DecodeSignal::toggle_decoder_visibility(int index)
116{
117 auto iter = stack_.cbegin();
118 for (int i = 0; i < index; i++, iter++)
119 assert(iter != stack_.end());
120
121 shared_ptr<Decoder> dec = *iter;
122
123 // Toggle decoder visibility
124 bool state = false;
125 if (dec) {
126 state = !dec->shown();
127 dec->show(state);
128 }
129
130 return state;
131}
132
133void DecodeSignal::reset_decode()
134{
135 if (decode_thread_.joinable()) {
136 decode_interrupt_ = true;
137 decode_input_cond_.notify_one();
138 decode_thread_.join();
139 }
140
141 if (logic_mux_thread_.joinable()) {
142 logic_mux_interrupt_ = true;
143 logic_mux_cond_.notify_one();
144 logic_mux_thread_.join();
145 }
146
147 stop_srd_session();
148
149 frame_complete_ = false;
150 samples_decoded_ = 0;
151 currently_processed_segment_ = 0;
152 error_message_ = QString();
153
154 rows_.clear();
155 current_rows_= nullptr;
156 class_rows_.clear();
157
158 logic_mux_data_.reset();
159 logic_mux_data_invalid_ = true;
160
161 decode_reset();
162}
163
164void DecodeSignal::begin_decode()
165{
166 if (decode_thread_.joinable()) {
167 decode_interrupt_ = true;
168 decode_input_cond_.notify_one();
169 decode_thread_.join();
170 }
171
172 if (logic_mux_thread_.joinable()) {
173 logic_mux_interrupt_ = true;
174 logic_mux_cond_.notify_one();
175 logic_mux_thread_.join();
176 }
177
178 reset_decode();
179
180 if (stack_.size() == 0) {
181 error_message_ = tr("No decoders");
182 return;
183 }
184
185 assert(channels_.size() > 0);
186
187 if (get_assigned_signal_count() == 0) {
188 error_message_ = tr("There are no channels assigned to this decoder");
189 return;
190 }
191
192 // Make sure that all assigned channels still provide logic data
193 // (can happen when a converted signal was assigned but the
194 // conversion removed in the meanwhile)
195 for (data::DecodeChannel &ch : channels_)
196 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
197 ch.assigned_signal = nullptr;
198
199 // Check that all decoders have the required channels
200 for (const shared_ptr<decode::Decoder> &dec : stack_)
201 if (!dec->have_required_channels()) {
202 error_message_ = tr("One or more required channels "
203 "have not been specified");
204 return;
205 }
206
207 // Map out all the annotation classes
208 for (const shared_ptr<decode::Decoder> &dec : stack_) {
209 assert(dec);
210 const srd_decoder *const decc = dec->decoder();
211 assert(dec->decoder());
212
213 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
214 const srd_decoder_annotation_row *const ann_row =
215 (srd_decoder_annotation_row *)l->data;
216 assert(ann_row);
217
218 const Row row(decc, ann_row);
219
220 for (const GSList *ll = ann_row->ann_classes;
221 ll; ll = ll->next)
222 class_rows_[make_pair(decc,
223 GPOINTER_TO_INT(ll->data))] = row;
224 }
225 }
226
227 prepare_annotation_segment();
228
229 // Free the logic data and its segment(s) if it needs to be updated
230 if (logic_mux_data_invalid_)
231 logic_mux_data_.reset();
232
233 if (!logic_mux_data_) {
234 const int64_t ch_count = get_assigned_signal_count();
235 const int64_t unit_size = (ch_count + 7) / 8;
236 logic_mux_data_ = make_shared<Logic>(ch_count);
237 logic_mux_segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
238 logic_mux_data_->push_segment(logic_mux_segment_);
239 }
240
241 // Make sure the logic output data is complete and up-to-date
242 logic_mux_interrupt_ = false;
243 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
244
245 // Decode the muxed logic data
246 decode_interrupt_ = false;
247 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
248
249 // Receive notifications when new sample data is available
250 connect_input_notifiers();
251}
252
253QString DecodeSignal::error_message() const
254{
255 lock_guard<mutex> lock(output_mutex_);
256 return error_message_;
257}
258
259const vector<data::DecodeChannel> DecodeSignal::get_channels() const
260{
261 return channels_;
262}
263
264void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
265{
266 bool new_assignment = false;
267
268 // Try to auto-select channels that don't have signals assigned yet
269 for (data::DecodeChannel &ch : channels_) {
270 // If a decoder is given, auto-assign only its channels
271 if (dec && (ch.decoder_ != dec))
272 continue;
273
274 if (ch.assigned_signal)
275 continue;
276
277 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
278 const QString ch_name = ch.name.toLower();
279 const QString s_name = s->name().toLower();
280
281 if (s->logic_data() &&
282 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
283 ch.assigned_signal = s.get();
284 new_assignment = true;
285 }
286 }
287 }
288
289 if (new_assignment) {
290 logic_mux_data_invalid_ = true;
291 commit_decoder_channels();
292 channels_updated();
293 }
294}
295
296void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
297{
298 for (data::DecodeChannel &ch : channels_)
299 if (ch.id == channel_id) {
300 ch.assigned_signal = signal;
301 logic_mux_data_invalid_ = true;
302 }
303
304 commit_decoder_channels();
305 channels_updated();
306 begin_decode();
307}
308
309int DecodeSignal::get_assigned_signal_count() const
310{
311 // Count all channels that have a signal assigned to them
312 return count_if(channels_.begin(), channels_.end(),
313 [](data::DecodeChannel ch) { return ch.assigned_signal; });
314}
315
316void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
317{
318 for (data::DecodeChannel &ch : channels_)
319 if (ch.id == channel_id)
320 ch.initial_pin_state = init_state;
321
322 channels_updated();
323
324 begin_decode();
325}
326
327double DecodeSignal::samplerate() const
328{
329 return samplerate_;
330}
331
332const pv::util::Timestamp& DecodeSignal::start_time() const
333{
334 return start_time_;
335}
336
337int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
338{
339 // The working sample count is the highest sample number for
340 // which all used signals have data available, so go through
341 // all channels and use the lowest overall sample count of the
342 // current segment
343
344 int64_t count = std::numeric_limits<int64_t>::max();
345 bool no_signals_assigned = true;
346
347 for (const data::DecodeChannel &ch : channels_)
348 if (ch.assigned_signal) {
349 no_signals_assigned = false;
350
351 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
352 if (!logic_data || logic_data->logic_segments().empty())
353 return 0;
354
355 try {
356 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
357 count = min(count, (int64_t)segment->get_sample_count());
358 } catch (out_of_range) {
359 return 0;
360 }
361 }
362
363 return (no_signals_assigned ? 0 : count);
364}
365
366int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id) const
367{
368 lock_guard<mutex> decode_lock(output_mutex_);
369
370 int64_t result = 0;
371
372 if (segment_id == currently_processed_segment_)
373 result = samples_decoded_;
374 else
375 if (segment_id < currently_processed_segment_)
376 // Segment was already decoded fully
377 result = get_working_sample_count(segment_id);
378 else
379 // Segment wasn't decoded at all yet
380 result = 0;
381
382 return result;
383}
384
385vector<Row> DecodeSignal::visible_rows() const
386{
387 lock_guard<mutex> lock(output_mutex_);
388
389 vector<Row> rows;
390
391 for (const shared_ptr<decode::Decoder> &dec : stack_) {
392 assert(dec);
393 if (!dec->shown())
394 continue;
395
396 const srd_decoder *const decc = dec->decoder();
397 assert(dec->decoder());
398
399 // Add a row for the decoder if it doesn't have a row list
400 if (!decc->annotation_rows)
401 rows.emplace_back(decc);
402
403 // Add the decoder rows
404 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
405 const srd_decoder_annotation_row *const ann_row =
406 (srd_decoder_annotation_row *)l->data;
407 assert(ann_row);
408 rows.emplace_back(decc, ann_row);
409 }
410 }
411
412 return rows;
413}
414
415void DecodeSignal::get_annotation_subset(
416 vector<pv::data::decode::Annotation> &dest,
417 const decode::Row &row, uint64_t start_sample,
418 uint64_t end_sample) const
419{
420 lock_guard<mutex> lock(output_mutex_);
421
422 if (!current_rows_)
423 return;
424
425 // TODO Instead of current_rows_, use rows_ and the ID of the segment
426
427 const auto iter = current_rows_->find(row);
428 if (iter != current_rows_->end())
429 (*iter).second.get_annotation_subset(dest,
430 start_sample, end_sample);
431}
432
433void DecodeSignal::save_settings(QSettings &settings) const
434{
435 SignalBase::save_settings(settings);
436
437 settings.setValue("decoders", (int)(stack_.size()));
438
439 // Save decoder stack
440 int decoder_idx = 0;
441 for (shared_ptr<decode::Decoder> decoder : stack_) {
442 settings.beginGroup("decoder" + QString::number(decoder_idx++));
443
444 settings.setValue("id", decoder->decoder()->id);
445
446 // Save decoder options
447 const map<string, GVariant*>& options = decoder->options();
448
449 settings.setValue("options", (int)options.size());
450
451 // Note: decode::Decoder::options() returns only the options
452 // that differ from the default. See binding::Decoder::getter()
453 int i = 0;
454 for (auto option : options) {
455 settings.beginGroup("option" + QString::number(i));
456 settings.setValue("name", QString::fromStdString(option.first));
457 GlobalSettings::store_gvariant(settings, option.second);
458 settings.endGroup();
459 i++;
460 }
461
462 settings.endGroup();
463 }
464
465 // Save channel mapping
466 settings.setValue("channels", (int)channels_.size());
467
468 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
469 auto channel = find_if(channels_.begin(), channels_.end(),
470 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
471
472 if (channel == channels_.end()) {
473 qDebug() << "ERROR: Gap in channel index:" << channel_id;
474 continue;
475 }
476
477 settings.beginGroup("channel" + QString::number(channel_id));
478
479 settings.setValue("name", channel->name); // Useful for debugging
480 settings.setValue("initial_pin_state", channel->initial_pin_state);
481
482 if (channel->assigned_signal)
483 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
484
485 settings.endGroup();
486 }
487}
488
489void DecodeSignal::restore_settings(QSettings &settings)
490{
491 SignalBase::restore_settings(settings);
492
493 // Restore decoder stack
494 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
495
496 int decoders = settings.value("decoders").toInt();
497
498 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
499 settings.beginGroup("decoder" + QString::number(decoder_idx));
500
501 QString id = settings.value("id").toString();
502
503 for (GSList *entry = dec_list; entry; entry = entry->next) {
504 const srd_decoder *dec = (srd_decoder*)entry->data;
505 if (!dec)
506 continue;
507
508 if (QString::fromUtf8(dec->id) == id) {
509 shared_ptr<decode::Decoder> decoder =
510 make_shared<decode::Decoder>(dec);
511
512 stack_.push_back(decoder);
513
514 // Restore decoder options that differ from their default
515 int options = settings.value("options").toInt();
516
517 for (int i = 0; i < options; i++) {
518 settings.beginGroup("option" + QString::number(i));
519 QString name = settings.value("name").toString();
520 GVariant *value = GlobalSettings::restore_gvariant(settings);
521 decoder->set_option(name.toUtf8(), value);
522 settings.endGroup();
523 }
524
525 // Include the newly created decode channels in the channel lists
526 update_channel_list();
527 break;
528 }
529 }
530
531 settings.endGroup();
532 channels_updated();
533 }
534
535 // Restore channel mapping
536 unsigned int channels = settings.value("channels").toInt();
537
538 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
539 session_.signalbases();
540
541 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
542 auto channel = find_if(channels_.begin(), channels_.end(),
543 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
544
545 if (channel == channels_.end()) {
546 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
547 continue;
548 }
549
550 settings.beginGroup("channel" + QString::number(channel_id));
551
552 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
553
554 for (shared_ptr<data::SignalBase> signal : signalbases)
555 if (signal->name() == assigned_signal_name)
556 channel->assigned_signal = signal.get();
557
558 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
559
560 settings.endGroup();
561 }
562
563 // Update the internal structures
564 update_channel_list();
565 commit_decoder_channels();
566
567 begin_decode();
568}
569
570void DecodeSignal::update_channel_list()
571{
572 vector<data::DecodeChannel> prev_channels = channels_;
573 channels_.clear();
574
575 uint16_t id = 0;
576
577 // Copy existing entries, create new as needed
578 for (shared_ptr<Decoder> decoder : stack_) {
579 const srd_decoder* srd_d = decoder->decoder();
580 const GSList *l;
581
582 // Mandatory channels
583 for (l = srd_d->channels; l; l = l->next) {
584 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
585 bool ch_added = false;
586
587 // Copy but update ID if this channel was in the list before
588 for (data::DecodeChannel &ch : prev_channels)
589 if (ch.pdch_ == pdch) {
590 ch.id = id++;
591 channels_.push_back(ch);
592 ch_added = true;
593 break;
594 }
595
596 if (!ch_added) {
597 // Create new entry without a mapped signal
598 data::DecodeChannel ch = {id++, 0, false, nullptr,
599 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
600 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
601 channels_.push_back(ch);
602 }
603 }
604
605 // Optional channels
606 for (l = srd_d->opt_channels; l; l = l->next) {
607 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
608 bool ch_added = false;
609
610 // Copy but update ID if this channel was in the list before
611 for (data::DecodeChannel &ch : prev_channels)
612 if (ch.pdch_ == pdch) {
613 ch.id = id++;
614 channels_.push_back(ch);
615 ch_added = true;
616 break;
617 }
618
619 if (!ch_added) {
620 // Create new entry without a mapped signal
621 data::DecodeChannel ch = {id++, 0, true, nullptr,
622 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
623 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
624 channels_.push_back(ch);
625 }
626 }
627 }
628
629 // Invalidate the logic output data if the channel assignment changed
630 if (prev_channels.size() != channels_.size()) {
631 // The number of channels changed, there's definitely a difference
632 logic_mux_data_invalid_ = true;
633 } else {
634 // Same number but assignment may still differ, so compare all channels
635 for (size_t i = 0; i < channels_.size(); i++) {
636 const data::DecodeChannel &p_ch = prev_channels[i];
637 const data::DecodeChannel &ch = channels_[i];
638
639 if ((p_ch.pdch_ != ch.pdch_) ||
640 (p_ch.assigned_signal != ch.assigned_signal)) {
641 logic_mux_data_invalid_ = true;
642 break;
643 }
644 }
645
646 }
647
648 channels_updated();
649}
650
651void DecodeSignal::commit_decoder_channels()
652{
653 // Submit channel list to every decoder, containing only the relevant channels
654 for (shared_ptr<decode::Decoder> dec : stack_) {
655 vector<data::DecodeChannel*> channel_list;
656
657 for (data::DecodeChannel &ch : channels_)
658 if (ch.decoder_ == dec)
659 channel_list.push_back(&ch);
660
661 dec->set_channels(channel_list);
662 }
663
664 // Channel bit IDs must be in sync with the channel's apperance in channels_
665 int id = 0;
666 for (data::DecodeChannel &ch : channels_)
667 if (ch.assigned_signal)
668 ch.bit_id = id++;
669}
670
671void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
672{
673 // Enforce end to be greater than start
674 if (end <= start)
675 return;
676
677 // Fetch all segments and their data
678 // TODO Currently, we assume only a single segment exists
679 vector<shared_ptr<LogicSegment> > segments;
680 vector<const uint8_t*> signal_data;
681 vector<uint8_t> signal_in_bytepos;
682 vector<uint8_t> signal_in_bitpos;
683
684 for (data::DecodeChannel &ch : channels_)
685 if (ch.assigned_signal) {
686 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
687 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
688 segments.push_back(segment);
689
690 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
691 segment->get_samples(start, end, data);
692 signal_data.push_back(data);
693
694 const int bitpos = ch.assigned_signal->logic_bit_index();
695 signal_in_bytepos.push_back(bitpos / 8);
696 signal_in_bitpos.push_back(bitpos % 8);
697 }
698
699 // Perform the muxing of signal data into the output data
700 uint8_t* output = new uint8_t[(end - start) * logic_mux_segment_->unit_size()];
701 unsigned int signal_count = signal_data.size();
702
703 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
704 int bitpos = 0;
705 uint8_t bytepos = 0;
706
707 const int out_sample_pos = sample_cnt * logic_mux_segment_->unit_size();
708 for (unsigned int i = 0; i < logic_mux_segment_->unit_size(); i++)
709 output[out_sample_pos + i] = 0;
710
711 for (unsigned int i = 0; i < signal_count; i++) {
712 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
713 const uint8_t in_sample = 1 &
714 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
715
716 const uint8_t out_sample = output[out_sample_pos + bytepos];
717
718 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
719
720 bitpos++;
721 if (bitpos > 7) {
722 bitpos = 0;
723 bytepos++;
724 }
725 }
726 }
727
728 logic_mux_segment_->append_payload(output, (end - start) * logic_mux_segment_->unit_size());
729 delete[] output;
730
731 for (const uint8_t* data : signal_data)
732 delete[] data;
733}
734
735void DecodeSignal::logic_mux_proc()
736{
737 do {
738 const uint64_t input_sample_count = get_working_sample_count(currently_processed_segment_);
739 const uint64_t output_sample_count = logic_mux_segment_->get_sample_count();
740
741 const uint64_t samples_to_process =
742 (input_sample_count > output_sample_count) ?
743 (input_sample_count - output_sample_count) : 0;
744
745 // Process the samples if necessary...
746 if (samples_to_process > 0) {
747 const uint64_t unit_size = logic_mux_segment_->unit_size();
748 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
749
750 uint64_t processed_samples = 0;
751 do {
752 const uint64_t start_sample = output_sample_count + processed_samples;
753 const uint64_t sample_count =
754 min(samples_to_process - processed_samples, chunk_sample_count);
755
756 mux_logic_samples(start_sample, start_sample + sample_count);
757 processed_samples += sample_count;
758
759 // ...and process the newly muxed logic data
760 decode_input_cond_.notify_one();
761 } while (processed_samples < samples_to_process);
762 }
763
764 if (samples_to_process == 0) {
765 // Wait for more input
766 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
767 logic_mux_cond_.wait(logic_mux_lock);
768 }
769 } while (!logic_mux_interrupt_);
770}
771
772void DecodeSignal::query_input_metadata()
773{
774 // Update the samplerate and start time because we cannot start
775 // the libsrd session without the current samplerate
776
777 // TODO Currently we assume all channels have the same sample rate
778 // and start time
779 bool samplerate_valid = false;
780 data::DecodeChannel *any_channel;
781 shared_ptr<Logic> logic_data;
782
783 do {
784 any_channel = &(*find_if(channels_.begin(), channels_.end(),
785 [](data::DecodeChannel ch) { return ch.assigned_signal; }));
786
787 logic_data = any_channel->assigned_signal->logic_data();
788
789 if (!logic_data) {
790 // Wait until input data is available or an interrupt was requested
791 unique_lock<mutex> input_wait_lock(input_mutex_);
792 decode_input_cond_.wait(input_wait_lock);
793 }
794 } while (!logic_data && !decode_interrupt_);
795
796 if (decode_interrupt_)
797 return;
798
799 do {
800 if (!logic_data->logic_segments().empty()) {
801 shared_ptr<LogicSegment> first_segment =
802 any_channel->assigned_signal->logic_data()->logic_segments().front();
803 start_time_ = first_segment->start_time();
804 samplerate_ = first_segment->samplerate();
805 if (samplerate_ > 0)
806 samplerate_valid = true;
807 }
808
809 if (!samplerate_valid) {
810 // Wait until input data is available or an interrupt was requested
811 unique_lock<mutex> input_wait_lock(input_mutex_);
812 decode_input_cond_.wait(input_wait_lock);
813 }
814 } while (!samplerate_valid && !decode_interrupt_);
815}
816
817void DecodeSignal::decode_data(
818 const int64_t abs_start_samplenum, const int64_t sample_count)
819{
820 const int64_t unit_size = logic_mux_segment_->unit_size();
821 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
822
823 for (int64_t i = abs_start_samplenum;
824 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
825 i += chunk_sample_count) {
826
827 const int64_t chunk_end = min(i + chunk_sample_count,
828 abs_start_samplenum + sample_count);
829
830 int64_t data_size = (chunk_end - i) * unit_size;
831 uint8_t* chunk = new uint8_t[data_size];
832 logic_mux_segment_->get_samples(i, chunk_end, chunk);
833
834 if (srd_session_send(srd_session_, i, chunk_end, chunk,
835 data_size, unit_size) != SRD_OK) {
836 error_message_ = tr("Decoder reported an error");
837 delete[] chunk;
838 break;
839 }
840
841 delete[] chunk;
842
843 {
844 lock_guard<mutex> lock(output_mutex_);
845 samples_decoded_ = chunk_end;
846 }
847
848 // Notify the frontend that we processed some data and
849 // possibly have new annotations as well
850 new_annotations();
851 }
852}
853
854void DecodeSignal::decode_proc()
855{
856 query_input_metadata();
857
858 if (decode_interrupt_)
859 return;
860
861 start_srd_session();
862
863 uint64_t sample_count;
864 uint64_t abs_start_samplenum = 0;
865 do {
866 // Keep processing new samples until we exhaust the input data
867 do {
868 lock_guard<mutex> input_lock(input_mutex_);
869 sample_count = logic_mux_segment_->get_sample_count() - abs_start_samplenum;
870
871 if (sample_count > 0) {
872 decode_data(abs_start_samplenum, sample_count);
873 abs_start_samplenum += sample_count;
874 }
875 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
876
877 if (error_message_.isEmpty() && !decode_interrupt_) {
878 if (sample_count == 0)
879 decode_finished();
880
881 // Wait for new input data or an interrupt was requested
882 unique_lock<mutex> input_wait_lock(input_mutex_);
883 decode_input_cond_.wait(input_wait_lock);
884 }
885 } while (error_message_.isEmpty() && !decode_interrupt_);
886}
887
888void DecodeSignal::start_srd_session()
889{
890 if (srd_session_)
891 stop_srd_session();
892
893 // Create the session
894 srd_session_new(&srd_session_);
895 assert(srd_session_);
896
897 // Create the decoders
898 srd_decoder_inst *prev_di = nullptr;
899 for (const shared_ptr<decode::Decoder> &dec : stack_) {
900 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
901
902 if (!di) {
903 error_message_ = tr("Failed to create decoder instance");
904 srd_session_destroy(srd_session_);
905 return;
906 }
907
908 if (prev_di)
909 srd_inst_stack(srd_session_, prev_di, di);
910
911 prev_di = di;
912 }
913
914 // Start the session
915 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
916 g_variant_new_uint64(samplerate_));
917
918 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
919 DecodeSignal::annotation_callback, this);
920
921 srd_session_start(srd_session_);
922}
923
924void DecodeSignal::stop_srd_session()
925{
926 if (srd_session_) {
927 // Destroy the session
928 srd_session_destroy(srd_session_);
929 srd_session_ = nullptr;
930 }
931}
932
933void DecodeSignal::connect_input_notifiers()
934{
935 // Disconnect the notification slot from the previous set of signals
936 disconnect(this, SLOT(on_data_cleared()));
937 disconnect(this, SLOT(on_data_received()));
938
939 // Connect the currently used signals to our slot
940 for (data::DecodeChannel &ch : channels_) {
941 if (!ch.assigned_signal)
942 continue;
943
944 const data::SignalBase *signal = ch.assigned_signal;
945 connect(signal, SIGNAL(samples_cleared()),
946 this, SLOT(on_data_cleared()));
947 connect(signal, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
948 this, SLOT(on_data_received()));
949 }
950}
951
952void DecodeSignal::prepare_annotation_segment()
953{
954 // TODO Won't work for multiple segments
955 rows_.emplace_back(map<const decode::Row, decode::RowData>());
956 current_rows_ = &(rows_.back());
957
958 // Add annotation classes
959 for (const shared_ptr<decode::Decoder> &dec : stack_) {
960 assert(dec);
961 const srd_decoder *const decc = dec->decoder();
962 assert(dec->decoder());
963
964 // Add a row for the decoder if it doesn't have a row list
965 if (!decc->annotation_rows)
966 (*current_rows_)[Row(decc)] = decode::RowData();
967
968 // Add the decoder rows
969 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
970 const srd_decoder_annotation_row *const ann_row =
971 (srd_decoder_annotation_row *)l->data;
972 assert(ann_row);
973
974 const Row row(decc, ann_row);
975
976 // Add a new empty row data object
977 (*current_rows_)[row] = decode::RowData();
978 }
979 }
980}
981
982void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
983{
984 assert(pdata);
985 assert(decode_signal);
986
987 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
988 assert(ds);
989
990 lock_guard<mutex> lock(ds->output_mutex_);
991
992 // Find the row
993 assert(pdata->pdo);
994 assert(pdata->pdo->di);
995 const srd_decoder *const decc = pdata->pdo->di->decoder;
996 assert(decc);
997 assert(ds->current_rows_);
998
999 const srd_proto_data_annotation *const pda =
1000 (const srd_proto_data_annotation*)pdata->data;
1001 assert(pda);
1002
1003 auto row_iter = ds->current_rows_->end();
1004
1005 // Try looking up the sub-row of this class
1006 const auto format = pda->ann_class;
1007 const auto r = ds->class_rows_.find(make_pair(decc, format));
1008 if (r != ds->class_rows_.end())
1009 row_iter = ds->current_rows_->find((*r).second);
1010 else {
1011 // Failing that, use the decoder as a key
1012 row_iter = ds->current_rows_->find(Row(decc));
1013 }
1014
1015 if (row_iter == ds->current_rows_->end()) {
1016 qDebug() << "Unexpected annotation: decoder = " << decc <<
1017 ", format = " << format;
1018 assert(false);
1019 return;
1020 }
1021
1022 // Add the annotation
1023 (*row_iter).second.emplace_annotation(pdata);
1024}
1025
1026void DecodeSignal::on_capture_state_changed(int state)
1027{
1028 // If a new acquisition was started, we need to start decoding from scratch
1029 if (state == Session::Running)
1030 begin_decode();
1031}
1032
1033void DecodeSignal::on_data_cleared()
1034{
1035 reset_decode();
1036}
1037
1038void DecodeSignal::on_data_received()
1039{
1040 if (!logic_mux_thread_.joinable())
1041 begin_decode();
1042 else
1043 logic_mux_cond_.notify_one();
1044}
1045
1046} // namespace data
1047} // namespace pv