2 * This file is part of the PulseView project.
4 * Copyright (C) 2017 Soeren Apel <soeren@apelpie.net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <forward_list>
27 #include "logicsegment.hpp"
28 #include "decodesignal.hpp"
29 #include "signaldata.hpp"
31 #include <pv/data/decode/decoder.hpp>
32 #include <pv/data/decode/row.hpp>
33 #include <pv/globalsettings.hpp>
34 #include <pv/session.hpp>
36 using std::forward_list;
37 using std::lock_guard;
39 using std::make_shared;
41 using std::out_of_range;
42 using std::shared_ptr;
43 using std::unique_lock;
44 using pv::data::decode::Annotation;
45 using pv::data::decode::AnnotationClass;
46 using pv::data::decode::DecodeChannel;
47 using pv::data::decode::Decoder;
48 using pv::data::decode::Row;
53 const double DecodeSignal::DecodeMargin = 1.0;
54 const double DecodeSignal::DecodeThreshold = 0.2;
55 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
58 DecodeSignal::DecodeSignal(pv::Session &session) :
59 SignalBase(nullptr, SignalBase::DecodeChannel),
61 srd_session_(nullptr),
62 logic_mux_data_invalid_(false),
63 stack_config_changed_(true),
64 current_segment_id_(0)
66 connect(&session_, SIGNAL(capture_state_changed(int)),
67 this, SLOT(on_capture_state_changed(int)));
70 DecodeSignal::~DecodeSignal()
75 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
80 void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
84 // Set name if this decoder is the first in the list or the name is unchanged
85 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
86 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
88 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
89 set_name(QString::fromUtf8(decoder->name));
91 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder);
92 stack_.push_back(dec);
94 // Include the newly created decode channels in the channel lists
95 update_channel_list();
97 stack_config_changed_ = true;
98 auto_assign_signals(dec);
99 commit_decoder_channels();
101 decoder_stacked((void*)dec.get());
107 void DecodeSignal::remove_decoder(int index)
110 assert(index < (int)stack_.size());
112 // Find the decoder in the stack
113 auto iter = stack_.begin();
114 for (int i = 0; i < index; i++, iter++)
115 assert(iter != stack_.end());
117 decoder_removed(iter->get());
119 // Delete the element
122 // Update channels and decoded data
123 stack_config_changed_ = true;
124 update_channel_list();
128 bool DecodeSignal::toggle_decoder_visibility(int index)
130 auto iter = stack_.cbegin();
131 for (int i = 0; i < index; i++, iter++)
132 assert(iter != stack_.end());
134 shared_ptr<Decoder> dec = *iter;
136 // Toggle decoder visibility
139 state = !dec->shown();
146 void DecodeSignal::reset_decode(bool shutting_down)
148 if (stack_config_changed_ || shutting_down)
151 terminate_srd_session();
153 if (decode_thread_.joinable()) {
154 decode_interrupt_ = true;
155 decode_input_cond_.notify_one();
156 decode_thread_.join();
159 if (logic_mux_thread_.joinable()) {
160 logic_mux_interrupt_ = true;
161 logic_mux_cond_.notify_one();
162 logic_mux_thread_.join();
165 resume_decode(); // Make sure the decode thread isn't blocked by pausing
167 current_segment_id_ = 0;
170 logic_mux_data_.reset();
171 logic_mux_data_invalid_ = true;
173 if (!error_message_.isEmpty()) {
174 error_message_ = QString();
175 // TODO Emulate noquote()
176 qDebug().nospace() << name() << ": Error cleared";
182 void DecodeSignal::begin_decode()
184 if (decode_thread_.joinable()) {
185 decode_interrupt_ = true;
186 decode_input_cond_.notify_one();
187 decode_thread_.join();
190 if (logic_mux_thread_.joinable()) {
191 logic_mux_interrupt_ = true;
192 logic_mux_cond_.notify_one();
193 logic_mux_thread_.join();
198 if (stack_.size() == 0) {
199 set_error_message(tr("No decoders"));
203 assert(channels_.size() > 0);
205 if (get_assigned_signal_count() == 0) {
206 set_error_message(tr("There are no channels assigned to this decoder"));
210 // Make sure that all assigned channels still provide logic data
211 // (can happen when a converted signal was assigned but the
212 // conversion removed in the meanwhile)
213 for (decode::DecodeChannel& ch : channels_)
214 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
215 ch.assigned_signal = nullptr;
217 // Check that all decoders have the required channels
218 for (const shared_ptr<Decoder>& dec : stack_)
219 if (!dec->have_required_channels()) {
220 set_error_message(tr("One or more required channels "
221 "have not been specified"));
225 // Free the logic data and its segment(s) if it needs to be updated
226 if (logic_mux_data_invalid_)
227 logic_mux_data_.reset();
229 if (!logic_mux_data_) {
230 const uint32_t ch_count = get_assigned_signal_count();
231 logic_mux_unit_size_ = (ch_count + 7) / 8;
232 logic_mux_data_ = make_shared<Logic>(ch_count);
235 // Receive notifications when new sample data is available
236 connect_input_notifiers();
238 if (get_input_segment_count() == 0) {
239 set_error_message(tr("No input data"));
243 // Make sure the logic output data is complete and up-to-date
244 logic_mux_interrupt_ = false;
245 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
247 // Decode the muxed logic data
248 decode_interrupt_ = false;
249 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
252 void DecodeSignal::pause_decode()
254 decode_paused_ = true;
257 void DecodeSignal::resume_decode()
259 // Manual unlocking is done before notifying, to avoid waking up the
260 // waiting thread only to block again (see notify_one for details)
261 decode_pause_mutex_.unlock();
262 decode_pause_cond_.notify_one();
263 decode_paused_ = false;
266 bool DecodeSignal::is_paused() const
268 return decode_paused_;
271 QString DecodeSignal::error_message() const
273 lock_guard<mutex> lock(output_mutex_);
274 return error_message_;
277 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
282 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
284 bool new_assignment = false;
286 // Try to auto-select channels that don't have signals assigned yet
287 for (decode::DecodeChannel& ch : channels_) {
288 // If a decoder is given, auto-assign only its channels
289 if (dec && (ch.decoder_ != dec))
292 if (ch.assigned_signal)
295 QString ch_name = ch.name.toLower();
296 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
298 shared_ptr<data::SignalBase> match;
299 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
303 QString s_name = s->name().toLower();
304 s_name = s_name.replace(QRegExp("[-_.]"), " ");
306 if (s->logic_data() &&
307 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
311 // Only replace an existing match if it matches more characters
312 int old_unmatched = ch_name.length() - match->name().length();
313 int new_unmatched = ch_name.length() - s->name().length();
314 if (abs(new_unmatched) < abs(old_unmatched))
321 ch.assigned_signal = match.get();
322 new_assignment = true;
326 if (new_assignment) {
327 logic_mux_data_invalid_ = true;
328 stack_config_changed_ = true;
329 commit_decoder_channels();
334 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
336 for (decode::DecodeChannel& ch : channels_)
337 if (ch.id == channel_id) {
338 ch.assigned_signal = signal;
339 logic_mux_data_invalid_ = true;
342 stack_config_changed_ = true;
343 commit_decoder_channels();
348 int DecodeSignal::get_assigned_signal_count() const
350 // Count all channels that have a signal assigned to them
351 return count_if(channels_.begin(), channels_.end(),
352 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
355 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
357 for (decode::DecodeChannel& ch : channels_)
358 if (ch.id == channel_id)
359 ch.initial_pin_state = init_state;
361 stack_config_changed_ = true;
366 double DecodeSignal::samplerate() const
370 // TODO For now, we simply return the first samplerate that we have
371 if (segments_.size() > 0)
372 result = segments_.front().samplerate;
377 const pv::util::Timestamp DecodeSignal::start_time() const
379 pv::util::Timestamp result;
381 // TODO For now, we simply return the first start time that we have
382 if (segments_.size() > 0)
383 result = segments_.front().start_time;
388 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
390 // The working sample count is the highest sample number for
391 // which all used signals have data available, so go through all
392 // channels and use the lowest overall sample count of the segment
394 int64_t count = std::numeric_limits<int64_t>::max();
395 bool no_signals_assigned = true;
397 for (const decode::DecodeChannel& ch : channels_)
398 if (ch.assigned_signal) {
399 no_signals_assigned = false;
401 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
402 if (!logic_data || logic_data->logic_segments().empty())
406 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
407 count = min(count, (int64_t)segment->get_sample_count());
408 } catch (out_of_range&) {
413 return (no_signals_assigned ? 0 : count);
416 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
417 bool include_processing) const
419 lock_guard<mutex> decode_lock(output_mutex_);
423 if (segment_id >= segments_.size())
426 if (include_processing)
427 result = segments_[segment_id].samples_decoded_incl;
429 result = segments_[segment_id].samples_decoded_excl;
434 vector<Row*> DecodeSignal::get_rows(bool visible_only)
438 for (const shared_ptr<Decoder>& dec : stack_) {
440 if (visible_only && !dec->shown())
443 for (Row* row : dec->get_rows())
450 vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
452 vector<const Row*> rows;
454 for (const shared_ptr<Decoder>& dec : stack_) {
456 if (visible_only && !dec->shown())
459 for (const Row* row : dec->get_rows())
467 uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
469 if (segment_id >= segments_.size())
472 const DecodeSegment* segment = &(segments_.at(segment_id));
474 auto row_it = segment->annotation_rows.find(row);
477 if (row_it == segment->annotation_rows.end()) {
478 // FIXME Use the fallback row, but how?
482 rd = &(row_it->second);
484 return rd->get_annotation_count();
487 void DecodeSignal::get_annotation_subset(vector<Annotation> &dest,
488 const Row* row, uint32_t segment_id, uint64_t start_sample,
489 uint64_t end_sample) const
491 lock_guard<mutex> lock(output_mutex_);
493 if (segment_id >= segments_.size())
496 const DecodeSegment* segment = &(segments_.at(segment_id));
498 auto row_it = segment->annotation_rows.find(row);
501 if (row_it == segment->annotation_rows.end()) {
502 // FIXME Use the fallback row, but how?
506 rd = &(row_it->second);
508 rd->get_annotation_subset(dest, start_sample, end_sample);
511 void DecodeSignal::get_annotation_subset(vector<Annotation> &dest,
512 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
514 // Use forward_lists for faster merging
515 forward_list<Annotation> *all_ann_list = new forward_list<Annotation>();
517 vector<const Row*> rows = get_rows();
518 for (const Row* row : rows) {
519 vector<Annotation> *ann_vector = new vector<Annotation>();
520 get_annotation_subset(*ann_vector, row, segment_id, start_sample, end_sample);
522 forward_list<Annotation> *ann_list =
523 new forward_list<Annotation>(ann_vector->begin(), ann_vector->end());
526 all_ann_list->merge(*ann_list);
530 move(all_ann_list->begin(), all_ann_list->end(), back_inserter(dest));
534 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
535 const Decoder* dec, uint32_t bin_class_id) const
537 if (segments_.size() == 0)
541 const DecodeSegment *segment = &(segments_.at(segment_id));
543 for (const DecodeBinaryClass& bc : segment->binary_classes)
544 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
545 return bc.chunks.size();
546 } catch (out_of_range&) {
553 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
554 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
555 const vector<uint8_t> **dest, uint64_t *size)
558 const DecodeSegment *segment = &(segments_.at(segment_id));
560 for (const DecodeBinaryClass& bc : segment->binary_classes)
561 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
562 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
563 if (size) *size = bc.chunks.at(chunk_id).data.size();
566 } catch (out_of_range&) {
571 void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
572 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
573 uint64_t end_sample, vector<uint8_t> *dest) const
575 assert(dest != nullptr);
578 const DecodeSegment *segment = &(segments_.at(segment_id));
580 const DecodeBinaryClass* bin_class = nullptr;
581 for (const DecodeBinaryClass& bc : segment->binary_classes)
582 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
585 // Determine overall size before copying to resize dest vector only once
587 uint64_t matches = 0;
588 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
589 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
590 size += chunk.data.size();
596 uint64_t matches2 = 0;
597 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
598 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
599 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
600 offset += chunk.data.size();
603 // Make sure we don't overwrite memory if the array grew in the meanwhile
604 if (matches2 == matches)
607 } catch (out_of_range&) {
612 void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
613 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
614 vector<uint8_t> *dest) const
616 assert(dest != nullptr);
619 const DecodeSegment *segment = &(segments_.at(segment_id));
621 const DecodeBinaryClass* bin_class = nullptr;
622 for (const DecodeBinaryClass& bc : segment->binary_classes)
623 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
626 // Determine overall size before copying to resize dest vector only once
629 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
631 size += chunk.data.size();
632 offset += chunk.data.size();
639 uint64_t dest_offset = 0;
640 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
641 if (offset >= start) {
642 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
643 dest_offset += chunk.data.size();
645 offset += chunk.data.size();
649 } catch (out_of_range&) {
654 const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
655 const Decoder* dec, uint32_t bin_class_id) const
658 const DecodeSegment *segment = &(segments_.at(segment_id));
660 for (const DecodeBinaryClass& bc : segment->binary_classes)
661 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
663 } catch (out_of_range&) {
670 void DecodeSignal::save_settings(QSettings &settings) const
672 SignalBase::save_settings(settings);
674 settings.setValue("decoders", (int)(stack_.size()));
676 // Save decoder stack
678 for (const shared_ptr<Decoder>& decoder : stack_) {
679 settings.beginGroup("decoder" + QString::number(decoder_idx++));
681 settings.setValue("id", decoder->get_srd_decoder()->id);
682 settings.setValue("shown", decoder->shown());
684 // Save decoder options
685 const map<string, GVariant*>& options = decoder->options();
687 settings.setValue("options", (int)options.size());
689 // Note: Decoder::options() returns only the options
690 // that differ from the default. See binding::Decoder::getter()
692 for (auto& option : options) {
693 settings.beginGroup("option" + QString::number(i));
694 settings.setValue("name", QString::fromStdString(option.first));
695 GlobalSettings::store_gvariant(settings, option.second);
703 // Save channel mapping
704 settings.setValue("channels", (int)channels_.size());
706 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
707 auto channel = find_if(channels_.begin(), channels_.end(),
708 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
710 if (channel == channels_.end()) {
711 qDebug() << "ERROR: Gap in channel index:" << channel_id;
715 settings.beginGroup("channel" + QString::number(channel_id));
717 settings.setValue("name", channel->name); // Useful for debugging
718 settings.setValue("initial_pin_state", channel->initial_pin_state);
720 if (channel->assigned_signal)
721 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
727 void DecodeSignal::restore_settings(QSettings &settings)
729 SignalBase::restore_settings(settings);
731 // Restore decoder stack
732 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
734 int decoders = settings.value("decoders").toInt();
736 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
737 settings.beginGroup("decoder" + QString::number(decoder_idx));
739 QString id = settings.value("id").toString();
741 for (GSList *entry = dec_list; entry; entry = entry->next) {
742 const srd_decoder *dec = (srd_decoder*)entry->data;
746 if (QString::fromUtf8(dec->id) == id) {
747 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec);
749 stack_.push_back(decoder);
750 decoder->show(settings.value("shown", true).toBool());
752 // Restore decoder options that differ from their default
753 int options = settings.value("options").toInt();
755 for (int i = 0; i < options; i++) {
756 settings.beginGroup("option" + QString::number(i));
757 QString name = settings.value("name").toString();
758 GVariant *value = GlobalSettings::restore_gvariant(settings);
759 decoder->set_option(name.toUtf8(), value);
763 // Include the newly created decode channels in the channel lists
764 update_channel_list();
773 // Restore channel mapping
774 unsigned int channels = settings.value("channels").toInt();
776 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
777 session_.signalbases();
779 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
780 auto channel = find_if(channels_.begin(), channels_.end(),
781 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
783 if (channel == channels_.end()) {
784 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
788 settings.beginGroup("channel" + QString::number(channel_id));
790 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
792 for (const shared_ptr<data::SignalBase>& signal : signalbases)
793 if (signal->name() == assigned_signal_name)
794 channel->assigned_signal = signal.get();
796 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
801 // Update the internal structures
802 stack_config_changed_ = true;
803 update_channel_list();
804 commit_decoder_channels();
809 void DecodeSignal::set_error_message(QString msg)
811 error_message_ = msg;
812 // TODO Emulate noquote()
813 qDebug().nospace() << name() << ": " << msg;
816 uint32_t DecodeSignal::get_input_segment_count() const
818 uint64_t count = std::numeric_limits<uint64_t>::max();
819 bool no_signals_assigned = true;
821 for (const decode::DecodeChannel& ch : channels_)
822 if (ch.assigned_signal) {
823 no_signals_assigned = false;
825 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
826 if (!logic_data || logic_data->logic_segments().empty())
829 // Find the min value of all segment counts
830 if ((uint64_t)(logic_data->logic_segments().size()) < count)
831 count = logic_data->logic_segments().size();
834 return (no_signals_assigned ? 0 : count);
837 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
839 double samplerate = 0;
841 for (const decode::DecodeChannel& ch : channels_)
842 if (ch.assigned_signal) {
843 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
844 if (!logic_data || logic_data->logic_segments().empty())
848 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
849 samplerate = segment->samplerate();
850 } catch (out_of_range&) {
859 Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
861 for (shared_ptr<Decoder>& d : stack_)
862 if (d->get_srd_decoder() == srd_dec)
868 void DecodeSignal::update_channel_list()
870 vector<decode::DecodeChannel> prev_channels = channels_;
875 // Copy existing entries, create new as needed
876 for (shared_ptr<Decoder>& decoder : stack_) {
877 const srd_decoder* srd_dec = decoder->get_srd_decoder();
880 // Mandatory channels
881 for (l = srd_dec->channels; l; l = l->next) {
882 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
883 bool ch_added = false;
885 // Copy but update ID if this channel was in the list before
886 for (decode::DecodeChannel& ch : prev_channels)
887 if (ch.pdch_ == pdch) {
889 channels_.push_back(ch);
895 // Create new entry without a mapped signal
896 decode::DecodeChannel ch = {id++, 0, false, nullptr,
897 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
898 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
899 channels_.push_back(ch);
904 for (l = srd_dec->opt_channels; l; l = l->next) {
905 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
906 bool ch_added = false;
908 // Copy but update ID if this channel was in the list before
909 for (decode::DecodeChannel& ch : prev_channels)
910 if (ch.pdch_ == pdch) {
912 channels_.push_back(ch);
918 // Create new entry without a mapped signal
919 decode::DecodeChannel ch = {id++, 0, true, nullptr,
920 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
921 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
922 channels_.push_back(ch);
927 // Invalidate the logic output data if the channel assignment changed
928 if (prev_channels.size() != channels_.size()) {
929 // The number of channels changed, there's definitely a difference
930 logic_mux_data_invalid_ = true;
932 // Same number but assignment may still differ, so compare all channels
933 for (size_t i = 0; i < channels_.size(); i++) {
934 const decode::DecodeChannel& p_ch = prev_channels[i];
935 const decode::DecodeChannel& ch = channels_[i];
937 if ((p_ch.pdch_ != ch.pdch_) ||
938 (p_ch.assigned_signal != ch.assigned_signal)) {
939 logic_mux_data_invalid_ = true;
949 void DecodeSignal::commit_decoder_channels()
951 // Submit channel list to every decoder, containing only the relevant channels
952 for (shared_ptr<Decoder> dec : stack_) {
953 vector<decode::DecodeChannel*> channel_list;
955 for (decode::DecodeChannel& ch : channels_)
956 if (ch.decoder_ == dec)
957 channel_list.push_back(&ch);
959 dec->set_channels(channel_list);
962 // Channel bit IDs must be in sync with the channel's apperance in channels_
964 for (decode::DecodeChannel& ch : channels_)
965 if (ch.assigned_signal)
969 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
971 // Enforce end to be greater than start
975 // Fetch the channel segments and their data
976 vector<shared_ptr<LogicSegment> > segments;
977 vector<const uint8_t*> signal_data;
978 vector<uint8_t> signal_in_bytepos;
979 vector<uint8_t> signal_in_bitpos;
981 for (decode::DecodeChannel& ch : channels_)
982 if (ch.assigned_signal) {
983 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
985 shared_ptr<LogicSegment> segment;
987 segment = logic_data->logic_segments().at(segment_id);
988 } catch (out_of_range&) {
989 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
990 << "has no logic segment" << segment_id;
993 segments.push_back(segment);
995 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
996 segment->get_samples(start, end, data);
997 signal_data.push_back(data);
999 const int bitpos = ch.assigned_signal->logic_bit_index();
1000 signal_in_bytepos.push_back(bitpos / 8);
1001 signal_in_bitpos.push_back(bitpos % 8);
1005 shared_ptr<LogicSegment> output_segment;
1007 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1008 } catch (out_of_range&) {
1009 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1010 << segment_id << "in mux_logic_samples(), mux segments size is" \
1011 << logic_mux_data_->logic_segments().size();
1015 // Perform the muxing of signal data into the output data
1016 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1017 unsigned int signal_count = signal_data.size();
1019 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1023 uint8_t bytepos = 0;
1025 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1026 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1027 output[out_sample_pos + i] = 0;
1029 for (unsigned int i = 0; i < signal_count; i++) {
1030 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1031 const uint8_t in_sample = 1 &
1032 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1034 const uint8_t out_sample = output[out_sample_pos + bytepos];
1036 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1046 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1049 for (const uint8_t* data : signal_data)
1053 void DecodeSignal::logic_mux_proc()
1055 uint32_t segment_id = 0;
1057 assert(logic_mux_data_);
1059 // Create initial logic mux segment
1060 shared_ptr<LogicSegment> output_segment =
1061 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1062 logic_mux_unit_size_, 0);
1063 logic_mux_data_->push_segment(output_segment);
1065 output_segment->set_samplerate(get_input_samplerate(0));
1068 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1069 const uint64_t output_sample_count = output_segment->get_sample_count();
1071 const uint64_t samples_to_process =
1072 (input_sample_count > output_sample_count) ?
1073 (input_sample_count - output_sample_count) : 0;
1075 // Process the samples if necessary...
1076 if (samples_to_process > 0) {
1077 const uint64_t unit_size = output_segment->unit_size();
1078 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1080 uint64_t processed_samples = 0;
1082 const uint64_t start_sample = output_sample_count + processed_samples;
1083 const uint64_t sample_count =
1084 min(samples_to_process - processed_samples, chunk_sample_count);
1086 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1087 processed_samples += sample_count;
1089 // ...and process the newly muxed logic data
1090 decode_input_cond_.notify_one();
1091 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1094 if (samples_to_process == 0) {
1095 // TODO Optimize this by caching the input segment count and only
1096 // querying it when the cached value was reached
1097 if (segment_id < get_input_segment_count() - 1) {
1098 // Process next segment
1102 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1103 logic_mux_unit_size_, 0);
1104 logic_mux_data_->push_segment(output_segment);
1106 output_segment->set_samplerate(get_input_samplerate(segment_id));
1109 // All segments have been processed
1110 logic_mux_data_invalid_ = false;
1112 // Wait for more input
1113 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1114 logic_mux_cond_.wait(logic_mux_lock);
1118 } while (!logic_mux_interrupt_);
1121 void DecodeSignal::decode_data(
1122 const int64_t abs_start_samplenum, const int64_t sample_count,
1123 const shared_ptr<LogicSegment> input_segment)
1125 const int64_t unit_size = input_segment->unit_size();
1126 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1128 for (int64_t i = abs_start_samplenum;
1129 error_message_.isEmpty() && !decode_interrupt_ &&
1130 (i < (abs_start_samplenum + sample_count));
1131 i += chunk_sample_count) {
1133 const int64_t chunk_end = min(i + chunk_sample_count,
1134 abs_start_samplenum + sample_count);
1137 lock_guard<mutex> lock(output_mutex_);
1138 // Update the sample count showing the samples including currently processed ones
1139 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1142 int64_t data_size = (chunk_end - i) * unit_size;
1143 uint8_t* chunk = new uint8_t[data_size];
1144 input_segment->get_samples(i, chunk_end, chunk);
1146 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1147 data_size, unit_size) != SRD_OK)
1148 set_error_message(tr("Decoder reported an error"));
1153 lock_guard<mutex> lock(output_mutex_);
1154 // Now that all samples are processed, the exclusive sample count catches up
1155 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1158 // Notify the frontend that we processed some data and
1159 // possibly have new annotations as well
1162 if (decode_paused_) {
1163 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1164 decode_pause_cond_.wait(pause_wait_lock);
1169 void DecodeSignal::decode_proc()
1171 current_segment_id_ = 0;
1173 // If there is no input data available yet, wait until it is or we're interrupted
1174 if (logic_mux_data_->logic_segments().size() == 0) {
1175 unique_lock<mutex> input_wait_lock(input_mutex_);
1176 decode_input_cond_.wait(input_wait_lock);
1179 if (decode_interrupt_)
1182 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
1183 assert(input_segment);
1185 // Create the initial segment and set its sample rate so that we can pass it to SRD
1186 create_decode_segment();
1187 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1188 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1190 start_srd_session();
1192 uint64_t sample_count = 0;
1193 uint64_t abs_start_samplenum = 0;
1195 // Keep processing new samples until we exhaust the input data
1197 lock_guard<mutex> input_lock(input_mutex_);
1198 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
1200 if (sample_count > 0) {
1201 decode_data(abs_start_samplenum, sample_count, input_segment);
1202 abs_start_samplenum += sample_count;
1204 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1206 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1207 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1208 // Process next segment
1209 current_segment_id_++;
1212 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1213 } catch (out_of_range&) {
1214 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1215 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1216 << logic_mux_data_->logic_segments().size();
1219 abs_start_samplenum = 0;
1221 // Create the next segment and set its metadata
1222 create_decode_segment();
1223 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1224 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1226 // Reset decoder state but keep the decoder stack intact
1227 terminate_srd_session();
1229 // All segments have been processed
1232 // Wait for new input data or an interrupt was requested
1233 unique_lock<mutex> input_wait_lock(input_mutex_);
1234 decode_input_cond_.wait(input_wait_lock);
1237 } while (error_message_.isEmpty() && !decode_interrupt_);
1239 // Potentially reap decoders when the application no longer is
1240 // interested in their (pending) results.
1241 if (decode_interrupt_)
1242 terminate_srd_session();
1245 void DecodeSignal::start_srd_session()
1247 // If there were stack changes, the session has been destroyed by now, so if
1248 // it hasn't been destroyed, we can just reset and re-use it
1250 // When a decoder stack was created before, re-use it
1251 // for the next stream of input data, after terminating
1252 // potentially still executing operations, and resetting
1253 // internal state. Skip the rather expensive (teardown
1254 // and) construction of another decoder stack.
1256 // TODO Reduce redundancy, use a common code path for
1257 // the meta/start sequence?
1258 terminate_srd_session();
1260 // Metadata is cleared also, so re-set it
1261 uint64_t samplerate = 0;
1262 if (segments_.size() > 0)
1263 samplerate = segments_.at(current_segment_id_).samplerate;
1265 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1266 g_variant_new_uint64(samplerate));
1267 for (const shared_ptr<Decoder>& dec : stack_)
1268 dec->apply_all_options();
1269 srd_session_start(srd_session_);
1274 // Create the session
1275 srd_session_new(&srd_session_);
1276 assert(srd_session_);
1278 // Create the decoders
1279 srd_decoder_inst *prev_di = nullptr;
1280 for (const shared_ptr<Decoder>& dec : stack_) {
1281 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1284 set_error_message(tr("Failed to create decoder instance"));
1285 srd_session_destroy(srd_session_);
1286 srd_session_ = nullptr;
1291 srd_inst_stack(srd_session_, prev_di, di);
1296 // Start the session
1297 if (segments_.size() > 0)
1298 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1299 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1301 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1302 DecodeSignal::annotation_callback, this);
1304 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1305 DecodeSignal::binary_callback, this);
1307 srd_session_start(srd_session_);
1309 // We just recreated the srd session, so all stack changes are applied now
1310 stack_config_changed_ = false;
1313 void DecodeSignal::terminate_srd_session()
1315 // Call the "terminate and reset" routine for the decoder stack
1316 // (if available). This does not harm those stacks which already
1317 // have completed their operation, and reduces response time for
1318 // those stacks which still are processing data while the
1319 // application no longer wants them to.
1321 srd_session_terminate_reset(srd_session_);
1323 // Metadata is cleared also, so re-set it
1324 uint64_t samplerate = 0;
1325 if (segments_.size() > 0)
1326 samplerate = segments_.at(current_segment_id_).samplerate;
1328 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1329 g_variant_new_uint64(samplerate));
1330 for (const shared_ptr<Decoder>& dec : stack_)
1331 dec->apply_all_options();
1335 void DecodeSignal::stop_srd_session()
1338 // Destroy the session
1339 srd_session_destroy(srd_session_);
1340 srd_session_ = nullptr;
1342 // Mark the decoder instances as non-existant since they were deleted
1343 for (const shared_ptr<Decoder>& dec : stack_)
1344 dec->invalidate_decoder_inst();
1348 void DecodeSignal::connect_input_notifiers()
1350 // Disconnect the notification slot from the previous set of signals
1351 disconnect(this, SLOT(on_data_cleared()));
1352 disconnect(this, SLOT(on_data_received()));
1354 // Connect the currently used signals to our slot
1355 for (decode::DecodeChannel& ch : channels_) {
1356 if (!ch.assigned_signal)
1359 const data::SignalBase *signal = ch.assigned_signal;
1360 connect(signal, SIGNAL(samples_cleared()),
1361 this, SLOT(on_data_cleared()));
1362 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1363 this, SLOT(on_data_received()));
1367 void DecodeSignal::create_decode_segment()
1369 // Create annotation segment
1370 segments_.emplace_back(DecodeSegment());
1372 // Add annotation classes
1373 for (const shared_ptr<Decoder> dec : stack_)
1374 for (Row* row : dec->get_rows())
1375 segments_.back().annotation_rows.emplace(row, RowData(row));
1377 // Prepare our binary output classes
1378 for (const shared_ptr<Decoder>& dec : stack_) {
1379 uint32_t n = dec->get_binary_class_count();
1381 for (uint32_t i = 0; i < n; i++)
1382 segments_.back().binary_classes.push_back(
1383 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1387 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1390 assert(decode_signal);
1392 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1395 if (ds->decode_interrupt_)
1398 lock_guard<mutex> lock(ds->output_mutex_);
1400 // Get the decoder and the annotation data
1402 assert(pdata->pdo->di);
1403 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1406 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1410 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1413 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1415 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1416 "with class ID" << pda->ann_class << "but there are only" <<
1417 dec->ann_classes().size() << "known classes";
1421 const Row* row = ann_class->row;
1424 row = dec->get_row_by_id(0);
1426 // Add the annotation
1427 ds->segments_[ds->current_segment_id_].annotation_rows.at(row).emplace_annotation(pdata);
1430 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1433 assert(decode_signal);
1435 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1438 if (ds->decode_interrupt_)
1441 // Get the decoder and the binary data
1443 assert(pdata->pdo->di);
1444 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1447 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1450 // Find the matching DecodeBinaryClass
1451 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1453 DecodeBinaryClass* bin_class = nullptr;
1454 for (DecodeBinaryClass& bc : segment->binary_classes)
1455 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1456 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1460 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1461 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1462 ", segment only knows" << segment->binary_classes.size() << "classes";
1466 // Add the data chunk
1467 bin_class->chunks.emplace_back();
1468 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1470 chunk->sample = pdata->start_sample;
1471 chunk->data.resize(pdb->size);
1472 memcpy(chunk->data.data(), pdb->data, pdb->size);
1474 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1476 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1479 void DecodeSignal::on_capture_state_changed(int state)
1481 // If a new acquisition was started, we need to start decoding from scratch
1482 if (state == Session::Running) {
1483 logic_mux_data_invalid_ = true;
1488 void DecodeSignal::on_data_cleared()
1493 void DecodeSignal::on_data_received()
1495 // If we detected a lack of input data when trying to start decoding,
1496 // we have set an error message. Only try again if we now have data
1498 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1501 if (!logic_mux_thread_.joinable())
1504 logic_mux_cond_.notify_one();