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::lock_guard;
37 using std::make_shared;
39 using std::out_of_range;
40 using std::shared_ptr;
41 using std::unique_lock;
42 using pv::data::decode::AnnotationClass;
43 using pv::data::decode::DecodeChannel;
48 const double DecodeSignal::DecodeMargin = 1.0;
49 const double DecodeSignal::DecodeThreshold = 0.2;
50 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
53 DecodeSignal::DecodeSignal(pv::Session &session) :
54 SignalBase(nullptr, SignalBase::DecodeChannel),
56 srd_session_(nullptr),
57 logic_mux_data_invalid_(false),
58 stack_config_changed_(true),
59 current_segment_id_(0)
61 connect(&session_, SIGNAL(capture_state_changed(int)),
62 this, SLOT(on_capture_state_changed(int)));
65 DecodeSignal::~DecodeSignal()
70 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
75 void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
79 // Set name if this decoder is the first in the list or the name is unchanged
80 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
81 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
83 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
84 set_name(QString::fromUtf8(decoder->name));
86 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder, stack_.size());
87 stack_.push_back(dec);
89 // Include the newly created decode channels in the channel lists
90 update_channel_list();
92 stack_config_changed_ = true;
93 auto_assign_signals(dec);
94 commit_decoder_channels();
96 decoder_stacked((void*)dec.get());
102 void DecodeSignal::remove_decoder(int index)
105 assert(index < (int)stack_.size());
107 // Find the decoder in the stack
108 auto iter = stack_.begin();
109 for (int i = 0; i < index; i++, iter++)
110 assert(iter != stack_.end());
112 decoder_removed(iter->get());
114 // Delete the element
117 // Update channels and decoded data
118 stack_config_changed_ = true;
119 update_channel_list();
123 bool DecodeSignal::toggle_decoder_visibility(int index)
125 auto iter = stack_.cbegin();
126 for (int i = 0; i < index; i++, iter++)
127 assert(iter != stack_.end());
129 shared_ptr<Decoder> dec = *iter;
131 // Toggle decoder visibility
134 state = !dec->visible();
135 dec->set_visible(state);
141 void DecodeSignal::reset_decode(bool shutting_down)
143 resume_decode(); // Make sure the decode thread isn't blocked by pausing
145 if (stack_config_changed_ || shutting_down)
148 terminate_srd_session();
150 if (decode_thread_.joinable()) {
151 decode_interrupt_ = true;
152 decode_input_cond_.notify_one();
153 decode_thread_.join();
156 if (logic_mux_thread_.joinable()) {
157 logic_mux_interrupt_ = true;
158 logic_mux_cond_.notify_one();
159 logic_mux_thread_.join();
162 current_segment_id_ = 0;
165 logic_mux_data_.reset();
166 logic_mux_data_invalid_ = true;
168 if (!error_message_.isEmpty()) {
169 error_message_ = QString();
170 // TODO Emulate noquote()
171 qDebug().nospace() << name() << ": Error cleared";
177 void DecodeSignal::begin_decode()
179 if (decode_thread_.joinable()) {
180 decode_interrupt_ = true;
181 decode_input_cond_.notify_one();
182 decode_thread_.join();
185 if (logic_mux_thread_.joinable()) {
186 logic_mux_interrupt_ = true;
187 logic_mux_cond_.notify_one();
188 logic_mux_thread_.join();
193 if (stack_.size() == 0) {
194 set_error_message(tr("No decoders"));
198 assert(channels_.size() > 0);
200 if (get_assigned_signal_count() == 0) {
201 set_error_message(tr("There are no channels assigned to this decoder"));
205 // Make sure that all assigned channels still provide logic data
206 // (can happen when a converted signal was assigned but the
207 // conversion removed in the meanwhile)
208 for (decode::DecodeChannel& ch : channels_)
209 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
210 ch.assigned_signal = nullptr;
212 // Check that all decoders have the required channels
213 for (const shared_ptr<Decoder>& dec : stack_)
214 if (!dec->have_required_channels()) {
215 set_error_message(tr("One or more required channels "
216 "have not been specified"));
220 // Free the logic data and its segment(s) if it needs to be updated
221 if (logic_mux_data_invalid_)
222 logic_mux_data_.reset();
224 if (!logic_mux_data_) {
225 const uint32_t ch_count = get_assigned_signal_count();
226 logic_mux_unit_size_ = (ch_count + 7) / 8;
227 logic_mux_data_ = make_shared<Logic>(ch_count);
230 // Receive notifications when new sample data is available
231 connect_input_notifiers();
233 if (get_input_segment_count() == 0) {
234 set_error_message(tr("No input data"));
238 // Make sure the logic output data is complete and up-to-date
239 logic_mux_interrupt_ = false;
240 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
242 // Decode the muxed logic data
243 decode_interrupt_ = false;
244 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
247 void DecodeSignal::pause_decode()
249 decode_paused_ = true;
252 void DecodeSignal::resume_decode()
254 // Manual unlocking is done before notifying, to avoid waking up the
255 // waiting thread only to block again (see notify_one for details)
256 decode_pause_mutex_.unlock();
257 decode_pause_cond_.notify_one();
258 decode_paused_ = false;
261 bool DecodeSignal::is_paused() const
263 return decode_paused_;
266 QString DecodeSignal::error_message() const
268 lock_guard<mutex> lock(output_mutex_);
269 return error_message_;
272 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
277 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
279 bool new_assignment = false;
281 // Try to auto-select channels that don't have signals assigned yet
282 for (decode::DecodeChannel& ch : channels_) {
283 // If a decoder is given, auto-assign only its channels
284 if (dec && (ch.decoder_ != dec))
287 if (ch.assigned_signal)
290 QString ch_name = ch.name.toLower();
291 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
293 shared_ptr<data::SignalBase> match;
294 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
298 QString s_name = s->name().toLower();
299 s_name = s_name.replace(QRegExp("[-_.]"), " ");
301 if (s->logic_data() &&
302 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
306 // Only replace an existing match if it matches more characters
307 int old_unmatched = ch_name.length() - match->name().length();
308 int new_unmatched = ch_name.length() - s->name().length();
309 if (abs(new_unmatched) < abs(old_unmatched))
316 ch.assigned_signal = match.get();
317 new_assignment = true;
321 if (new_assignment) {
322 logic_mux_data_invalid_ = true;
323 stack_config_changed_ = true;
324 commit_decoder_channels();
329 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
331 for (decode::DecodeChannel& ch : channels_)
332 if (ch.id == channel_id) {
333 ch.assigned_signal = signal;
334 logic_mux_data_invalid_ = true;
337 stack_config_changed_ = true;
338 commit_decoder_channels();
343 int DecodeSignal::get_assigned_signal_count() const
345 // Count all channels that have a signal assigned to them
346 return count_if(channels_.begin(), channels_.end(),
347 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
350 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
352 for (decode::DecodeChannel& ch : channels_)
353 if (ch.id == channel_id)
354 ch.initial_pin_state = init_state;
356 stack_config_changed_ = true;
361 double DecodeSignal::get_samplerate() const
365 // TODO For now, we simply return the first samplerate that we have
366 if (segments_.size() > 0)
367 result = segments_.front().samplerate;
372 const pv::util::Timestamp DecodeSignal::start_time() const
374 pv::util::Timestamp result;
376 // TODO For now, we simply return the first start time that we have
377 if (segments_.size() > 0)
378 result = segments_.front().start_time;
383 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
385 // The working sample count is the highest sample number for
386 // which all used signals have data available, so go through all
387 // channels and use the lowest overall sample count of the segment
389 int64_t count = std::numeric_limits<int64_t>::max();
390 bool no_signals_assigned = true;
392 for (const decode::DecodeChannel& ch : channels_)
393 if (ch.assigned_signal) {
394 no_signals_assigned = false;
396 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
397 if (!logic_data || logic_data->logic_segments().empty())
401 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
402 count = min(count, (int64_t)segment->get_sample_count());
403 } catch (out_of_range&) {
408 return (no_signals_assigned ? 0 : count);
411 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
412 bool include_processing) const
414 lock_guard<mutex> decode_lock(output_mutex_);
418 if (segment_id >= segments_.size())
421 if (include_processing)
422 result = segments_[segment_id].samples_decoded_incl;
424 result = segments_[segment_id].samples_decoded_excl;
429 vector<Row*> DecodeSignal::get_rows(bool visible_only)
433 for (const shared_ptr<Decoder>& dec : stack_) {
435 if (visible_only && !dec->visible())
438 for (Row* row : dec->get_rows())
445 vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
447 vector<const Row*> rows;
449 for (const shared_ptr<Decoder>& dec : stack_) {
451 if (visible_only && !dec->visible())
454 for (const Row* row : dec->get_rows())
462 uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
464 if (segment_id >= segments_.size())
467 const DecodeSegment* segment = &(segments_.at(segment_id));
469 auto row_it = segment->annotation_rows.find(row);
472 if (row_it == segment->annotation_rows.end())
475 rd = &(row_it->second);
477 return rd->get_annotation_count();
480 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
481 const Row* row, uint32_t segment_id, uint64_t start_sample,
482 uint64_t end_sample) const
484 lock_guard<mutex> lock(output_mutex_);
486 if (segment_id >= segments_.size())
489 const DecodeSegment* segment = &(segments_.at(segment_id));
491 auto row_it = segment->annotation_rows.find(row);
494 if (row_it == segment->annotation_rows.end())
497 rd = &(row_it->second);
499 rd->get_annotation_subset(dest, start_sample, end_sample);
502 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
503 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
505 for (const Row* row : get_rows())
506 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
509 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
510 const Decoder* dec, uint32_t bin_class_id) const
512 if (segments_.size() == 0)
516 const DecodeSegment *segment = &(segments_.at(segment_id));
518 for (const DecodeBinaryClass& bc : segment->binary_classes)
519 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
520 return bc.chunks.size();
521 } catch (out_of_range&) {
528 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
529 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
530 const vector<uint8_t> **dest, uint64_t *size)
533 const DecodeSegment *segment = &(segments_.at(segment_id));
535 for (const DecodeBinaryClass& bc : segment->binary_classes)
536 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
537 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
538 if (size) *size = bc.chunks.at(chunk_id).data.size();
541 } catch (out_of_range&) {
546 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
547 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
548 uint64_t end_sample, vector<uint8_t> *dest) const
550 assert(dest != nullptr);
553 const DecodeSegment *segment = &(segments_.at(segment_id));
555 const DecodeBinaryClass* bin_class = nullptr;
556 for (const DecodeBinaryClass& bc : segment->binary_classes)
557 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
560 // Determine overall size before copying to resize dest vector only once
562 uint64_t matches = 0;
563 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
564 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
565 size += chunk.data.size();
571 uint64_t matches2 = 0;
572 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
573 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
574 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
575 offset += chunk.data.size();
578 // Make sure we don't overwrite memory if the array grew in the meanwhile
579 if (matches2 == matches)
582 } catch (out_of_range&) {
587 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
588 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
589 vector<uint8_t> *dest) const
591 assert(dest != nullptr);
594 const DecodeSegment *segment = &(segments_.at(segment_id));
596 const DecodeBinaryClass* bin_class = nullptr;
597 for (const DecodeBinaryClass& bc : segment->binary_classes)
598 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
601 // Determine overall size before copying to resize dest vector only once
604 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
606 size += chunk.data.size();
607 offset += chunk.data.size();
614 uint64_t dest_offset = 0;
615 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
616 if (offset >= start) {
617 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
618 dest_offset += chunk.data.size();
620 offset += chunk.data.size();
624 } catch (out_of_range&) {
629 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
630 const Decoder* dec, uint32_t bin_class_id) const
633 const DecodeSegment *segment = &(segments_.at(segment_id));
635 for (const DecodeBinaryClass& bc : segment->binary_classes)
636 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
638 } catch (out_of_range&) {
645 const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
646 uint32_t segment_id) const
649 const DecodeSegment *segment = &(segments_.at(segment_id));
650 return &(segment->all_annotations);
651 } catch (out_of_range&) {
658 void DecodeSignal::save_settings(QSettings &settings) const
660 SignalBase::save_settings(settings);
662 settings.setValue("decoders", (int)(stack_.size()));
664 // Save decoder stack
666 for (const shared_ptr<Decoder>& decoder : stack_) {
667 settings.beginGroup("decoder" + QString::number(decoder_idx++));
669 settings.setValue("id", decoder->get_srd_decoder()->id);
670 settings.setValue("visible", decoder->visible());
672 // Save decoder options
673 const map<string, GVariant*>& options = decoder->options();
675 settings.setValue("options", (int)options.size());
677 // Note: Decoder::options() returns only the options
678 // that differ from the default. See binding::Decoder::getter()
680 for (auto& option : options) {
681 settings.beginGroup("option" + QString::number(i));
682 settings.setValue("name", QString::fromStdString(option.first));
683 GlobalSettings::store_gvariant(settings, option.second);
688 // Save row properties
690 for (const Row* row : decoder->get_rows()) {
691 settings.beginGroup("row" + QString::number(i));
692 settings.setValue("visible", row->visible());
697 // Save class properties
699 for (const AnnotationClass* ann_class : decoder->ann_classes()) {
700 settings.beginGroup("ann_class" + QString::number(i));
701 settings.setValue("visible", ann_class->visible);
709 // Save channel mapping
710 settings.setValue("channels", (int)channels_.size());
712 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
713 auto channel = find_if(channels_.begin(), channels_.end(),
714 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
716 if (channel == channels_.end()) {
717 qDebug() << "ERROR: Gap in channel index:" << channel_id;
721 settings.beginGroup("channel" + QString::number(channel_id));
723 settings.setValue("name", channel->name); // Useful for debugging
724 settings.setValue("initial_pin_state", channel->initial_pin_state);
726 if (channel->assigned_signal)
727 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
733 void DecodeSignal::restore_settings(QSettings &settings)
735 SignalBase::restore_settings(settings);
737 // Restore decoder stack
738 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
740 int decoders = settings.value("decoders").toInt();
742 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
743 settings.beginGroup("decoder" + QString::number(decoder_idx));
745 QString id = settings.value("id").toString();
747 for (GSList *entry = dec_list; entry; entry = entry->next) {
748 const srd_decoder *dec = (srd_decoder*)entry->data;
752 if (QString::fromUtf8(dec->id) == id) {
753 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec, stack_.size());
755 stack_.push_back(decoder);
756 decoder->set_visible(settings.value("visible", true).toBool());
758 // Restore decoder options that differ from their default
759 int options = settings.value("options").toInt();
761 for (int i = 0; i < options; i++) {
762 settings.beginGroup("option" + QString::number(i));
763 QString name = settings.value("name").toString();
764 GVariant *value = GlobalSettings::restore_gvariant(settings);
765 decoder->set_option(name.toUtf8(), value);
769 // Include the newly created decode channels in the channel lists
770 update_channel_list();
772 // Restore row properties
774 for (Row* row : decoder->get_rows()) {
775 settings.beginGroup("row" + QString::number(i));
776 row->set_visible(settings.value("visible", true).toBool());
781 // Restore class properties
783 for (AnnotationClass* ann_class : decoder->ann_classes()) {
784 settings.beginGroup("ann_class" + QString::number(i));
785 ann_class->visible = settings.value("visible", true).toBool();
798 // Restore channel mapping
799 unsigned int channels = settings.value("channels").toInt();
801 const vector< shared_ptr<data::SignalBase> > signalbases =
802 session_.signalbases();
804 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
805 auto channel = find_if(channels_.begin(), channels_.end(),
806 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
808 if (channel == channels_.end()) {
809 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
813 settings.beginGroup("channel" + QString::number(channel_id));
815 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
817 for (const shared_ptr<data::SignalBase>& signal : signalbases)
818 if (signal->name() == assigned_signal_name)
819 channel->assigned_signal = signal.get();
821 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
826 // Update the internal structures
827 stack_config_changed_ = true;
828 update_channel_list();
829 commit_decoder_channels();
834 void DecodeSignal::set_error_message(QString msg)
836 error_message_ = msg;
837 // TODO Emulate noquote()
838 qDebug().nospace() << name() << ": " << msg;
841 uint32_t DecodeSignal::get_input_segment_count() const
843 uint64_t count = std::numeric_limits<uint64_t>::max();
844 bool no_signals_assigned = true;
846 for (const decode::DecodeChannel& ch : channels_)
847 if (ch.assigned_signal) {
848 no_signals_assigned = false;
850 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
851 if (!logic_data || logic_data->logic_segments().empty())
854 // Find the min value of all segment counts
855 if ((uint64_t)(logic_data->logic_segments().size()) < count)
856 count = logic_data->logic_segments().size();
859 return (no_signals_assigned ? 0 : count);
862 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
864 double samplerate = 0;
866 for (const decode::DecodeChannel& ch : channels_)
867 if (ch.assigned_signal) {
868 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
869 if (!logic_data || logic_data->logic_segments().empty())
873 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
874 samplerate = segment->samplerate();
875 } catch (out_of_range&) {
884 Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
886 for (shared_ptr<Decoder>& d : stack_)
887 if (d->get_srd_decoder() == srd_dec)
893 void DecodeSignal::update_channel_list()
895 vector<decode::DecodeChannel> prev_channels = channels_;
900 // Copy existing entries, create new as needed
901 for (shared_ptr<Decoder>& decoder : stack_) {
902 const srd_decoder* srd_dec = decoder->get_srd_decoder();
905 // Mandatory channels
906 for (l = srd_dec->channels; l; l = l->next) {
907 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
908 bool ch_added = false;
910 // Copy but update ID if this channel was in the list before
911 for (decode::DecodeChannel& ch : prev_channels)
912 if (ch.pdch_ == pdch) {
914 channels_.push_back(ch);
920 // Create new entry without a mapped signal
921 decode::DecodeChannel ch = {id++, 0, false, nullptr,
922 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
923 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
924 channels_.push_back(ch);
929 for (l = srd_dec->opt_channels; l; l = l->next) {
930 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
931 bool ch_added = false;
933 // Copy but update ID if this channel was in the list before
934 for (decode::DecodeChannel& ch : prev_channels)
935 if (ch.pdch_ == pdch) {
937 channels_.push_back(ch);
943 // Create new entry without a mapped signal
944 decode::DecodeChannel ch = {id++, 0, true, nullptr,
945 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
946 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
947 channels_.push_back(ch);
952 // Invalidate the logic output data if the channel assignment changed
953 if (prev_channels.size() != channels_.size()) {
954 // The number of channels changed, there's definitely a difference
955 logic_mux_data_invalid_ = true;
957 // Same number but assignment may still differ, so compare all channels
958 for (size_t i = 0; i < channels_.size(); i++) {
959 const decode::DecodeChannel& p_ch = prev_channels[i];
960 const decode::DecodeChannel& ch = channels_[i];
962 if ((p_ch.pdch_ != ch.pdch_) ||
963 (p_ch.assigned_signal != ch.assigned_signal)) {
964 logic_mux_data_invalid_ = true;
974 void DecodeSignal::commit_decoder_channels()
976 // Submit channel list to every decoder, containing only the relevant channels
977 for (shared_ptr<Decoder> dec : stack_) {
978 vector<decode::DecodeChannel*> channel_list;
980 for (decode::DecodeChannel& ch : channels_)
981 if (ch.decoder_ == dec)
982 channel_list.push_back(&ch);
984 dec->set_channels(channel_list);
987 // Channel bit IDs must be in sync with the channel's apperance in channels_
989 for (decode::DecodeChannel& ch : channels_)
990 if (ch.assigned_signal)
994 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
996 // Enforce end to be greater than start
1000 // Fetch the channel segments and their data
1001 vector<shared_ptr<LogicSegment> > segments;
1002 vector<const uint8_t*> signal_data;
1003 vector<uint8_t> signal_in_bytepos;
1004 vector<uint8_t> signal_in_bitpos;
1006 for (decode::DecodeChannel& ch : channels_)
1007 if (ch.assigned_signal) {
1008 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1010 shared_ptr<LogicSegment> segment;
1012 segment = logic_data->logic_segments().at(segment_id);
1013 } catch (out_of_range&) {
1014 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1015 << "has no logic segment" << segment_id;
1018 segments.push_back(segment);
1020 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1021 segment->get_samples(start, end, data);
1022 signal_data.push_back(data);
1024 const int bitpos = ch.assigned_signal->logic_bit_index();
1025 signal_in_bytepos.push_back(bitpos / 8);
1026 signal_in_bitpos.push_back(bitpos % 8);
1030 shared_ptr<LogicSegment> output_segment;
1032 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1033 } catch (out_of_range&) {
1034 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1035 << segment_id << "in mux_logic_samples(), mux segments size is" \
1036 << logic_mux_data_->logic_segments().size();
1040 // Perform the muxing of signal data into the output data
1041 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1042 unsigned int signal_count = signal_data.size();
1044 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1048 uint8_t bytepos = 0;
1050 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1051 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1052 output[out_sample_pos + i] = 0;
1054 for (unsigned int i = 0; i < signal_count; i++) {
1055 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1056 const uint8_t in_sample = 1 &
1057 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1059 const uint8_t out_sample = output[out_sample_pos + bytepos];
1061 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1071 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1074 for (const uint8_t* data : signal_data)
1078 void DecodeSignal::logic_mux_proc()
1080 uint32_t segment_id = 0;
1082 assert(logic_mux_data_);
1084 // Create initial logic mux segment
1085 shared_ptr<LogicSegment> output_segment =
1086 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1087 logic_mux_unit_size_, 0);
1088 logic_mux_data_->push_segment(output_segment);
1090 output_segment->set_samplerate(get_input_samplerate(0));
1093 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1094 const uint64_t output_sample_count = output_segment->get_sample_count();
1096 const uint64_t samples_to_process =
1097 (input_sample_count > output_sample_count) ?
1098 (input_sample_count - output_sample_count) : 0;
1100 // Process the samples if necessary...
1101 if (samples_to_process > 0) {
1102 const uint64_t unit_size = output_segment->unit_size();
1103 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1105 uint64_t processed_samples = 0;
1107 const uint64_t start_sample = output_sample_count + processed_samples;
1108 const uint64_t sample_count =
1109 min(samples_to_process - processed_samples, chunk_sample_count);
1111 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1112 processed_samples += sample_count;
1114 // ...and process the newly muxed logic data
1115 decode_input_cond_.notify_one();
1116 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1119 if (samples_to_process == 0) {
1120 // TODO Optimize this by caching the input segment count and only
1121 // querying it when the cached value was reached
1122 if (segment_id < get_input_segment_count() - 1) {
1123 // Process next segment
1127 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1128 logic_mux_unit_size_, 0);
1129 logic_mux_data_->push_segment(output_segment);
1131 output_segment->set_samplerate(get_input_samplerate(segment_id));
1134 // All segments have been processed
1135 logic_mux_data_invalid_ = false;
1137 // Wait for more input
1138 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1139 logic_mux_cond_.wait(logic_mux_lock);
1143 } while (!logic_mux_interrupt_);
1146 void DecodeSignal::decode_data(
1147 const int64_t abs_start_samplenum, const int64_t sample_count,
1148 const shared_ptr<LogicSegment> input_segment)
1150 const int64_t unit_size = input_segment->unit_size();
1151 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1153 for (int64_t i = abs_start_samplenum;
1154 error_message_.isEmpty() && !decode_interrupt_ &&
1155 (i < (abs_start_samplenum + sample_count));
1156 i += chunk_sample_count) {
1158 const int64_t chunk_end = min(i + chunk_sample_count,
1159 abs_start_samplenum + sample_count);
1162 lock_guard<mutex> lock(output_mutex_);
1163 // Update the sample count showing the samples including currently processed ones
1164 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1167 int64_t data_size = (chunk_end - i) * unit_size;
1168 uint8_t* chunk = new uint8_t[data_size];
1169 input_segment->get_samples(i, chunk_end, chunk);
1171 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1172 data_size, unit_size) != SRD_OK)
1173 set_error_message(tr("Decoder reported an error"));
1178 lock_guard<mutex> lock(output_mutex_);
1179 // Now that all samples are processed, the exclusive sample count catches up
1180 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1183 // Notify the frontend that we processed some data and
1184 // possibly have new annotations as well
1187 if (decode_paused_) {
1188 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1189 decode_pause_cond_.wait(pause_wait_lock);
1194 void DecodeSignal::decode_proc()
1196 current_segment_id_ = 0;
1198 // If there is no input data available yet, wait until it is or we're interrupted
1199 if (logic_mux_data_->logic_segments().size() == 0) {
1200 unique_lock<mutex> input_wait_lock(input_mutex_);
1201 decode_input_cond_.wait(input_wait_lock);
1204 if (decode_interrupt_)
1207 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
1208 assert(input_segment);
1210 // Create the initial segment and set its sample rate so that we can pass it to SRD
1211 create_decode_segment();
1212 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1213 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1215 start_srd_session();
1217 uint64_t sample_count = 0;
1218 uint64_t abs_start_samplenum = 0;
1220 // Keep processing new samples until we exhaust the input data
1222 lock_guard<mutex> input_lock(input_mutex_);
1223 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
1225 if (sample_count > 0) {
1226 decode_data(abs_start_samplenum, sample_count, input_segment);
1227 abs_start_samplenum += sample_count;
1229 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1231 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1232 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1233 // Process next segment
1234 current_segment_id_++;
1237 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1238 } catch (out_of_range&) {
1239 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1240 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1241 << logic_mux_data_->logic_segments().size();
1244 abs_start_samplenum = 0;
1246 // Create the next segment and set its metadata
1247 create_decode_segment();
1248 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1249 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1251 // Reset decoder state but keep the decoder stack intact
1252 terminate_srd_session();
1254 // All segments have been processed
1257 // Wait for new input data or an interrupt was requested
1258 unique_lock<mutex> input_wait_lock(input_mutex_);
1259 decode_input_cond_.wait(input_wait_lock);
1262 } while (error_message_.isEmpty() && !decode_interrupt_);
1264 // Potentially reap decoders when the application no longer is
1265 // interested in their (pending) results.
1266 if (decode_interrupt_)
1267 terminate_srd_session();
1270 void DecodeSignal::start_srd_session()
1272 // If there were stack changes, the session has been destroyed by now, so if
1273 // it hasn't been destroyed, we can just reset and re-use it
1275 // When a decoder stack was created before, re-use it
1276 // for the next stream of input data, after terminating
1277 // potentially still executing operations, and resetting
1278 // internal state. Skip the rather expensive (teardown
1279 // and) construction of another decoder stack.
1281 // TODO Reduce redundancy, use a common code path for
1282 // the meta/start sequence?
1283 terminate_srd_session();
1285 // Metadata is cleared also, so re-set it
1286 uint64_t samplerate = 0;
1287 if (segments_.size() > 0)
1288 samplerate = segments_.at(current_segment_id_).samplerate;
1290 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1291 g_variant_new_uint64(samplerate));
1292 for (const shared_ptr<Decoder>& dec : stack_)
1293 dec->apply_all_options();
1294 srd_session_start(srd_session_);
1299 // Create the session
1300 srd_session_new(&srd_session_);
1301 assert(srd_session_);
1303 // Create the decoders
1304 srd_decoder_inst *prev_di = nullptr;
1305 for (const shared_ptr<Decoder>& dec : stack_) {
1306 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1309 set_error_message(tr("Failed to create decoder instance"));
1310 srd_session_destroy(srd_session_);
1311 srd_session_ = nullptr;
1316 srd_inst_stack(srd_session_, prev_di, di);
1321 // Start the session
1322 if (segments_.size() > 0)
1323 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1324 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1326 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1327 DecodeSignal::annotation_callback, this);
1329 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1330 DecodeSignal::binary_callback, this);
1332 srd_session_start(srd_session_);
1334 // We just recreated the srd session, so all stack changes are applied now
1335 stack_config_changed_ = false;
1338 void DecodeSignal::terminate_srd_session()
1340 // Call the "terminate and reset" routine for the decoder stack
1341 // (if available). This does not harm those stacks which already
1342 // have completed their operation, and reduces response time for
1343 // those stacks which still are processing data while the
1344 // application no longer wants them to.
1346 srd_session_terminate_reset(srd_session_);
1348 // Metadata is cleared also, so re-set it
1349 uint64_t samplerate = 0;
1350 if (segments_.size() > 0)
1351 samplerate = segments_.at(current_segment_id_).samplerate;
1353 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1354 g_variant_new_uint64(samplerate));
1355 for (const shared_ptr<Decoder>& dec : stack_)
1356 dec->apply_all_options();
1360 void DecodeSignal::stop_srd_session()
1363 // Destroy the session
1364 srd_session_destroy(srd_session_);
1365 srd_session_ = nullptr;
1367 // Mark the decoder instances as non-existant since they were deleted
1368 for (const shared_ptr<Decoder>& dec : stack_)
1369 dec->invalidate_decoder_inst();
1373 void DecodeSignal::connect_input_notifiers()
1375 // Disconnect the notification slot from the previous set of signals
1376 disconnect(this, SLOT(on_data_cleared()));
1377 disconnect(this, SLOT(on_data_received()));
1379 // Connect the currently used signals to our slot
1380 for (decode::DecodeChannel& ch : channels_) {
1381 if (!ch.assigned_signal)
1384 const data::SignalBase *signal = ch.assigned_signal;
1385 connect(signal, SIGNAL(samples_cleared()),
1386 this, SLOT(on_data_cleared()));
1387 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1388 this, SLOT(on_data_received()));
1392 void DecodeSignal::create_decode_segment()
1394 // Create annotation segment
1395 segments_.emplace_back();
1397 // Add annotation classes
1398 for (const shared_ptr<Decoder>& dec : stack_)
1399 for (Row* row : dec->get_rows())
1400 segments_.back().annotation_rows.emplace(row, RowData(row));
1402 // Prepare our binary output classes
1403 for (const shared_ptr<Decoder>& dec : stack_) {
1404 uint32_t n = dec->get_binary_class_count();
1406 for (uint32_t i = 0; i < n; i++)
1407 segments_.back().binary_classes.push_back(
1408 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1412 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1415 assert(decode_signal);
1417 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1420 if (ds->decode_interrupt_)
1423 if (ds->segments_.empty())
1426 lock_guard<mutex> lock(ds->output_mutex_);
1428 // Get the decoder and the annotation data
1430 assert(pdata->pdo->di);
1431 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1434 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1438 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1441 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1443 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1444 "with class ID" << pda->ann_class << "but there are only" <<
1445 dec->ann_classes().size() << "known classes";
1449 const Row* row = ann_class->row;
1452 row = dec->get_row_by_id(0);
1454 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1456 // Add the annotation to the row
1457 const Annotation* ann = row_data.emplace_annotation(pdata);
1459 // We insert the annotation into the global annotation list in a way so that
1460 // the annotation list is sorted by start sample and length. Otherwise, we'd
1461 // have to sort the model, which is expensive
1462 deque<const Annotation*>& all_annotations =
1463 ds->segments_[ds->current_segment_id_].all_annotations;
1465 if (all_annotations.empty()) {
1466 all_annotations.emplace_back(ann);
1468 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1469 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1470 bool ann_is_longer = (new_ann_len >
1471 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1473 if (ann_has_earlier_start && ann_is_longer) {
1474 bool ann_has_same_start;
1475 auto it = all_annotations.end();
1479 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1480 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
1481 ann_is_longer = (new_ann_len > (*it)->length());
1482 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1484 // Allow inserting at the front
1485 if (it != all_annotations.begin())
1488 all_annotations.emplace(it, ann);
1490 all_annotations.emplace_back(ann);
1493 // When emplace_annotation() inserts instead of appends an annotation,
1494 // the pointers in all_annotations that follow the inserted annotation and
1495 // point to annotations for this row are off by one and must be updated
1496 if (&(row_data.annotations().back()) != ann) {
1497 // Search backwards until we find the annotation we just added
1498 auto row_it = row_data.annotations().end();
1499 auto all_it = all_annotations.end();
1502 if ((*all_it)->row_data() == &row_data)
1504 } while (&(*row_it) != ann);
1506 // Update the annotation addresses for this row's annotations until the end
1508 if ((*all_it)->row_data() == &row_data) {
1509 *all_it = &(*row_it);
1513 } while (all_it != all_annotations.end());
1517 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1520 assert(decode_signal);
1522 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1525 if (ds->decode_interrupt_)
1528 // Get the decoder and the binary data
1530 assert(pdata->pdo->di);
1531 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1534 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1537 // Find the matching DecodeBinaryClass
1538 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1540 DecodeBinaryClass* bin_class = nullptr;
1541 for (DecodeBinaryClass& bc : segment->binary_classes)
1542 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1543 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1547 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1548 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1549 ", segment only knows" << segment->binary_classes.size() << "classes";
1553 // Add the data chunk
1554 bin_class->chunks.emplace_back();
1555 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1557 chunk->sample = pdata->start_sample;
1558 chunk->data.resize(pdb->size);
1559 memcpy(chunk->data.data(), pdb->data, pdb->size);
1561 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1563 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1566 void DecodeSignal::on_capture_state_changed(int state)
1568 // If a new acquisition was started, we need to start decoding from scratch
1569 if (state == Session::Running) {
1570 logic_mux_data_invalid_ = true;
1575 void DecodeSignal::on_data_cleared()
1580 void DecodeSignal::on_data_received()
1582 // If we detected a lack of input data when trying to start decoding,
1583 // we have set an error message. Only try again if we now have data
1585 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1588 if (!logic_mux_thread_.joinable())
1591 logic_mux_cond_.notify_one();