2 * This file is part of the PulseView project.
4 * Copyright (C) 2017 Soeren Apel <soeren@apelpie.net>
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.
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.
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/>.
21 #include <forward_list>
27 #include "logicsegment.hpp"
28 #include "decodesignal.hpp"
29 #include "signaldata.hpp"
31 #include <pv/data/decode/decoder.hpp>
32 #include <pv/data/decode/row.hpp>
33 #include <pv/globalsettings.hpp>
34 #include <pv/session.hpp>
36 using std::forward_list;
37 using std::lock_guard;
39 using std::make_shared;
41 using std::out_of_range;
42 using std::shared_ptr;
43 using std::unique_lock;
44 using pv::data::decode::Annotation;
45 using pv::data::decode::DecodeChannel;
46 using pv::data::decode::Decoder;
47 using pv::data::decode::Row;
52 const double DecodeSignal::DecodeMargin = 1.0;
53 const double DecodeSignal::DecodeThreshold = 0.2;
54 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
57 DecodeSignal::DecodeSignal(pv::Session &session) :
58 SignalBase(nullptr, SignalBase::DecodeChannel),
60 srd_session_(nullptr),
61 logic_mux_data_invalid_(false),
62 stack_config_changed_(true),
63 current_segment_id_(0)
65 connect(&session_, SIGNAL(capture_state_changed(int)),
66 this, SLOT(on_capture_state_changed(int)));
69 DecodeSignal::~DecodeSignal()
74 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
79 void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
83 // Set name if this decoder is the first in the list or the name is unchanged
84 const srd_decoder* prev_dec =
85 stack_.empty() ? nullptr : stack_.back()->decoder();
86 const QString prev_dec_name =
87 prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
89 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
90 set_name(QString::fromUtf8(decoder->name));
92 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
93 stack_.push_back(dec);
95 // Include the newly created decode channels in the channel lists
96 update_channel_list();
98 stack_config_changed_ = true;
99 auto_assign_signals(dec);
100 commit_decoder_channels();
102 decoder_stacked((void*)dec.get());
108 void DecodeSignal::remove_decoder(int index)
111 assert(index < (int)stack_.size());
113 // Find the decoder in the stack
114 auto iter = stack_.begin();
115 for (int i = 0; i < index; i++, iter++)
116 assert(iter != stack_.end());
118 decoder_removed(iter->get());
120 // Delete the element
123 // Update channels and decoded data
124 stack_config_changed_ = true;
125 update_channel_list();
129 bool DecodeSignal::toggle_decoder_visibility(int index)
131 auto iter = stack_.cbegin();
132 for (int i = 0; i < index; i++, iter++)
133 assert(iter != stack_.end());
135 shared_ptr<Decoder> dec = *iter;
137 // Toggle decoder visibility
140 state = !dec->shown();
147 void DecodeSignal::reset_decode(bool shutting_down)
149 if (stack_config_changed_ || shutting_down)
152 terminate_srd_session();
154 if (decode_thread_.joinable()) {
155 decode_interrupt_ = true;
156 decode_input_cond_.notify_one();
157 decode_thread_.join();
160 if (logic_mux_thread_.joinable()) {
161 logic_mux_interrupt_ = true;
162 logic_mux_cond_.notify_one();
163 logic_mux_thread_.join();
166 resume_decode(); // Make sure the decode thread isn't blocked by pausing
169 current_segment_id_ = 0;
172 logic_mux_data_.reset();
173 logic_mux_data_invalid_ = true;
175 if (!error_message_.isEmpty()) {
176 error_message_ = QString();
177 // TODO Emulate noquote()
178 qDebug().nospace() << name() << ": Error cleared";
184 void DecodeSignal::begin_decode()
186 if (decode_thread_.joinable()) {
187 decode_interrupt_ = true;
188 decode_input_cond_.notify_one();
189 decode_thread_.join();
192 if (logic_mux_thread_.joinable()) {
193 logic_mux_interrupt_ = true;
194 logic_mux_cond_.notify_one();
195 logic_mux_thread_.join();
200 if (stack_.size() == 0) {
201 set_error_message(tr("No decoders"));
205 assert(channels_.size() > 0);
207 if (get_assigned_signal_count() == 0) {
208 set_error_message(tr("There are no channels assigned to this decoder"));
212 // Make sure that all assigned channels still provide logic data
213 // (can happen when a converted signal was assigned but the
214 // conversion removed in the meanwhile)
215 for (decode::DecodeChannel& ch : channels_)
216 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
217 ch.assigned_signal = nullptr;
219 // Check that all decoders have the required channels
220 for (const shared_ptr<decode::Decoder>& dec : stack_)
221 if (!dec->have_required_channels()) {
222 set_error_message(tr("One or more required channels "
223 "have not been specified"));
227 // Map out all the annotation classes
229 for (const shared_ptr<decode::Decoder>& dec : stack_) {
231 const srd_decoder *const decc = dec->decoder();
232 assert(dec->decoder());
234 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
235 const srd_decoder_annotation_row *const ann_row =
236 (srd_decoder_annotation_row *)l->data;
239 const Row row(row_index++, decc, ann_row);
241 for (const GSList *ll = ann_row->ann_classes;
243 class_rows_[make_pair(decc,
244 GPOINTER_TO_INT(ll->data))] = row;
248 // Free the logic data and its segment(s) if it needs to be updated
249 if (logic_mux_data_invalid_)
250 logic_mux_data_.reset();
252 if (!logic_mux_data_) {
253 const uint32_t ch_count = get_assigned_signal_count();
254 logic_mux_unit_size_ = (ch_count + 7) / 8;
255 logic_mux_data_ = make_shared<Logic>(ch_count);
258 // Receive notifications when new sample data is available
259 connect_input_notifiers();
261 if (get_input_segment_count() == 0) {
262 set_error_message(tr("No input data"));
266 // Make sure the logic output data is complete and up-to-date
267 logic_mux_interrupt_ = false;
268 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
270 // Decode the muxed logic data
271 decode_interrupt_ = false;
272 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
275 void DecodeSignal::pause_decode()
277 decode_paused_ = true;
280 void DecodeSignal::resume_decode()
282 // Manual unlocking is done before notifying, to avoid waking up the
283 // waiting thread only to block again (see notify_one for details)
284 decode_pause_mutex_.unlock();
285 decode_pause_cond_.notify_one();
286 decode_paused_ = false;
289 bool DecodeSignal::is_paused() const
291 return decode_paused_;
294 QString DecodeSignal::error_message() const
296 lock_guard<mutex> lock(output_mutex_);
297 return error_message_;
300 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
305 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
307 bool new_assignment = false;
309 // Try to auto-select channels that don't have signals assigned yet
310 for (decode::DecodeChannel& ch : channels_) {
311 // If a decoder is given, auto-assign only its channels
312 if (dec && (ch.decoder_ != dec))
315 if (ch.assigned_signal)
318 QString ch_name = ch.name.toLower();
319 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
321 shared_ptr<data::SignalBase> match;
322 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
326 QString s_name = s->name().toLower();
327 s_name = s_name.replace(QRegExp("[-_.]"), " ");
329 if (s->logic_data() &&
330 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
334 // Only replace an existing match if it matches more characters
335 int old_unmatched = ch_name.length() - match->name().length();
336 int new_unmatched = ch_name.length() - s->name().length();
337 if (abs(new_unmatched) < abs(old_unmatched))
344 ch.assigned_signal = match.get();
345 new_assignment = true;
349 if (new_assignment) {
350 logic_mux_data_invalid_ = true;
351 stack_config_changed_ = true;
352 commit_decoder_channels();
357 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
359 for (decode::DecodeChannel& ch : channels_)
360 if (ch.id == channel_id) {
361 ch.assigned_signal = signal;
362 logic_mux_data_invalid_ = true;
365 stack_config_changed_ = true;
366 commit_decoder_channels();
371 int DecodeSignal::get_assigned_signal_count() const
373 // Count all channels that have a signal assigned to them
374 return count_if(channels_.begin(), channels_.end(),
375 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
378 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
380 for (decode::DecodeChannel& ch : channels_)
381 if (ch.id == channel_id)
382 ch.initial_pin_state = init_state;
384 stack_config_changed_ = true;
389 double DecodeSignal::samplerate() const
393 // TODO For now, we simply return the first samplerate that we have
394 if (segments_.size() > 0)
395 result = segments_.front().samplerate;
400 const pv::util::Timestamp DecodeSignal::start_time() const
402 pv::util::Timestamp result;
404 // TODO For now, we simply return the first start time that we have
405 if (segments_.size() > 0)
406 result = segments_.front().start_time;
411 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
413 // The working sample count is the highest sample number for
414 // which all used signals have data available, so go through all
415 // channels and use the lowest overall sample count of the segment
417 int64_t count = std::numeric_limits<int64_t>::max();
418 bool no_signals_assigned = true;
420 for (const decode::DecodeChannel& ch : channels_)
421 if (ch.assigned_signal) {
422 no_signals_assigned = false;
424 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
425 if (!logic_data || logic_data->logic_segments().empty())
429 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
430 count = min(count, (int64_t)segment->get_sample_count());
431 } catch (out_of_range&) {
436 return (no_signals_assigned ? 0 : count);
439 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
440 bool include_processing) const
442 lock_guard<mutex> decode_lock(output_mutex_);
446 if (segment_id >= segments_.size())
449 if (include_processing)
450 result = segments_[segment_id].samples_decoded_incl;
452 result = segments_[segment_id].samples_decoded_excl;
457 vector<Row> DecodeSignal::get_rows(bool visible_only) const
459 lock_guard<mutex> lock(output_mutex_);
463 for (const shared_ptr<decode::Decoder>& dec : stack_) {
465 if (visible_only && !dec->shown())
468 const srd_decoder *const decc = dec->decoder();
469 assert(dec->decoder());
472 // Add a row for the decoder if it doesn't have a row list
473 if (!decc->annotation_rows)
474 rows.emplace_back(row_index++, decc);
476 // Add the decoder rows
477 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
478 const srd_decoder_annotation_row *const ann_row =
479 (srd_decoder_annotation_row *)l->data;
481 rows.emplace_back(row_index++, decc, ann_row);
488 void DecodeSignal::get_annotation_subset(
489 vector<pv::data::decode::Annotation> &dest,
490 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
491 uint64_t end_sample) const
493 lock_guard<mutex> lock(output_mutex_);
495 if (segment_id >= segments_.size())
498 const DecodeSegment *segment = &(segments_.at(segment_id));
499 const map<const decode::Row, decode::RowData> *rows =
500 &(segment->annotation_rows);
502 const auto iter = rows->find(row);
503 if (iter != rows->end())
504 (*iter).second.get_annotation_subset(dest, start_sample, end_sample);
507 void DecodeSignal::get_annotation_subset(
508 vector<pv::data::decode::Annotation> &dest,
509 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
511 // Note: We put all vectors and lists on the heap, not the stack
513 const vector<Row> rows = get_rows(true);
515 // Use forward_lists for faster merging
516 forward_list<Annotation> *all_ann_list = new forward_list<Annotation>();
518 for (const Row& row : rows) {
519 vector<Annotation> *ann_vector = new vector<Annotation>();
520 get_annotation_subset(*ann_vector, row, segment_id, start_sample, end_sample);
522 forward_list<Annotation> *ann_list =
523 new forward_list<Annotation>(ann_vector->begin(), ann_vector->end());
526 all_ann_list->merge(*ann_list);
530 move(all_ann_list->begin(), all_ann_list->end(), back_inserter(dest));
534 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
535 const Decoder* dec, uint32_t bin_class_id) const
537 if (segments_.size() == 0)
541 const DecodeSegment *segment = &(segments_.at(segment_id));
543 for (const DecodeBinaryClass& bc : segment->binary_classes)
544 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
545 return bc.chunks.size();
546 } catch (out_of_range&) {
553 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
554 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
555 const vector<uint8_t> **dest, uint64_t *size)
558 const DecodeSegment *segment = &(segments_.at(segment_id));
560 for (const DecodeBinaryClass& bc : segment->binary_classes)
561 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
562 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
563 if (size) *size = bc.chunks.at(chunk_id).data.size();
566 } catch (out_of_range&) {
571 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
572 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
573 uint64_t end_sample, vector<uint8_t> *dest) const
575 assert(dest != nullptr);
578 const DecodeSegment *segment = &(segments_.at(segment_id));
580 const DecodeBinaryClass* bin_class = nullptr;
581 for (const DecodeBinaryClass& bc : segment->binary_classes)
582 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
585 // Determine overall size before copying to resize dest vector only once
587 uint64_t matches = 0;
588 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
589 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
590 size += chunk.data.size();
596 uint64_t matches2 = 0;
597 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
598 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
599 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
600 offset += chunk.data.size();
603 // Make sure we don't overwrite memory if the array grew in the meanwhile
604 if (matches2 == matches)
607 } catch (out_of_range&) {
612 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
613 const data::decode::Decoder* dec, uint32_t bin_class_id, uint64_t start,
614 uint64_t end, vector<uint8_t> *dest) const
616 assert(dest != nullptr);
619 const DecodeSegment *segment = &(segments_.at(segment_id));
621 const DecodeBinaryClass* bin_class = nullptr;
622 for (const DecodeBinaryClass& bc : segment->binary_classes)
623 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
626 // Determine overall size before copying to resize dest vector only once
629 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
631 size += chunk.data.size();
632 offset += chunk.data.size();
639 uint64_t dest_offset = 0;
640 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
641 if (offset >= start) {
642 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
643 dest_offset += chunk.data.size();
645 offset += chunk.data.size();
649 } catch (out_of_range&) {
654 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
655 const data::decode::Decoder* dec, uint32_t bin_class_id) const
658 const DecodeSegment *segment = &(segments_.at(segment_id));
660 for (const DecodeBinaryClass& bc : segment->binary_classes)
661 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
663 } catch (out_of_range&) {
670 void DecodeSignal::save_settings(QSettings &settings) const
672 SignalBase::save_settings(settings);
674 settings.setValue("decoders", (int)(stack_.size()));
676 // Save decoder stack
678 for (const shared_ptr<decode::Decoder>& decoder : stack_) {
679 settings.beginGroup("decoder" + QString::number(decoder_idx++));
681 settings.setValue("id", decoder->decoder()->id);
682 settings.setValue("shown", decoder->shown());
684 // Save decoder options
685 const map<string, GVariant*>& options = decoder->options();
687 settings.setValue("options", (int)options.size());
689 // Note: decode::Decoder::options() returns only the options
690 // that differ from the default. See binding::Decoder::getter()
692 for (auto& option : options) {
693 settings.beginGroup("option" + QString::number(i));
694 settings.setValue("name", QString::fromStdString(option.first));
695 GlobalSettings::store_gvariant(settings, option.second);
703 // Save channel mapping
704 settings.setValue("channels", (int)channels_.size());
706 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
707 auto channel = find_if(channels_.begin(), channels_.end(),
708 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
710 if (channel == channels_.end()) {
711 qDebug() << "ERROR: Gap in channel index:" << channel_id;
715 settings.beginGroup("channel" + QString::number(channel_id));
717 settings.setValue("name", channel->name); // Useful for debugging
718 settings.setValue("initial_pin_state", channel->initial_pin_state);
720 if (channel->assigned_signal)
721 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
727 void DecodeSignal::restore_settings(QSettings &settings)
729 SignalBase::restore_settings(settings);
731 // Restore decoder stack
732 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
734 int decoders = settings.value("decoders").toInt();
736 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
737 settings.beginGroup("decoder" + QString::number(decoder_idx));
739 QString id = settings.value("id").toString();
741 for (GSList *entry = dec_list; entry; entry = entry->next) {
742 const srd_decoder *dec = (srd_decoder*)entry->data;
746 if (QString::fromUtf8(dec->id) == id) {
747 shared_ptr<decode::Decoder> decoder =
748 make_shared<decode::Decoder>(dec);
750 stack_.push_back(decoder);
751 decoder->show(settings.value("shown", true).toBool());
753 // Restore decoder options that differ from their default
754 int options = settings.value("options").toInt();
756 for (int i = 0; i < options; i++) {
757 settings.beginGroup("option" + QString::number(i));
758 QString name = settings.value("name").toString();
759 GVariant *value = GlobalSettings::restore_gvariant(settings);
760 decoder->set_option(name.toUtf8(), value);
764 // Include the newly created decode channels in the channel lists
765 update_channel_list();
774 // Restore channel mapping
775 unsigned int channels = settings.value("channels").toInt();
777 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
778 session_.signalbases();
780 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
781 auto channel = find_if(channels_.begin(), channels_.end(),
782 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
784 if (channel == channels_.end()) {
785 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
789 settings.beginGroup("channel" + QString::number(channel_id));
791 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
793 for (const shared_ptr<data::SignalBase>& signal : signalbases)
794 if (signal->name() == assigned_signal_name)
795 channel->assigned_signal = signal.get();
797 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
802 // Update the internal structures
803 stack_config_changed_ = true;
804 update_channel_list();
805 commit_decoder_channels();
810 void DecodeSignal::set_error_message(QString msg)
812 error_message_ = msg;
813 // TODO Emulate noquote()
814 qDebug().nospace() << name() << ": " << msg;
817 uint32_t DecodeSignal::get_input_segment_count() const
819 uint64_t count = std::numeric_limits<uint64_t>::max();
820 bool no_signals_assigned = true;
822 for (const decode::DecodeChannel& ch : channels_)
823 if (ch.assigned_signal) {
824 no_signals_assigned = false;
826 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
827 if (!logic_data || logic_data->logic_segments().empty())
830 // Find the min value of all segment counts
831 if ((uint64_t)(logic_data->logic_segments().size()) < count)
832 count = logic_data->logic_segments().size();
835 return (no_signals_assigned ? 0 : count);
838 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
840 double samplerate = 0;
842 for (const decode::DecodeChannel& ch : channels_)
843 if (ch.assigned_signal) {
844 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
845 if (!logic_data || logic_data->logic_segments().empty())
849 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
850 samplerate = segment->samplerate();
851 } catch (out_of_range&) {
860 void DecodeSignal::update_channel_list()
862 vector<decode::DecodeChannel> prev_channels = channels_;
867 // Copy existing entries, create new as needed
868 for (shared_ptr<Decoder>& decoder : stack_) {
869 const srd_decoder* srd_d = decoder->decoder();
872 // Mandatory channels
873 for (l = srd_d->channels; l; l = l->next) {
874 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
875 bool ch_added = false;
877 // Copy but update ID if this channel was in the list before
878 for (decode::DecodeChannel& ch : prev_channels)
879 if (ch.pdch_ == pdch) {
881 channels_.push_back(ch);
887 // Create new entry without a mapped signal
888 decode::DecodeChannel ch = {id++, 0, false, nullptr,
889 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
890 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
891 channels_.push_back(ch);
896 for (l = srd_d->opt_channels; l; l = l->next) {
897 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
898 bool ch_added = false;
900 // Copy but update ID if this channel was in the list before
901 for (decode::DecodeChannel& ch : prev_channels)
902 if (ch.pdch_ == pdch) {
904 channels_.push_back(ch);
910 // Create new entry without a mapped signal
911 decode::DecodeChannel ch = {id++, 0, true, nullptr,
912 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
913 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
914 channels_.push_back(ch);
919 // Invalidate the logic output data if the channel assignment changed
920 if (prev_channels.size() != channels_.size()) {
921 // The number of channels changed, there's definitely a difference
922 logic_mux_data_invalid_ = true;
924 // Same number but assignment may still differ, so compare all channels
925 for (size_t i = 0; i < channels_.size(); i++) {
926 const decode::DecodeChannel& p_ch = prev_channels[i];
927 const decode::DecodeChannel& ch = channels_[i];
929 if ((p_ch.pdch_ != ch.pdch_) ||
930 (p_ch.assigned_signal != ch.assigned_signal)) {
931 logic_mux_data_invalid_ = true;
941 void DecodeSignal::commit_decoder_channels()
943 // Submit channel list to every decoder, containing only the relevant channels
944 for (shared_ptr<decode::Decoder> dec : stack_) {
945 vector<decode::DecodeChannel*> channel_list;
947 for (decode::DecodeChannel& ch : channels_)
948 if (ch.decoder_ == dec)
949 channel_list.push_back(&ch);
951 dec->set_channels(channel_list);
954 // Channel bit IDs must be in sync with the channel's apperance in channels_
956 for (decode::DecodeChannel& ch : channels_)
957 if (ch.assigned_signal)
961 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
963 // Enforce end to be greater than start
967 // Fetch the channel segments and their data
968 vector<shared_ptr<LogicSegment> > segments;
969 vector<const uint8_t*> signal_data;
970 vector<uint8_t> signal_in_bytepos;
971 vector<uint8_t> signal_in_bitpos;
973 for (decode::DecodeChannel& ch : channels_)
974 if (ch.assigned_signal) {
975 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
977 shared_ptr<LogicSegment> segment;
979 segment = logic_data->logic_segments().at(segment_id);
980 } catch (out_of_range&) {
981 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
982 << "has no logic segment" << segment_id;
985 segments.push_back(segment);
987 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
988 segment->get_samples(start, end, data);
989 signal_data.push_back(data);
991 const int bitpos = ch.assigned_signal->logic_bit_index();
992 signal_in_bytepos.push_back(bitpos / 8);
993 signal_in_bitpos.push_back(bitpos % 8);
997 shared_ptr<LogicSegment> output_segment;
999 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1000 } catch (out_of_range&) {
1001 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1002 << segment_id << "in mux_logic_samples(), mux segments size is" \
1003 << logic_mux_data_->logic_segments().size();
1007 // Perform the muxing of signal data into the output data
1008 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1009 unsigned int signal_count = signal_data.size();
1011 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1015 uint8_t bytepos = 0;
1017 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1018 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1019 output[out_sample_pos + i] = 0;
1021 for (unsigned int i = 0; i < signal_count; i++) {
1022 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1023 const uint8_t in_sample = 1 &
1024 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1026 const uint8_t out_sample = output[out_sample_pos + bytepos];
1028 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1038 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1041 for (const uint8_t* data : signal_data)
1045 void DecodeSignal::logic_mux_proc()
1047 uint32_t segment_id = 0;
1049 assert(logic_mux_data_);
1051 // Create initial logic mux segment
1052 shared_ptr<LogicSegment> output_segment =
1053 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1054 logic_mux_unit_size_, 0);
1055 logic_mux_data_->push_segment(output_segment);
1057 output_segment->set_samplerate(get_input_samplerate(0));
1060 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1061 const uint64_t output_sample_count = output_segment->get_sample_count();
1063 const uint64_t samples_to_process =
1064 (input_sample_count > output_sample_count) ?
1065 (input_sample_count - output_sample_count) : 0;
1067 // Process the samples if necessary...
1068 if (samples_to_process > 0) {
1069 const uint64_t unit_size = output_segment->unit_size();
1070 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1072 uint64_t processed_samples = 0;
1074 const uint64_t start_sample = output_sample_count + processed_samples;
1075 const uint64_t sample_count =
1076 min(samples_to_process - processed_samples, chunk_sample_count);
1078 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1079 processed_samples += sample_count;
1081 // ...and process the newly muxed logic data
1082 decode_input_cond_.notify_one();
1083 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1086 if (samples_to_process == 0) {
1087 // TODO Optimize this by caching the input segment count and only
1088 // querying it when the cached value was reached
1089 if (segment_id < get_input_segment_count() - 1) {
1090 // Process next segment
1094 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1095 logic_mux_unit_size_, 0);
1096 logic_mux_data_->push_segment(output_segment);
1098 output_segment->set_samplerate(get_input_samplerate(segment_id));
1101 // All segments have been processed
1102 logic_mux_data_invalid_ = false;
1104 // Wait for more input
1105 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1106 logic_mux_cond_.wait(logic_mux_lock);
1110 } while (!logic_mux_interrupt_);
1113 void DecodeSignal::decode_data(
1114 const int64_t abs_start_samplenum, const int64_t sample_count,
1115 const shared_ptr<LogicSegment> input_segment)
1117 const int64_t unit_size = input_segment->unit_size();
1118 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1120 for (int64_t i = abs_start_samplenum;
1121 error_message_.isEmpty() && !decode_interrupt_ &&
1122 (i < (abs_start_samplenum + sample_count));
1123 i += chunk_sample_count) {
1125 const int64_t chunk_end = min(i + chunk_sample_count,
1126 abs_start_samplenum + sample_count);
1129 lock_guard<mutex> lock(output_mutex_);
1130 // Update the sample count showing the samples including currently processed ones
1131 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1134 int64_t data_size = (chunk_end - i) * unit_size;
1135 uint8_t* chunk = new uint8_t[data_size];
1136 input_segment->get_samples(i, chunk_end, chunk);
1138 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1139 data_size, unit_size) != SRD_OK)
1140 set_error_message(tr("Decoder reported an error"));
1145 lock_guard<mutex> lock(output_mutex_);
1146 // Now that all samples are processed, the exclusive sample count catches up
1147 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1150 // Notify the frontend that we processed some data and
1151 // possibly have new annotations as well
1154 if (decode_paused_) {
1155 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1156 decode_pause_cond_.wait(pause_wait_lock);
1161 void DecodeSignal::decode_proc()
1163 current_segment_id_ = 0;
1165 // If there is no input data available yet, wait until it is or we're interrupted
1166 if (logic_mux_data_->logic_segments().size() == 0) {
1167 unique_lock<mutex> input_wait_lock(input_mutex_);
1168 decode_input_cond_.wait(input_wait_lock);
1171 if (decode_interrupt_)
1174 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
1175 assert(input_segment);
1177 // Create the initial segment and set its sample rate so that we can pass it to SRD
1178 create_decode_segment();
1179 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1180 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1182 start_srd_session();
1184 uint64_t sample_count = 0;
1185 uint64_t abs_start_samplenum = 0;
1187 // Keep processing new samples until we exhaust the input data
1189 lock_guard<mutex> input_lock(input_mutex_);
1190 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
1192 if (sample_count > 0) {
1193 decode_data(abs_start_samplenum, sample_count, input_segment);
1194 abs_start_samplenum += sample_count;
1196 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1198 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1199 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1200 // Process next segment
1201 current_segment_id_++;
1204 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1205 } catch (out_of_range&) {
1206 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1207 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1208 << logic_mux_data_->logic_segments().size();
1211 abs_start_samplenum = 0;
1213 // Create the next segment and set its metadata
1214 create_decode_segment();
1215 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1216 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1218 // Reset decoder state but keep the decoder stack intact
1219 terminate_srd_session();
1221 // All segments have been processed
1224 // Wait for new input data or an interrupt was requested
1225 unique_lock<mutex> input_wait_lock(input_mutex_);
1226 decode_input_cond_.wait(input_wait_lock);
1229 } while (error_message_.isEmpty() && !decode_interrupt_);
1231 // Potentially reap decoders when the application no longer is
1232 // interested in their (pending) results.
1233 if (decode_interrupt_)
1234 terminate_srd_session();
1237 void DecodeSignal::start_srd_session()
1239 // If there were stack changes, the session has been destroyed by now, so if
1240 // it hasn't been destroyed, we can just reset and re-use it
1242 // When a decoder stack was created before, re-use it
1243 // for the next stream of input data, after terminating
1244 // potentially still executing operations, and resetting
1245 // internal state. Skip the rather expensive (teardown
1246 // and) construction of another decoder stack.
1248 // TODO Reduce redundancy, use a common code path for
1249 // the meta/start sequence?
1250 terminate_srd_session();
1252 // Metadata is cleared also, so re-set it
1253 uint64_t samplerate = 0;
1254 if (segments_.size() > 0)
1255 samplerate = segments_.at(current_segment_id_).samplerate;
1257 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1258 g_variant_new_uint64(samplerate));
1259 for (const shared_ptr<decode::Decoder>& dec : stack_)
1260 dec->apply_all_options();
1261 srd_session_start(srd_session_);
1266 // Create the session
1267 srd_session_new(&srd_session_);
1268 assert(srd_session_);
1270 // Create the decoders
1271 srd_decoder_inst *prev_di = nullptr;
1272 for (const shared_ptr<decode::Decoder>& dec : stack_) {
1273 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1276 set_error_message(tr("Failed to create decoder instance"));
1277 srd_session_destroy(srd_session_);
1278 srd_session_ = nullptr;
1283 srd_inst_stack(srd_session_, prev_di, di);
1288 // Start the session
1289 if (segments_.size() > 0)
1290 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1291 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1293 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1294 DecodeSignal::annotation_callback, this);
1296 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1297 DecodeSignal::binary_callback, this);
1299 srd_session_start(srd_session_);
1301 // We just recreated the srd session, so all stack changes are applied now
1302 stack_config_changed_ = false;
1305 void DecodeSignal::terminate_srd_session()
1307 // Call the "terminate and reset" routine for the decoder stack
1308 // (if available). This does not harm those stacks which already
1309 // have completed their operation, and reduces response time for
1310 // those stacks which still are processing data while the
1311 // application no longer wants them to.
1313 srd_session_terminate_reset(srd_session_);
1315 // Metadata is cleared also, so re-set it
1316 uint64_t samplerate = 0;
1317 if (segments_.size() > 0)
1318 samplerate = segments_.at(current_segment_id_).samplerate;
1320 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1321 g_variant_new_uint64(samplerate));
1322 for (const shared_ptr<decode::Decoder>& dec : stack_)
1323 dec->apply_all_options();
1327 void DecodeSignal::stop_srd_session()
1330 // Destroy the session
1331 srd_session_destroy(srd_session_);
1332 srd_session_ = nullptr;
1334 // Mark the decoder instances as non-existant since they were deleted
1335 for (const shared_ptr<decode::Decoder>& dec : stack_)
1336 dec->invalidate_decoder_inst();
1340 void DecodeSignal::connect_input_notifiers()
1342 // Disconnect the notification slot from the previous set of signals
1343 disconnect(this, SLOT(on_data_cleared()));
1344 disconnect(this, SLOT(on_data_received()));
1346 // Connect the currently used signals to our slot
1347 for (decode::DecodeChannel& ch : channels_) {
1348 if (!ch.assigned_signal)
1351 const data::SignalBase *signal = ch.assigned_signal;
1352 connect(signal, SIGNAL(samples_cleared()),
1353 this, SLOT(on_data_cleared()));
1354 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1355 this, SLOT(on_data_received()));
1359 void DecodeSignal::create_decode_segment()
1361 // Create annotation segment
1362 segments_.emplace_back(DecodeSegment());
1364 // Add annotation classes
1365 for (const shared_ptr<decode::Decoder>& dec : stack_) {
1367 const srd_decoder *const decc = dec->decoder();
1368 assert(dec->decoder());
1371 // Add a row for the decoder if it doesn't have a row list
1372 if (!decc->annotation_rows)
1373 (segments_.back().annotation_rows)[Row(row_index++, decc)] =
1376 // Add the decoder rows
1377 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1378 const srd_decoder_annotation_row *const ann_row =
1379 (srd_decoder_annotation_row *)l->data;
1382 const Row row(row_index++, decc, ann_row);
1384 // Add a new empty row data object
1385 (segments_.back().annotation_rows)[row] =
1390 // Prepare our binary output classes
1391 for (const shared_ptr<decode::Decoder>& dec : stack_) {
1392 uint32_t n = dec->get_binary_class_count();
1394 for (uint32_t i = 0; i < n; i++)
1395 segments_.back().binary_classes.push_back(
1396 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1400 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1403 assert(decode_signal);
1405 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1408 if (ds->decode_interrupt_)
1411 lock_guard<mutex> lock(ds->output_mutex_);
1413 // Get the decoder and the annotation data
1415 assert(pdata->pdo->di);
1416 const srd_decoder *const decc = pdata->pdo->di->decoder;
1419 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1423 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
1425 // Try finding a better row match than the default by looking up the sub-row of this class
1426 const auto format = pda->ann_class;
1427 const auto r = ds->class_rows_.find(make_pair(decc, format));
1428 if (r != ds->class_rows_.end())
1429 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
1431 // Failing that, use the decoder as a key
1432 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(0, decc));
1435 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
1436 qDebug() << "Unexpected annotation: decoder = " << decc <<
1437 ", format = " << format;
1442 // Add the annotation
1443 (*row_iter).second.emplace_annotation(pdata, &((*row_iter).first));
1446 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1449 assert(decode_signal);
1451 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1454 if (ds->decode_interrupt_)
1457 // Get the decoder and the binary data
1459 assert(pdata->pdo->di);
1460 const srd_decoder *const decc = pdata->pdo->di->decoder;
1463 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1466 // Find the matching DecodeBinaryClass
1467 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1469 DecodeBinaryClass* bin_class = nullptr;
1470 for (DecodeBinaryClass& bc : segment->binary_classes)
1471 if ((bc.decoder->decoder() == decc) && (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1475 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1476 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1477 ", segment only knows" << segment->binary_classes.size() << "classes";
1481 // Add the data chunk
1482 bin_class->chunks.emplace_back();
1483 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1485 chunk->sample = pdata->start_sample;
1486 chunk->data.resize(pdb->size);
1487 memcpy(chunk->data.data(), pdb->data, pdb->size);
1489 // Find decoder class instance
1490 Decoder* dec = nullptr;
1491 for (const shared_ptr<decode::Decoder>& d : ds->decoder_stack())
1492 if (d->decoder() == decc) {
1497 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1500 void DecodeSignal::on_capture_state_changed(int state)
1502 // If a new acquisition was started, we need to start decoding from scratch
1503 if (state == Session::Running) {
1504 logic_mux_data_invalid_ = true;
1509 void DecodeSignal::on_data_cleared()
1514 void DecodeSignal::on_data_received()
1516 // If we detected a lack of input data when trying to start decoding,
1517 // we have set an error message. Only try again if we now have data
1519 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1522 if (!logic_mux_thread_.joinable())
1525 logic_mux_cond_.notify_one();