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/>.
23 #include <forward_list>
27 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
28 #include <QRegularExpression>
32 #include "logicsegment.hpp"
33 #include "decodesignal.hpp"
34 #include "signaldata.hpp"
36 #include <pv/data/decode/decoder.hpp>
37 #include <pv/data/decode/row.hpp>
38 #include <pv/globalsettings.hpp>
39 #include <pv/session.hpp>
41 using std::dynamic_pointer_cast;
42 using std::lock_guard;
43 using std::make_shared;
45 using std::out_of_range;
46 using std::shared_ptr;
47 using std::unique_lock;
48 using pv::data::decode::AnnotationClass;
49 using pv::data::decode::DecodeChannel;
54 const double DecodeSignal::DecodeMargin = 1.0;
55 const double DecodeSignal::DecodeThreshold = 0.2;
56 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
59 DecodeSignal::DecodeSignal(pv::Session &session) :
60 SignalBase(nullptr, SignalBase::DecodeChannel),
62 srd_session_(nullptr),
63 logic_mux_data_invalid_(false),
64 stack_config_changed_(true),
65 current_segment_id_(0)
67 connect(&session_, SIGNAL(capture_state_changed(int)),
68 this, SLOT(on_capture_state_changed(int)));
71 DecodeSignal::~DecodeSignal()
76 void DecodeSignal::set_name(QString name)
78 SignalBase::set_name(name);
80 update_output_signals();
83 void DecodeSignal::set_color(QColor color)
85 SignalBase::set_color(color);
87 update_output_signals();
90 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
95 void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
99 // Set name if this decoder is the first in the list or the name is unchanged
100 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
101 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
103 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
104 set_name(QString::fromUtf8(decoder->name));
106 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder, stack_.size());
107 stack_.push_back(dec);
109 connect(dec.get(), SIGNAL(annotation_visibility_changed()),
110 this, SLOT(on_annotation_visibility_changed()));
112 // Include the newly created decode channels in the channel lists
113 update_channel_list();
115 stack_config_changed_ = true;
116 auto_assign_signals(dec);
117 commit_decoder_channels();
118 update_output_signals();
120 decoder_stacked((void*)dec.get());
126 void DecodeSignal::remove_decoder(int index)
129 assert(index < (int)stack_.size());
131 // Find the decoder in the stack
132 auto iter = stack_.begin() + index;
133 assert(iter != stack_.end());
135 shared_ptr<Decoder> dec = *iter;
137 decoder_removed(dec.get());
139 // Delete the element
142 // Update channels and decoded data
143 stack_config_changed_ = true;
144 update_channel_list();
148 bool DecodeSignal::toggle_decoder_visibility(int index)
150 auto iter = stack_.cbegin();
151 for (int i = 0; i < index; i++, iter++)
152 assert(iter != stack_.end());
154 shared_ptr<Decoder> dec = *iter;
156 // Toggle decoder visibility
159 state = !dec->visible();
160 dec->set_visible(state);
166 void DecodeSignal::reset_decode(bool shutting_down)
168 resume_decode(); // Make sure the decode thread isn't blocked by pausing
170 if (stack_config_changed_ || shutting_down)
173 terminate_srd_session();
175 if (decode_thread_.joinable()) {
176 decode_interrupt_ = true;
177 decode_input_cond_.notify_one();
178 decode_thread_.join();
181 if (logic_mux_thread_.joinable()) {
182 logic_mux_interrupt_ = true;
183 logic_mux_cond_.notify_one();
184 logic_mux_thread_.join();
187 current_segment_id_ = 0;
190 for (const shared_ptr<decode::Decoder>& dec : stack_)
191 if (dec->has_logic_output())
192 output_logic_[dec->get_srd_decoder()]->clear();
194 logic_mux_data_.reset();
195 logic_mux_data_invalid_ = true;
197 if (!error_message_.isEmpty()) {
198 error_message_.clear();
199 // TODO Emulate noquote()
200 qDebug().nospace() << name() << ": Error cleared";
206 void DecodeSignal::begin_decode()
208 if (decode_thread_.joinable()) {
209 decode_interrupt_ = true;
210 decode_input_cond_.notify_one();
211 decode_thread_.join();
214 if (logic_mux_thread_.joinable()) {
215 logic_mux_interrupt_ = true;
216 logic_mux_cond_.notify_one();
217 logic_mux_thread_.join();
222 if (stack_.size() == 0) {
223 set_error_message(tr("No decoders"));
227 assert(channels_.size() > 0);
229 if (get_assigned_signal_count() == 0) {
230 set_error_message(tr("There are no channels assigned to this decoder"));
234 // Make sure that all assigned channels still provide logic data
235 // (can happen when a converted signal was assigned but the
236 // conversion removed in the meanwhile)
237 for (decode::DecodeChannel& ch : channels_)
238 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
239 ch.assigned_signal = nullptr;
241 // Check that all decoders have the required channels
242 for (const shared_ptr<Decoder>& dec : stack_)
243 if (!dec->have_required_channels()) {
244 set_error_message(tr("One or more required channels "
245 "have not been specified"));
249 // Free the logic data and its segment(s) if it needs to be updated
250 if (logic_mux_data_invalid_)
251 logic_mux_data_.reset();
253 if (!logic_mux_data_) {
254 const uint32_t ch_count = get_assigned_signal_count();
255 logic_mux_unit_size_ = (ch_count + 7) / 8;
256 logic_mux_data_ = make_shared<Logic>(ch_count);
259 if (get_input_segment_count() == 0)
260 set_error_message(tr("No input data"));
262 // Make sure the logic output data is complete and up-to-date
263 logic_mux_interrupt_ = false;
264 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
266 // Decode the muxed logic data
267 decode_interrupt_ = false;
268 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
271 void DecodeSignal::pause_decode()
273 decode_paused_ = true;
276 void DecodeSignal::resume_decode()
278 // Manual unlocking is done before notifying, to avoid waking up the
279 // waiting thread only to block again (see notify_one for details)
280 decode_pause_mutex_.unlock();
281 decode_pause_cond_.notify_one();
282 decode_paused_ = false;
285 bool DecodeSignal::is_paused() const
287 return decode_paused_;
290 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
295 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
297 bool new_assignment = false;
299 // Disconnect all input signal notifications so we don't have duplicate connections
300 disconnect_input_notifiers();
302 // Try to auto-select channels that don't have signals assigned yet
303 for (decode::DecodeChannel& ch : channels_) {
304 // If a decoder is given, auto-assign only its channels
305 if (dec && (ch.decoder_ != dec))
308 if (ch.assigned_signal)
311 QString ch_name = ch.name.toLower();
312 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
313 ch_name = ch_name.replace(QRegularExpression("[-_.]"), " ");
315 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
318 shared_ptr<data::SignalBase> match;
319 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
323 QString s_name = s->name().toLower();
324 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
325 s_name = s_name.replace(QRegularExpression("[-_.]"), " ");
327 s_name = s_name.replace(QRegExp("[-_.]"), " ");
330 if (s->logic_data() &&
331 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
335 // Only replace an existing match if it matches more characters
336 int old_unmatched = ch_name.length() - match->name().length();
337 int new_unmatched = ch_name.length() - s->name().length();
338 if (abs(new_unmatched) < abs(old_unmatched))
344 // Prevent using a signal more than once as D1 would match e.g. D1 and D10
345 bool signal_not_already_used = true;
346 for (decode::DecodeChannel& ch : channels_)
347 if (ch.assigned_signal && (ch.assigned_signal == match))
348 signal_not_already_used = false;
350 if (match && signal_not_already_used) {
351 ch.assigned_signal = match;
352 new_assignment = true;
356 if (new_assignment) {
357 // Receive notifications when new sample data is available
358 connect_input_notifiers();
360 logic_mux_data_invalid_ = true;
361 stack_config_changed_ = true;
362 commit_decoder_channels();
367 void DecodeSignal::assign_signal(const uint16_t channel_id, shared_ptr<const SignalBase> signal)
369 // Disconnect all input signal notifications so we don't have duplicate connections
370 disconnect_input_notifiers();
372 for (decode::DecodeChannel& ch : channels_)
373 if (ch.id == channel_id) {
374 ch.assigned_signal = signal;
375 logic_mux_data_invalid_ = true;
378 // Receive notifications when new sample data is available
379 connect_input_notifiers();
381 stack_config_changed_ = true;
382 commit_decoder_channels();
387 int DecodeSignal::get_assigned_signal_count() const
389 // Count all channels that have a signal assigned to them
390 return count_if(channels_.begin(), channels_.end(),
391 [](decode::DecodeChannel ch) { return ch.assigned_signal.get(); });
394 void DecodeSignal::update_output_signals()
396 for (const shared_ptr<decode::Decoder>& dec : stack_) {
399 if (dec->has_logic_output()) {
400 const vector<decode::DecoderLogicOutputChannel> logic_channels =
401 dec->logic_output_channels();
403 // All signals of a decoder share the same LogicSegment, so it's
404 // sufficient to check for only the first channel
405 const decode::DecoderLogicOutputChannel& first_ch = logic_channels[0];
407 bool ch_exists = false;
408 for (const shared_ptr<SignalBase>& signal : output_signals_)
409 if (signal->internal_name() == first_ch.id)
413 shared_ptr<Logic> logic_data = make_shared<Logic>(logic_channels.size());
414 logic_data->set_samplerate(get_samplerate());
415 output_logic_[dec->get_srd_decoder()] = logic_data;
416 output_logic_muxed_data_[dec->get_srd_decoder()] = vector<uint8_t>();
418 shared_ptr<LogicSegment> logic_segment = make_shared<data::LogicSegment>(
419 *logic_data, 0, (logic_data->num_channels() + 7) / 8, get_samplerate());
420 logic_data->push_segment(logic_segment);
423 for (const decode::DecoderLogicOutputChannel& logic_ch : logic_channels) {
424 shared_ptr<data::SignalBase> signal =
425 make_shared<data::SignalBase>(nullptr, LogicChannel);
426 signal->set_internal_name(logic_ch.id);
427 signal->set_index(index);
428 signal->set_data(logic_data);
429 output_signals_.push_back(signal);
430 session_.add_generated_signal(signal);
434 shared_ptr<Logic> logic_data = output_logic_[dec->get_srd_decoder()];
435 logic_data->set_samplerate(get_samplerate());
436 for (shared_ptr<LogicSegment>& segment : logic_data->logic_segments())
437 segment->set_samplerate(get_samplerate());
442 for (shared_ptr<SignalBase> s : output_signals_) {
443 s->set_name(s->internal_name() + " (" + name() + ")");
444 s->set_color(color());
447 // TODO Assert that all sample rates are the same as the session's
450 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
452 for (decode::DecodeChannel& ch : channels_)
453 if (ch.id == channel_id)
454 ch.initial_pin_state = init_state;
456 stack_config_changed_ = true;
461 double DecodeSignal::get_samplerate() const
465 // TODO For now, we simply return the first samplerate that we have
466 if (segments_.size() > 0)
467 result = segments_.front().samplerate;
472 const pv::util::Timestamp DecodeSignal::start_time() const
474 pv::util::Timestamp result;
476 // TODO For now, we simply return the first start time that we have
477 if (segments_.size() > 0)
478 result = segments_.front().start_time;
483 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
485 // The working sample count is the highest sample number for
486 // which all used signals have data available, so go through all
487 // channels and use the lowest overall sample count of the segment
489 int64_t count = std::numeric_limits<int64_t>::max();
490 bool no_signals_assigned = true;
492 for (const decode::DecodeChannel& ch : channels_)
493 if (ch.assigned_signal) {
494 if (!ch.assigned_signal->logic_data())
497 no_signals_assigned = false;
499 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
500 if (logic_data->logic_segments().empty())
503 if (segment_id >= logic_data->logic_segments().size())
506 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
508 count = min(count, (int64_t)segment->get_sample_count());
511 return (no_signals_assigned ? 0 : count);
514 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
515 bool include_processing) const
517 lock_guard<mutex> decode_lock(output_mutex_);
521 if (segment_id >= segments_.size())
524 if (include_processing)
525 result = segments_[segment_id].samples_decoded_incl;
527 result = segments_[segment_id].samples_decoded_excl;
532 vector<Row*> DecodeSignal::get_rows(bool visible_only)
536 for (const shared_ptr<Decoder>& dec : stack_) {
538 if (visible_only && !dec->visible())
541 for (Row* row : dec->get_rows())
548 vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
550 vector<const Row*> rows;
552 for (const shared_ptr<Decoder>& dec : stack_) {
554 if (visible_only && !dec->visible())
557 for (const Row* row : dec->get_rows())
564 uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
566 if (segment_id >= segments_.size())
569 const DecodeSegment* segment = &(segments_.at(segment_id));
571 auto row_it = segment->annotation_rows.find(row);
574 if (row_it == segment->annotation_rows.end())
577 rd = &(row_it->second);
579 return rd->get_annotation_count();
582 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
583 const Row* row, uint32_t segment_id, uint64_t start_sample,
584 uint64_t end_sample) const
586 lock_guard<mutex> lock(output_mutex_);
588 if (segment_id >= segments_.size())
591 const DecodeSegment* segment = &(segments_.at(segment_id));
593 auto row_it = segment->annotation_rows.find(row);
596 if (row_it == segment->annotation_rows.end())
599 rd = &(row_it->second);
601 rd->get_annotation_subset(dest, start_sample, end_sample);
604 void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
605 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
607 for (const Row* row : get_rows())
608 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
611 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
612 const Decoder* dec, uint32_t bin_class_id) const
614 if ((segments_.size() == 0) || (segment_id >= segments_.size()))
617 const DecodeSegment *segment = &(segments_[segment_id]);
619 for (const DecodeBinaryClass& bc : segment->binary_classes)
620 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
621 return bc.chunks.size();
626 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
627 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
628 const vector<uint8_t> **dest, uint64_t *size)
630 if (segment_id >= segments_.size())
633 const DecodeSegment *segment = &(segments_[segment_id]);
635 for (const DecodeBinaryClass& bc : segment->binary_classes)
636 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
637 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
638 if (size) *size = bc.chunks.at(chunk_id).data.size();
643 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
644 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
645 uint64_t end_sample, vector<uint8_t> *dest) const
647 assert(dest != nullptr);
649 if (segment_id >= segments_.size())
652 const DecodeSegment *segment = &(segments_[segment_id]);
654 const DecodeBinaryClass* bin_class = nullptr;
655 for (const DecodeBinaryClass& bc : segment->binary_classes)
656 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
659 // Determine overall size before copying to resize dest vector only once
661 uint64_t matches = 0;
662 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
663 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
664 size += chunk.data.size();
670 uint64_t matches2 = 0;
671 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
672 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
673 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
674 offset += chunk.data.size();
677 // Make sure we don't overwrite memory if the array grew in the meanwhile
678 if (matches2 == matches)
683 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
684 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
685 vector<uint8_t> *dest) const
687 assert(dest != nullptr);
689 if (segment_id >= segments_.size())
692 const DecodeSegment *segment = &(segments_[segment_id]);
694 const DecodeBinaryClass* bin_class = nullptr;
695 for (const DecodeBinaryClass& bc : segment->binary_classes)
696 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
699 // Determine overall size before copying to resize dest vector only once
702 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
704 size += chunk.data.size();
705 offset += chunk.data.size();
712 uint64_t dest_offset = 0;
713 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
714 if (offset >= start) {
715 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
716 dest_offset += chunk.data.size();
718 offset += chunk.data.size();
724 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
725 const Decoder* dec, uint32_t bin_class_id) const
727 if (segment_id >= segments_.size())
730 const DecodeSegment *segment = &(segments_[segment_id]);
732 for (const DecodeBinaryClass& bc : segment->binary_classes)
733 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
739 const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
740 uint32_t segment_id) const
742 if (segment_id >= segments_.size())
745 const DecodeSegment *segment = &(segments_[segment_id]);
747 return &(segment->all_annotations);
750 void DecodeSignal::save_settings(QSettings &settings) const
752 SignalBase::save_settings(settings);
754 settings.setValue("decoders", (int)(stack_.size()));
756 // Save decoder stack
758 for (const shared_ptr<Decoder>& decoder : stack_) {
759 settings.beginGroup("decoder" + QString::number(decoder_idx++));
761 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
762 settings.setValue("id", (const char *)decoder->get_srd_decoder()->id);
764 settings.setValue("id", decoder->get_srd_decoder()->id);
766 settings.setValue("visible", decoder->visible());
768 // Save decoder options
769 const map<string, GVariant*>& options = decoder->options();
771 settings.setValue("options", (int)options.size());
773 // Note: Decoder::options() returns only the options
774 // that differ from the default. See binding::Decoder::getter()
776 for (auto& option : options) {
777 settings.beginGroup("option" + QString::number(i));
778 settings.setValue("name", QString::fromStdString(option.first));
779 GlobalSettings::store_gvariant(settings, option.second);
784 // Save row properties
786 for (const Row* row : decoder->get_rows()) {
787 settings.beginGroup("row" + QString::number(i));
788 settings.setValue("visible", row->visible());
793 // Save class properties
795 for (const AnnotationClass* ann_class : decoder->ann_classes()) {
796 settings.beginGroup("ann_class" + QString::number(i));
797 settings.setValue("visible", ann_class->visible());
805 // Save channel mapping
806 settings.setValue("channels", (int)channels_.size());
808 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
809 auto channel = find_if(channels_.begin(), channels_.end(),
810 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
812 if (channel == channels_.end()) {
813 qDebug() << "ERROR: Gap in channel index:" << channel_id;
817 settings.beginGroup("channel" + QString::number(channel_id));
819 settings.setValue("name", channel->name); // Useful for debugging
820 settings.setValue("initial_pin_state", channel->initial_pin_state);
822 if (channel->assigned_signal)
823 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
828 // TODO Save logic output signal settings
831 void DecodeSignal::restore_settings(QSettings &settings)
833 SignalBase::restore_settings(settings);
835 // Restore decoder stack
836 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
838 int decoders = settings.value("decoders").toInt();
840 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
841 settings.beginGroup("decoder" + QString::number(decoder_idx));
843 QString id = settings.value("id").toString();
845 for (GSList *entry = dec_list; entry; entry = entry->next) {
846 const srd_decoder *dec = (srd_decoder*)entry->data;
850 if (QString::fromUtf8(dec->id) == id) {
851 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec, stack_.size());
853 connect(decoder.get(), SIGNAL(annotation_visibility_changed()),
854 this, SLOT(on_annotation_visibility_changed()));
856 stack_.push_back(decoder);
857 decoder->set_visible(settings.value("visible", true).toBool());
859 // Restore decoder options that differ from their default
860 int options = settings.value("options").toInt();
862 for (int i = 0; i < options; i++) {
863 settings.beginGroup("option" + QString::number(i));
864 QString name = settings.value("name").toString();
865 GVariant *value = GlobalSettings::restore_gvariant(settings);
866 decoder->set_option(name.toUtf8(), value);
870 // Include the newly created decode channels in the channel lists
871 update_channel_list();
873 // Restore row properties
875 for (Row* row : decoder->get_rows()) {
876 settings.beginGroup("row" + QString::number(i));
877 row->set_visible(settings.value("visible", true).toBool());
882 // Restore class properties
884 for (AnnotationClass* ann_class : decoder->ann_classes()) {
885 settings.beginGroup("ann_class" + QString::number(i));
886 ann_class->set_visible(settings.value("visible", true).toBool());
899 // Restore channel mapping
900 unsigned int channels = settings.value("channels").toInt();
902 const vector< shared_ptr<data::SignalBase> > signalbases =
903 session_.signalbases();
905 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
906 auto channel = find_if(channels_.begin(), channels_.end(),
907 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
909 if (channel == channels_.end()) {
910 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
914 settings.beginGroup("channel" + QString::number(channel_id));
916 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
918 for (const shared_ptr<data::SignalBase>& signal : signalbases)
919 if ((signal->name() == assigned_signal_name) && (signal->type() != SignalBase::DecodeChannel))
920 channel->assigned_signal = signal;
922 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
927 connect_input_notifiers();
929 // Update the internal structures
930 stack_config_changed_ = true;
931 update_channel_list();
932 commit_decoder_channels();
933 update_output_signals();
935 // TODO Restore logic output signal settings
940 bool DecodeSignal::all_input_segments_complete(uint32_t segment_id) const
942 bool all_complete = true;
944 for (const decode::DecodeChannel& ch : channels_)
945 if (ch.assigned_signal) {
946 if (!ch.assigned_signal->logic_data())
949 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
950 if (logic_data->logic_segments().empty())
953 if (segment_id >= logic_data->logic_segments().size())
956 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
957 if (segment && !segment->is_complete())
958 all_complete = false;
964 uint32_t DecodeSignal::get_input_segment_count() const
966 uint64_t count = std::numeric_limits<uint64_t>::max();
967 bool no_signals_assigned = true;
969 for (const decode::DecodeChannel& ch : channels_)
970 if (ch.assigned_signal) {
971 no_signals_assigned = false;
973 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
974 if (!logic_data || logic_data->logic_segments().empty())
977 // Find the min value of all segment counts
978 if ((uint64_t)(logic_data->logic_segments().size()) < count)
979 count = logic_data->logic_segments().size();
982 return (no_signals_assigned ? 0 : count);
985 double DecodeSignal::get_input_samplerate(uint32_t segment_id) const
987 double samplerate = 0;
989 for (const decode::DecodeChannel& ch : channels_)
990 if (ch.assigned_signal) {
991 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
992 if (!logic_data || logic_data->logic_segments().empty())
996 const shared_ptr<const LogicSegment> segment =
997 logic_data->logic_segments().at(segment_id)->get_shared_ptr();
999 samplerate = segment->samplerate();
1000 } catch (out_of_range&) {
1009 Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
1011 for (shared_ptr<Decoder>& d : stack_)
1012 if (d->get_srd_decoder() == srd_dec)
1018 void DecodeSignal::update_channel_list()
1020 vector<decode::DecodeChannel> prev_channels = channels_;
1025 // Copy existing entries, create new as needed
1026 for (shared_ptr<Decoder>& decoder : stack_) {
1027 const srd_decoder* srd_dec = decoder->get_srd_decoder();
1030 // Mandatory channels
1031 for (l = srd_dec->channels; l; l = l->next) {
1032 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
1033 bool ch_added = false;
1035 // Copy but update ID if this channel was in the list before
1036 for (decode::DecodeChannel& ch : prev_channels)
1037 if (ch.pdch_ == pdch) {
1039 channels_.push_back(ch);
1045 // Create new entry without a mapped signal
1046 decode::DecodeChannel ch = {id++, 0, false, nullptr,
1047 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
1048 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
1049 channels_.push_back(ch);
1053 // Optional channels
1054 for (l = srd_dec->opt_channels; l; l = l->next) {
1055 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
1056 bool ch_added = false;
1058 // Copy but update ID if this channel was in the list before
1059 for (decode::DecodeChannel& ch : prev_channels)
1060 if (ch.pdch_ == pdch) {
1062 channels_.push_back(ch);
1068 // Create new entry without a mapped signal
1069 decode::DecodeChannel ch = {id++, 0, true, nullptr,
1070 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
1071 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
1072 channels_.push_back(ch);
1077 // Invalidate the logic output data if the channel assignment changed
1078 if (prev_channels.size() != channels_.size()) {
1079 // The number of channels changed, there's definitely a difference
1080 logic_mux_data_invalid_ = true;
1082 // Same number but assignment may still differ, so compare all channels
1083 for (size_t i = 0; i < channels_.size(); i++) {
1084 const decode::DecodeChannel& p_ch = prev_channels[i];
1085 const decode::DecodeChannel& ch = channels_[i];
1087 if ((p_ch.pdch_ != ch.pdch_) ||
1088 (p_ch.assigned_signal != ch.assigned_signal)) {
1089 logic_mux_data_invalid_ = true;
1099 void DecodeSignal::commit_decoder_channels()
1101 // Submit channel list to every decoder, containing only the relevant channels
1102 for (shared_ptr<Decoder> dec : stack_) {
1103 vector<decode::DecodeChannel*> channel_list;
1105 for (decode::DecodeChannel& ch : channels_)
1106 if (ch.decoder_ == dec)
1107 channel_list.push_back(&ch);
1109 dec->set_channels(channel_list);
1112 // Channel bit IDs must be in sync with the channel's apperance in channels_
1114 for (decode::DecodeChannel& ch : channels_)
1115 if (ch.assigned_signal)
1119 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
1121 // Enforce end to be greater than start
1125 // Fetch the channel segments and their data
1126 vector<shared_ptr<const LogicSegment> > segments;
1127 vector<const uint8_t*> signal_data;
1128 vector<uint8_t> signal_in_bytepos;
1129 vector<uint8_t> signal_in_bitpos;
1131 for (decode::DecodeChannel& ch : channels_)
1132 if (ch.assigned_signal) {
1133 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1135 shared_ptr<const LogicSegment> segment;
1136 if (segment_id < logic_data->logic_segments().size()) {
1137 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
1139 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1140 << "has no logic segment" << segment_id;
1141 logic_mux_interrupt_ = true;
1148 segments.push_back(segment);
1150 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1151 segment->get_samples(start, end, data);
1152 signal_data.push_back(data);
1154 const int bitpos = ch.assigned_signal->logic_bit_index();
1155 signal_in_bytepos.push_back(bitpos / 8);
1156 signal_in_bitpos.push_back(bitpos % 8);
1159 shared_ptr<LogicSegment> output_segment;
1161 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1162 } catch (out_of_range&) {
1163 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1164 << segment_id << "in mux_logic_samples(), mux segments size is" \
1165 << logic_mux_data_->logic_segments().size();
1166 logic_mux_interrupt_ = true;
1170 // Perform the muxing of signal data into the output data
1171 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1172 unsigned int signal_count = signal_data.size();
1174 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1178 uint8_t bytepos = 0;
1180 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1181 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1182 output[out_sample_pos + i] = 0;
1184 for (unsigned int i = 0; i < signal_count; i++) {
1185 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1186 const uint8_t in_sample = 1 &
1187 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1189 const uint8_t out_sample = output[out_sample_pos + bytepos];
1191 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1201 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1204 for (const uint8_t* data : signal_data)
1208 void DecodeSignal::logic_mux_proc()
1210 uint32_t input_segment_count;
1212 input_segment_count = get_input_segment_count();
1213 if (input_segment_count == 0) {
1214 // Wait for input data
1215 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1216 logic_mux_cond_.wait(logic_mux_lock);
1218 } while ((!logic_mux_interrupt_) && (input_segment_count == 0));
1220 if (logic_mux_interrupt_)
1223 assert(logic_mux_data_);
1225 uint32_t segment_id = 0;
1227 // Create initial logic mux segment
1228 shared_ptr<LogicSegment> output_segment =
1229 make_shared<LogicSegment>(*logic_mux_data_, segment_id, logic_mux_unit_size_, 0);
1230 logic_mux_data_->push_segment(output_segment);
1232 output_segment->set_samplerate(get_input_samplerate(0));
1234 // Logic mux data is being updated
1235 logic_mux_data_invalid_ = false;
1237 uint64_t samples_to_process;
1240 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1241 const uint64_t output_sample_count = output_segment->get_sample_count();
1243 samples_to_process =
1244 (input_sample_count > output_sample_count) ?
1245 (input_sample_count - output_sample_count) : 0;
1247 if (samples_to_process > 0) {
1248 const uint64_t unit_size = output_segment->unit_size();
1249 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1251 uint64_t processed_samples = 0;
1253 const uint64_t start_sample = output_sample_count + processed_samples;
1254 const uint64_t sample_count =
1255 min(samples_to_process - processed_samples, chunk_sample_count);
1257 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1258 processed_samples += sample_count;
1260 // ...and process the newly muxed logic data
1261 decode_input_cond_.notify_one();
1262 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1264 } while (!logic_mux_interrupt_ && (samples_to_process > 0));
1266 if (!logic_mux_interrupt_) {
1267 // samples_to_process is now 0, we've exhausted the currently available input data
1269 // If the input segments are complete, we've completed this segment
1270 if (all_input_segments_complete(segment_id)) {
1271 if (!output_segment->is_complete())
1272 output_segment->set_complete();
1274 if (segment_id < get_input_segment_count() - 1) {
1276 // Process next segment
1280 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1281 logic_mux_unit_size_, 0);
1282 logic_mux_data_->push_segment(output_segment);
1284 output_segment->set_samplerate(get_input_samplerate(segment_id));
1286 // Wait for more input data if we're processing the currently last segment
1287 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1288 logic_mux_cond_.wait(logic_mux_lock);
1291 // Input segments aren't all complete yet but samples_to_process is 0, wait for more input data
1292 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1293 logic_mux_cond_.wait(logic_mux_lock);
1296 } while (!logic_mux_interrupt_);
1299 void DecodeSignal::decode_data(
1300 const int64_t abs_start_samplenum, const int64_t sample_count,
1301 const shared_ptr<const LogicSegment> input_segment)
1303 const int64_t unit_size = input_segment->unit_size();
1304 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1306 for (int64_t i = abs_start_samplenum;
1307 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
1308 i += chunk_sample_count) {
1310 const int64_t chunk_end = min(i + chunk_sample_count,
1311 abs_start_samplenum + sample_count);
1314 lock_guard<mutex> lock(output_mutex_);
1315 // Update the sample count showing the samples including currently processed ones
1316 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1319 int64_t data_size = (chunk_end - i) * unit_size;
1320 uint8_t* chunk = new uint8_t[data_size];
1321 input_segment->get_samples(i, chunk_end, chunk);
1323 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1324 data_size, unit_size) != SRD_OK) {
1325 set_error_message(tr("Decoder reported an error"));
1326 decode_interrupt_ = true;
1332 lock_guard<mutex> lock(output_mutex_);
1333 // Now that all samples are processed, the exclusive sample count catches up
1334 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1337 // Notify the frontend that we processed some data and
1338 // possibly have new annotations as well
1341 if (decode_paused_) {
1342 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1343 decode_pause_cond_.wait(pause_wait_lock);
1348 void DecodeSignal::decode_proc()
1350 current_segment_id_ = 0;
1352 // If there is no input data available yet, wait until it is or we're interrupted
1354 if (logic_mux_data_->logic_segments().size() == 0) {
1355 // Wait for input data
1356 unique_lock<mutex> input_wait_lock(input_mutex_);
1357 decode_input_cond_.wait(input_wait_lock);
1359 } while ((!decode_interrupt_) && (logic_mux_data_->logic_segments().size() == 0));
1361 if (decode_interrupt_)
1364 shared_ptr<const LogicSegment> input_segment = logic_mux_data_->logic_segments().front()->get_shared_ptr();
1368 // Create the initial segment and set its sample rate so that we can pass it to SRD
1369 create_decode_segment();
1370 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1371 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1373 start_srd_session();
1375 uint64_t samples_to_process = 0;
1376 uint64_t abs_start_samplenum = 0;
1378 // Keep processing new samples until we exhaust the input data
1380 samples_to_process = input_segment->get_sample_count() - abs_start_samplenum;
1382 if (samples_to_process > 0) {
1383 decode_data(abs_start_samplenum, samples_to_process, input_segment);
1384 abs_start_samplenum += samples_to_process;
1386 } while (!decode_interrupt_ && (samples_to_process > 0));
1388 if (!decode_interrupt_) {
1389 // samples_to_process is now 0, we've exhausted the currently available input data
1391 // If the input segment is complete, we've exhausted this segment
1392 if (input_segment->is_complete()) {
1393 #if defined HAVE_SRD_SESSION_SEND_EOF && HAVE_SRD_SESSION_SEND_EOF
1394 // Tell protocol decoders about the end of
1395 // the input data, which may result in more
1396 // annotations being emitted
1397 (void)srd_session_send_eof(srd_session_);
1401 if (current_segment_id_ < (logic_mux_data_->logic_segments().size() - 1)) {
1402 // Process next segment
1403 current_segment_id_++;
1406 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1407 } catch (out_of_range&) {
1408 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1409 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1410 << logic_mux_data_->logic_segments().size();
1411 decode_interrupt_ = true;
1414 abs_start_samplenum = 0;
1416 // Create the next segment and set its metadata
1417 create_decode_segment();
1418 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1419 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1421 // Reset decoder state but keep the decoder stack intact
1422 terminate_srd_session();
1424 // All segments have been processed
1425 if (!decode_interrupt_)
1428 // Wait for more input data
1429 unique_lock<mutex> input_wait_lock(input_mutex_);
1430 decode_input_cond_.wait(input_wait_lock);
1433 // Input segment isn't complete yet but samples_to_process is 0, wait for more input data
1434 unique_lock<mutex> input_wait_lock(input_mutex_);
1435 decode_input_cond_.wait(input_wait_lock);
1439 } while (!decode_interrupt_);
1442 void DecodeSignal::start_srd_session()
1444 // If there were stack changes, the session has been destroyed by now, so if
1445 // it hasn't been destroyed, we can just reset and re-use it
1447 // When a decoder stack was created before, re-use it
1448 // for the next stream of input data, after terminating
1449 // potentially still executing operations, and resetting
1450 // internal state. Skip the rather expensive (teardown
1451 // and) construction of another decoder stack.
1453 // TODO Reduce redundancy, use a common code path for
1454 // the meta/start sequence?
1455 terminate_srd_session();
1457 // Metadata is cleared also, so re-set it
1458 uint64_t samplerate = 0;
1459 if (segments_.size() > 0)
1460 samplerate = segments_.at(current_segment_id_).samplerate;
1462 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1463 g_variant_new_uint64(samplerate));
1464 for (const shared_ptr<Decoder>& dec : stack_)
1465 dec->apply_all_options();
1466 srd_session_start(srd_session_);
1471 // Update the samplerates for the output logic channels
1472 update_output_signals();
1474 // Create the session
1475 srd_session_new(&srd_session_);
1476 assert(srd_session_);
1478 // Create the decoders
1479 srd_decoder_inst *prev_di = nullptr;
1480 for (const shared_ptr<Decoder>& dec : stack_) {
1481 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1484 set_error_message(tr("Failed to create decoder instance"));
1485 srd_session_destroy(srd_session_);
1486 srd_session_ = nullptr;
1491 srd_inst_stack(srd_session_, prev_di, di);
1496 // Start the session
1497 if (segments_.size() > 0)
1498 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1499 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1501 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1502 DecodeSignal::annotation_callback, this);
1504 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1505 DecodeSignal::binary_callback, this);
1507 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_LOGIC,
1508 DecodeSignal::logic_output_callback, this);
1510 srd_session_start(srd_session_);
1512 // We just recreated the srd session, so all stack changes are applied now
1513 stack_config_changed_ = false;
1516 void DecodeSignal::terminate_srd_session()
1518 // Call the "terminate and reset" routine for the decoder stack
1519 // (if available). This does not harm those stacks which already
1520 // have completed their operation, and reduces response time for
1521 // those stacks which still are processing data while the
1522 // application no longer wants them to.
1524 #if defined HAVE_SRD_SESSION_SEND_EOF && HAVE_SRD_SESSION_SEND_EOF
1525 (void)srd_session_send_eof(srd_session_);
1527 srd_session_terminate_reset(srd_session_);
1529 // Metadata is cleared also, so re-set it
1530 uint64_t samplerate = 0;
1531 if (segments_.size() > 0)
1532 samplerate = segments_.at(current_segment_id_).samplerate;
1534 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1535 g_variant_new_uint64(samplerate));
1536 for (const shared_ptr<Decoder>& dec : stack_)
1537 dec->apply_all_options();
1541 void DecodeSignal::stop_srd_session()
1544 // Destroy the session
1545 srd_session_destroy(srd_session_);
1546 srd_session_ = nullptr;
1548 // Mark the decoder instances as non-existant since they were deleted
1549 for (const shared_ptr<Decoder>& dec : stack_)
1550 dec->invalidate_decoder_inst();
1554 void DecodeSignal::connect_input_notifiers()
1556 // Connect the currently used signals to our slot
1557 for (decode::DecodeChannel& ch : channels_) {
1558 if (!ch.assigned_signal)
1560 const data::SignalBase *signal = ch.assigned_signal.get();
1562 connect(signal, SIGNAL(samples_cleared()),
1563 this, SLOT(on_data_cleared()), Qt::UniqueConnection);
1564 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1565 this, SLOT(on_data_received()), Qt::UniqueConnection);
1567 if (signal->logic_data())
1568 connect(signal->logic_data().get(), SIGNAL(segment_completed()),
1569 this, SLOT(on_input_segment_completed()), Qt::UniqueConnection);
1573 void DecodeSignal::disconnect_input_notifiers()
1575 // Disconnect the notification slot from the previous set of signals
1576 for (decode::DecodeChannel& ch : channels_) {
1577 if (!ch.assigned_signal)
1579 const data::SignalBase *signal = ch.assigned_signal.get();
1580 disconnect(signal, nullptr, this, SLOT(on_data_cleared()));
1581 disconnect(signal, nullptr, this, SLOT(on_data_received()));
1583 if (signal->logic_data())
1584 disconnect(signal->logic_data().get(), nullptr, this, SLOT(on_input_segment_completed()));
1588 void DecodeSignal::create_decode_segment()
1590 // Create annotation segment
1591 segments_.emplace_back();
1593 // Add annotation classes
1594 for (const shared_ptr<Decoder>& dec : stack_)
1595 for (Row* row : dec->get_rows())
1596 segments_.back().annotation_rows.emplace(row, RowData(row));
1598 // Prepare our binary output classes
1599 for (const shared_ptr<Decoder>& dec : stack_) {
1600 uint32_t n = dec->get_binary_class_count();
1602 for (uint32_t i = 0; i < n; i++)
1603 segments_.back().binary_classes.push_back(
1604 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1608 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1611 assert(decode_signal);
1613 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1616 if (ds->decode_interrupt_)
1619 if (ds->segments_.empty())
1622 lock_guard<mutex> lock(ds->output_mutex_);
1624 // Get the decoder and the annotation data
1626 assert(pdata->pdo->di);
1627 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1630 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1634 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1637 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1639 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1640 "with class ID" << pda->ann_class << "but there are only" <<
1641 dec->ann_classes().size() << "known classes";
1645 const Row* row = ann_class->row;
1648 row = dec->get_row_by_id(0);
1650 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1652 // Add the annotation to the row
1653 const Annotation* ann = row_data.emplace_annotation(pdata);
1655 // We insert the annotation into the global annotation list in a way so that
1656 // the annotation list is sorted by start sample and length. Otherwise, we'd
1657 // have to sort the model, which is expensive
1658 deque<const Annotation*>& all_annotations =
1659 ds->segments_[ds->current_segment_id_].all_annotations;
1661 if (all_annotations.empty()) {
1662 all_annotations.emplace_back(ann);
1664 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1665 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1666 bool ann_is_longer = (new_ann_len >
1667 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1669 if (ann_has_earlier_start && ann_is_longer) {
1670 bool ann_has_same_start;
1671 auto it = all_annotations.end();
1675 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1676 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
1677 ann_is_longer = (new_ann_len > (*it)->length());
1678 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1680 // Allow inserting at the front
1681 if (it != all_annotations.begin())
1684 all_annotations.emplace(it, ann);
1686 all_annotations.emplace_back(ann);
1689 // When emplace_annotation() inserts instead of appends an annotation,
1690 // the pointers in all_annotations that follow the inserted annotation and
1691 // point to annotations for this row are off by one and must be updated
1692 if (&(row_data.annotations().back()) != ann) {
1693 // Search backwards until we find the annotation we just added
1694 auto row_it = row_data.annotations().end();
1695 auto all_it = all_annotations.end();
1698 if ((*all_it)->row_data() == &row_data)
1700 } while (&(*row_it) != ann);
1702 // Update the annotation addresses for this row's annotations until the end
1704 if ((*all_it)->row_data() == &row_data) {
1705 *all_it = &(*row_it);
1709 } while (all_it != all_annotations.end());
1713 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1716 assert(decode_signal);
1718 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1721 if (ds->decode_interrupt_)
1724 // Get the decoder and the binary data
1726 assert(pdata->pdo->di);
1727 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1730 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1733 // Find the matching DecodeBinaryClass
1734 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1736 DecodeBinaryClass* bin_class = nullptr;
1737 for (DecodeBinaryClass& bc : segment->binary_classes)
1738 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1739 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1743 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1744 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1745 ", segment only knows" << segment->binary_classes.size() << "classes";
1749 // Add the data chunk
1750 bin_class->chunks.emplace_back();
1751 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1753 chunk->sample = pdata->start_sample;
1754 chunk->data.resize(pdb->size);
1755 memcpy(chunk->data.data(), pdb->data, pdb->size);
1757 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1759 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1762 void DecodeSignal::logic_output_callback(srd_proto_data *pdata, void *decode_signal)
1765 assert(decode_signal);
1767 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1770 if (ds->decode_interrupt_)
1773 lock_guard<mutex> lock(ds->output_mutex_);
1776 assert(pdata->pdo->di);
1777 const srd_decoder *const decc = pdata->pdo->di->decoder;
1780 const srd_proto_data_logic *const pdl = (const srd_proto_data_logic*)pdata->data;
1783 // FIXME Only one group supported for now
1784 if (pdl->logic_group > 0) {
1785 qWarning() << "Received logic output state change for group" << pdl->logic_group << "from decoder" \
1786 << QString::fromUtf8(decc->name) << "but only group 0 is currently supported";
1790 shared_ptr<Logic> output_logic = ds->output_logic_.at(decc);
1792 vector< shared_ptr<Segment> > segments = output_logic->segments();
1794 shared_ptr<LogicSegment> last_segment;
1796 if (!segments.empty())
1797 last_segment = dynamic_pointer_cast<LogicSegment>(segments.back());
1799 // Happens when the data was cleared - all segments are gone then
1800 // segment_id is always 0 as it's the first segment
1801 last_segment = make_shared<data::LogicSegment>(
1802 *output_logic, 0, (output_logic->num_channels() + 7) / 8, output_logic->get_samplerate());
1803 output_logic->push_segment(last_segment);
1806 if (pdata->start_sample < pdata->end_sample) {
1807 vector<uint8_t> data;
1808 const unsigned int unit_size = last_segment->unit_size();
1809 data.resize(unit_size * (1 + pdl->repeat_count));
1812 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1813 data.data()[i * unit_size] = *((uint8_t*)pdl->data);
1814 else if (unit_size == 2)
1815 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1816 data.data()[i * unit_size] = *((uint16_t*)pdl->data);
1817 else if (unit_size <= 4)
1818 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1819 data.data()[i * unit_size] = *((uint32_t*)pdl->data);
1820 else if (unit_size <= 8)
1821 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1822 data.data()[i * unit_size] = *((uint64_t*)pdl->data);
1824 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1825 memcpy((void*)&data.data()[i * unit_size], (void*)pdl->data, unit_size);
1827 last_segment->append_payload(data.data(), data.size());
1829 qWarning() << "Ignoring malformed logic output state change for group" << pdl->logic_group << "from decoder" \
1830 << QString::fromUtf8(decc->name) << "from" << pdata->start_sample << "to" << pdata->end_sample;
1833 void DecodeSignal::on_capture_state_changed(int state)
1835 // If a new acquisition was started, we need to start decoding from scratch
1836 if (state == Session::Running) {
1837 logic_mux_data_invalid_ = true;
1842 void DecodeSignal::on_data_cleared()
1847 void DecodeSignal::on_data_received()
1849 // If we detected a lack of input data when trying to start decoding,
1850 // we have set an error message. Bail out if we still don't have data
1852 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1855 if (!error_message_.isEmpty()) {
1856 error_message_.clear();
1857 // TODO Emulate noquote()
1858 qDebug().nospace() << name() << ": Input data available, error cleared";
1861 if (!logic_mux_thread_.joinable())
1864 logic_mux_cond_.notify_one();
1867 void DecodeSignal::on_input_segment_completed()
1869 if (!logic_mux_thread_.joinable())
1870 logic_mux_cond_.notify_one();
1873 void DecodeSignal::on_annotation_visibility_changed()
1875 annotation_visibility_changed();