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/>.
25 #include "logicsegment.hpp"
26 #include "decodesignal.hpp"
27 #include "signaldata.hpp"
29 #include <pv/binding/decoder.hpp>
30 #include <pv/data/decode/decoder.hpp>
31 #include <pv/data/decode/row.hpp>
32 #include <pv/globalsettings.hpp>
33 #include <pv/session.hpp>
35 using std::lock_guard;
37 using std::make_shared;
39 using std::out_of_range;
40 using std::shared_ptr;
41 using std::unique_lock;
42 using pv::data::decode::Annotation;
43 using pv::data::decode::Decoder;
44 using pv::data::decode::Row;
49 const double DecodeSignal::DecodeMargin = 1.0;
50 const double DecodeSignal::DecodeThreshold = 0.2;
51 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
54 DecodeSignal::DecodeSignal(pv::Session &session) :
55 SignalBase(nullptr, SignalBase::DecodeChannel),
57 srd_session_(nullptr),
58 logic_mux_data_invalid_(false),
59 stack_config_changed_(true),
60 current_segment_id_(0)
62 connect(&session_, SIGNAL(capture_state_changed(int)),
63 this, SLOT(on_capture_state_changed(int)));
66 DecodeSignal::~DecodeSignal()
71 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
76 void DecodeSignal::stack_decoder(const srd_decoder *decoder)
79 const shared_ptr<Decoder> dec = make_shared<decode::Decoder>(decoder);
81 stack_.push_back(dec);
83 // Set name if this decoder is the first in the list
84 if (stack_.size() == 1)
85 set_name(QString::fromUtf8(decoder->name));
87 // Include the newly created decode channels in the channel lists
88 update_channel_list();
90 stack_config_changed_ = true;
91 auto_assign_signals(dec);
92 commit_decoder_channels();
96 void DecodeSignal::remove_decoder(int index)
99 assert(index < (int)stack_.size());
101 // Find the decoder in the stack
102 auto iter = stack_.begin();
103 for (int i = 0; i < index; i++, iter++)
104 assert(iter != stack_.end());
106 // Delete the element
109 // Update channels and decoded data
110 stack_config_changed_ = true;
111 update_channel_list();
115 bool DecodeSignal::toggle_decoder_visibility(int index)
117 auto iter = stack_.cbegin();
118 for (int i = 0; i < index; i++, iter++)
119 assert(iter != stack_.end());
121 shared_ptr<Decoder> dec = *iter;
123 // Toggle decoder visibility
126 state = !dec->shown();
133 void DecodeSignal::reset_decode(bool shutting_down)
135 if (stack_config_changed_ || shutting_down)
138 terminate_srd_session();
140 if (decode_thread_.joinable()) {
141 decode_interrupt_ = true;
142 decode_input_cond_.notify_one();
143 decode_thread_.join();
146 if (logic_mux_thread_.joinable()) {
147 logic_mux_interrupt_ = true;
148 logic_mux_cond_.notify_one();
149 logic_mux_thread_.join();
153 current_segment_id_ = 0;
156 logic_mux_data_.reset();
157 logic_mux_data_invalid_ = true;
159 if (!error_message_.isEmpty()) {
160 error_message_ = QString();
161 qDebug().noquote().nospace() << name() << ": Error cleared";
167 void DecodeSignal::begin_decode()
169 if (decode_thread_.joinable()) {
170 decode_interrupt_ = true;
171 decode_input_cond_.notify_one();
172 decode_thread_.join();
175 if (logic_mux_thread_.joinable()) {
176 logic_mux_interrupt_ = true;
177 logic_mux_cond_.notify_one();
178 logic_mux_thread_.join();
183 if (stack_.size() == 0) {
184 set_error_message(tr("No decoders"));
188 assert(channels_.size() > 0);
190 if (get_assigned_signal_count() == 0) {
191 set_error_message(tr("There are no channels assigned to this decoder"));
195 // Make sure that all assigned channels still provide logic data
196 // (can happen when a converted signal was assigned but the
197 // conversion removed in the meanwhile)
198 for (data::DecodeChannel &ch : channels_)
199 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
200 ch.assigned_signal = nullptr;
202 // Check that all decoders have the required channels
203 for (const shared_ptr<decode::Decoder> &dec : stack_)
204 if (!dec->have_required_channels()) {
205 set_error_message(tr("One or more required channels "
206 "have not been specified"));
210 // Map out all the annotation classes
211 for (const shared_ptr<decode::Decoder> &dec : stack_) {
213 const srd_decoder *const decc = dec->decoder();
214 assert(dec->decoder());
216 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
217 const srd_decoder_annotation_row *const ann_row =
218 (srd_decoder_annotation_row *)l->data;
221 const Row row(decc, ann_row);
223 for (const GSList *ll = ann_row->ann_classes;
225 class_rows_[make_pair(decc,
226 GPOINTER_TO_INT(ll->data))] = row;
230 // Free the logic data and its segment(s) if it needs to be updated
231 if (logic_mux_data_invalid_)
232 logic_mux_data_.reset();
234 if (!logic_mux_data_) {
235 const uint32_t ch_count = get_assigned_signal_count();
236 logic_mux_unit_size_ = (ch_count + 7) / 8;
237 logic_mux_data_ = make_shared<Logic>(ch_count);
240 // Receive notifications when new sample data is available
241 connect_input_notifiers();
243 if (get_input_segment_count() == 0) {
244 set_error_message(tr("No input data"));
248 // Make sure the logic output data is complete and up-to-date
249 logic_mux_interrupt_ = false;
250 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
252 // Decode the muxed logic data
253 decode_interrupt_ = false;
254 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
257 QString DecodeSignal::error_message() const
259 lock_guard<mutex> lock(output_mutex_);
260 return error_message_;
263 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
268 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
270 bool new_assignment = false;
272 // Try to auto-select channels that don't have signals assigned yet
273 for (data::DecodeChannel &ch : channels_) {
274 // If a decoder is given, auto-assign only its channels
275 if (dec && (ch.decoder_ != dec))
278 if (ch.assigned_signal)
281 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
282 const QString ch_name = ch.name.toLower();
283 const QString s_name = s->name().toLower();
285 if (s->logic_data() &&
286 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
287 ch.assigned_signal = s.get();
288 new_assignment = true;
293 if (new_assignment) {
294 logic_mux_data_invalid_ = true;
295 stack_config_changed_ = true;
296 commit_decoder_channels();
301 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
303 for (data::DecodeChannel &ch : channels_)
304 if (ch.id == channel_id) {
305 ch.assigned_signal = signal;
306 logic_mux_data_invalid_ = true;
309 stack_config_changed_ = true;
310 commit_decoder_channels();
315 int DecodeSignal::get_assigned_signal_count() const
317 // Count all channels that have a signal assigned to them
318 return count_if(channels_.begin(), channels_.end(),
319 [](data::DecodeChannel ch) { return ch.assigned_signal; });
322 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
324 for (data::DecodeChannel &ch : channels_)
325 if (ch.id == channel_id)
326 ch.initial_pin_state = init_state;
328 stack_config_changed_ = true;
333 double DecodeSignal::samplerate() const
337 // TODO For now, we simply return the first samplerate that we have
338 if (segments_.size() > 0)
339 result = segments_.front().samplerate;
344 const pv::util::Timestamp DecodeSignal::start_time() const
346 pv::util::Timestamp result;
348 // TODO For now, we simply return the first start time that we have
349 if (segments_.size() > 0)
350 result = segments_.front().start_time;
355 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
357 // The working sample count is the highest sample number for
358 // which all used signals have data available, so go through all
359 // channels and use the lowest overall sample count of the segment
361 int64_t count = std::numeric_limits<int64_t>::max();
362 bool no_signals_assigned = true;
364 for (const data::DecodeChannel &ch : channels_)
365 if (ch.assigned_signal) {
366 no_signals_assigned = false;
368 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
369 if (!logic_data || logic_data->logic_segments().empty())
373 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
374 count = min(count, (int64_t)segment->get_sample_count());
375 } catch (out_of_range&) {
380 return (no_signals_assigned ? 0 : count);
383 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id) const
385 lock_guard<mutex> decode_lock(output_mutex_);
390 const DecodeSegment *segment = &(segments_.at(segment_id));
391 result = segment->samples_decoded;
392 } catch (out_of_range&) {
399 vector<Row> DecodeSignal::visible_rows() const
401 lock_guard<mutex> lock(output_mutex_);
405 for (const shared_ptr<decode::Decoder> &dec : stack_) {
410 const srd_decoder *const decc = dec->decoder();
411 assert(dec->decoder());
413 // Add a row for the decoder if it doesn't have a row list
414 if (!decc->annotation_rows)
415 rows.emplace_back(decc);
417 // Add the decoder rows
418 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
419 const srd_decoder_annotation_row *const ann_row =
420 (srd_decoder_annotation_row *)l->data;
422 rows.emplace_back(decc, ann_row);
429 void DecodeSignal::get_annotation_subset(
430 vector<pv::data::decode::Annotation> &dest,
431 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
432 uint64_t end_sample) const
434 lock_guard<mutex> lock(output_mutex_);
437 const DecodeSegment *segment = &(segments_.at(segment_id));
438 const map<const decode::Row, decode::RowData> *rows =
439 &(segment->annotation_rows);
441 const auto iter = rows->find(row);
442 if (iter != rows->end())
443 (*iter).second.get_annotation_subset(dest,
444 start_sample, end_sample);
445 } catch (out_of_range&) {
450 void DecodeSignal::save_settings(QSettings &settings) const
452 SignalBase::save_settings(settings);
454 settings.setValue("decoders", (int)(stack_.size()));
456 // Save decoder stack
458 for (shared_ptr<decode::Decoder> decoder : stack_) {
459 settings.beginGroup("decoder" + QString::number(decoder_idx++));
461 settings.setValue("id", decoder->decoder()->id);
463 // Save decoder options
464 const map<string, GVariant*>& options = decoder->options();
466 settings.setValue("options", (int)options.size());
468 // Note: decode::Decoder::options() returns only the options
469 // that differ from the default. See binding::Decoder::getter()
471 for (auto option : options) {
472 settings.beginGroup("option" + QString::number(i));
473 settings.setValue("name", QString::fromStdString(option.first));
474 GlobalSettings::store_gvariant(settings, option.second);
482 // Save channel mapping
483 settings.setValue("channels", (int)channels_.size());
485 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
486 auto channel = find_if(channels_.begin(), channels_.end(),
487 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
489 if (channel == channels_.end()) {
490 qDebug() << "ERROR: Gap in channel index:" << channel_id;
494 settings.beginGroup("channel" + QString::number(channel_id));
496 settings.setValue("name", channel->name); // Useful for debugging
497 settings.setValue("initial_pin_state", channel->initial_pin_state);
499 if (channel->assigned_signal)
500 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
506 void DecodeSignal::restore_settings(QSettings &settings)
508 SignalBase::restore_settings(settings);
510 // Restore decoder stack
511 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
513 int decoders = settings.value("decoders").toInt();
515 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
516 settings.beginGroup("decoder" + QString::number(decoder_idx));
518 QString id = settings.value("id").toString();
520 for (GSList *entry = dec_list; entry; entry = entry->next) {
521 const srd_decoder *dec = (srd_decoder*)entry->data;
525 if (QString::fromUtf8(dec->id) == id) {
526 shared_ptr<decode::Decoder> decoder =
527 make_shared<decode::Decoder>(dec);
529 stack_.push_back(decoder);
531 // Restore decoder options that differ from their default
532 int options = settings.value("options").toInt();
534 for (int i = 0; i < options; i++) {
535 settings.beginGroup("option" + QString::number(i));
536 QString name = settings.value("name").toString();
537 GVariant *value = GlobalSettings::restore_gvariant(settings);
538 decoder->set_option(name.toUtf8(), value);
542 // Include the newly created decode channels in the channel lists
543 update_channel_list();
552 // Restore channel mapping
553 unsigned int channels = settings.value("channels").toInt();
555 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
556 session_.signalbases();
558 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
559 auto channel = find_if(channels_.begin(), channels_.end(),
560 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
562 if (channel == channels_.end()) {
563 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
567 settings.beginGroup("channel" + QString::number(channel_id));
569 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
571 for (shared_ptr<data::SignalBase> signal : signalbases)
572 if (signal->name() == assigned_signal_name)
573 channel->assigned_signal = signal.get();
575 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
580 // Update the internal structures
581 stack_config_changed_ = true;
582 update_channel_list();
583 commit_decoder_channels();
588 void DecodeSignal::set_error_message(QString msg)
590 error_message_ = msg;
591 qDebug().noquote().nospace() << name() << ": " << msg;
594 uint32_t DecodeSignal::get_input_segment_count() const
596 uint64_t count = std::numeric_limits<uint64_t>::max();
597 bool no_signals_assigned = true;
599 for (const data::DecodeChannel &ch : channels_)
600 if (ch.assigned_signal) {
601 no_signals_assigned = false;
603 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
604 if (!logic_data || logic_data->logic_segments().empty())
607 // Find the min value of all segment counts
608 if ((uint64_t)(logic_data->logic_segments().size()) < count)
609 count = logic_data->logic_segments().size();
612 return (no_signals_assigned ? 0 : count);
615 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
617 double samplerate = 0;
619 for (const data::DecodeChannel &ch : channels_)
620 if (ch.assigned_signal) {
621 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
622 if (!logic_data || logic_data->logic_segments().empty())
626 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
627 samplerate = segment->samplerate();
628 } catch (out_of_range&) {
637 void DecodeSignal::update_channel_list()
639 vector<data::DecodeChannel> prev_channels = channels_;
644 // Copy existing entries, create new as needed
645 for (shared_ptr<Decoder> decoder : stack_) {
646 const srd_decoder* srd_d = decoder->decoder();
649 // Mandatory channels
650 for (l = srd_d->channels; l; l = l->next) {
651 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
652 bool ch_added = false;
654 // Copy but update ID if this channel was in the list before
655 for (data::DecodeChannel &ch : prev_channels)
656 if (ch.pdch_ == pdch) {
658 channels_.push_back(ch);
664 // Create new entry without a mapped signal
665 data::DecodeChannel ch = {id++, 0, false, nullptr,
666 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
667 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
668 channels_.push_back(ch);
673 for (l = srd_d->opt_channels; l; l = l->next) {
674 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
675 bool ch_added = false;
677 // Copy but update ID if this channel was in the list before
678 for (data::DecodeChannel &ch : prev_channels)
679 if (ch.pdch_ == pdch) {
681 channels_.push_back(ch);
687 // Create new entry without a mapped signal
688 data::DecodeChannel ch = {id++, 0, true, nullptr,
689 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
690 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
691 channels_.push_back(ch);
696 // Invalidate the logic output data if the channel assignment changed
697 if (prev_channels.size() != channels_.size()) {
698 // The number of channels changed, there's definitely a difference
699 logic_mux_data_invalid_ = true;
701 // Same number but assignment may still differ, so compare all channels
702 for (size_t i = 0; i < channels_.size(); i++) {
703 const data::DecodeChannel &p_ch = prev_channels[i];
704 const data::DecodeChannel &ch = channels_[i];
706 if ((p_ch.pdch_ != ch.pdch_) ||
707 (p_ch.assigned_signal != ch.assigned_signal)) {
708 logic_mux_data_invalid_ = true;
718 void DecodeSignal::commit_decoder_channels()
720 // Submit channel list to every decoder, containing only the relevant channels
721 for (shared_ptr<decode::Decoder> dec : stack_) {
722 vector<data::DecodeChannel*> channel_list;
724 for (data::DecodeChannel &ch : channels_)
725 if (ch.decoder_ == dec)
726 channel_list.push_back(&ch);
728 dec->set_channels(channel_list);
731 // Channel bit IDs must be in sync with the channel's apperance in channels_
733 for (data::DecodeChannel &ch : channels_)
734 if (ch.assigned_signal)
738 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
740 // Enforce end to be greater than start
744 // Fetch the channel segments and their data
745 vector<shared_ptr<LogicSegment> > segments;
746 vector<const uint8_t*> signal_data;
747 vector<uint8_t> signal_in_bytepos;
748 vector<uint8_t> signal_in_bitpos;
750 for (data::DecodeChannel &ch : channels_)
751 if (ch.assigned_signal) {
752 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
754 shared_ptr<LogicSegment> segment;
756 segment = logic_data->logic_segments().at(segment_id);
757 } catch (out_of_range&) {
758 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
759 << "has no logic segment" << segment_id;
762 segments.push_back(segment);
764 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
765 segment->get_samples(start, end, data);
766 signal_data.push_back(data);
768 const int bitpos = ch.assigned_signal->logic_bit_index();
769 signal_in_bytepos.push_back(bitpos / 8);
770 signal_in_bitpos.push_back(bitpos % 8);
774 shared_ptr<LogicSegment> output_segment;
776 output_segment = logic_mux_data_->logic_segments().at(segment_id);
777 } catch (out_of_range&) {
778 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
779 << segment_id << "in mux_logic_samples(), mux segments size is" \
780 << logic_mux_data_->logic_segments().size();
784 // Perform the muxing of signal data into the output data
785 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
786 unsigned int signal_count = signal_data.size();
788 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
792 const int out_sample_pos = sample_cnt * output_segment->unit_size();
793 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
794 output[out_sample_pos + i] = 0;
796 for (unsigned int i = 0; i < signal_count; i++) {
797 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
798 const uint8_t in_sample = 1 &
799 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
801 const uint8_t out_sample = output[out_sample_pos + bytepos];
803 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
813 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
816 for (const uint8_t* data : signal_data)
820 void DecodeSignal::logic_mux_proc()
822 uint32_t segment_id = 0;
824 assert(logic_mux_data_);
826 // Create initial logic mux segment
827 shared_ptr<LogicSegment> output_segment =
828 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
829 logic_mux_unit_size_, 0);
830 logic_mux_data_->push_segment(output_segment);
832 output_segment->set_samplerate(get_input_samplerate(0));
835 const uint64_t input_sample_count = get_working_sample_count(segment_id);
836 const uint64_t output_sample_count = output_segment->get_sample_count();
838 const uint64_t samples_to_process =
839 (input_sample_count > output_sample_count) ?
840 (input_sample_count - output_sample_count) : 0;
842 // Process the samples if necessary...
843 if (samples_to_process > 0) {
844 const uint64_t unit_size = output_segment->unit_size();
845 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
847 uint64_t processed_samples = 0;
849 const uint64_t start_sample = output_sample_count + processed_samples;
850 const uint64_t sample_count =
851 min(samples_to_process - processed_samples, chunk_sample_count);
853 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
854 processed_samples += sample_count;
856 // ...and process the newly muxed logic data
857 decode_input_cond_.notify_one();
858 } while (processed_samples < samples_to_process);
861 if (samples_to_process == 0) {
862 // TODO Optimize this by caching the input segment count and only
863 // querying it when the cached value was reached
864 if (segment_id < get_input_segment_count() - 1) {
865 // Process next segment
869 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
870 logic_mux_unit_size_, 0);
871 logic_mux_data_->push_segment(output_segment);
873 output_segment->set_samplerate(get_input_samplerate(segment_id));
876 // All segments have been processed
877 logic_mux_data_invalid_ = false;
879 // Wait for more input
880 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
881 logic_mux_cond_.wait(logic_mux_lock);
884 } while (!logic_mux_interrupt_);
887 void DecodeSignal::decode_data(
888 const int64_t abs_start_samplenum, const int64_t sample_count,
889 const shared_ptr<LogicSegment> input_segment)
891 const int64_t unit_size = input_segment->unit_size();
892 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
894 for (int64_t i = abs_start_samplenum;
895 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
896 i += chunk_sample_count) {
898 const int64_t chunk_end = min(i + chunk_sample_count,
899 abs_start_samplenum + sample_count);
901 int64_t data_size = (chunk_end - i) * unit_size;
902 uint8_t* chunk = new uint8_t[data_size];
903 input_segment->get_samples(i, chunk_end, chunk);
905 if (srd_session_send(srd_session_, i, chunk_end, chunk,
906 data_size, unit_size) != SRD_OK) {
907 set_error_message(tr("Decoder reported an error"));
915 lock_guard<mutex> lock(output_mutex_);
916 segments_.at(current_segment_id_).samples_decoded = chunk_end;
919 // Notify the frontend that we processed some data and
920 // possibly have new annotations as well
925 void DecodeSignal::decode_proc()
927 current_segment_id_ = 0;
929 // If there is no input data available yet, wait until it is or we're interrupted
930 if (logic_mux_data_->logic_segments().size() == 0) {
931 unique_lock<mutex> input_wait_lock(input_mutex_);
932 decode_input_cond_.wait(input_wait_lock);
935 if (decode_interrupt_)
938 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
939 assert(input_segment);
941 // Create the initial segment and set its sample rate so that we can pass it to SRD
942 create_decode_segment();
943 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
944 segments_.at(current_segment_id_).start_time = input_segment->start_time();
948 uint64_t sample_count = 0;
949 uint64_t abs_start_samplenum = 0;
951 // Keep processing new samples until we exhaust the input data
953 lock_guard<mutex> input_lock(input_mutex_);
954 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
956 if (sample_count > 0) {
957 decode_data(abs_start_samplenum, sample_count, input_segment);
958 abs_start_samplenum += sample_count;
960 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
962 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
963 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
964 // Process next segment
965 current_segment_id_++;
968 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
969 } catch (out_of_range&) {
970 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
971 << current_segment_id_ << "in decode_proc(), mux segments size is" \
972 << logic_mux_data_->logic_segments().size();
975 abs_start_samplenum = 0;
977 // Create the next segment and set its metadata
978 create_decode_segment();
979 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
980 segments_.at(current_segment_id_).start_time = input_segment->start_time();
982 // Reset decoder state but keep the decoder stack intact
983 terminate_srd_session();
985 // All segments have been processed
988 // Wait for new input data or an interrupt was requested
989 unique_lock<mutex> input_wait_lock(input_mutex_);
990 decode_input_cond_.wait(input_wait_lock);
993 } while (error_message_.isEmpty() && !decode_interrupt_);
995 // Potentially reap decoders when the application no longer is
996 // interested in their (pending) results.
997 if (decode_interrupt_)
998 terminate_srd_session();
1001 void DecodeSignal::start_srd_session()
1003 uint64_t samplerate;
1005 // If there were stack changes, the session has been destroyed by now, so if
1006 // it hasn't been destroyed, we can just reset and re-use it
1008 // When a decoder stack was created before, re-use it
1009 // for the next stream of input data, after terminating
1010 // potentially still executing operations, and resetting
1011 // internal state. Skip the rather expensive (teardown
1012 // and) construction of another decoder stack.
1014 // TODO Reduce redundancy, use a common code path for
1015 // the meta/cb/start sequence?
1016 terminate_srd_session();
1017 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1018 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1019 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1020 DecodeSignal::annotation_callback, this);
1021 srd_session_start(srd_session_);
1025 // Create the session
1026 srd_session_new(&srd_session_);
1027 assert(srd_session_);
1029 // Create the decoders
1030 srd_decoder_inst *prev_di = nullptr;
1031 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1032 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1035 set_error_message(tr("Failed to create decoder instance"));
1036 srd_session_destroy(srd_session_);
1037 srd_session_ = nullptr;
1042 srd_inst_stack(srd_session_, prev_di, di);
1047 // Start the session
1048 samplerate = segments_.at(current_segment_id_).samplerate;
1050 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1051 g_variant_new_uint64(samplerate));
1053 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1054 DecodeSignal::annotation_callback, this);
1056 srd_session_start(srd_session_);
1058 // We just recreated the srd session, so all stack changes are applied now
1059 stack_config_changed_ = false;
1062 void DecodeSignal::terminate_srd_session()
1064 // Call the "terminate and reset" routine for the decoder stack
1065 // (if available). This does not harm those stacks which already
1066 // have completed their operation, and reduces response time for
1067 // those stacks which still are processing data while the
1068 // application no longer wants them to.
1070 srd_session_terminate_reset(srd_session_);
1073 void DecodeSignal::stop_srd_session()
1076 // Destroy the session
1077 srd_session_destroy(srd_session_);
1078 srd_session_ = nullptr;
1080 // Mark the decoder instances as non-existant since they were deleted
1081 for (const shared_ptr<decode::Decoder> &dec : stack_)
1082 dec->invalidate_decoder_inst();
1086 void DecodeSignal::connect_input_notifiers()
1088 // Disconnect the notification slot from the previous set of signals
1089 disconnect(this, SLOT(on_data_cleared()));
1090 disconnect(this, SLOT(on_data_received()));
1092 // Connect the currently used signals to our slot
1093 for (data::DecodeChannel &ch : channels_) {
1094 if (!ch.assigned_signal)
1097 const data::SignalBase *signal = ch.assigned_signal;
1098 connect(signal, SIGNAL(samples_cleared()),
1099 this, SLOT(on_data_cleared()));
1100 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1101 this, SLOT(on_data_received()));
1105 void DecodeSignal::create_decode_segment()
1107 // Create annotation segment
1108 segments_.emplace_back(DecodeSegment());
1110 // Add annotation classes
1111 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1113 const srd_decoder *const decc = dec->decoder();
1114 assert(dec->decoder());
1116 // Add a row for the decoder if it doesn't have a row list
1117 if (!decc->annotation_rows)
1118 (segments_.back().annotation_rows)[Row(decc)] =
1121 // Add the decoder rows
1122 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1123 const srd_decoder_annotation_row *const ann_row =
1124 (srd_decoder_annotation_row *)l->data;
1127 const Row row(decc, ann_row);
1129 // Add a new empty row data object
1130 (segments_.back().annotation_rows)[row] =
1136 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1139 assert(decode_signal);
1141 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1144 lock_guard<mutex> lock(ds->output_mutex_);
1148 assert(pdata->pdo->di);
1149 const srd_decoder *const decc = pdata->pdo->di->decoder;
1152 const srd_proto_data_annotation *const pda =
1153 (const srd_proto_data_annotation*)pdata->data;
1156 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
1158 // Try looking up the sub-row of this class
1159 const auto format = pda->ann_class;
1160 const auto r = ds->class_rows_.find(make_pair(decc, format));
1161 if (r != ds->class_rows_.end())
1162 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
1164 // Failing that, use the decoder as a key
1165 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(decc));
1168 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
1169 qDebug() << "Unexpected annotation: decoder = " << decc <<
1170 ", format = " << format;
1175 // Add the annotation
1176 (*row_iter).second.emplace_annotation(pdata);
1179 void DecodeSignal::on_capture_state_changed(int state)
1181 // If a new acquisition was started, we need to start decoding from scratch
1182 if (state == Session::Running) {
1183 logic_mux_data_invalid_ = true;
1188 void DecodeSignal::on_data_cleared()
1193 void DecodeSignal::on_data_received()
1195 if (!logic_mux_thread_.joinable())
1198 logic_mux_cond_.notify_one();