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/session.hpp>
34 using std::lock_guard;
36 using std::make_shared;
38 using std::shared_ptr;
39 using std::unique_lock;
40 using pv::data::decode::Annotation;
41 using pv::data::decode::Decoder;
42 using pv::data::decode::Row;
47 const double DecodeSignal::DecodeMargin = 1.0;
48 const double DecodeSignal::DecodeThreshold = 0.2;
49 const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
51 mutex DecodeSignal::global_srd_mutex_;
54 DecodeSignal::DecodeSignal(pv::Session &session) :
55 SignalBase(nullptr, SignalBase::DecodeChannel),
57 srd_session_(nullptr),
58 logic_mux_data_invalid_(false),
62 frame_complete_(false)
64 connect(&session_, SIGNAL(capture_state_changed(int)),
65 this, SLOT(on_capture_state_changed(int)));
67 set_name(tr("Empty decoder signal"));
70 DecodeSignal::~DecodeSignal()
72 if (decode_thread_.joinable()) {
73 decode_interrupt_ = true;
74 decode_input_cond_.notify_one();
75 decode_thread_.join();
78 if (logic_mux_thread_.joinable()) {
79 logic_mux_interrupt_ = true;
80 logic_mux_cond_.notify_one();
81 logic_mux_thread_.join();
87 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
92 void DecodeSignal::stack_decoder(srd_decoder *decoder)
95 stack_.push_back(make_shared<decode::Decoder>(decoder));
97 // Set name if this decoder is the first in the list
98 if (stack_.size() == 1)
99 set_name(QString::fromUtf8(decoder->name));
101 // Include the newly created decode channels in the channel lists
102 update_channel_list();
104 auto_assign_signals();
105 commit_decoder_channels();
109 void DecodeSignal::remove_decoder(int index)
112 assert(index < (int)stack_.size());
114 // Find the decoder in the stack
115 auto iter = stack_.begin();
116 for (int i = 0; i < index; i++, iter++)
117 assert(iter != stack_.end());
119 // Delete the element
122 // Update channels and decoded data
123 update_channel_list();
127 bool DecodeSignal::toggle_decoder_visibility(int index)
129 auto iter = stack_.cbegin();
130 for (int i = 0; i < index; i++, iter++)
131 assert(iter != stack_.end());
133 shared_ptr<Decoder> dec = *iter;
135 // Toggle decoder visibility
138 state = !dec->shown();
145 void DecodeSignal::reset_decode()
149 frame_complete_ = false;
150 samples_decoded_ = 0;
151 error_message_ = QString();
156 void DecodeSignal::begin_decode()
158 if (decode_thread_.joinable()) {
159 decode_interrupt_ = true;
160 decode_input_cond_.notify_one();
161 decode_thread_.join();
164 if (logic_mux_thread_.joinable()) {
165 logic_mux_interrupt_ = true;
166 logic_mux_cond_.notify_one();
167 logic_mux_thread_.join();
172 if (stack_.size() == 0) {
173 error_message_ = tr("No decoders");
177 assert(channels_.size() > 0);
179 if (get_assigned_signal_count() == 0) {
180 error_message_ = tr("There are no channels assigned to this decoder");
184 // Make sure that all assigned channels still provide logic data
185 // (can happen when a converted signal was assigned but the
186 // conversion removed in the meanwhile)
187 for (data::DecodeChannel &ch : channels_)
188 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
189 ch.assigned_signal = nullptr;
191 // Check that all decoders have the required channels
192 for (const shared_ptr<decode::Decoder> &dec : stack_)
193 if (!dec->have_required_channels()) {
194 error_message_ = tr("One or more required channels "
195 "have not been specified");
199 // Add annotation classes
200 for (const shared_ptr<decode::Decoder> &dec : stack_) {
202 const srd_decoder *const decc = dec->decoder();
203 assert(dec->decoder());
205 // Add a row for the decoder if it doesn't have a row list
206 if (!decc->annotation_rows)
207 rows_[Row(decc)] = decode::RowData();
209 // Add the decoder rows
210 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
211 const srd_decoder_annotation_row *const ann_row =
212 (srd_decoder_annotation_row *)l->data;
215 const Row row(decc, ann_row);
217 // Add a new empty row data object
218 rows_[row] = decode::RowData();
220 // Map out all the classes
221 for (const GSList *ll = ann_row->ann_classes;
223 class_rows_[make_pair(decc,
224 GPOINTER_TO_INT(ll->data))] = row;
228 // Free the logic data and its segment(s) if it needs to be updated
229 if (logic_mux_data_invalid_)
230 logic_mux_data_.reset();
232 if (!logic_mux_data_) {
233 const int64_t ch_count = get_assigned_signal_count();
234 const int64_t unit_size = (ch_count + 7) / 8;
235 logic_mux_data_ = make_shared<Logic>(ch_count);
236 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
237 logic_mux_data_->push_segment(segment_);
240 // Make sure the logic output data is complete and up-to-date
241 logic_mux_interrupt_ = false;
242 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
244 // Decode the muxed logic data
245 decode_interrupt_ = false;
246 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
248 // Receive notifications when new sample data is available
249 connect_input_notifiers();
252 QString DecodeSignal::error_message() const
254 lock_guard<mutex> lock(output_mutex_);
255 return error_message_;
258 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
263 void DecodeSignal::auto_assign_signals()
265 bool new_assignment = false;
267 // Try to auto-select channels that don't have signals assigned yet
268 for (data::DecodeChannel &ch : channels_) {
269 if (ch.assigned_signal)
272 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
273 const QString ch_name = ch.name.toLower();
274 const QString s_name = s->name().toLower();
276 if (s->logic_data() &&
277 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
278 ch.assigned_signal = s.get();
279 new_assignment = true;
284 if (new_assignment) {
285 logic_mux_data_invalid_ = true;
286 commit_decoder_channels();
291 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
293 for (data::DecodeChannel &ch : channels_)
294 if (ch.id == channel_id) {
295 ch.assigned_signal = signal;
296 logic_mux_data_invalid_ = true;
299 commit_decoder_channels();
304 int DecodeSignal::get_assigned_signal_count() const
306 // Count all channels that have a signal assigned to them
307 return count_if(channels_.begin(), channels_.end(),
308 [](data::DecodeChannel ch) { return ch.assigned_signal; });
311 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
313 for (data::DecodeChannel &ch : channels_)
314 if (ch.id == channel_id)
315 ch.initial_pin_state = init_state;
322 double DecodeSignal::samplerate() const
327 const pv::util::Timestamp& DecodeSignal::start_time() const
332 int64_t DecodeSignal::get_working_sample_count() const
334 // The working sample count is the highest sample number for
335 // which all used signals have data available, so go through
336 // all channels and use the lowest overall sample count of the
339 // TODO Currently, we assume only a single segment exists
341 int64_t count = std::numeric_limits<int64_t>::max();
342 bool no_signals_assigned = true;
344 for (const data::DecodeChannel &ch : channels_)
345 if (ch.assigned_signal) {
346 no_signals_assigned = false;
348 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
349 if (!logic_data || logic_data->logic_segments().empty())
352 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
353 count = min(count, (int64_t)segment->get_sample_count());
356 return (no_signals_assigned ? 0 : count);
359 int64_t DecodeSignal::get_decoded_sample_count() const
361 lock_guard<mutex> decode_lock(output_mutex_);
362 return samples_decoded_;
365 vector<Row> DecodeSignal::visible_rows() const
367 lock_guard<mutex> lock(output_mutex_);
371 for (const shared_ptr<decode::Decoder> &dec : stack_) {
376 const srd_decoder *const decc = dec->decoder();
377 assert(dec->decoder());
379 // Add a row for the decoder if it doesn't have a row list
380 if (!decc->annotation_rows)
381 rows.emplace_back(decc);
383 // Add the decoder rows
384 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
385 const srd_decoder_annotation_row *const ann_row =
386 (srd_decoder_annotation_row *)l->data;
388 rows.emplace_back(decc, ann_row);
395 void DecodeSignal::get_annotation_subset(
396 vector<pv::data::decode::Annotation> &dest,
397 const decode::Row &row, uint64_t start_sample,
398 uint64_t end_sample) const
400 lock_guard<mutex> lock(output_mutex_);
402 const auto iter = rows_.find(row);
403 if (iter != rows_.end())
404 (*iter).second.get_annotation_subset(dest,
405 start_sample, end_sample);
408 void DecodeSignal::save_settings(QSettings &settings) const
410 SignalBase::save_settings(settings);
412 // TODO Save decoder stack, channel mapping and decoder options
415 void DecodeSignal::restore_settings(QSettings &settings)
417 SignalBase::restore_settings(settings);
419 // TODO Restore decoder stack, channel mapping and decoder options
422 void DecodeSignal::update_channel_list()
424 vector<data::DecodeChannel> prev_channels = channels_;
429 // Copy existing entries, create new as needed
430 for (shared_ptr<Decoder> decoder : stack_) {
431 const srd_decoder* srd_d = decoder->decoder();
434 // Mandatory channels
435 for (l = srd_d->channels; l; l = l->next) {
436 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
437 bool ch_added = false;
439 // Copy but update ID if this channel was in the list before
440 for (data::DecodeChannel &ch : prev_channels)
441 if (ch.pdch_ == pdch) {
443 channels_.push_back(ch);
449 // Create new entry without a mapped signal
450 data::DecodeChannel ch = {id++, false, nullptr,
451 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
452 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
453 channels_.push_back(ch);
458 for (l = srd_d->opt_channels; l; l = l->next) {
459 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
460 bool ch_added = false;
462 // Copy but update ID if this channel was in the list before
463 for (data::DecodeChannel &ch : prev_channels)
464 if (ch.pdch_ == pdch) {
466 channels_.push_back(ch);
472 // Create new entry without a mapped signal
473 data::DecodeChannel ch = {id++, true, nullptr,
474 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
475 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
476 channels_.push_back(ch);
481 // Invalidate the logic output data if the channel assignment changed
482 if (prev_channels.size() != channels_.size()) {
483 // The number of channels changed, there's definitely a difference
484 logic_mux_data_invalid_ = true;
486 // Same number but assignment may still differ, so compare all channels
487 for (size_t i = 0; i < channels_.size(); i++) {
488 const data::DecodeChannel &p_ch = prev_channels[i];
489 const data::DecodeChannel &ch = channels_[i];
491 if ((p_ch.pdch_ != ch.pdch_) ||
492 (p_ch.assigned_signal != ch.assigned_signal)) {
493 logic_mux_data_invalid_ = true;
503 void DecodeSignal::commit_decoder_channels()
505 // Submit channel list to every decoder, containing only the relevant channels
506 for (shared_ptr<decode::Decoder> dec : stack_) {
507 vector<data::DecodeChannel*> channel_list;
509 for (data::DecodeChannel &ch : channels_)
510 if (ch.decoder_ == dec)
511 channel_list.push_back(&ch);
513 dec->set_channels(channel_list);
517 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
519 // Enforce end to be greater than start
523 // Fetch all segments and their data
524 // TODO Currently, we assume only a single segment exists
525 vector<shared_ptr<LogicSegment> > segments;
526 vector<const uint8_t*> signal_data;
527 vector<uint8_t> signal_in_bytepos;
528 vector<uint8_t> signal_in_bitpos;
530 for (data::DecodeChannel &ch : channels_)
531 if (ch.assigned_signal) {
532 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
533 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
534 segments.push_back(segment);
535 signal_data.push_back(segment->get_samples(start, end));
537 const int bitpos = ch.assigned_signal->logic_bit_index();
538 signal_in_bytepos.push_back(bitpos / 8);
539 signal_in_bitpos.push_back(bitpos % 8);
542 // Perform the muxing of signal data into the output data
543 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
544 unsigned int signal_count = signal_data.size();
546 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
550 const int out_sample_pos = sample_cnt * segment_->unit_size();
551 for (unsigned int i = 0; i < segment_->unit_size(); i++)
552 output[out_sample_pos + i] = 0;
554 for (unsigned int i = 0; i < signal_count; i++) {
555 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
556 const uint8_t in_sample = 1 &
557 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
559 const uint8_t out_sample = output[out_sample_pos + bytepos];
561 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
571 segment_->append_payload(output, (end - start) * segment_->unit_size());
574 for (const uint8_t* data : signal_data)
578 void DecodeSignal::logic_mux_proc()
581 const uint64_t input_sample_count = get_working_sample_count();
582 const uint64_t output_sample_count = segment_->get_sample_count();
584 const uint64_t samples_to_process =
585 (input_sample_count > output_sample_count) ?
586 (input_sample_count - output_sample_count) : 0;
588 // Process the samples if necessary...
589 if (samples_to_process > 0) {
590 const uint64_t unit_size = segment_->unit_size();
591 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
593 uint64_t processed_samples = 0;
595 const uint64_t start_sample = output_sample_count + processed_samples;
596 const uint64_t sample_count =
597 min(samples_to_process - processed_samples, chunk_sample_count);
599 mux_logic_samples(start_sample, start_sample + sample_count);
600 processed_samples += sample_count;
602 // ...and process the newly muxed logic data
603 decode_input_cond_.notify_one();
604 } while (processed_samples < samples_to_process);
607 if (samples_to_process == 0) {
608 // Wait for more input
609 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
610 logic_mux_cond_.wait(logic_mux_lock);
612 } while (!logic_mux_interrupt_);
614 // No more input data and session is stopped, let the decode thread
615 // process any pending data, terminate and release the global SRD mutex
616 // in order to let other decoders run
617 decode_input_cond_.notify_one();
620 void DecodeSignal::query_input_metadata()
622 // Update the samplerate and start time because we cannot start
623 // the libsrd session without the current samplerate
625 // TODO Currently we assume all channels have the same sample rate
627 bool samplerate_valid = false;
629 auto any_channel = find_if(channels_.begin(), channels_.end(),
630 [](data::DecodeChannel ch) { return ch.assigned_signal; });
632 shared_ptr<Logic> logic_data =
633 any_channel->assigned_signal->logic_data();
636 if (!logic_data->logic_segments().empty()) {
637 shared_ptr<LogicSegment> first_segment =
638 any_channel->assigned_signal->logic_data()->logic_segments().front();
639 start_time_ = first_segment->start_time();
640 samplerate_ = first_segment->samplerate();
642 samplerate_valid = true;
645 if (!samplerate_valid) {
646 // Wait until input data is available or an interrupt was requested
647 unique_lock<mutex> input_wait_lock(input_mutex_);
648 decode_input_cond_.wait(input_wait_lock);
650 } while (!samplerate_valid && !decode_interrupt_);
653 void DecodeSignal::decode_data(
654 const int64_t abs_start_samplenum, const int64_t sample_count)
656 const int64_t unit_size = segment_->unit_size();
657 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
659 for (int64_t i = abs_start_samplenum;
660 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
661 i += chunk_sample_count) {
663 const int64_t chunk_end = min(i + chunk_sample_count,
664 abs_start_samplenum + sample_count);
666 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
668 if (srd_session_send(srd_session_, i, chunk_end, chunk,
669 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
670 error_message_ = tr("Decoder reported an error");
677 // Notify the frontend that we processed some data and
678 // possibly have new annotations as well
682 lock_guard<mutex> lock(output_mutex_);
683 samples_decoded_ = chunk_end;
688 void DecodeSignal::decode_proc()
690 query_input_metadata();
692 if (decode_interrupt_)
697 uint64_t sample_count;
698 uint64_t abs_start_samplenum = 0;
700 // Keep processing new samples until we exhaust the input data
702 // Prevent any other decode threads from accessing libsigrokdecode
703 lock_guard<mutex> srd_lock(global_srd_mutex_);
706 lock_guard<mutex> input_lock(input_mutex_);
707 sample_count = segment_->get_sample_count() - abs_start_samplenum;
710 if (sample_count > 0) {
711 decode_data(abs_start_samplenum, sample_count);
712 abs_start_samplenum += sample_count;
714 } while (error_message_.isEmpty() && (sample_count > 0));
716 if (error_message_.isEmpty()) {
717 // Wait for new input data or an interrupt was requested
718 unique_lock<mutex> input_wait_lock(input_mutex_);
719 decode_input_cond_.wait(input_wait_lock);
721 } while (error_message_.isEmpty() && !decode_interrupt_);
724 void DecodeSignal::start_srd_session()
729 // Create the session
730 srd_session_new(&srd_session_);
731 assert(srd_session_);
733 // Create the decoders
734 srd_decoder_inst *prev_di = nullptr;
735 for (const shared_ptr<decode::Decoder> &dec : stack_) {
736 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
739 error_message_ = tr("Failed to create decoder instance");
740 srd_session_destroy(srd_session_);
745 srd_inst_stack(srd_session_, prev_di, di);
751 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
752 g_variant_new_uint64(samplerate_));
754 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
755 DecodeSignal::annotation_callback, this);
757 srd_session_start(srd_session_);
760 void DecodeSignal::stop_srd_session()
763 // Destroy the session
764 srd_session_destroy(srd_session_);
765 srd_session_ = nullptr;
769 void DecodeSignal::connect_input_notifiers()
771 // Disconnect the notification slot from the previous set of signals
772 disconnect(this, SLOT(on_data_received()));
774 // Connect the currently used signals to our slot
775 for (data::DecodeChannel &ch : channels_) {
776 if (!ch.assigned_signal)
779 shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
780 connect(logic_data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
781 this, SLOT(on_data_received()));
785 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
790 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
793 lock_guard<mutex> lock(ds->output_mutex_);
795 const decode::Annotation a(pdata);
799 assert(pdata->pdo->di);
800 const srd_decoder *const decc = pdata->pdo->di->decoder;
803 auto row_iter = ds->rows_.end();
805 // Try looking up the sub-row of this class
806 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
807 if (r != ds->class_rows_.end())
808 row_iter = ds->rows_.find((*r).second);
810 // Failing that, use the decoder as a key
811 row_iter = ds->rows_.find(Row(decc));
814 assert(row_iter != ds->rows_.end());
815 if (row_iter == ds->rows_.end()) {
816 qDebug() << "Unexpected annotation: decoder = " << decc <<
817 ", format = " << a.format();
822 // Add the annotation
823 (*row_iter).second.push_annotation(a);
826 void DecodeSignal::on_capture_state_changed(int state)
828 // If a new acquisition was started, we need to start decoding from scratch
829 if (state == Session::Running)
833 void DecodeSignal::on_data_received()
835 logic_mux_cond_.notify_one();