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::AnnotationClass;
45 using pv::data::decode::DecodeChannel;
50 const double DecodeSignal::DecodeMargin = 1.0;
51 const double DecodeSignal::DecodeThreshold = 0.2;
52 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
55 DecodeSignal::DecodeSignal(pv::Session &session) :
56 SignalBase(nullptr, SignalBase::DecodeChannel),
58 srd_session_(nullptr),
59 logic_mux_data_invalid_(false),
60 stack_config_changed_(true),
61 current_segment_id_(0)
63 connect(&session_, SIGNAL(capture_state_changed(int)),
64 this, SLOT(on_capture_state_changed(int)));
67 DecodeSignal::~DecodeSignal()
72 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
77 void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
81 // Set name if this decoder is the first in the list or the name is unchanged
82 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
83 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
85 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
86 set_name(QString::fromUtf8(decoder->name));
88 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder);
89 stack_.push_back(dec);
91 // Include the newly created decode channels in the channel lists
92 update_channel_list();
94 stack_config_changed_ = true;
95 auto_assign_signals(dec);
96 commit_decoder_channels();
98 decoder_stacked((void*)dec.get());
104 void DecodeSignal::remove_decoder(int index)
107 assert(index < (int)stack_.size());
109 // Find the decoder in the stack
110 auto iter = stack_.begin();
111 for (int i = 0; i < index; i++, iter++)
112 assert(iter != stack_.end());
114 decoder_removed(iter->get());
116 // Delete the element
119 // Update channels and decoded data
120 stack_config_changed_ = true;
121 update_channel_list();
125 bool DecodeSignal::toggle_decoder_visibility(int index)
127 auto iter = stack_.cbegin();
128 for (int i = 0; i < index; i++, iter++)
129 assert(iter != stack_.end());
131 shared_ptr<Decoder> dec = *iter;
133 // Toggle decoder visibility
136 state = !dec->visible();
137 dec->set_visible(state);
143 void DecodeSignal::reset_decode(bool shutting_down)
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 resume_decode(); // Make sure the decode thread isn't blocked by pausing
164 current_segment_id_ = 0;
167 logic_mux_data_.reset();
168 logic_mux_data_invalid_ = true;
170 if (!error_message_.isEmpty()) {
171 error_message_ = QString();
172 // TODO Emulate noquote()
173 qDebug().nospace() << name() << ": Error cleared";
179 void DecodeSignal::begin_decode()
181 if (decode_thread_.joinable()) {
182 decode_interrupt_ = true;
183 decode_input_cond_.notify_one();
184 decode_thread_.join();
187 if (logic_mux_thread_.joinable()) {
188 logic_mux_interrupt_ = true;
189 logic_mux_cond_.notify_one();
190 logic_mux_thread_.join();
195 if (stack_.size() == 0) {
196 set_error_message(tr("No decoders"));
200 assert(channels_.size() > 0);
202 if (get_assigned_signal_count() == 0) {
203 set_error_message(tr("There are no channels assigned to this decoder"));
207 // Make sure that all assigned channels still provide logic data
208 // (can happen when a converted signal was assigned but the
209 // conversion removed in the meanwhile)
210 for (decode::DecodeChannel& ch : channels_)
211 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
212 ch.assigned_signal = nullptr;
214 // Check that all decoders have the required channels
215 for (const shared_ptr<Decoder>& dec : stack_)
216 if (!dec->have_required_channels()) {
217 set_error_message(tr("One or more required channels "
218 "have not been specified"));
222 // Free the logic data and its segment(s) if it needs to be updated
223 if (logic_mux_data_invalid_)
224 logic_mux_data_.reset();
226 if (!logic_mux_data_) {
227 const uint32_t ch_count = get_assigned_signal_count();
228 logic_mux_unit_size_ = (ch_count + 7) / 8;
229 logic_mux_data_ = make_shared<Logic>(ch_count);
232 // Receive notifications when new sample data is available
233 connect_input_notifiers();
235 if (get_input_segment_count() == 0) {
236 set_error_message(tr("No input data"));
240 // Make sure the logic output data is complete and up-to-date
241 logic_mux_interrupt_ = false;
242 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
244 // Decode the muxed logic data
245 decode_interrupt_ = false;
246 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
249 void DecodeSignal::pause_decode()
251 decode_paused_ = true;
254 void DecodeSignal::resume_decode()
256 // Manual unlocking is done before notifying, to avoid waking up the
257 // waiting thread only to block again (see notify_one for details)
258 decode_pause_mutex_.unlock();
259 decode_pause_cond_.notify_one();
260 decode_paused_ = false;
263 bool DecodeSignal::is_paused() const
265 return decode_paused_;
268 QString DecodeSignal::error_message() const
270 lock_guard<mutex> lock(output_mutex_);
271 return error_message_;
274 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
279 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
281 bool new_assignment = false;
283 // Try to auto-select channels that don't have signals assigned yet
284 for (decode::DecodeChannel& ch : channels_) {
285 // If a decoder is given, auto-assign only its channels
286 if (dec && (ch.decoder_ != dec))
289 if (ch.assigned_signal)
292 QString ch_name = ch.name.toLower();
293 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
295 shared_ptr<data::SignalBase> match;
296 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
300 QString s_name = s->name().toLower();
301 s_name = s_name.replace(QRegExp("[-_.]"), " ");
303 if (s->logic_data() &&
304 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
308 // Only replace an existing match if it matches more characters
309 int old_unmatched = ch_name.length() - match->name().length();
310 int new_unmatched = ch_name.length() - s->name().length();
311 if (abs(new_unmatched) < abs(old_unmatched))
318 ch.assigned_signal = match.get();
319 new_assignment = true;
323 if (new_assignment) {
324 logic_mux_data_invalid_ = true;
325 stack_config_changed_ = true;
326 commit_decoder_channels();
331 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
333 for (decode::DecodeChannel& ch : channels_)
334 if (ch.id == channel_id) {
335 ch.assigned_signal = signal;
336 logic_mux_data_invalid_ = true;
339 stack_config_changed_ = true;
340 commit_decoder_channels();
345 int DecodeSignal::get_assigned_signal_count() const
347 // Count all channels that have a signal assigned to them
348 return count_if(channels_.begin(), channels_.end(),
349 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
352 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
354 for (decode::DecodeChannel& ch : channels_)
355 if (ch.id == channel_id)
356 ch.initial_pin_state = init_state;
358 stack_config_changed_ = true;
363 double DecodeSignal::samplerate() const
367 // TODO For now, we simply return the first samplerate that we have
368 if (segments_.size() > 0)
369 result = segments_.front().samplerate;
374 const pv::util::Timestamp DecodeSignal::start_time() const
376 pv::util::Timestamp result;
378 // TODO For now, we simply return the first start time that we have
379 if (segments_.size() > 0)
380 result = segments_.front().start_time;
385 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
387 // The working sample count is the highest sample number for
388 // which all used signals have data available, so go through all
389 // channels and use the lowest overall sample count of the segment
391 int64_t count = std::numeric_limits<int64_t>::max();
392 bool no_signals_assigned = true;
394 for (const decode::DecodeChannel& ch : channels_)
395 if (ch.assigned_signal) {
396 no_signals_assigned = false;
398 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
399 if (!logic_data || logic_data->logic_segments().empty())
403 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
404 count = min(count, (int64_t)segment->get_sample_count());
405 } catch (out_of_range&) {
410 return (no_signals_assigned ? 0 : count);
413 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
414 bool include_processing) const
416 lock_guard<mutex> decode_lock(output_mutex_);
420 if (segment_id >= segments_.size())
423 if (include_processing)
424 result = segments_[segment_id].samples_decoded_incl;
426 result = segments_[segment_id].samples_decoded_excl;
431 vector<Row*> DecodeSignal::get_rows(bool visible_only)
435 for (const shared_ptr<Decoder>& dec : stack_) {
437 if (visible_only && !dec->visible())
440 for (Row* row : dec->get_rows())
447 vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
449 vector<const Row*> rows;
451 for (const shared_ptr<Decoder>& dec : stack_) {
453 if (visible_only && !dec->visible())
456 for (const Row* row : dec->get_rows())
464 uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
466 if (segment_id >= segments_.size())
469 const DecodeSegment* segment = &(segments_.at(segment_id));
471 auto row_it = segment->annotation_rows.find(row);
474 if (row_it == segment->annotation_rows.end())
477 rd = &(row_it->second);
479 return rd->get_annotation_count();
482 void DecodeSignal::get_annotation_subset(vector<const Annotation*> &dest,
483 const Row* row, uint32_t segment_id, uint64_t start_sample,
484 uint64_t end_sample) const
486 lock_guard<mutex> lock(output_mutex_);
488 if (segment_id >= segments_.size())
491 const DecodeSegment* segment = &(segments_.at(segment_id));
493 auto row_it = segment->annotation_rows.find(row);
496 if (row_it == segment->annotation_rows.end())
499 rd = &(row_it->second);
501 rd->get_annotation_subset(dest, start_sample, end_sample);
504 void DecodeSignal::get_annotation_subset(vector<const Annotation*> &dest,
505 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
507 // Use forward_lists for faster merging
508 forward_list<const Annotation*> *all_ann_list = new forward_list<const Annotation*>();
510 vector<const Row*> rows = get_rows();
511 for (const Row* row : rows) {
512 vector<const Annotation*> *ann_vector = new vector<const Annotation*>();
513 get_annotation_subset(*ann_vector, row, segment_id, start_sample, end_sample);
515 forward_list<const Annotation*> *ann_list =
516 new forward_list<const Annotation*>(ann_vector->begin(), ann_vector->end());
519 all_ann_list->merge(*ann_list);
523 move(all_ann_list->begin(), all_ann_list->end(), back_inserter(dest));
527 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
528 const Decoder* dec, uint32_t bin_class_id) const
530 if (segments_.size() == 0)
534 const DecodeSegment *segment = &(segments_.at(segment_id));
536 for (const DecodeBinaryClass& bc : segment->binary_classes)
537 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
538 return bc.chunks.size();
539 } catch (out_of_range&) {
546 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
547 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
548 const vector<uint8_t> **dest, uint64_t *size)
551 const DecodeSegment *segment = &(segments_.at(segment_id));
553 for (const DecodeBinaryClass& bc : segment->binary_classes)
554 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
555 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
556 if (size) *size = bc.chunks.at(chunk_id).data.size();
559 } catch (out_of_range&) {
564 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
565 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
566 uint64_t end_sample, vector<uint8_t> *dest) const
568 assert(dest != nullptr);
571 const DecodeSegment *segment = &(segments_.at(segment_id));
573 const DecodeBinaryClass* bin_class = nullptr;
574 for (const DecodeBinaryClass& bc : segment->binary_classes)
575 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
578 // Determine overall size before copying to resize dest vector only once
580 uint64_t matches = 0;
581 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
582 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
583 size += chunk.data.size();
589 uint64_t matches2 = 0;
590 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
591 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
592 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
593 offset += chunk.data.size();
596 // Make sure we don't overwrite memory if the array grew in the meanwhile
597 if (matches2 == matches)
600 } catch (out_of_range&) {
605 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
606 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
607 vector<uint8_t> *dest) const
609 assert(dest != nullptr);
612 const DecodeSegment *segment = &(segments_.at(segment_id));
614 const DecodeBinaryClass* bin_class = nullptr;
615 for (const DecodeBinaryClass& bc : segment->binary_classes)
616 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
619 // Determine overall size before copying to resize dest vector only once
622 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
624 size += chunk.data.size();
625 offset += chunk.data.size();
632 uint64_t dest_offset = 0;
633 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
634 if (offset >= start) {
635 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
636 dest_offset += chunk.data.size();
638 offset += chunk.data.size();
642 } catch (out_of_range&) {
647 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
648 const Decoder* dec, uint32_t bin_class_id) const
651 const DecodeSegment *segment = &(segments_.at(segment_id));
653 for (const DecodeBinaryClass& bc : segment->binary_classes)
654 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
656 } catch (out_of_range&) {
663 void DecodeSignal::save_settings(QSettings &settings) const
665 SignalBase::save_settings(settings);
667 settings.setValue("decoders", (int)(stack_.size()));
669 // Save decoder stack
671 for (const shared_ptr<Decoder>& decoder : stack_) {
672 settings.beginGroup("decoder" + QString::number(decoder_idx++));
674 settings.setValue("id", decoder->get_srd_decoder()->id);
675 settings.setValue("visible", decoder->visible());
677 // Save decoder options
678 const map<string, GVariant*>& options = decoder->options();
680 settings.setValue("options", (int)options.size());
682 // Note: Decoder::options() returns only the options
683 // that differ from the default. See binding::Decoder::getter()
685 for (auto& option : options) {
686 settings.beginGroup("option" + QString::number(i));
687 settings.setValue("name", QString::fromStdString(option.first));
688 GlobalSettings::store_gvariant(settings, option.second);
696 // Save channel mapping
697 settings.setValue("channels", (int)channels_.size());
699 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
700 auto channel = find_if(channels_.begin(), channels_.end(),
701 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
703 if (channel == channels_.end()) {
704 qDebug() << "ERROR: Gap in channel index:" << channel_id;
708 settings.beginGroup("channel" + QString::number(channel_id));
710 settings.setValue("name", channel->name); // Useful for debugging
711 settings.setValue("initial_pin_state", channel->initial_pin_state);
713 if (channel->assigned_signal)
714 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
720 void DecodeSignal::restore_settings(QSettings &settings)
722 SignalBase::restore_settings(settings);
724 // Restore decoder stack
725 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
727 int decoders = settings.value("decoders").toInt();
729 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
730 settings.beginGroup("decoder" + QString::number(decoder_idx));
732 QString id = settings.value("id").toString();
734 for (GSList *entry = dec_list; entry; entry = entry->next) {
735 const srd_decoder *dec = (srd_decoder*)entry->data;
739 if (QString::fromUtf8(dec->id) == id) {
740 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec);
742 stack_.push_back(decoder);
743 decoder->set_visible(settings.value("visible", true).toBool());
745 // Restore decoder options that differ from their default
746 int options = settings.value("options").toInt();
748 for (int i = 0; i < options; i++) {
749 settings.beginGroup("option" + QString::number(i));
750 QString name = settings.value("name").toString();
751 GVariant *value = GlobalSettings::restore_gvariant(settings);
752 decoder->set_option(name.toUtf8(), value);
756 // Include the newly created decode channels in the channel lists
757 update_channel_list();
766 // Restore channel mapping
767 unsigned int channels = settings.value("channels").toInt();
769 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
770 session_.signalbases();
772 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
773 auto channel = find_if(channels_.begin(), channels_.end(),
774 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
776 if (channel == channels_.end()) {
777 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
781 settings.beginGroup("channel" + QString::number(channel_id));
783 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
785 for (const shared_ptr<data::SignalBase>& signal : signalbases)
786 if (signal->name() == assigned_signal_name)
787 channel->assigned_signal = signal.get();
789 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
794 // Update the internal structures
795 stack_config_changed_ = true;
796 update_channel_list();
797 commit_decoder_channels();
802 void DecodeSignal::set_error_message(QString msg)
804 error_message_ = msg;
805 // TODO Emulate noquote()
806 qDebug().nospace() << name() << ": " << msg;
809 uint32_t DecodeSignal::get_input_segment_count() const
811 uint64_t count = std::numeric_limits<uint64_t>::max();
812 bool no_signals_assigned = true;
814 for (const decode::DecodeChannel& ch : channels_)
815 if (ch.assigned_signal) {
816 no_signals_assigned = false;
818 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
819 if (!logic_data || logic_data->logic_segments().empty())
822 // Find the min value of all segment counts
823 if ((uint64_t)(logic_data->logic_segments().size()) < count)
824 count = logic_data->logic_segments().size();
827 return (no_signals_assigned ? 0 : count);
830 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
832 double samplerate = 0;
834 for (const decode::DecodeChannel& ch : channels_)
835 if (ch.assigned_signal) {
836 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
837 if (!logic_data || logic_data->logic_segments().empty())
841 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
842 samplerate = segment->samplerate();
843 } catch (out_of_range&) {
852 Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
854 for (shared_ptr<Decoder>& d : stack_)
855 if (d->get_srd_decoder() == srd_dec)
861 void DecodeSignal::update_channel_list()
863 vector<decode::DecodeChannel> prev_channels = channels_;
868 // Copy existing entries, create new as needed
869 for (shared_ptr<Decoder>& decoder : stack_) {
870 const srd_decoder* srd_dec = decoder->get_srd_decoder();
873 // Mandatory channels
874 for (l = srd_dec->channels; l; l = l->next) {
875 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
876 bool ch_added = false;
878 // Copy but update ID if this channel was in the list before
879 for (decode::DecodeChannel& ch : prev_channels)
880 if (ch.pdch_ == pdch) {
882 channels_.push_back(ch);
888 // Create new entry without a mapped signal
889 decode::DecodeChannel ch = {id++, 0, false, nullptr,
890 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
891 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
892 channels_.push_back(ch);
897 for (l = srd_dec->opt_channels; l; l = l->next) {
898 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
899 bool ch_added = false;
901 // Copy but update ID if this channel was in the list before
902 for (decode::DecodeChannel& ch : prev_channels)
903 if (ch.pdch_ == pdch) {
905 channels_.push_back(ch);
911 // Create new entry without a mapped signal
912 decode::DecodeChannel ch = {id++, 0, true, nullptr,
913 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
914 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
915 channels_.push_back(ch);
920 // Invalidate the logic output data if the channel assignment changed
921 if (prev_channels.size() != channels_.size()) {
922 // The number of channels changed, there's definitely a difference
923 logic_mux_data_invalid_ = true;
925 // Same number but assignment may still differ, so compare all channels
926 for (size_t i = 0; i < channels_.size(); i++) {
927 const decode::DecodeChannel& p_ch = prev_channels[i];
928 const decode::DecodeChannel& ch = channels_[i];
930 if ((p_ch.pdch_ != ch.pdch_) ||
931 (p_ch.assigned_signal != ch.assigned_signal)) {
932 logic_mux_data_invalid_ = true;
942 void DecodeSignal::commit_decoder_channels()
944 // Submit channel list to every decoder, containing only the relevant channels
945 for (shared_ptr<Decoder> dec : stack_) {
946 vector<decode::DecodeChannel*> channel_list;
948 for (decode::DecodeChannel& ch : channels_)
949 if (ch.decoder_ == dec)
950 channel_list.push_back(&ch);
952 dec->set_channels(channel_list);
955 // Channel bit IDs must be in sync with the channel's apperance in channels_
957 for (decode::DecodeChannel& ch : channels_)
958 if (ch.assigned_signal)
962 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
964 // Enforce end to be greater than start
968 // Fetch the channel segments and their data
969 vector<shared_ptr<LogicSegment> > segments;
970 vector<const uint8_t*> signal_data;
971 vector<uint8_t> signal_in_bytepos;
972 vector<uint8_t> signal_in_bitpos;
974 for (decode::DecodeChannel& ch : channels_)
975 if (ch.assigned_signal) {
976 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
978 shared_ptr<LogicSegment> segment;
980 segment = logic_data->logic_segments().at(segment_id);
981 } catch (out_of_range&) {
982 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
983 << "has no logic segment" << segment_id;
986 segments.push_back(segment);
988 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
989 segment->get_samples(start, end, data);
990 signal_data.push_back(data);
992 const int bitpos = ch.assigned_signal->logic_bit_index();
993 signal_in_bytepos.push_back(bitpos / 8);
994 signal_in_bitpos.push_back(bitpos % 8);
998 shared_ptr<LogicSegment> output_segment;
1000 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1001 } catch (out_of_range&) {
1002 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1003 << segment_id << "in mux_logic_samples(), mux segments size is" \
1004 << logic_mux_data_->logic_segments().size();
1008 // Perform the muxing of signal data into the output data
1009 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1010 unsigned int signal_count = signal_data.size();
1012 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1016 uint8_t bytepos = 0;
1018 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1019 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1020 output[out_sample_pos + i] = 0;
1022 for (unsigned int i = 0; i < signal_count; i++) {
1023 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1024 const uint8_t in_sample = 1 &
1025 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1027 const uint8_t out_sample = output[out_sample_pos + bytepos];
1029 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1039 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1042 for (const uint8_t* data : signal_data)
1046 void DecodeSignal::logic_mux_proc()
1048 uint32_t segment_id = 0;
1050 assert(logic_mux_data_);
1052 // Create initial logic mux segment
1053 shared_ptr<LogicSegment> output_segment =
1054 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1055 logic_mux_unit_size_, 0);
1056 logic_mux_data_->push_segment(output_segment);
1058 output_segment->set_samplerate(get_input_samplerate(0));
1061 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1062 const uint64_t output_sample_count = output_segment->get_sample_count();
1064 const uint64_t samples_to_process =
1065 (input_sample_count > output_sample_count) ?
1066 (input_sample_count - output_sample_count) : 0;
1068 // Process the samples if necessary...
1069 if (samples_to_process > 0) {
1070 const uint64_t unit_size = output_segment->unit_size();
1071 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1073 uint64_t processed_samples = 0;
1075 const uint64_t start_sample = output_sample_count + processed_samples;
1076 const uint64_t sample_count =
1077 min(samples_to_process - processed_samples, chunk_sample_count);
1079 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1080 processed_samples += sample_count;
1082 // ...and process the newly muxed logic data
1083 decode_input_cond_.notify_one();
1084 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1087 if (samples_to_process == 0) {
1088 // TODO Optimize this by caching the input segment count and only
1089 // querying it when the cached value was reached
1090 if (segment_id < get_input_segment_count() - 1) {
1091 // Process next segment
1095 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1096 logic_mux_unit_size_, 0);
1097 logic_mux_data_->push_segment(output_segment);
1099 output_segment->set_samplerate(get_input_samplerate(segment_id));
1102 // All segments have been processed
1103 logic_mux_data_invalid_ = false;
1105 // Wait for more input
1106 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1107 logic_mux_cond_.wait(logic_mux_lock);
1111 } while (!logic_mux_interrupt_);
1114 void DecodeSignal::decode_data(
1115 const int64_t abs_start_samplenum, const int64_t sample_count,
1116 const shared_ptr<LogicSegment> input_segment)
1118 const int64_t unit_size = input_segment->unit_size();
1119 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1121 for (int64_t i = abs_start_samplenum;
1122 error_message_.isEmpty() && !decode_interrupt_ &&
1123 (i < (abs_start_samplenum + sample_count));
1124 i += chunk_sample_count) {
1126 const int64_t chunk_end = min(i + chunk_sample_count,
1127 abs_start_samplenum + sample_count);
1130 lock_guard<mutex> lock(output_mutex_);
1131 // Update the sample count showing the samples including currently processed ones
1132 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1135 int64_t data_size = (chunk_end - i) * unit_size;
1136 uint8_t* chunk = new uint8_t[data_size];
1137 input_segment->get_samples(i, chunk_end, chunk);
1139 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1140 data_size, unit_size) != SRD_OK)
1141 set_error_message(tr("Decoder reported an error"));
1146 lock_guard<mutex> lock(output_mutex_);
1147 // Now that all samples are processed, the exclusive sample count catches up
1148 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1151 // Notify the frontend that we processed some data and
1152 // possibly have new annotations as well
1155 if (decode_paused_) {
1156 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1157 decode_pause_cond_.wait(pause_wait_lock);
1162 void DecodeSignal::decode_proc()
1164 current_segment_id_ = 0;
1166 // If there is no input data available yet, wait until it is or we're interrupted
1167 if (logic_mux_data_->logic_segments().size() == 0) {
1168 unique_lock<mutex> input_wait_lock(input_mutex_);
1169 decode_input_cond_.wait(input_wait_lock);
1172 if (decode_interrupt_)
1175 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
1176 assert(input_segment);
1178 // Create the initial segment and set its sample rate so that we can pass it to SRD
1179 create_decode_segment();
1180 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1181 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1183 start_srd_session();
1185 uint64_t sample_count = 0;
1186 uint64_t abs_start_samplenum = 0;
1188 // Keep processing new samples until we exhaust the input data
1190 lock_guard<mutex> input_lock(input_mutex_);
1191 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
1193 if (sample_count > 0) {
1194 decode_data(abs_start_samplenum, sample_count, input_segment);
1195 abs_start_samplenum += sample_count;
1197 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1199 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1200 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1201 // Process next segment
1202 current_segment_id_++;
1205 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1206 } catch (out_of_range&) {
1207 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1208 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1209 << logic_mux_data_->logic_segments().size();
1212 abs_start_samplenum = 0;
1214 // Create the next segment and set its metadata
1215 create_decode_segment();
1216 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1217 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1219 // Reset decoder state but keep the decoder stack intact
1220 terminate_srd_session();
1222 // All segments have been processed
1225 // Wait for new input data or an interrupt was requested
1226 unique_lock<mutex> input_wait_lock(input_mutex_);
1227 decode_input_cond_.wait(input_wait_lock);
1230 } while (error_message_.isEmpty() && !decode_interrupt_);
1232 // Potentially reap decoders when the application no longer is
1233 // interested in their (pending) results.
1234 if (decode_interrupt_)
1235 terminate_srd_session();
1238 void DecodeSignal::start_srd_session()
1240 // If there were stack changes, the session has been destroyed by now, so if
1241 // it hasn't been destroyed, we can just reset and re-use it
1243 // When a decoder stack was created before, re-use it
1244 // for the next stream of input data, after terminating
1245 // potentially still executing operations, and resetting
1246 // internal state. Skip the rather expensive (teardown
1247 // and) construction of another decoder stack.
1249 // TODO Reduce redundancy, use a common code path for
1250 // the meta/start sequence?
1251 terminate_srd_session();
1253 // Metadata is cleared also, so re-set it
1254 uint64_t samplerate = 0;
1255 if (segments_.size() > 0)
1256 samplerate = segments_.at(current_segment_id_).samplerate;
1258 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1259 g_variant_new_uint64(samplerate));
1260 for (const shared_ptr<Decoder>& dec : stack_)
1261 dec->apply_all_options();
1262 srd_session_start(srd_session_);
1267 // Create the session
1268 srd_session_new(&srd_session_);
1269 assert(srd_session_);
1271 // Create the decoders
1272 srd_decoder_inst *prev_di = nullptr;
1273 for (const shared_ptr<Decoder>& dec : stack_) {
1274 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1277 set_error_message(tr("Failed to create decoder instance"));
1278 srd_session_destroy(srd_session_);
1279 srd_session_ = nullptr;
1284 srd_inst_stack(srd_session_, prev_di, di);
1289 // Start the session
1290 if (segments_.size() > 0)
1291 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1292 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1294 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1295 DecodeSignal::annotation_callback, this);
1297 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1298 DecodeSignal::binary_callback, this);
1300 srd_session_start(srd_session_);
1302 // We just recreated the srd session, so all stack changes are applied now
1303 stack_config_changed_ = false;
1306 void DecodeSignal::terminate_srd_session()
1308 // Call the "terminate and reset" routine for the decoder stack
1309 // (if available). This does not harm those stacks which already
1310 // have completed their operation, and reduces response time for
1311 // those stacks which still are processing data while the
1312 // application no longer wants them to.
1314 srd_session_terminate_reset(srd_session_);
1316 // Metadata is cleared also, so re-set it
1317 uint64_t samplerate = 0;
1318 if (segments_.size() > 0)
1319 samplerate = segments_.at(current_segment_id_).samplerate;
1321 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1322 g_variant_new_uint64(samplerate));
1323 for (const shared_ptr<Decoder>& dec : stack_)
1324 dec->apply_all_options();
1328 void DecodeSignal::stop_srd_session()
1331 // Destroy the session
1332 srd_session_destroy(srd_session_);
1333 srd_session_ = nullptr;
1335 // Mark the decoder instances as non-existant since they were deleted
1336 for (const shared_ptr<Decoder>& dec : stack_)
1337 dec->invalidate_decoder_inst();
1341 void DecodeSignal::connect_input_notifiers()
1343 // Disconnect the notification slot from the previous set of signals
1344 disconnect(this, SLOT(on_data_cleared()));
1345 disconnect(this, SLOT(on_data_received()));
1347 // Connect the currently used signals to our slot
1348 for (decode::DecodeChannel& ch : channels_) {
1349 if (!ch.assigned_signal)
1352 const data::SignalBase *signal = ch.assigned_signal;
1353 connect(signal, SIGNAL(samples_cleared()),
1354 this, SLOT(on_data_cleared()));
1355 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1356 this, SLOT(on_data_received()));
1360 void DecodeSignal::create_decode_segment()
1362 // Create annotation segment
1363 segments_.emplace_back(DecodeSegment());
1365 // Add annotation classes
1366 for (const shared_ptr<Decoder> dec : stack_)
1367 for (Row* row : dec->get_rows())
1368 segments_.back().annotation_rows.emplace(row, RowData(row));
1370 // Prepare our binary output classes
1371 for (const shared_ptr<Decoder>& dec : stack_) {
1372 uint32_t n = dec->get_binary_class_count();
1374 for (uint32_t i = 0; i < n; i++)
1375 segments_.back().binary_classes.push_back(
1376 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1380 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1383 assert(decode_signal);
1385 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1388 if (ds->decode_interrupt_)
1391 lock_guard<mutex> lock(ds->output_mutex_);
1393 // Get the decoder and the annotation data
1395 assert(pdata->pdo->di);
1396 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1399 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1403 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1406 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1408 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1409 "with class ID" << pda->ann_class << "but there are only" <<
1410 dec->ann_classes().size() << "known classes";
1414 const Row* row = ann_class->row;
1417 row = dec->get_row_by_id(0);
1419 // Add the annotation
1420 ds->segments_[ds->current_segment_id_].annotation_rows.at(row).emplace_annotation(pdata);
1423 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1426 assert(decode_signal);
1428 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1431 if (ds->decode_interrupt_)
1434 // Get the decoder and the binary data
1436 assert(pdata->pdo->di);
1437 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1440 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1443 // Find the matching DecodeBinaryClass
1444 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1446 DecodeBinaryClass* bin_class = nullptr;
1447 for (DecodeBinaryClass& bc : segment->binary_classes)
1448 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1449 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1453 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1454 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1455 ", segment only knows" << segment->binary_classes.size() << "classes";
1459 // Add the data chunk
1460 bin_class->chunks.emplace_back();
1461 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1463 chunk->sample = pdata->start_sample;
1464 chunk->data.resize(pdb->size);
1465 memcpy(chunk->data.data(), pdb->data, pdb->size);
1467 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1469 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1472 void DecodeSignal::on_capture_state_changed(int state)
1474 // If a new acquisition was started, we need to start decoding from scratch
1475 if (state == Session::Running) {
1476 logic_mux_data_invalid_ = true;
1481 void DecodeSignal::on_data_cleared()
1486 void DecodeSignal::on_data_received()
1488 // If we detected a lack of input data when trying to start decoding,
1489 // we have set an error message. Only try again if we now have data
1491 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1494 if (!logic_mux_thread_.joinable())
1497 logic_mux_cond_.notify_one();