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::DecodeChannel;
46 using pv::data::decode::Decoder;
47 using pv::data::decode::Row;
52 const double DecodeSignal::DecodeMargin = 1.0;
53 const double DecodeSignal::DecodeThreshold = 0.2;
54 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
57 DecodeSignal::DecodeSignal(pv::Session &session) :
58 SignalBase(nullptr, SignalBase::DecodeChannel),
60 srd_session_(nullptr),
61 logic_mux_data_invalid_(false),
62 stack_config_changed_(true),
63 current_segment_id_(0)
65 connect(&session_, SIGNAL(capture_state_changed(int)),
66 this, SLOT(on_capture_state_changed(int)));
69 DecodeSignal::~DecodeSignal()
74 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
79 void DecodeSignal::stack_decoder(const srd_decoder *decoder)
83 // Set name if this decoder is the first in the list or the name is unchanged
84 const srd_decoder* prev_dec =
85 stack_.empty() ? nullptr : stack_.back()->decoder();
86 const QString prev_dec_name =
87 prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
89 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
90 set_name(QString::fromUtf8(decoder->name));
92 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
93 stack_.push_back(dec);
95 // Include the newly created decode channels in the channel lists
96 update_channel_list();
98 stack_config_changed_ = true;
99 auto_assign_signals(dec);
100 commit_decoder_channels();
104 void DecodeSignal::remove_decoder(int index)
107 assert(index < (int)stack_.size());
109 // Find the decoder in the stack
110 auto iter = stack_.begin();
111 for (int i = 0; i < index; i++, iter++)
112 assert(iter != stack_.end());
114 // Delete the element
117 // Update channels and decoded data
118 stack_config_changed_ = true;
119 update_channel_list();
123 bool DecodeSignal::toggle_decoder_visibility(int index)
125 auto iter = stack_.cbegin();
126 for (int i = 0; i < index; i++, iter++)
127 assert(iter != stack_.end());
129 shared_ptr<Decoder> dec = *iter;
131 // Toggle decoder visibility
134 state = !dec->shown();
141 void DecodeSignal::reset_decode(bool shutting_down)
143 if (stack_config_changed_ || shutting_down)
146 terminate_srd_session();
148 if (decode_thread_.joinable()) {
149 decode_interrupt_ = true;
150 decode_input_cond_.notify_one();
151 decode_thread_.join();
154 if (logic_mux_thread_.joinable()) {
155 logic_mux_interrupt_ = true;
156 logic_mux_cond_.notify_one();
157 logic_mux_thread_.join();
160 resume_decode(); // Make sure the decode thread isn't blocked by pausing
163 current_segment_id_ = 0;
166 logic_mux_data_.reset();
167 logic_mux_data_invalid_ = true;
169 if (!error_message_.isEmpty()) {
170 error_message_ = QString();
171 // TODO Emulate noquote()
172 qDebug().nospace() << name() << ": Error cleared";
178 void DecodeSignal::begin_decode()
180 if (decode_thread_.joinable()) {
181 decode_interrupt_ = true;
182 decode_input_cond_.notify_one();
183 decode_thread_.join();
186 if (logic_mux_thread_.joinable()) {
187 logic_mux_interrupt_ = true;
188 logic_mux_cond_.notify_one();
189 logic_mux_thread_.join();
194 if (stack_.size() == 0) {
195 set_error_message(tr("No decoders"));
199 assert(channels_.size() > 0);
201 if (get_assigned_signal_count() == 0) {
202 set_error_message(tr("There are no channels assigned to this decoder"));
206 // Make sure that all assigned channels still provide logic data
207 // (can happen when a converted signal was assigned but the
208 // conversion removed in the meanwhile)
209 for (decode::DecodeChannel& ch : channels_)
210 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
211 ch.assigned_signal = nullptr;
213 // Check that all decoders have the required channels
214 for (const shared_ptr<decode::Decoder>& dec : stack_)
215 if (!dec->have_required_channels()) {
216 set_error_message(tr("One or more required channels "
217 "have not been specified"));
221 // Map out all the annotation classes
223 for (const shared_ptr<decode::Decoder>& dec : stack_) {
225 const srd_decoder *const decc = dec->decoder();
226 assert(dec->decoder());
228 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
229 const srd_decoder_annotation_row *const ann_row =
230 (srd_decoder_annotation_row *)l->data;
233 const Row row(row_index++, decc, ann_row);
235 for (const GSList *ll = ann_row->ann_classes;
237 class_rows_[make_pair(decc,
238 GPOINTER_TO_INT(ll->data))] = row;
242 // Free the logic data and its segment(s) if it needs to be updated
243 if (logic_mux_data_invalid_)
244 logic_mux_data_.reset();
246 if (!logic_mux_data_) {
247 const uint32_t ch_count = get_assigned_signal_count();
248 logic_mux_unit_size_ = (ch_count + 7) / 8;
249 logic_mux_data_ = make_shared<Logic>(ch_count);
252 // Receive notifications when new sample data is available
253 connect_input_notifiers();
255 if (get_input_segment_count() == 0) {
256 set_error_message(tr("No input data"));
260 // Make sure the logic output data is complete and up-to-date
261 logic_mux_interrupt_ = false;
262 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
264 // Decode the muxed logic data
265 decode_interrupt_ = false;
266 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
269 void DecodeSignal::pause_decode()
271 decode_paused_ = true;
274 void DecodeSignal::resume_decode()
276 // Manual unlocking is done before notifying, to avoid waking up the
277 // waiting thread only to block again (see notify_one for details)
278 decode_pause_mutex_.unlock();
279 decode_pause_cond_.notify_one();
280 decode_paused_ = false;
283 bool DecodeSignal::is_paused() const
285 return decode_paused_;
288 QString DecodeSignal::error_message() const
290 lock_guard<mutex> lock(output_mutex_);
291 return error_message_;
294 const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
299 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
301 bool new_assignment = false;
303 // Try to auto-select channels that don't have signals assigned yet
304 for (decode::DecodeChannel& ch : channels_) {
305 // If a decoder is given, auto-assign only its channels
306 if (dec && (ch.decoder_ != dec))
309 if (ch.assigned_signal)
312 QString ch_name = ch.name.toLower();
313 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
315 shared_ptr<data::SignalBase> match;
316 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
320 QString s_name = s->name().toLower();
321 s_name = s_name.replace(QRegExp("[-_.]"), " ");
323 if (s->logic_data() &&
324 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
328 // Only replace an existing match if it matches more characters
329 int old_unmatched = ch_name.length() - match->name().length();
330 int new_unmatched = ch_name.length() - s->name().length();
331 if (abs(new_unmatched) < abs(old_unmatched))
338 ch.assigned_signal = match.get();
339 new_assignment = true;
343 if (new_assignment) {
344 logic_mux_data_invalid_ = true;
345 stack_config_changed_ = true;
346 commit_decoder_channels();
351 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
353 for (decode::DecodeChannel& ch : channels_)
354 if (ch.id == channel_id) {
355 ch.assigned_signal = signal;
356 logic_mux_data_invalid_ = true;
359 stack_config_changed_ = true;
360 commit_decoder_channels();
365 int DecodeSignal::get_assigned_signal_count() const
367 // Count all channels that have a signal assigned to them
368 return count_if(channels_.begin(), channels_.end(),
369 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
372 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
374 for (decode::DecodeChannel& ch : channels_)
375 if (ch.id == channel_id)
376 ch.initial_pin_state = init_state;
378 stack_config_changed_ = true;
383 double DecodeSignal::samplerate() const
387 // TODO For now, we simply return the first samplerate that we have
388 if (segments_.size() > 0)
389 result = segments_.front().samplerate;
394 const pv::util::Timestamp DecodeSignal::start_time() const
396 pv::util::Timestamp result;
398 // TODO For now, we simply return the first start time that we have
399 if (segments_.size() > 0)
400 result = segments_.front().start_time;
405 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
407 // The working sample count is the highest sample number for
408 // which all used signals have data available, so go through all
409 // channels and use the lowest overall sample count of the segment
411 int64_t count = std::numeric_limits<int64_t>::max();
412 bool no_signals_assigned = true;
414 for (const decode::DecodeChannel& ch : channels_)
415 if (ch.assigned_signal) {
416 no_signals_assigned = false;
418 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
419 if (!logic_data || logic_data->logic_segments().empty())
423 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
424 count = min(count, (int64_t)segment->get_sample_count());
425 } catch (out_of_range&) {
430 return (no_signals_assigned ? 0 : count);
433 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
434 bool include_processing) const
436 lock_guard<mutex> decode_lock(output_mutex_);
441 const DecodeSegment *segment = &(segments_.at(segment_id));
442 if (include_processing)
443 result = segment->samples_decoded_incl;
445 result = segment->samples_decoded_excl;
446 } catch (out_of_range&) {
453 vector<Row> DecodeSignal::get_rows(bool visible_only) const
455 lock_guard<mutex> lock(output_mutex_);
459 for (const shared_ptr<decode::Decoder>& dec : stack_) {
461 if (visible_only && !dec->shown())
464 const srd_decoder *const decc = dec->decoder();
465 assert(dec->decoder());
468 // Add a row for the decoder if it doesn't have a row list
469 if (!decc->annotation_rows)
470 rows.emplace_back(row_index++, decc);
472 // Add the decoder rows
473 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
474 const srd_decoder_annotation_row *const ann_row =
475 (srd_decoder_annotation_row *)l->data;
477 rows.emplace_back(row_index++, decc, ann_row);
484 void DecodeSignal::get_annotation_subset(
485 vector<pv::data::decode::Annotation> &dest,
486 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
487 uint64_t end_sample) const
489 lock_guard<mutex> lock(output_mutex_);
492 const DecodeSegment *segment = &(segments_.at(segment_id));
493 const map<const decode::Row, decode::RowData> *rows =
494 &(segment->annotation_rows);
496 const auto iter = rows->find(row);
497 if (iter != rows->end())
498 (*iter).second.get_annotation_subset(dest,
499 start_sample, end_sample);
500 } catch (out_of_range&) {
505 void DecodeSignal::get_annotation_subset(
506 vector<pv::data::decode::Annotation> &dest,
507 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
509 // Note: We put all vectors and lists on the heap, not the stack
511 const vector<Row> rows = get_rows(true);
513 // Use forward_lists for faster merging
514 forward_list<Annotation> *all_ann_list = new forward_list<Annotation>();
516 for (const Row& row : rows) {
517 vector<Annotation> *ann_vector = new vector<Annotation>();
518 get_annotation_subset(*ann_vector, row, segment_id, start_sample, end_sample);
520 forward_list<Annotation> *ann_list =
521 new forward_list<Annotation>(ann_vector->begin(), ann_vector->end());
524 all_ann_list->merge(*ann_list);
528 move(all_ann_list->begin(), all_ann_list->end(), back_inserter(dest));
532 uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id) const
537 const DecodeSegment *segment = &(segments_.at(segment_id));
538 count = segment->binary_data.size();
539 } catch (out_of_range&) {
546 void DecodeSignal::get_binary_data_chunk(uint32_t segment_id, uint32_t chunk_id,
547 const vector<uint8_t> **dest, uint64_t *size)
550 const DecodeSegment *segment = &(segments_.at(segment_id));
552 *dest = &(segment->binary_data.at(chunk_id).data);
554 *size = segment->binary_data.at(chunk_id).data.size();
555 } catch (out_of_range&) {
560 void DecodeSignal::get_binary_data_chunks_merged(uint32_t segment_id,
561 uint64_t start_sample, uint64_t end_sample, vector<uint8_t> *dest) const
563 assert(dest != nullptr);
566 const DecodeSegment *segment = &(segments_.at(segment_id));
568 // Determine overall size before copying to resize dest vector only once
570 uint64_t matches = 0;
571 for (const DecodeBinaryData& d : segment->binary_data)
572 if ((d.sample >= start_sample) && (d.sample < end_sample)) {
573 size += d.data.size();
579 uint64_t matches2 = 0;
580 for (const DecodeBinaryData& d : segment->binary_data)
581 if ((d.sample >= start_sample) && (d.sample < end_sample)) {
582 memcpy(dest->data() + offset, d.data.data(), d.data.size());
583 offset += d.data.size();
586 // Make sure we don't overwrite memory if the array grew in the meanwhile
587 if (matches2 == matches)
590 } catch (out_of_range&) {
596 void DecodeSignal::save_settings(QSettings &settings) const
598 SignalBase::save_settings(settings);
600 settings.setValue("decoders", (int)(stack_.size()));
602 // Save decoder stack
604 for (const shared_ptr<decode::Decoder>& decoder : stack_) {
605 settings.beginGroup("decoder" + QString::number(decoder_idx++));
607 settings.setValue("id", decoder->decoder()->id);
608 settings.setValue("shown", decoder->shown());
610 // Save decoder options
611 const map<string, GVariant*>& options = decoder->options();
613 settings.setValue("options", (int)options.size());
615 // Note: decode::Decoder::options() returns only the options
616 // that differ from the default. See binding::Decoder::getter()
618 for (auto& option : options) {
619 settings.beginGroup("option" + QString::number(i));
620 settings.setValue("name", QString::fromStdString(option.first));
621 GlobalSettings::store_gvariant(settings, option.second);
629 // Save channel mapping
630 settings.setValue("channels", (int)channels_.size());
632 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
633 auto channel = find_if(channels_.begin(), channels_.end(),
634 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
636 if (channel == channels_.end()) {
637 qDebug() << "ERROR: Gap in channel index:" << channel_id;
641 settings.beginGroup("channel" + QString::number(channel_id));
643 settings.setValue("name", channel->name); // Useful for debugging
644 settings.setValue("initial_pin_state", channel->initial_pin_state);
646 if (channel->assigned_signal)
647 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
653 void DecodeSignal::restore_settings(QSettings &settings)
655 SignalBase::restore_settings(settings);
657 // Restore decoder stack
658 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
660 int decoders = settings.value("decoders").toInt();
662 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
663 settings.beginGroup("decoder" + QString::number(decoder_idx));
665 QString id = settings.value("id").toString();
667 for (GSList *entry = dec_list; entry; entry = entry->next) {
668 const srd_decoder *dec = (srd_decoder*)entry->data;
672 if (QString::fromUtf8(dec->id) == id) {
673 shared_ptr<decode::Decoder> decoder =
674 make_shared<decode::Decoder>(dec);
676 stack_.push_back(decoder);
677 decoder->show(settings.value("shown", true).toBool());
679 // Restore decoder options that differ from their default
680 int options = settings.value("options").toInt();
682 for (int i = 0; i < options; i++) {
683 settings.beginGroup("option" + QString::number(i));
684 QString name = settings.value("name").toString();
685 GVariant *value = GlobalSettings::restore_gvariant(settings);
686 decoder->set_option(name.toUtf8(), value);
690 // Include the newly created decode channels in the channel lists
691 update_channel_list();
700 // Restore channel mapping
701 unsigned int channels = settings.value("channels").toInt();
703 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
704 session_.signalbases();
706 for (unsigned int channel_id = 0; channel_id < channels; 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: Non-existant channel index:" << channel_id;
715 settings.beginGroup("channel" + QString::number(channel_id));
717 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
719 for (const shared_ptr<data::SignalBase>& signal : signalbases)
720 if (signal->name() == assigned_signal_name)
721 channel->assigned_signal = signal.get();
723 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
728 // Update the internal structures
729 stack_config_changed_ = true;
730 update_channel_list();
731 commit_decoder_channels();
736 void DecodeSignal::set_error_message(QString msg)
738 error_message_ = msg;
739 // TODO Emulate noquote()
740 qDebug().nospace() << name() << ": " << msg;
743 uint32_t DecodeSignal::get_input_segment_count() const
745 uint64_t count = std::numeric_limits<uint64_t>::max();
746 bool no_signals_assigned = true;
748 for (const decode::DecodeChannel& ch : channels_)
749 if (ch.assigned_signal) {
750 no_signals_assigned = false;
752 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
753 if (!logic_data || logic_data->logic_segments().empty())
756 // Find the min value of all segment counts
757 if ((uint64_t)(logic_data->logic_segments().size()) < count)
758 count = logic_data->logic_segments().size();
761 return (no_signals_assigned ? 0 : count);
764 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
766 double samplerate = 0;
768 for (const decode::DecodeChannel& ch : channels_)
769 if (ch.assigned_signal) {
770 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
771 if (!logic_data || logic_data->logic_segments().empty())
775 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
776 samplerate = segment->samplerate();
777 } catch (out_of_range&) {
786 void DecodeSignal::update_channel_list()
788 vector<decode::DecodeChannel> prev_channels = channels_;
793 // Copy existing entries, create new as needed
794 for (shared_ptr<Decoder>& decoder : stack_) {
795 const srd_decoder* srd_d = decoder->decoder();
798 // Mandatory channels
799 for (l = srd_d->channels; l; l = l->next) {
800 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
801 bool ch_added = false;
803 // Copy but update ID if this channel was in the list before
804 for (decode::DecodeChannel& ch : prev_channels)
805 if (ch.pdch_ == pdch) {
807 channels_.push_back(ch);
813 // Create new entry without a mapped signal
814 decode::DecodeChannel ch = {id++, 0, false, nullptr,
815 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
816 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
817 channels_.push_back(ch);
822 for (l = srd_d->opt_channels; l; l = l->next) {
823 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
824 bool ch_added = false;
826 // Copy but update ID if this channel was in the list before
827 for (decode::DecodeChannel& ch : prev_channels)
828 if (ch.pdch_ == pdch) {
830 channels_.push_back(ch);
836 // Create new entry without a mapped signal
837 decode::DecodeChannel ch = {id++, 0, true, nullptr,
838 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
839 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
840 channels_.push_back(ch);
845 // Invalidate the logic output data if the channel assignment changed
846 if (prev_channels.size() != channels_.size()) {
847 // The number of channels changed, there's definitely a difference
848 logic_mux_data_invalid_ = true;
850 // Same number but assignment may still differ, so compare all channels
851 for (size_t i = 0; i < channels_.size(); i++) {
852 const decode::DecodeChannel& p_ch = prev_channels[i];
853 const decode::DecodeChannel& ch = channels_[i];
855 if ((p_ch.pdch_ != ch.pdch_) ||
856 (p_ch.assigned_signal != ch.assigned_signal)) {
857 logic_mux_data_invalid_ = true;
867 void DecodeSignal::commit_decoder_channels()
869 // Submit channel list to every decoder, containing only the relevant channels
870 for (shared_ptr<decode::Decoder> dec : stack_) {
871 vector<decode::DecodeChannel*> channel_list;
873 for (decode::DecodeChannel& ch : channels_)
874 if (ch.decoder_ == dec)
875 channel_list.push_back(&ch);
877 dec->set_channels(channel_list);
880 // Channel bit IDs must be in sync with the channel's apperance in channels_
882 for (decode::DecodeChannel& ch : channels_)
883 if (ch.assigned_signal)
887 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
889 // Enforce end to be greater than start
893 // Fetch the channel segments and their data
894 vector<shared_ptr<LogicSegment> > segments;
895 vector<const uint8_t*> signal_data;
896 vector<uint8_t> signal_in_bytepos;
897 vector<uint8_t> signal_in_bitpos;
899 for (decode::DecodeChannel& ch : channels_)
900 if (ch.assigned_signal) {
901 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
903 shared_ptr<LogicSegment> segment;
905 segment = logic_data->logic_segments().at(segment_id);
906 } catch (out_of_range&) {
907 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
908 << "has no logic segment" << segment_id;
911 segments.push_back(segment);
913 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
914 segment->get_samples(start, end, data);
915 signal_data.push_back(data);
917 const int bitpos = ch.assigned_signal->logic_bit_index();
918 signal_in_bytepos.push_back(bitpos / 8);
919 signal_in_bitpos.push_back(bitpos % 8);
923 shared_ptr<LogicSegment> output_segment;
925 output_segment = logic_mux_data_->logic_segments().at(segment_id);
926 } catch (out_of_range&) {
927 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
928 << segment_id << "in mux_logic_samples(), mux segments size is" \
929 << logic_mux_data_->logic_segments().size();
933 // Perform the muxing of signal data into the output data
934 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
935 unsigned int signal_count = signal_data.size();
937 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
943 const int out_sample_pos = sample_cnt * output_segment->unit_size();
944 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
945 output[out_sample_pos + i] = 0;
947 for (unsigned int i = 0; i < signal_count; i++) {
948 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
949 const uint8_t in_sample = 1 &
950 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
952 const uint8_t out_sample = output[out_sample_pos + bytepos];
954 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
964 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
967 for (const uint8_t* data : signal_data)
971 void DecodeSignal::logic_mux_proc()
973 uint32_t segment_id = 0;
975 assert(logic_mux_data_);
977 // Create initial logic mux segment
978 shared_ptr<LogicSegment> output_segment =
979 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
980 logic_mux_unit_size_, 0);
981 logic_mux_data_->push_segment(output_segment);
983 output_segment->set_samplerate(get_input_samplerate(0));
986 const uint64_t input_sample_count = get_working_sample_count(segment_id);
987 const uint64_t output_sample_count = output_segment->get_sample_count();
989 const uint64_t samples_to_process =
990 (input_sample_count > output_sample_count) ?
991 (input_sample_count - output_sample_count) : 0;
993 // Process the samples if necessary...
994 if (samples_to_process > 0) {
995 const uint64_t unit_size = output_segment->unit_size();
996 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
998 uint64_t processed_samples = 0;
1000 const uint64_t start_sample = output_sample_count + processed_samples;
1001 const uint64_t sample_count =
1002 min(samples_to_process - processed_samples, chunk_sample_count);
1004 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1005 processed_samples += sample_count;
1007 // ...and process the newly muxed logic data
1008 decode_input_cond_.notify_one();
1009 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1012 if (samples_to_process == 0) {
1013 // TODO Optimize this by caching the input segment count and only
1014 // querying it when the cached value was reached
1015 if (segment_id < get_input_segment_count() - 1) {
1016 // Process next segment
1020 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1021 logic_mux_unit_size_, 0);
1022 logic_mux_data_->push_segment(output_segment);
1024 output_segment->set_samplerate(get_input_samplerate(segment_id));
1027 // All segments have been processed
1028 logic_mux_data_invalid_ = false;
1030 // Wait for more input
1031 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1032 logic_mux_cond_.wait(logic_mux_lock);
1036 } while (!logic_mux_interrupt_);
1039 void DecodeSignal::decode_data(
1040 const int64_t abs_start_samplenum, const int64_t sample_count,
1041 const shared_ptr<LogicSegment> input_segment)
1043 const int64_t unit_size = input_segment->unit_size();
1044 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1046 for (int64_t i = abs_start_samplenum;
1047 error_message_.isEmpty() && !decode_interrupt_ &&
1048 (i < (abs_start_samplenum + sample_count));
1049 i += chunk_sample_count) {
1051 const int64_t chunk_end = min(i + chunk_sample_count,
1052 abs_start_samplenum + sample_count);
1055 lock_guard<mutex> lock(output_mutex_);
1056 // Update the sample count showing the samples including currently processed ones
1057 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1060 int64_t data_size = (chunk_end - i) * unit_size;
1061 uint8_t* chunk = new uint8_t[data_size];
1062 input_segment->get_samples(i, chunk_end, chunk);
1064 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1065 data_size, unit_size) != SRD_OK)
1066 set_error_message(tr("Decoder reported an error"));
1071 lock_guard<mutex> lock(output_mutex_);
1072 // Now that all samples are processed, the exclusive sample count catches up
1073 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1076 // Notify the frontend that we processed some data and
1077 // possibly have new annotations as well
1080 if (decode_paused_) {
1081 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1082 decode_pause_cond_.wait(pause_wait_lock);
1087 void DecodeSignal::decode_proc()
1089 current_segment_id_ = 0;
1091 // If there is no input data available yet, wait until it is or we're interrupted
1092 if (logic_mux_data_->logic_segments().size() == 0) {
1093 unique_lock<mutex> input_wait_lock(input_mutex_);
1094 decode_input_cond_.wait(input_wait_lock);
1097 if (decode_interrupt_)
1100 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
1101 assert(input_segment);
1103 // Create the initial segment and set its sample rate so that we can pass it to SRD
1104 create_decode_segment();
1105 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1106 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1108 start_srd_session();
1110 uint64_t sample_count = 0;
1111 uint64_t abs_start_samplenum = 0;
1113 // Keep processing new samples until we exhaust the input data
1115 lock_guard<mutex> input_lock(input_mutex_);
1116 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
1118 if (sample_count > 0) {
1119 decode_data(abs_start_samplenum, sample_count, input_segment);
1120 abs_start_samplenum += sample_count;
1122 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1124 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1125 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1126 // Process next segment
1127 current_segment_id_++;
1130 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1131 } catch (out_of_range&) {
1132 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1133 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1134 << logic_mux_data_->logic_segments().size();
1137 abs_start_samplenum = 0;
1139 // Create the next segment and set its metadata
1140 create_decode_segment();
1141 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1142 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1144 // Reset decoder state but keep the decoder stack intact
1145 terminate_srd_session();
1147 // All segments have been processed
1150 // Wait for new input data or an interrupt was requested
1151 unique_lock<mutex> input_wait_lock(input_mutex_);
1152 decode_input_cond_.wait(input_wait_lock);
1155 } while (error_message_.isEmpty() && !decode_interrupt_);
1157 // Potentially reap decoders when the application no longer is
1158 // interested in their (pending) results.
1159 if (decode_interrupt_)
1160 terminate_srd_session();
1163 void DecodeSignal::start_srd_session()
1165 // If there were stack changes, the session has been destroyed by now, so if
1166 // it hasn't been destroyed, we can just reset and re-use it
1168 // When a decoder stack was created before, re-use it
1169 // for the next stream of input data, after terminating
1170 // potentially still executing operations, and resetting
1171 // internal state. Skip the rather expensive (teardown
1172 // and) construction of another decoder stack.
1174 // TODO Reduce redundancy, use a common code path for
1175 // the meta/start sequence?
1176 terminate_srd_session();
1178 // Metadata is cleared also, so re-set it
1179 uint64_t samplerate = 0;
1180 if (segments_.size() > 0)
1181 samplerate = segments_.at(current_segment_id_).samplerate;
1183 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1184 g_variant_new_uint64(samplerate));
1185 for (const shared_ptr<decode::Decoder>& dec : stack_)
1186 dec->apply_all_options();
1187 srd_session_start(srd_session_);
1192 // Create the session
1193 srd_session_new(&srd_session_);
1194 assert(srd_session_);
1196 // Create the decoders
1197 srd_decoder_inst *prev_di = nullptr;
1198 for (const shared_ptr<decode::Decoder>& dec : stack_) {
1199 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1202 set_error_message(tr("Failed to create decoder instance"));
1203 srd_session_destroy(srd_session_);
1204 srd_session_ = nullptr;
1209 srd_inst_stack(srd_session_, prev_di, di);
1214 // Start the session
1215 if (segments_.size() > 0)
1216 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1217 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1219 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1220 DecodeSignal::annotation_callback, this);
1222 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1223 DecodeSignal::binary_callback, this);
1225 srd_session_start(srd_session_);
1227 // We just recreated the srd session, so all stack changes are applied now
1228 stack_config_changed_ = false;
1231 void DecodeSignal::terminate_srd_session()
1233 // Call the "terminate and reset" routine for the decoder stack
1234 // (if available). This does not harm those stacks which already
1235 // have completed their operation, and reduces response time for
1236 // those stacks which still are processing data while the
1237 // application no longer wants them to.
1239 srd_session_terminate_reset(srd_session_);
1241 // Metadata is cleared also, so re-set it
1242 uint64_t samplerate = 0;
1243 if (segments_.size() > 0)
1244 samplerate = segments_.at(current_segment_id_).samplerate;
1246 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1247 g_variant_new_uint64(samplerate));
1248 for (const shared_ptr<decode::Decoder>& dec : stack_)
1249 dec->apply_all_options();
1253 void DecodeSignal::stop_srd_session()
1256 // Destroy the session
1257 srd_session_destroy(srd_session_);
1258 srd_session_ = nullptr;
1260 // Mark the decoder instances as non-existant since they were deleted
1261 for (const shared_ptr<decode::Decoder>& dec : stack_)
1262 dec->invalidate_decoder_inst();
1266 void DecodeSignal::connect_input_notifiers()
1268 // Disconnect the notification slot from the previous set of signals
1269 disconnect(this, SLOT(on_data_cleared()));
1270 disconnect(this, SLOT(on_data_received()));
1272 // Connect the currently used signals to our slot
1273 for (decode::DecodeChannel& ch : channels_) {
1274 if (!ch.assigned_signal)
1277 const data::SignalBase *signal = ch.assigned_signal;
1278 connect(signal, SIGNAL(samples_cleared()),
1279 this, SLOT(on_data_cleared()));
1280 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1281 this, SLOT(on_data_received()));
1285 void DecodeSignal::create_decode_segment()
1287 // Create annotation segment
1288 segments_.emplace_back(DecodeSegment());
1290 // Add annotation classes
1291 for (const shared_ptr<decode::Decoder>& dec : stack_) {
1293 const srd_decoder *const decc = dec->decoder();
1294 assert(dec->decoder());
1297 // Add a row for the decoder if it doesn't have a row list
1298 if (!decc->annotation_rows)
1299 (segments_.back().annotation_rows)[Row(row_index++, decc)] =
1302 // Add the decoder rows
1303 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1304 const srd_decoder_annotation_row *const ann_row =
1305 (srd_decoder_annotation_row *)l->data;
1308 const Row row(row_index++, decc, ann_row);
1310 // Add a new empty row data object
1311 (segments_.back().annotation_rows)[row] =
1317 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1320 assert(decode_signal);
1322 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1325 if (ds->decode_interrupt_)
1328 lock_guard<mutex> lock(ds->output_mutex_);
1330 // Get the decoder and the annotation data
1332 assert(pdata->pdo->di);
1333 const srd_decoder *const decc = pdata->pdo->di->decoder;
1336 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1340 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
1342 // Try finding a better row match than the default by looking up the sub-row of this class
1343 const auto format = pda->ann_class;
1344 const auto r = ds->class_rows_.find(make_pair(decc, format));
1345 if (r != ds->class_rows_.end())
1346 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
1348 // Failing that, use the decoder as a key
1349 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(0, decc));
1352 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
1353 qDebug() << "Unexpected annotation: decoder = " << decc <<
1354 ", format = " << format;
1359 // Add the annotation
1360 (*row_iter).second.emplace_annotation(pdata, &((*row_iter).first));
1363 void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1366 assert(decode_signal);
1368 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1371 if (ds->decode_interrupt_)
1374 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1377 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1379 segment->binary_data.emplace_back();
1380 DecodeBinaryData* bin_data = &(segment->binary_data.back());
1382 bin_data->sample = pdata->start_sample;
1383 bin_data->data.resize(pdb->size);
1384 memcpy(bin_data->data.data(), pdb->data, pdb->size);
1386 ds->new_binary_data(ds->current_segment_id_);
1389 void DecodeSignal::on_capture_state_changed(int state)
1391 // If a new acquisition was started, we need to start decoding from scratch
1392 if (state == Session::Running) {
1393 logic_mux_data_invalid_ = true;
1398 void DecodeSignal::on_data_cleared()
1403 void DecodeSignal::on_data_received()
1405 // If we detected a lack of input data when trying to start decoding,
1406 // we have set an error message. Only try again if we now have data
1408 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1411 if (!logic_mux_thread_.joinable())
1414 logic_mux_cond_.notify_one();