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 // TODO Emulate noquote()
162 qDebug().nospace() << name() << ": Error cleared";
168 void DecodeSignal::begin_decode()
170 if (decode_thread_.joinable()) {
171 decode_interrupt_ = true;
172 decode_input_cond_.notify_one();
173 decode_thread_.join();
176 if (logic_mux_thread_.joinable()) {
177 logic_mux_interrupt_ = true;
178 logic_mux_cond_.notify_one();
179 logic_mux_thread_.join();
184 if (stack_.size() == 0) {
185 set_error_message(tr("No decoders"));
189 assert(channels_.size() > 0);
191 if (get_assigned_signal_count() == 0) {
192 set_error_message(tr("There are no channels assigned to this decoder"));
196 // Make sure that all assigned channels still provide logic data
197 // (can happen when a converted signal was assigned but the
198 // conversion removed in the meanwhile)
199 for (data::DecodeChannel &ch : channels_)
200 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
201 ch.assigned_signal = nullptr;
203 // Check that all decoders have the required channels
204 for (const shared_ptr<decode::Decoder> &dec : stack_)
205 if (!dec->have_required_channels()) {
206 set_error_message(tr("One or more required channels "
207 "have not been specified"));
211 // Map out all the annotation classes
212 for (const shared_ptr<decode::Decoder> &dec : stack_) {
214 const srd_decoder *const decc = dec->decoder();
215 assert(dec->decoder());
217 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
218 const srd_decoder_annotation_row *const ann_row =
219 (srd_decoder_annotation_row *)l->data;
222 const Row row(decc, ann_row);
224 for (const GSList *ll = ann_row->ann_classes;
226 class_rows_[make_pair(decc,
227 GPOINTER_TO_INT(ll->data))] = row;
231 // Free the logic data and its segment(s) if it needs to be updated
232 if (logic_mux_data_invalid_)
233 logic_mux_data_.reset();
235 if (!logic_mux_data_) {
236 const uint32_t ch_count = get_assigned_signal_count();
237 logic_mux_unit_size_ = (ch_count + 7) / 8;
238 logic_mux_data_ = make_shared<Logic>(ch_count);
241 // Receive notifications when new sample data is available
242 connect_input_notifiers();
244 if (get_input_segment_count() == 0) {
245 set_error_message(tr("No input data"));
249 // Make sure the logic output data is complete and up-to-date
250 logic_mux_interrupt_ = false;
251 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
253 // Decode the muxed logic data
254 decode_interrupt_ = false;
255 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
258 QString DecodeSignal::error_message() const
260 lock_guard<mutex> lock(output_mutex_);
261 return error_message_;
264 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
269 void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
271 bool new_assignment = false;
273 // Try to auto-select channels that don't have signals assigned yet
274 for (data::DecodeChannel &ch : channels_) {
275 // If a decoder is given, auto-assign only its channels
276 if (dec && (ch.decoder_ != dec))
279 if (ch.assigned_signal)
282 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
286 const QString ch_name = ch.name.toLower();
287 const QString s_name = s->name().toLower();
289 if (s->logic_data() &&
290 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
291 ch.assigned_signal = s.get();
292 new_assignment = true;
297 if (new_assignment) {
298 logic_mux_data_invalid_ = true;
299 stack_config_changed_ = true;
300 commit_decoder_channels();
305 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
307 for (data::DecodeChannel &ch : channels_)
308 if (ch.id == channel_id) {
309 ch.assigned_signal = signal;
310 logic_mux_data_invalid_ = true;
313 stack_config_changed_ = true;
314 commit_decoder_channels();
319 int DecodeSignal::get_assigned_signal_count() const
321 // Count all channels that have a signal assigned to them
322 return count_if(channels_.begin(), channels_.end(),
323 [](data::DecodeChannel ch) { return ch.assigned_signal; });
326 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
328 for (data::DecodeChannel &ch : channels_)
329 if (ch.id == channel_id)
330 ch.initial_pin_state = init_state;
332 stack_config_changed_ = true;
337 double DecodeSignal::samplerate() const
341 // TODO For now, we simply return the first samplerate that we have
342 if (segments_.size() > 0)
343 result = segments_.front().samplerate;
348 const pv::util::Timestamp DecodeSignal::start_time() const
350 pv::util::Timestamp result;
352 // TODO For now, we simply return the first start time that we have
353 if (segments_.size() > 0)
354 result = segments_.front().start_time;
359 int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
361 // The working sample count is the highest sample number for
362 // which all used signals have data available, so go through all
363 // channels and use the lowest overall sample count of the segment
365 int64_t count = std::numeric_limits<int64_t>::max();
366 bool no_signals_assigned = true;
368 for (const data::DecodeChannel &ch : channels_)
369 if (ch.assigned_signal) {
370 no_signals_assigned = false;
372 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
373 if (!logic_data || logic_data->logic_segments().empty())
377 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
378 count = min(count, (int64_t)segment->get_sample_count());
379 } catch (out_of_range&) {
384 return (no_signals_assigned ? 0 : count);
387 int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id) const
389 lock_guard<mutex> decode_lock(output_mutex_);
394 const DecodeSegment *segment = &(segments_.at(segment_id));
395 result = segment->samples_decoded;
396 } catch (out_of_range&) {
403 vector<Row> DecodeSignal::visible_rows() const
405 lock_guard<mutex> lock(output_mutex_);
409 for (const shared_ptr<decode::Decoder> &dec : stack_) {
414 const srd_decoder *const decc = dec->decoder();
415 assert(dec->decoder());
417 // Add a row for the decoder if it doesn't have a row list
418 if (!decc->annotation_rows)
419 rows.emplace_back(decc);
421 // Add the decoder rows
422 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
423 const srd_decoder_annotation_row *const ann_row =
424 (srd_decoder_annotation_row *)l->data;
426 rows.emplace_back(decc, ann_row);
433 void DecodeSignal::get_annotation_subset(
434 vector<pv::data::decode::Annotation> &dest,
435 const decode::Row &row, uint32_t segment_id, uint64_t start_sample,
436 uint64_t end_sample) const
438 lock_guard<mutex> lock(output_mutex_);
441 const DecodeSegment *segment = &(segments_.at(segment_id));
442 const map<const decode::Row, decode::RowData> *rows =
443 &(segment->annotation_rows);
445 const auto iter = rows->find(row);
446 if (iter != rows->end())
447 (*iter).second.get_annotation_subset(dest,
448 start_sample, end_sample);
449 } catch (out_of_range&) {
454 void DecodeSignal::save_settings(QSettings &settings) const
456 SignalBase::save_settings(settings);
458 settings.setValue("decoders", (int)(stack_.size()));
460 // Save decoder stack
462 for (shared_ptr<decode::Decoder> decoder : stack_) {
463 settings.beginGroup("decoder" + QString::number(decoder_idx++));
465 settings.setValue("id", decoder->decoder()->id);
467 // Save decoder options
468 const map<string, GVariant*>& options = decoder->options();
470 settings.setValue("options", (int)options.size());
472 // Note: decode::Decoder::options() returns only the options
473 // that differ from the default. See binding::Decoder::getter()
475 for (auto option : options) {
476 settings.beginGroup("option" + QString::number(i));
477 settings.setValue("name", QString::fromStdString(option.first));
478 GlobalSettings::store_gvariant(settings, option.second);
486 // Save channel mapping
487 settings.setValue("channels", (int)channels_.size());
489 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
490 auto channel = find_if(channels_.begin(), channels_.end(),
491 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
493 if (channel == channels_.end()) {
494 qDebug() << "ERROR: Gap in channel index:" << channel_id;
498 settings.beginGroup("channel" + QString::number(channel_id));
500 settings.setValue("name", channel->name); // Useful for debugging
501 settings.setValue("initial_pin_state", channel->initial_pin_state);
503 if (channel->assigned_signal)
504 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
510 void DecodeSignal::restore_settings(QSettings &settings)
512 SignalBase::restore_settings(settings);
514 // Restore decoder stack
515 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
517 int decoders = settings.value("decoders").toInt();
519 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
520 settings.beginGroup("decoder" + QString::number(decoder_idx));
522 QString id = settings.value("id").toString();
524 for (GSList *entry = dec_list; entry; entry = entry->next) {
525 const srd_decoder *dec = (srd_decoder*)entry->data;
529 if (QString::fromUtf8(dec->id) == id) {
530 shared_ptr<decode::Decoder> decoder =
531 make_shared<decode::Decoder>(dec);
533 stack_.push_back(decoder);
535 // Restore decoder options that differ from their default
536 int options = settings.value("options").toInt();
538 for (int i = 0; i < options; i++) {
539 settings.beginGroup("option" + QString::number(i));
540 QString name = settings.value("name").toString();
541 GVariant *value = GlobalSettings::restore_gvariant(settings);
542 decoder->set_option(name.toUtf8(), value);
546 // Include the newly created decode channels in the channel lists
547 update_channel_list();
556 // Restore channel mapping
557 unsigned int channels = settings.value("channels").toInt();
559 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
560 session_.signalbases();
562 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
563 auto channel = find_if(channels_.begin(), channels_.end(),
564 [&](data::DecodeChannel ch) { return ch.id == channel_id; });
566 if (channel == channels_.end()) {
567 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
571 settings.beginGroup("channel" + QString::number(channel_id));
573 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
575 for (shared_ptr<data::SignalBase> signal : signalbases)
576 if (signal->name() == assigned_signal_name)
577 channel->assigned_signal = signal.get();
579 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
584 // Update the internal structures
585 stack_config_changed_ = true;
586 update_channel_list();
587 commit_decoder_channels();
592 void DecodeSignal::set_error_message(QString msg)
594 error_message_ = msg;
595 // TODO Emulate noquote()
596 qDebug().nospace() << name() << ": " << msg;
599 uint32_t DecodeSignal::get_input_segment_count() const
601 uint64_t count = std::numeric_limits<uint64_t>::max();
602 bool no_signals_assigned = true;
604 for (const data::DecodeChannel &ch : channels_)
605 if (ch.assigned_signal) {
606 no_signals_assigned = false;
608 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
609 if (!logic_data || logic_data->logic_segments().empty())
612 // Find the min value of all segment counts
613 if ((uint64_t)(logic_data->logic_segments().size()) < count)
614 count = logic_data->logic_segments().size();
617 return (no_signals_assigned ? 0 : count);
620 uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
622 double samplerate = 0;
624 for (const data::DecodeChannel &ch : channels_)
625 if (ch.assigned_signal) {
626 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
627 if (!logic_data || logic_data->logic_segments().empty())
631 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
632 samplerate = segment->samplerate();
633 } catch (out_of_range&) {
642 void DecodeSignal::update_channel_list()
644 vector<data::DecodeChannel> prev_channels = channels_;
649 // Copy existing entries, create new as needed
650 for (shared_ptr<Decoder> decoder : stack_) {
651 const srd_decoder* srd_d = decoder->decoder();
654 // Mandatory channels
655 for (l = srd_d->channels; l; l = l->next) {
656 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
657 bool ch_added = false;
659 // Copy but update ID if this channel was in the list before
660 for (data::DecodeChannel &ch : prev_channels)
661 if (ch.pdch_ == pdch) {
663 channels_.push_back(ch);
669 // Create new entry without a mapped signal
670 data::DecodeChannel ch = {id++, 0, false, nullptr,
671 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
672 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
673 channels_.push_back(ch);
678 for (l = srd_d->opt_channels; l; l = l->next) {
679 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
680 bool ch_added = false;
682 // Copy but update ID if this channel was in the list before
683 for (data::DecodeChannel &ch : prev_channels)
684 if (ch.pdch_ == pdch) {
686 channels_.push_back(ch);
692 // Create new entry without a mapped signal
693 data::DecodeChannel ch = {id++, 0, true, nullptr,
694 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
695 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
696 channels_.push_back(ch);
701 // Invalidate the logic output data if the channel assignment changed
702 if (prev_channels.size() != channels_.size()) {
703 // The number of channels changed, there's definitely a difference
704 logic_mux_data_invalid_ = true;
706 // Same number but assignment may still differ, so compare all channels
707 for (size_t i = 0; i < channels_.size(); i++) {
708 const data::DecodeChannel &p_ch = prev_channels[i];
709 const data::DecodeChannel &ch = channels_[i];
711 if ((p_ch.pdch_ != ch.pdch_) ||
712 (p_ch.assigned_signal != ch.assigned_signal)) {
713 logic_mux_data_invalid_ = true;
723 void DecodeSignal::commit_decoder_channels()
725 // Submit channel list to every decoder, containing only the relevant channels
726 for (shared_ptr<decode::Decoder> dec : stack_) {
727 vector<data::DecodeChannel*> channel_list;
729 for (data::DecodeChannel &ch : channels_)
730 if (ch.decoder_ == dec)
731 channel_list.push_back(&ch);
733 dec->set_channels(channel_list);
736 // Channel bit IDs must be in sync with the channel's apperance in channels_
738 for (data::DecodeChannel &ch : channels_)
739 if (ch.assigned_signal)
743 void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
745 // Enforce end to be greater than start
749 // Fetch the channel segments and their data
750 vector<shared_ptr<LogicSegment> > segments;
751 vector<const uint8_t*> signal_data;
752 vector<uint8_t> signal_in_bytepos;
753 vector<uint8_t> signal_in_bitpos;
755 for (data::DecodeChannel &ch : channels_)
756 if (ch.assigned_signal) {
757 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
759 shared_ptr<LogicSegment> segment;
761 segment = logic_data->logic_segments().at(segment_id);
762 } catch (out_of_range&) {
763 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
764 << "has no logic segment" << segment_id;
767 segments.push_back(segment);
769 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
770 segment->get_samples(start, end, data);
771 signal_data.push_back(data);
773 const int bitpos = ch.assigned_signal->logic_bit_index();
774 signal_in_bytepos.push_back(bitpos / 8);
775 signal_in_bitpos.push_back(bitpos % 8);
779 shared_ptr<LogicSegment> output_segment;
781 output_segment = logic_mux_data_->logic_segments().at(segment_id);
782 } catch (out_of_range&) {
783 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
784 << segment_id << "in mux_logic_samples(), mux segments size is" \
785 << logic_mux_data_->logic_segments().size();
789 // Perform the muxing of signal data into the output data
790 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
791 unsigned int signal_count = signal_data.size();
793 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
799 const int out_sample_pos = sample_cnt * output_segment->unit_size();
800 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
801 output[out_sample_pos + i] = 0;
803 for (unsigned int i = 0; i < signal_count; i++) {
804 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
805 const uint8_t in_sample = 1 &
806 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
808 const uint8_t out_sample = output[out_sample_pos + bytepos];
810 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
820 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
823 for (const uint8_t* data : signal_data)
827 void DecodeSignal::logic_mux_proc()
829 uint32_t segment_id = 0;
831 assert(logic_mux_data_);
833 // Create initial logic mux segment
834 shared_ptr<LogicSegment> output_segment =
835 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
836 logic_mux_unit_size_, 0);
837 logic_mux_data_->push_segment(output_segment);
839 output_segment->set_samplerate(get_input_samplerate(0));
842 const uint64_t input_sample_count = get_working_sample_count(segment_id);
843 const uint64_t output_sample_count = output_segment->get_sample_count();
845 const uint64_t samples_to_process =
846 (input_sample_count > output_sample_count) ?
847 (input_sample_count - output_sample_count) : 0;
849 // Process the samples if necessary...
850 if (samples_to_process > 0) {
851 const uint64_t unit_size = output_segment->unit_size();
852 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
854 uint64_t processed_samples = 0;
856 const uint64_t start_sample = output_sample_count + processed_samples;
857 const uint64_t sample_count =
858 min(samples_to_process - processed_samples, chunk_sample_count);
860 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
861 processed_samples += sample_count;
863 // ...and process the newly muxed logic data
864 decode_input_cond_.notify_one();
865 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
868 if (samples_to_process == 0) {
869 // TODO Optimize this by caching the input segment count and only
870 // querying it when the cached value was reached
871 if (segment_id < get_input_segment_count() - 1) {
872 // Process next segment
876 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
877 logic_mux_unit_size_, 0);
878 logic_mux_data_->push_segment(output_segment);
880 output_segment->set_samplerate(get_input_samplerate(segment_id));
883 // All segments have been processed
884 logic_mux_data_invalid_ = false;
886 // Wait for more input
887 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
888 logic_mux_cond_.wait(logic_mux_lock);
891 } while (!logic_mux_interrupt_);
894 void DecodeSignal::decode_data(
895 const int64_t abs_start_samplenum, const int64_t sample_count,
896 const shared_ptr<LogicSegment> input_segment)
898 const int64_t unit_size = input_segment->unit_size();
899 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
901 for (int64_t i = abs_start_samplenum;
902 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
903 i += chunk_sample_count) {
905 const int64_t chunk_end = min(i + chunk_sample_count,
906 abs_start_samplenum + sample_count);
908 // Report this chunk as already decoded so that annotations don't
909 // appear in an area that we claim to not having been been decoded yet
911 lock_guard<mutex> lock(output_mutex_);
912 segments_.at(current_segment_id_).samples_decoded = chunk_end;
915 int64_t data_size = (chunk_end - i) * unit_size;
916 uint8_t* chunk = new uint8_t[data_size];
917 input_segment->get_samples(i, chunk_end, chunk);
919 if (srd_session_send(srd_session_, i, chunk_end, chunk,
920 data_size, unit_size) != SRD_OK) {
921 set_error_message(tr("Decoder reported an error"));
928 // Notify the frontend that we processed some data and
929 // possibly have new annotations as well
934 void DecodeSignal::decode_proc()
936 current_segment_id_ = 0;
938 // If there is no input data available yet, wait until it is or we're interrupted
939 if (logic_mux_data_->logic_segments().size() == 0) {
940 unique_lock<mutex> input_wait_lock(input_mutex_);
941 decode_input_cond_.wait(input_wait_lock);
944 if (decode_interrupt_)
947 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
948 assert(input_segment);
950 // Create the initial segment and set its sample rate so that we can pass it to SRD
951 create_decode_segment();
952 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
953 segments_.at(current_segment_id_).start_time = input_segment->start_time();
957 uint64_t sample_count = 0;
958 uint64_t abs_start_samplenum = 0;
960 // Keep processing new samples until we exhaust the input data
962 lock_guard<mutex> input_lock(input_mutex_);
963 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
965 if (sample_count > 0) {
966 decode_data(abs_start_samplenum, sample_count, input_segment);
967 abs_start_samplenum += sample_count;
969 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
971 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
972 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
973 // Process next segment
974 current_segment_id_++;
977 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
978 } catch (out_of_range&) {
979 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
980 << current_segment_id_ << "in decode_proc(), mux segments size is" \
981 << logic_mux_data_->logic_segments().size();
984 abs_start_samplenum = 0;
986 // Create the next segment and set its metadata
987 create_decode_segment();
988 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
989 segments_.at(current_segment_id_).start_time = input_segment->start_time();
991 // Reset decoder state but keep the decoder stack intact
992 terminate_srd_session();
994 // All segments have been processed
997 // Wait for new input data or an interrupt was requested
998 unique_lock<mutex> input_wait_lock(input_mutex_);
999 decode_input_cond_.wait(input_wait_lock);
1002 } while (error_message_.isEmpty() && !decode_interrupt_);
1004 // Potentially reap decoders when the application no longer is
1005 // interested in their (pending) results.
1006 if (decode_interrupt_)
1007 terminate_srd_session();
1010 void DecodeSignal::start_srd_session()
1012 // If there were stack changes, the session has been destroyed by now, so if
1013 // it hasn't been destroyed, we can just reset and re-use it
1015 // When a decoder stack was created before, re-use it
1016 // for the next stream of input data, after terminating
1017 // potentially still executing operations, and resetting
1018 // internal state. Skip the rather expensive (teardown
1019 // and) construction of another decoder stack.
1021 // TODO Reduce redundancy, use a common code path for
1022 // the meta/start sequence?
1023 terminate_srd_session();
1025 // Metadata is cleared also, so re-set it
1026 uint64_t samplerate = 0;
1027 if (segments_.size() > 0)
1028 samplerate = segments_.at(current_segment_id_).samplerate;
1030 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1031 g_variant_new_uint64(samplerate));
1032 for (const shared_ptr<decode::Decoder> &dec : stack_)
1033 dec->apply_all_options();
1034 srd_session_start(srd_session_);
1039 // Create the session
1040 srd_session_new(&srd_session_);
1041 assert(srd_session_);
1043 // Create the decoders
1044 srd_decoder_inst *prev_di = nullptr;
1045 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1046 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1049 set_error_message(tr("Failed to create decoder instance"));
1050 srd_session_destroy(srd_session_);
1051 srd_session_ = nullptr;
1056 srd_inst_stack(srd_session_, prev_di, di);
1061 // Start the session
1062 if (segments_.size() > 0)
1063 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1064 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1066 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1067 DecodeSignal::annotation_callback, this);
1069 srd_session_start(srd_session_);
1071 // We just recreated the srd session, so all stack changes are applied now
1072 stack_config_changed_ = false;
1075 void DecodeSignal::terminate_srd_session()
1077 // Call the "terminate and reset" routine for the decoder stack
1078 // (if available). This does not harm those stacks which already
1079 // have completed their operation, and reduces response time for
1080 // those stacks which still are processing data while the
1081 // application no longer wants them to.
1083 srd_session_terminate_reset(srd_session_);
1085 // Metadata is cleared also, so re-set it
1086 uint64_t samplerate = 0;
1087 if (segments_.size() > 0)
1088 samplerate = segments_.at(current_segment_id_).samplerate;
1090 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1091 g_variant_new_uint64(samplerate));
1092 for (const shared_ptr<decode::Decoder> &dec : stack_)
1093 dec->apply_all_options();
1097 void DecodeSignal::stop_srd_session()
1100 // Destroy the session
1101 srd_session_destroy(srd_session_);
1102 srd_session_ = nullptr;
1104 // Mark the decoder instances as non-existant since they were deleted
1105 for (const shared_ptr<decode::Decoder> &dec : stack_)
1106 dec->invalidate_decoder_inst();
1110 void DecodeSignal::connect_input_notifiers()
1112 // Disconnect the notification slot from the previous set of signals
1113 disconnect(this, SLOT(on_data_cleared()));
1114 disconnect(this, SLOT(on_data_received()));
1116 // Connect the currently used signals to our slot
1117 for (data::DecodeChannel &ch : channels_) {
1118 if (!ch.assigned_signal)
1121 const data::SignalBase *signal = ch.assigned_signal;
1122 connect(signal, SIGNAL(samples_cleared()),
1123 this, SLOT(on_data_cleared()));
1124 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1125 this, SLOT(on_data_received()));
1129 void DecodeSignal::create_decode_segment()
1131 // Create annotation segment
1132 segments_.emplace_back(DecodeSegment());
1134 // Add annotation classes
1135 for (const shared_ptr<decode::Decoder> &dec : stack_) {
1137 const srd_decoder *const decc = dec->decoder();
1138 assert(dec->decoder());
1140 // Add a row for the decoder if it doesn't have a row list
1141 if (!decc->annotation_rows)
1142 (segments_.back().annotation_rows)[Row(decc)] =
1145 // Add the decoder rows
1146 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
1147 const srd_decoder_annotation_row *const ann_row =
1148 (srd_decoder_annotation_row *)l->data;
1151 const Row row(decc, ann_row);
1153 // Add a new empty row data object
1154 (segments_.back().annotation_rows)[row] =
1160 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1163 assert(decode_signal);
1165 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1168 if (ds->decode_interrupt_)
1171 lock_guard<mutex> lock(ds->output_mutex_);
1175 assert(pdata->pdo->di);
1176 const srd_decoder *const decc = pdata->pdo->di->decoder;
1179 const srd_proto_data_annotation *const pda =
1180 (const srd_proto_data_annotation*)pdata->data;
1183 auto row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.end();
1185 // Try looking up the sub-row of this class
1186 const auto format = pda->ann_class;
1187 const auto r = ds->class_rows_.find(make_pair(decc, format));
1188 if (r != ds->class_rows_.end())
1189 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find((*r).second);
1191 // Failing that, use the decoder as a key
1192 row_iter = ds->segments_.at(ds->current_segment_id_).annotation_rows.find(Row(decc));
1195 if (row_iter == ds->segments_.at(ds->current_segment_id_).annotation_rows.end()) {
1196 qDebug() << "Unexpected annotation: decoder = " << decc <<
1197 ", format = " << format;
1202 // Add the annotation
1203 (*row_iter).second.emplace_annotation(pdata);
1206 void DecodeSignal::on_capture_state_changed(int state)
1208 // If a new acquisition was started, we need to start decoding from scratch
1209 if (state == Session::Running) {
1210 logic_mux_data_invalid_ = true;
1215 void DecodeSignal::on_data_cleared()
1220 void DecodeSignal::on_data_received()
1222 // If we detected a lack of input data when trying to start decoding,
1223 // we have set an error message. Only try again if we now have data
1225 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1228 if (!logic_mux_thread_.joinable())
1231 logic_mux_cond_.notify_one();