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 connect(dec.get(), SIGNAL(annotation_visibility_changed()),
90 this, SLOT(on_annotation_visibility_changed()));
92 // Include the newly created decode channels in the channel lists
93 update_channel_list();
95 stack_config_changed_ = true;
96 auto_assign_signals(dec);
97 commit_decoder_channels();
99 decoder_stacked((void*)dec.get());
105 void DecodeSignal::remove_decoder(int index)
108 assert(index < (int)stack_.size());
110 // Find the decoder in the stack
111 auto iter = stack_.begin() + index;
112 assert(iter != stack_.end());
114 shared_ptr<Decoder> dec = *iter;
116 decoder_removed(dec.get());
118 // Delete the element
121 // Update channels and decoded data
122 stack_config_changed_ = true;
123 update_channel_list();
127 bool DecodeSignal::toggle_decoder_visibility(int index)
129 auto iter = stack_.cbegin();
130 for (int i = 0; i < index; i++, iter++)
131 assert(iter != stack_.end());
133 shared_ptr<Decoder> dec = *iter;
135 // Toggle decoder visibility
138 state = !dec->visible();
139 dec->set_visible(state);
145 void DecodeSignal::reset_decode(bool shutting_down)
147 resume_decode(); // Make sure the decode thread isn't blocked by pausing
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 current_segment_id_ = 0;
169 logic_mux_data_.reset();
170 logic_mux_data_invalid_ = true;
172 if (!error_message_.isEmpty()) {
173 error_message_.clear();
174 // TODO Emulate noquote()
175 qDebug().nospace() << name() << ": Error cleared";
181 void DecodeSignal::begin_decode()
183 if (decode_thread_.joinable()) {
184 decode_interrupt_ = true;
185 decode_input_cond_.notify_one();
186 decode_thread_.join();
189 if (logic_mux_thread_.joinable()) {
190 logic_mux_interrupt_ = true;
191 logic_mux_cond_.notify_one();
192 logic_mux_thread_.join();
197 if (stack_.size() == 0) {
198 set_error_message(tr("No decoders"));
202 assert(channels_.size() > 0);
204 if (get_assigned_signal_count() == 0) {
205 set_error_message(tr("There are no channels assigned to this decoder"));
209 // Make sure that all assigned channels still provide logic data
210 // (can happen when a converted signal was assigned but the
211 // conversion removed in the meanwhile)
212 for (decode::DecodeChannel& ch : channels_)
213 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
214 ch.assigned_signal = nullptr;
216 // Check that all decoders have the required channels
217 for (const shared_ptr<Decoder>& dec : stack_)
218 if (!dec->have_required_channels()) {
219 set_error_message(tr("One or more required channels "
220 "have not been specified"));
224 // Free the logic data and its segment(s) if it needs to be updated
225 if (logic_mux_data_invalid_)
226 logic_mux_data_.reset();
228 if (!logic_mux_data_) {
229 const uint32_t ch_count = get_assigned_signal_count();
230 logic_mux_unit_size_ = (ch_count + 7) / 8;
231 logic_mux_data_ = make_shared<Logic>(ch_count);
234 // Receive notifications when new sample data is available
235 connect_input_notifiers();
237 if (get_input_segment_count() == 0)
238 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 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
273 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
275 bool new_assignment = false;
277 // Try to auto-select channels that don't have signals assigned yet
278 for (decode::DecodeChannel& ch : channels_) {
279 // If a decoder is given, auto-assign only its channels
280 if (dec && (ch.decoder_ != dec))
283 if (ch.assigned_signal)
286 QString ch_name = ch.name.toLower();
287 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
289 shared_ptr<data::SignalBase> match;
290 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
294 QString s_name = s->name().toLower();
295 s_name = s_name.replace(QRegExp("[-_.]"), " ");
297 if (s->logic_data() &&
298 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
302 // Only replace an existing match if it matches more characters
303 int old_unmatched = ch_name.length() - match->name().length();
304 int new_unmatched = ch_name.length() - s->name().length();
305 if (abs(new_unmatched) < abs(old_unmatched))
312 ch.assigned_signal = match;
313 new_assignment = true;
317 if (new_assignment) {
318 logic_mux_data_invalid_ = true;
319 stack_config_changed_ = true;
320 commit_decoder_channels();
325 void DecodeSignal::assign_signal(const uint16_t channel_id, shared_ptr<const SignalBase> signal)
327 for (decode::DecodeChannel& ch : channels_)
328 if (ch.id == channel_id) {
329 ch.assigned_signal = signal;
330 logic_mux_data_invalid_ = true;
333 stack_config_changed_ = true;
334 commit_decoder_channels();
339 int DecodeSignal::get_assigned_signal_count() const
341 // Count all channels that have a signal assigned to them
342 return count_if(channels_.begin(), channels_.end(),
343 [](decode::DecodeChannel ch) { return ch.assigned_signal.get(); });
346 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
348 for (decode::DecodeChannel& ch : channels_)
349 if (ch.id == channel_id)
350 ch.initial_pin_state = init_state;
352 stack_config_changed_ = true;
357 double DecodeSignal::get_samplerate() const
361 // TODO For now, we simply return the first samplerate that we have
362 if (segments_.size() > 0)
363 result = segments_.front().samplerate;
368 const pv::util::Timestamp DecodeSignal::start_time() const
370 pv::util::Timestamp result;
372 // TODO For now, we simply return the first start time that we have
373 if (segments_.size() > 0)
374 result = segments_.front().start_time;
379 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
381 // The working sample count is the highest sample number for
382 // which all used signals have data available, so go through all
383 // channels and use the lowest overall sample count of the segment
385 int64_t count = std::numeric_limits<int64_t>::max();
386 bool no_signals_assigned = true;
388 for (const decode::DecodeChannel& ch : channels_)
389 if (ch.assigned_signal) {
390 if (!ch.assigned_signal->logic_data())
393 no_signals_assigned = false;
395 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
396 if (logic_data->logic_segments().empty())
399 if (segment_id >= logic_data->logic_segments().size())
402 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
404 count = min(count, (int64_t)segment->get_sample_count());
407 return (no_signals_assigned ? 0 : count);
410 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
411 bool include_processing) const
413 lock_guard<mutex> decode_lock(output_mutex_);
417 if (segment_id >= segments_.size())
420 if (include_processing)
421 result = segments_[segment_id].samples_decoded_incl;
423 result = segments_[segment_id].samples_decoded_excl;
428 vector<Row*> DecodeSignal::get_rows(bool visible_only)
432 for (const shared_ptr<Decoder>& dec : stack_) {
434 if (visible_only && !dec->visible())
437 for (Row* row : dec->get_rows())
444 vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
446 vector<const Row*> rows;
448 for (const shared_ptr<Decoder>& dec : stack_) {
450 if (visible_only && !dec->visible())
453 for (const Row* row : dec->get_rows())
461 uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
463 if (segment_id >= segments_.size())
466 const DecodeSegment* segment = &(segments_.at(segment_id));
468 auto row_it = segment->annotation_rows.find(row);
471 if (row_it == segment->annotation_rows.end())
474 rd = &(row_it->second);
476 return rd->get_annotation_count();
479 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
480 const Row* row, uint32_t segment_id, uint64_t start_sample,
481 uint64_t end_sample) const
483 lock_guard<mutex> lock(output_mutex_);
485 if (segment_id >= segments_.size())
488 const DecodeSegment* segment = &(segments_.at(segment_id));
490 auto row_it = segment->annotation_rows.find(row);
493 if (row_it == segment->annotation_rows.end())
496 rd = &(row_it->second);
498 rd->get_annotation_subset(dest, start_sample, end_sample);
501 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
502 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
504 for (const Row* row : get_rows())
505 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
508 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
509 const Decoder* dec, uint32_t bin_class_id) const
511 if ((segments_.size() == 0) || (segment_id >= segments_.size()))
514 const DecodeSegment *segment = &(segments_[segment_id]);
516 for (const DecodeBinaryClass& bc : segment->binary_classes)
517 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
518 return bc.chunks.size();
523 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
524 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
525 const vector<uint8_t> **dest, uint64_t *size)
527 if (segment_id >= segments_.size())
530 const DecodeSegment *segment = &(segments_[segment_id]);
532 for (const DecodeBinaryClass& bc : segment->binary_classes)
533 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
534 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
535 if (size) *size = bc.chunks.at(chunk_id).data.size();
540 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
541 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
542 uint64_t end_sample, vector<uint8_t> *dest) const
544 assert(dest != nullptr);
546 if (segment_id >= segments_.size())
549 const DecodeSegment *segment = &(segments_[segment_id]);
551 const DecodeBinaryClass* bin_class = nullptr;
552 for (const DecodeBinaryClass& bc : segment->binary_classes)
553 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
556 // Determine overall size before copying to resize dest vector only once
558 uint64_t matches = 0;
559 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
560 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
561 size += chunk.data.size();
567 uint64_t matches2 = 0;
568 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
569 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
570 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
571 offset += chunk.data.size();
574 // Make sure we don't overwrite memory if the array grew in the meanwhile
575 if (matches2 == matches)
580 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
581 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
582 vector<uint8_t> *dest) const
584 assert(dest != nullptr);
586 if (segment_id >= segments_.size())
589 const DecodeSegment *segment = &(segments_[segment_id]);
591 const DecodeBinaryClass* bin_class = nullptr;
592 for (const DecodeBinaryClass& bc : segment->binary_classes)
593 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
596 // Determine overall size before copying to resize dest vector only once
599 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
601 size += chunk.data.size();
602 offset += chunk.data.size();
609 uint64_t dest_offset = 0;
610 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
611 if (offset >= start) {
612 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
613 dest_offset += chunk.data.size();
615 offset += chunk.data.size();
621 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
622 const Decoder* dec, uint32_t bin_class_id) const
624 if (segment_id >= segments_.size())
627 const DecodeSegment *segment = &(segments_[segment_id]);
629 for (const DecodeBinaryClass& bc : segment->binary_classes)
630 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
636 const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
637 uint32_t segment_id) const
639 if (segment_id >= segments_.size())
642 const DecodeSegment *segment = &(segments_[segment_id]);
644 return &(segment->all_annotations);
647 void DecodeSignal::save_settings(QSettings &settings) const
649 SignalBase::save_settings(settings);
651 settings.setValue("decoders", (int)(stack_.size()));
653 // Save decoder stack
655 for (const shared_ptr<Decoder>& decoder : stack_) {
656 settings.beginGroup("decoder" + QString::number(decoder_idx++));
658 settings.setValue("id", decoder->get_srd_decoder()->id);
659 settings.setValue("visible", decoder->visible());
661 // Save decoder options
662 const map<string, GVariant*>& options = decoder->options();
664 settings.setValue("options", (int)options.size());
666 // Note: Decoder::options() returns only the options
667 // that differ from the default. See binding::Decoder::getter()
669 for (auto& option : options) {
670 settings.beginGroup("option" + QString::number(i));
671 settings.setValue("name", QString::fromStdString(option.first));
672 GlobalSettings::store_gvariant(settings, option.second);
677 // Save row properties
679 for (const Row* row : decoder->get_rows()) {
680 settings.beginGroup("row" + QString::number(i));
681 settings.setValue("visible", row->visible());
686 // Save class properties
688 for (const AnnotationClass* ann_class : decoder->ann_classes()) {
689 settings.beginGroup("ann_class" + QString::number(i));
690 settings.setValue("visible", ann_class->visible());
698 // Save channel mapping
699 settings.setValue("channels", (int)channels_.size());
701 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
702 auto channel = find_if(channels_.begin(), channels_.end(),
703 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
705 if (channel == channels_.end()) {
706 qDebug() << "ERROR: Gap in channel index:" << channel_id;
710 settings.beginGroup("channel" + QString::number(channel_id));
712 settings.setValue("name", channel->name); // Useful for debugging
713 settings.setValue("initial_pin_state", channel->initial_pin_state);
715 if (channel->assigned_signal)
716 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
722 void DecodeSignal::restore_settings(QSettings &settings)
724 SignalBase::restore_settings(settings);
726 // Restore decoder stack
727 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
729 int decoders = settings.value("decoders").toInt();
731 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
732 settings.beginGroup("decoder" + QString::number(decoder_idx));
734 QString id = settings.value("id").toString();
736 for (GSList *entry = dec_list; entry; entry = entry->next) {
737 const srd_decoder *dec = (srd_decoder*)entry->data;
741 if (QString::fromUtf8(dec->id) == id) {
742 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec, stack_.size());
744 connect(decoder.get(), SIGNAL(annotation_visibility_changed()),
745 this, SLOT(on_annotation_visibility_changed()));
747 stack_.push_back(decoder);
748 decoder->set_visible(settings.value("visible", true).toBool());
750 // Restore decoder options that differ from their default
751 int options = settings.value("options").toInt();
753 for (int i = 0; i < options; i++) {
754 settings.beginGroup("option" + QString::number(i));
755 QString name = settings.value("name").toString();
756 GVariant *value = GlobalSettings::restore_gvariant(settings);
757 decoder->set_option(name.toUtf8(), value);
761 // Include the newly created decode channels in the channel lists
762 update_channel_list();
764 // Restore row properties
766 for (Row* row : decoder->get_rows()) {
767 settings.beginGroup("row" + QString::number(i));
768 row->set_visible(settings.value("visible", true).toBool());
773 // Restore class properties
775 for (AnnotationClass* ann_class : decoder->ann_classes()) {
776 settings.beginGroup("ann_class" + QString::number(i));
777 ann_class->set_visible(settings.value("visible", true).toBool());
790 // Restore channel mapping
791 unsigned int channels = settings.value("channels").toInt();
793 const vector< shared_ptr<data::SignalBase> > signalbases =
794 session_.signalbases();
796 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
797 auto channel = find_if(channels_.begin(), channels_.end(),
798 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
800 if (channel == channels_.end()) {
801 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
805 settings.beginGroup("channel" + QString::number(channel_id));
807 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
809 for (const shared_ptr<data::SignalBase>& signal : signalbases)
810 if ((signal->name() == assigned_signal_name) && (signal->type() != SignalBase::DecodeChannel))
811 channel->assigned_signal = signal;
813 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
818 // Update the internal structures
819 stack_config_changed_ = true;
820 update_channel_list();
821 commit_decoder_channels();
826 bool DecodeSignal::all_input_segments_complete(uint32_t segment_id) const
828 bool all_complete = true;
830 for (const decode::DecodeChannel& ch : channels_)
831 if (ch.assigned_signal) {
832 if (!ch.assigned_signal->logic_data())
835 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
836 if (logic_data->logic_segments().empty())
839 if (segment_id >= logic_data->logic_segments().size())
842 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
843 if (segment && !segment->is_complete())
844 all_complete = false;
850 uint32_t DecodeSignal::get_input_segment_count() const
852 uint64_t count = std::numeric_limits<uint64_t>::max();
853 bool no_signals_assigned = true;
855 for (const decode::DecodeChannel& ch : channels_)
856 if (ch.assigned_signal) {
857 no_signals_assigned = false;
859 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
860 if (!logic_data || logic_data->logic_segments().empty())
863 // Find the min value of all segment counts
864 if ((uint64_t)(logic_data->logic_segments().size()) < count)
865 count = logic_data->logic_segments().size();
868 return (no_signals_assigned ? 0 : count);
871 double DecodeSignal::get_input_samplerate(uint32_t segment_id) const
873 double samplerate = 0;
875 for (const decode::DecodeChannel& ch : channels_)
876 if (ch.assigned_signal) {
877 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
878 if (!logic_data || logic_data->logic_segments().empty())
882 const shared_ptr<const LogicSegment> segment =
883 logic_data->logic_segments().at(segment_id)->get_shared_ptr();
885 samplerate = segment->samplerate();
886 } catch (out_of_range&) {
895 Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
897 for (shared_ptr<Decoder>& d : stack_)
898 if (d->get_srd_decoder() == srd_dec)
904 void DecodeSignal::update_channel_list()
906 vector<decode::DecodeChannel> prev_channels = channels_;
911 // Copy existing entries, create new as needed
912 for (shared_ptr<Decoder>& decoder : stack_) {
913 const srd_decoder* srd_dec = decoder->get_srd_decoder();
916 // Mandatory channels
917 for (l = srd_dec->channels; l; l = l->next) {
918 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
919 bool ch_added = false;
921 // Copy but update ID if this channel was in the list before
922 for (decode::DecodeChannel& ch : prev_channels)
923 if (ch.pdch_ == pdch) {
925 channels_.push_back(ch);
931 // Create new entry without a mapped signal
932 decode::DecodeChannel ch = {id++, 0, false, nullptr,
933 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
934 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
935 channels_.push_back(ch);
940 for (l = srd_dec->opt_channels; l; l = l->next) {
941 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
942 bool ch_added = false;
944 // Copy but update ID if this channel was in the list before
945 for (decode::DecodeChannel& ch : prev_channels)
946 if (ch.pdch_ == pdch) {
948 channels_.push_back(ch);
954 // Create new entry without a mapped signal
955 decode::DecodeChannel ch = {id++, 0, true, nullptr,
956 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
957 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
958 channels_.push_back(ch);
963 // Invalidate the logic output data if the channel assignment changed
964 if (prev_channels.size() != channels_.size()) {
965 // The number of channels changed, there's definitely a difference
966 logic_mux_data_invalid_ = true;
968 // Same number but assignment may still differ, so compare all channels
969 for (size_t i = 0; i < channels_.size(); i++) {
970 const decode::DecodeChannel& p_ch = prev_channels[i];
971 const decode::DecodeChannel& ch = channels_[i];
973 if ((p_ch.pdch_ != ch.pdch_) ||
974 (p_ch.assigned_signal != ch.assigned_signal)) {
975 logic_mux_data_invalid_ = true;
985 void DecodeSignal::commit_decoder_channels()
987 // Submit channel list to every decoder, containing only the relevant channels
988 for (shared_ptr<Decoder> dec : stack_) {
989 vector<decode::DecodeChannel*> channel_list;
991 for (decode::DecodeChannel& ch : channels_)
992 if (ch.decoder_ == dec)
993 channel_list.push_back(&ch);
995 dec->set_channels(channel_list);
998 // Channel bit IDs must be in sync with the channel's apperance in channels_
1000 for (decode::DecodeChannel& ch : channels_)
1001 if (ch.assigned_signal)
1005 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
1007 // Enforce end to be greater than start
1011 // Fetch the channel segments and their data
1012 vector<shared_ptr<const LogicSegment> > segments;
1013 vector<const uint8_t*> signal_data;
1014 vector<uint8_t> signal_in_bytepos;
1015 vector<uint8_t> signal_in_bitpos;
1017 for (decode::DecodeChannel& ch : channels_)
1018 if (ch.assigned_signal) {
1019 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1021 shared_ptr<const LogicSegment> segment;
1022 if (segment_id < logic_data->logic_segments().size()) {
1023 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
1025 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1026 << "has no logic segment" << segment_id;
1027 logic_mux_interrupt_ = true;
1034 segments.push_back(segment);
1036 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1037 segment->get_samples(start, end, data);
1038 signal_data.push_back(data);
1040 const int bitpos = ch.assigned_signal->logic_bit_index();
1041 signal_in_bytepos.push_back(bitpos / 8);
1042 signal_in_bitpos.push_back(bitpos % 8);
1045 shared_ptr<LogicSegment> output_segment;
1047 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1048 } catch (out_of_range&) {
1049 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1050 << segment_id << "in mux_logic_samples(), mux segments size is" \
1051 << logic_mux_data_->logic_segments().size();
1052 logic_mux_interrupt_ = true;
1056 // Perform the muxing of signal data into the output data
1057 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1058 unsigned int signal_count = signal_data.size();
1060 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1064 uint8_t bytepos = 0;
1066 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1067 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1068 output[out_sample_pos + i] = 0;
1070 for (unsigned int i = 0; i < signal_count; i++) {
1071 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1072 const uint8_t in_sample = 1 &
1073 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1075 const uint8_t out_sample = output[out_sample_pos + bytepos];
1077 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1087 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1090 for (const uint8_t* data : signal_data)
1094 void DecodeSignal::logic_mux_proc()
1096 uint32_t input_segment_count;
1098 input_segment_count = get_input_segment_count();
1099 if (input_segment_count == 0) {
1100 // Wait for input data
1101 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1102 logic_mux_cond_.wait(logic_mux_lock);
1104 } while ((!logic_mux_interrupt_) && (input_segment_count == 0));
1106 if (logic_mux_interrupt_)
1109 assert(logic_mux_data_);
1111 uint32_t segment_id = 0;
1113 // Create initial logic mux segment
1114 shared_ptr<LogicSegment> output_segment =
1115 make_shared<LogicSegment>(*logic_mux_data_, segment_id, logic_mux_unit_size_, 0);
1116 logic_mux_data_->push_segment(output_segment);
1118 output_segment->set_samplerate(get_input_samplerate(0));
1120 // Logic mux data is being updated
1121 logic_mux_data_invalid_ = false;
1123 uint64_t samples_to_process;
1126 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1127 const uint64_t output_sample_count = output_segment->get_sample_count();
1129 samples_to_process =
1130 (input_sample_count > output_sample_count) ?
1131 (input_sample_count - output_sample_count) : 0;
1133 if (samples_to_process > 0) {
1134 const uint64_t unit_size = output_segment->unit_size();
1135 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1137 uint64_t processed_samples = 0;
1139 const uint64_t start_sample = output_sample_count + processed_samples;
1140 const uint64_t sample_count =
1141 min(samples_to_process - processed_samples, chunk_sample_count);
1143 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1144 processed_samples += sample_count;
1146 // ...and process the newly muxed logic data
1147 decode_input_cond_.notify_one();
1148 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1150 } while (!logic_mux_interrupt_ && (samples_to_process > 0));
1152 if (!logic_mux_interrupt_) {
1153 // samples_to_process is now 0, we've exhausted the currently available input data
1155 // If the input segments are complete, we've completed this segment
1156 if (all_input_segments_complete(segment_id)) {
1157 if (!output_segment->is_complete())
1158 output_segment->set_complete();
1160 if (segment_id < get_input_segment_count() - 1) {
1161 // Process next segment
1165 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1166 logic_mux_unit_size_, 0);
1167 logic_mux_data_->push_segment(output_segment);
1169 output_segment->set_samplerate(get_input_samplerate(segment_id));
1173 if (segment_id == (get_input_segment_count() - 1)) {
1174 // Wait for more input data if we're processing the currently last segment
1175 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1176 logic_mux_cond_.wait(logic_mux_lock);
1179 } while (!logic_mux_interrupt_);
1182 void DecodeSignal::decode_data(
1183 const int64_t abs_start_samplenum, const int64_t sample_count,
1184 const shared_ptr<const LogicSegment> input_segment)
1186 const int64_t unit_size = input_segment->unit_size();
1187 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1189 for (int64_t i = abs_start_samplenum;
1190 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
1191 i += chunk_sample_count) {
1193 const int64_t chunk_end = min(i + chunk_sample_count,
1194 abs_start_samplenum + sample_count);
1197 lock_guard<mutex> lock(output_mutex_);
1198 // Update the sample count showing the samples including currently processed ones
1199 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1202 int64_t data_size = (chunk_end - i) * unit_size;
1203 uint8_t* chunk = new uint8_t[data_size];
1204 input_segment->get_samples(i, chunk_end, chunk);
1206 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1207 data_size, unit_size) != SRD_OK) {
1208 set_error_message(tr("Decoder reported an error"));
1209 decode_interrupt_ = true;
1215 lock_guard<mutex> lock(output_mutex_);
1216 // Now that all samples are processed, the exclusive sample count catches up
1217 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1220 // Notify the frontend that we processed some data and
1221 // possibly have new annotations as well
1224 if (decode_paused_) {
1225 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1226 decode_pause_cond_.wait(pause_wait_lock);
1231 void DecodeSignal::decode_proc()
1233 current_segment_id_ = 0;
1235 // If there is no input data available yet, wait until it is or we're interrupted
1237 if (logic_mux_data_->logic_segments().size() == 0) {
1238 // Wait for input data
1239 unique_lock<mutex> input_wait_lock(input_mutex_);
1240 decode_input_cond_.wait(input_wait_lock);
1242 } while ((!decode_interrupt_) && (logic_mux_data_->logic_segments().size() == 0));
1244 if (decode_interrupt_)
1247 shared_ptr<const LogicSegment> input_segment = logic_mux_data_->logic_segments().front()->get_shared_ptr();
1251 // Create the initial segment and set its sample rate so that we can pass it to SRD
1252 create_decode_segment();
1253 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1254 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1256 start_srd_session();
1258 uint64_t samples_to_process = 0;
1259 uint64_t abs_start_samplenum = 0;
1261 // Keep processing new samples until we exhaust the input data
1263 samples_to_process = input_segment->get_sample_count() - abs_start_samplenum;
1265 if (samples_to_process > 0) {
1266 decode_data(abs_start_samplenum, samples_to_process, input_segment);
1267 abs_start_samplenum += samples_to_process;
1269 } while (!decode_interrupt_ && (samples_to_process > 0));
1271 if (!decode_interrupt_) {
1272 // samples_to_process is now 0, we've exhausted the currently available input data
1274 // If the input segment is complete, we've exhausted this segment
1275 if (input_segment->is_complete()) {
1276 if (current_segment_id_ < (logic_mux_data_->logic_segments().size() - 1)) {
1277 // Process next segment
1278 current_segment_id_++;
1281 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1282 } catch (out_of_range&) {
1283 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1284 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1285 << logic_mux_data_->logic_segments().size();
1286 decode_interrupt_ = true;
1289 abs_start_samplenum = 0;
1291 // Create the next segment and set its metadata
1292 create_decode_segment();
1293 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1294 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1296 // Reset decoder state but keep the decoder stack intact
1297 terminate_srd_session();
1299 // All segments have been processed
1300 if (!decode_interrupt_)
1305 if (current_segment_id_ == (logic_mux_data_->logic_segments().size() - 1)) {
1306 // Wait for more input data if we're processing the currently last segment
1307 unique_lock<mutex> input_wait_lock(input_mutex_);
1308 decode_input_cond_.wait(input_wait_lock);
1311 } while (!decode_interrupt_);
1314 void DecodeSignal::start_srd_session()
1316 // If there were stack changes, the session has been destroyed by now, so if
1317 // it hasn't been destroyed, we can just reset and re-use it
1319 // When a decoder stack was created before, re-use it
1320 // for the next stream of input data, after terminating
1321 // potentially still executing operations, and resetting
1322 // internal state. Skip the rather expensive (teardown
1323 // and) construction of another decoder stack.
1325 // TODO Reduce redundancy, use a common code path for
1326 // the meta/start sequence?
1327 terminate_srd_session();
1329 // Metadata is cleared also, so re-set it
1330 uint64_t samplerate = 0;
1331 if (segments_.size() > 0)
1332 samplerate = segments_.at(current_segment_id_).samplerate;
1334 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1335 g_variant_new_uint64(samplerate));
1336 for (const shared_ptr<Decoder>& dec : stack_)
1337 dec->apply_all_options();
1338 srd_session_start(srd_session_);
1343 // Create the session
1344 srd_session_new(&srd_session_);
1345 assert(srd_session_);
1347 // Create the decoders
1348 srd_decoder_inst *prev_di = nullptr;
1349 for (const shared_ptr<Decoder>& dec : stack_) {
1350 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1353 set_error_message(tr("Failed to create decoder instance"));
1354 srd_session_destroy(srd_session_);
1355 srd_session_ = nullptr;
1360 srd_inst_stack(srd_session_, prev_di, di);
1365 // Start the session
1366 if (segments_.size() > 0)
1367 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1368 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1370 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1371 DecodeSignal::annotation_callback, this);
1373 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1374 DecodeSignal::binary_callback, this);
1376 srd_session_start(srd_session_);
1378 // We just recreated the srd session, so all stack changes are applied now
1379 stack_config_changed_ = false;
1382 void DecodeSignal::terminate_srd_session()
1384 // Call the "terminate and reset" routine for the decoder stack
1385 // (if available). This does not harm those stacks which already
1386 // have completed their operation, and reduces response time for
1387 // those stacks which still are processing data while the
1388 // application no longer wants them to.
1390 srd_session_terminate_reset(srd_session_);
1392 // Metadata is cleared also, so re-set it
1393 uint64_t samplerate = 0;
1394 if (segments_.size() > 0)
1395 samplerate = segments_.at(current_segment_id_).samplerate;
1397 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1398 g_variant_new_uint64(samplerate));
1399 for (const shared_ptr<Decoder>& dec : stack_)
1400 dec->apply_all_options();
1404 void DecodeSignal::stop_srd_session()
1407 // Destroy the session
1408 srd_session_destroy(srd_session_);
1409 srd_session_ = nullptr;
1411 // Mark the decoder instances as non-existant since they were deleted
1412 for (const shared_ptr<Decoder>& dec : stack_)
1413 dec->invalidate_decoder_inst();
1417 void DecodeSignal::connect_input_notifiers()
1419 // Disconnect the notification slot from the previous set of signals
1420 disconnect(this, SLOT(on_data_cleared()));
1421 disconnect(this, SLOT(on_data_received()));
1423 // Connect the currently used signals to our slot
1424 for (decode::DecodeChannel& ch : channels_) {
1425 if (!ch.assigned_signal)
1428 const data::SignalBase *signal = ch.assigned_signal.get();
1429 connect(signal, &data::SignalBase::samples_cleared,
1430 this, &DecodeSignal::on_data_cleared);
1431 connect(signal, &data::SignalBase::samples_added,
1432 this, &DecodeSignal::on_data_received);
1436 void DecodeSignal::create_decode_segment()
1438 // Create annotation segment
1439 segments_.emplace_back();
1441 // Add annotation classes
1442 for (const shared_ptr<Decoder>& dec : stack_)
1443 for (Row* row : dec->get_rows())
1444 segments_.back().annotation_rows.emplace(row, RowData(row));
1446 // Prepare our binary output classes
1447 for (const shared_ptr<Decoder>& dec : stack_) {
1448 uint32_t n = dec->get_binary_class_count();
1450 for (uint32_t i = 0; i < n; i++)
1451 segments_.back().binary_classes.push_back(
1452 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1456 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1459 assert(decode_signal);
1461 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1464 if (ds->decode_interrupt_)
1467 if (ds->segments_.empty())
1470 lock_guard<mutex> lock(ds->output_mutex_);
1472 // Get the decoder and the annotation data
1474 assert(pdata->pdo->di);
1475 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1478 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1482 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1485 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1487 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1488 "with class ID" << pda->ann_class << "but there are only" <<
1489 dec->ann_classes().size() << "known classes";
1493 const Row* row = ann_class->row;
1496 row = dec->get_row_by_id(0);
1498 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1500 // Add the annotation to the row
1501 const Annotation* ann = row_data.emplace_annotation(pdata);
1503 // We insert the annotation into the global annotation list in a way so that
1504 // the annotation list is sorted by start sample and length. Otherwise, we'd
1505 // have to sort the model, which is expensive
1506 deque<const Annotation*>& all_annotations =
1507 ds->segments_[ds->current_segment_id_].all_annotations;
1509 if (all_annotations.empty()) {
1510 all_annotations.emplace_back(ann);
1512 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1513 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1514 bool ann_is_longer = (new_ann_len >
1515 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1517 if (ann_has_earlier_start && ann_is_longer) {
1518 bool ann_has_same_start;
1519 auto it = all_annotations.end();
1523 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1524 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
1525 ann_is_longer = (new_ann_len > (*it)->length());
1526 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1528 // Allow inserting at the front
1529 if (it != all_annotations.begin())
1532 all_annotations.emplace(it, ann);
1534 all_annotations.emplace_back(ann);
1537 // When emplace_annotation() inserts instead of appends an annotation,
1538 // the pointers in all_annotations that follow the inserted annotation and
1539 // point to annotations for this row are off by one and must be updated
1540 if (&(row_data.annotations().back()) != ann) {
1541 // Search backwards until we find the annotation we just added
1542 auto row_it = row_data.annotations().end();
1543 auto all_it = all_annotations.end();
1546 if ((*all_it)->row_data() == &row_data)
1548 } while (&(*row_it) != ann);
1550 // Update the annotation addresses for this row's annotations until the end
1552 if ((*all_it)->row_data() == &row_data) {
1553 *all_it = &(*row_it);
1557 } while (all_it != all_annotations.end());
1561 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1564 assert(decode_signal);
1566 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1569 if (ds->decode_interrupt_)
1572 // Get the decoder and the binary data
1574 assert(pdata->pdo->di);
1575 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1578 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1581 // Find the matching DecodeBinaryClass
1582 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1584 DecodeBinaryClass* bin_class = nullptr;
1585 for (DecodeBinaryClass& bc : segment->binary_classes)
1586 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1587 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1591 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1592 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1593 ", segment only knows" << segment->binary_classes.size() << "classes";
1597 // Add the data chunk
1598 bin_class->chunks.emplace_back();
1599 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1601 chunk->sample = pdata->start_sample;
1602 chunk->data.resize(pdb->size);
1603 memcpy(chunk->data.data(), pdb->data, pdb->size);
1605 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1607 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1610 void DecodeSignal::on_capture_state_changed(int state)
1612 // If a new acquisition was started, we need to start decoding from scratch
1613 if (state == Session::Running) {
1614 logic_mux_data_invalid_ = true;
1619 void DecodeSignal::on_data_cleared()
1624 void DecodeSignal::on_data_received()
1626 // If we detected a lack of input data when trying to start decoding,
1627 // we have set an error message. Only try again if we now have data
1629 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1632 error_message_.clear();
1633 // TODO Emulate noquote()
1634 qDebug().nospace() << name() << ": Error cleared";
1637 if (!logic_mux_thread_.joinable())
1640 logic_mux_cond_.notify_one();
1643 void DecodeSignal::on_annotation_visibility_changed()
1645 annotation_visibility_changed();