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 = 10 * 1024 * 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 // Check that all decoders have the required channels
185 for (const shared_ptr<decode::Decoder> &dec : stack_)
186 if (!dec->have_required_channels()) {
187 error_message_ = tr("One or more required channels "
188 "have not been specified");
192 // Add annotation classes
193 for (const shared_ptr<decode::Decoder> &dec : stack_) {
195 const srd_decoder *const decc = dec->decoder();
196 assert(dec->decoder());
198 // Add a row for the decoder if it doesn't have a row list
199 if (!decc->annotation_rows)
200 rows_[Row(decc)] = decode::RowData();
202 // Add the decoder rows
203 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
204 const srd_decoder_annotation_row *const ann_row =
205 (srd_decoder_annotation_row *)l->data;
208 const Row row(decc, ann_row);
210 // Add a new empty row data object
211 rows_[row] = decode::RowData();
213 // Map out all the classes
214 for (const GSList *ll = ann_row->ann_classes;
216 class_rows_[make_pair(decc,
217 GPOINTER_TO_INT(ll->data))] = row;
221 // Free the logic data and its segment(s) if it needs to be updated
222 if (logic_mux_data_invalid_)
223 logic_mux_data_.reset();
225 if (!logic_mux_data_) {
226 const int64_t ch_count = get_assigned_signal_count();
227 const int64_t unit_size = (ch_count + 7) / 8;
228 logic_mux_data_ = make_shared<Logic>(ch_count);
229 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
230 logic_mux_data_->push_segment(segment_);
233 // Make sure the logic output data is complete and up-to-date
234 logic_mux_interrupt_ = false;
235 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
237 // Decode the muxed logic data
238 decode_interrupt_ = false;
239 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
241 // Receive notifications when new sample data is available
242 connect_input_notifiers();
245 QString DecodeSignal::error_message() const
247 lock_guard<mutex> lock(output_mutex_);
248 return error_message_;
251 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
256 void DecodeSignal::auto_assign_signals()
258 bool new_assignment = false;
260 // Try to auto-select channels that don't have signals assigned yet
261 for (data::DecodeChannel &ch : channels_) {
262 if (ch.assigned_signal)
265 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
266 const QString ch_name = ch.name.toLower();
267 const QString s_name = s->name().toLower();
269 if (s->logic_data() &&
270 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
271 ch.assigned_signal = s.get();
272 new_assignment = true;
277 if (new_assignment) {
278 logic_mux_data_invalid_ = true;
279 commit_decoder_channels();
284 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
286 for (data::DecodeChannel &ch : channels_)
287 if (ch.id == channel_id) {
288 ch.assigned_signal = signal;
289 logic_mux_data_invalid_ = true;
292 commit_decoder_channels();
297 int DecodeSignal::get_assigned_signal_count() const
299 // Count all channels that have a signal assigned to them
300 return count_if(channels_.begin(), channels_.end(),
301 [](data::DecodeChannel ch) { return ch.assigned_signal; });
304 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
306 for (data::DecodeChannel &ch : channels_)
307 if (ch.id == channel_id)
308 ch.initial_pin_state = init_state;
315 double DecodeSignal::samplerate() const
320 const pv::util::Timestamp& DecodeSignal::start_time() const
325 int64_t DecodeSignal::get_working_sample_count() const
327 // The working sample count is the highest sample number for
328 // which all used signals have data available, so go through
329 // all channels and use the lowest overall sample count of the
332 // TODO Currently, we assume only a single segment exists
334 int64_t count = std::numeric_limits<int64_t>::max();
335 bool no_signals_assigned = true;
337 for (const data::DecodeChannel &ch : channels_)
338 if (ch.assigned_signal) {
339 no_signals_assigned = false;
341 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
342 if (!logic_data || logic_data->logic_segments().empty())
345 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
346 count = min(count, (int64_t)segment->get_sample_count());
349 return (no_signals_assigned ? 0 : count);
352 int64_t DecodeSignal::get_decoded_sample_count() const
354 lock_guard<mutex> decode_lock(output_mutex_);
355 return samples_decoded_;
358 vector<Row> DecodeSignal::visible_rows() const
360 lock_guard<mutex> lock(output_mutex_);
364 for (const shared_ptr<decode::Decoder> &dec : stack_) {
369 const srd_decoder *const decc = dec->decoder();
370 assert(dec->decoder());
372 // Add a row for the decoder if it doesn't have a row list
373 if (!decc->annotation_rows)
374 rows.emplace_back(decc);
376 // Add the decoder rows
377 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
378 const srd_decoder_annotation_row *const ann_row =
379 (srd_decoder_annotation_row *)l->data;
381 rows.emplace_back(decc, ann_row);
388 void DecodeSignal::get_annotation_subset(
389 vector<pv::data::decode::Annotation> &dest,
390 const decode::Row &row, uint64_t start_sample,
391 uint64_t end_sample) const
393 lock_guard<mutex> lock(output_mutex_);
395 const auto iter = rows_.find(row);
396 if (iter != rows_.end())
397 (*iter).second.get_annotation_subset(dest,
398 start_sample, end_sample);
401 void DecodeSignal::save_settings(QSettings &settings) const
403 SignalBase::save_settings(settings);
405 // TODO Save decoder stack, channel mapping and decoder options
408 void DecodeSignal::restore_settings(QSettings &settings)
410 SignalBase::restore_settings(settings);
412 // TODO Restore decoder stack, channel mapping and decoder options
415 void DecodeSignal::update_channel_list()
417 vector<data::DecodeChannel> prev_channels = channels_;
422 // Copy existing entries, create new as needed
423 for (shared_ptr<Decoder> decoder : stack_) {
424 const srd_decoder* srd_d = decoder->decoder();
427 // Mandatory channels
428 for (l = srd_d->channels; l; l = l->next) {
429 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
430 bool ch_added = false;
432 // Copy but update ID if this channel was in the list before
433 for (data::DecodeChannel &ch : prev_channels)
434 if (ch.pdch_ == pdch) {
436 channels_.push_back(ch);
442 // Create new entry without a mapped signal
443 data::DecodeChannel ch = {id++, false, nullptr,
444 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
445 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
446 channels_.push_back(ch);
451 for (l = srd_d->opt_channels; l; l = l->next) {
452 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
453 bool ch_added = false;
455 // Copy but update ID if this channel was in the list before
456 for (data::DecodeChannel &ch : prev_channels)
457 if (ch.pdch_ == pdch) {
459 channels_.push_back(ch);
465 // Create new entry without a mapped signal
466 data::DecodeChannel ch = {id++, true, nullptr,
467 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
468 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
469 channels_.push_back(ch);
474 // Invalidate the logic output data if the channel assignment changed
475 if (prev_channels.size() != channels_.size()) {
476 // The number of channels changed, there's definitely a difference
477 logic_mux_data_invalid_ = true;
479 // Same number but assignment may still differ, so compare all channels
480 for (size_t i = 0; i < channels_.size(); i++) {
481 const data::DecodeChannel &p_ch = prev_channels[i];
482 const data::DecodeChannel &ch = channels_[i];
484 if ((p_ch.pdch_ != ch.pdch_) ||
485 (p_ch.assigned_signal != ch.assigned_signal)) {
486 logic_mux_data_invalid_ = true;
496 void DecodeSignal::commit_decoder_channels()
498 // Submit channel list to every decoder, containing only the relevant channels
499 for (shared_ptr<decode::Decoder> dec : stack_) {
500 vector<data::DecodeChannel*> channel_list;
502 for (data::DecodeChannel &ch : channels_)
503 if (ch.decoder_ == dec)
504 channel_list.push_back(&ch);
506 dec->set_channels(channel_list);
510 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
512 // Enforce end to be greater than start
516 // Fetch all segments and their data
517 // TODO Currently, we assume only a single segment exists
518 vector<shared_ptr<LogicSegment> > segments;
519 vector<const uint8_t*> signal_data;
520 vector<uint8_t> signal_in_bytepos;
521 vector<uint8_t> signal_in_bitpos;
523 for (data::DecodeChannel &ch : channels_)
524 if (ch.assigned_signal) {
525 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
526 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
527 segments.push_back(segment);
528 signal_data.push_back(segment->get_samples(start, end));
530 const int bitpos = ch.assigned_signal->logic_bit_index();
531 signal_in_bytepos.push_back(bitpos / 8);
532 signal_in_bitpos.push_back(bitpos % 8);
535 // Perform the muxing of signal data into the output data
536 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
537 unsigned int signal_count = signal_data.size();
539 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
543 const int out_sample_pos = sample_cnt * segment_->unit_size();
544 for (unsigned int i = 0; i < segment_->unit_size(); i++)
545 output[out_sample_pos + i] = 0;
547 for (unsigned int i = 0; i < signal_count; i++) {
548 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
549 const uint8_t in_sample = 1 &
550 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
552 const uint8_t out_sample = output[out_sample_pos + bytepos];
554 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
564 segment_->append_payload(output, (end - start) * segment_->unit_size());
567 for (const uint8_t* data : signal_data)
571 void DecodeSignal::logic_mux_proc()
574 const uint64_t input_sample_count = get_working_sample_count();
575 const uint64_t output_sample_count = segment_->get_sample_count();
577 const uint64_t samples_to_process =
578 (input_sample_count > output_sample_count) ?
579 (input_sample_count - output_sample_count) : 0;
581 // Process the samples if necessary...
582 if (samples_to_process > 0) {
583 const uint64_t unit_size = segment_->unit_size();
584 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
586 uint64_t processed_samples = 0;
588 const uint64_t start_sample = output_sample_count + processed_samples;
589 const uint64_t sample_count =
590 min(samples_to_process - processed_samples, chunk_sample_count);
592 mux_logic_samples(start_sample, start_sample + sample_count);
593 processed_samples += sample_count;
595 // ...and process the newly muxed logic data
596 decode_input_cond_.notify_one();
597 } while (processed_samples < samples_to_process);
600 if (samples_to_process == 0) {
601 // Wait for more input
602 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
603 logic_mux_cond_.wait(logic_mux_lock);
605 } while (!logic_mux_interrupt_);
607 // No more input data and session is stopped, let the decode thread
608 // process any pending data, terminate and release the global SRD mutex
609 // in order to let other decoders run
610 decode_input_cond_.notify_one();
613 void DecodeSignal::query_input_metadata()
615 // Update the samplerate and start time because we cannot start
616 // the libsrd session without the current samplerate
618 // TODO Currently we assume all channels have the same sample rate
620 bool samplerate_valid = false;
622 auto any_channel = find_if(channels_.begin(), channels_.end(),
623 [](data::DecodeChannel ch) { return ch.assigned_signal; });
625 shared_ptr<Logic> logic_data =
626 any_channel->assigned_signal->logic_data();
629 if (!logic_data->logic_segments().empty()) {
630 shared_ptr<LogicSegment> first_segment =
631 any_channel->assigned_signal->logic_data()->logic_segments().front();
632 start_time_ = first_segment->start_time();
633 samplerate_ = first_segment->samplerate();
635 samplerate_valid = true;
638 if (!samplerate_valid) {
639 // Wait until input data is available or an interrupt was requested
640 unique_lock<mutex> input_wait_lock(input_mutex_);
641 decode_input_cond_.wait(input_wait_lock);
643 } while (!samplerate_valid && !decode_interrupt_);
646 void DecodeSignal::decode_data(
647 const int64_t abs_start_samplenum, const int64_t sample_count)
649 const int64_t unit_size = segment_->unit_size();
650 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
652 for (int64_t i = abs_start_samplenum;
653 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
654 i += chunk_sample_count) {
656 const int64_t chunk_end = min(i + chunk_sample_count,
657 abs_start_samplenum + sample_count);
659 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
661 if (srd_session_send(srd_session_, i, chunk_end, chunk,
662 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
663 error_message_ = tr("Decoder reported an error");
670 // Notify the frontend that we processed some data and
671 // possibly have new annotations as well
675 lock_guard<mutex> lock(output_mutex_);
676 samples_decoded_ = chunk_end;
681 void DecodeSignal::decode_proc()
683 query_input_metadata();
685 if (decode_interrupt_)
690 uint64_t sample_count;
691 uint64_t abs_start_samplenum = 0;
693 // Keep processing new samples until we exhaust the input data
695 // Prevent any other decode threads from accessing libsigrokdecode
696 lock_guard<mutex> srd_lock(global_srd_mutex_);
699 lock_guard<mutex> input_lock(input_mutex_);
700 sample_count = segment_->get_sample_count() - abs_start_samplenum;
703 if (sample_count > 0) {
704 decode_data(abs_start_samplenum, sample_count);
705 abs_start_samplenum += sample_count;
707 } while (error_message_.isEmpty() && (sample_count > 0));
709 if (error_message_.isEmpty()) {
710 // Wait for new input data or an interrupt was requested
711 unique_lock<mutex> input_wait_lock(input_mutex_);
712 decode_input_cond_.wait(input_wait_lock);
714 } while (error_message_.isEmpty() && !decode_interrupt_);
717 void DecodeSignal::start_srd_session()
722 // Create the session
723 srd_session_new(&srd_session_);
724 assert(srd_session_);
726 // Create the decoders
727 srd_decoder_inst *prev_di = nullptr;
728 for (const shared_ptr<decode::Decoder> &dec : stack_) {
729 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
732 error_message_ = tr("Failed to create decoder instance");
733 srd_session_destroy(srd_session_);
738 srd_inst_stack(srd_session_, prev_di, di);
744 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
745 g_variant_new_uint64(samplerate_));
747 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
748 DecodeSignal::annotation_callback, this);
750 srd_session_start(srd_session_);
753 void DecodeSignal::stop_srd_session()
756 // Destroy the session
757 srd_session_destroy(srd_session_);
758 srd_session_ = nullptr;
762 void DecodeSignal::connect_input_notifiers()
764 // Disconnect the notification slot from the previous set of signals
765 disconnect(this, SLOT(on_data_received()));
767 // Connect the currently used signals to our slot
768 for (data::DecodeChannel &ch : channels_) {
769 if (!ch.assigned_signal)
772 shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
773 connect(logic_data.get(), SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
774 this, SLOT(on_data_received()));
778 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
783 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
786 lock_guard<mutex> lock(ds->output_mutex_);
788 const decode::Annotation a(pdata);
792 assert(pdata->pdo->di);
793 const srd_decoder *const decc = pdata->pdo->di->decoder;
796 auto row_iter = ds->rows_.end();
798 // Try looking up the sub-row of this class
799 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
800 if (r != ds->class_rows_.end())
801 row_iter = ds->rows_.find((*r).second);
803 // Failing that, use the decoder as a key
804 row_iter = ds->rows_.find(Row(decc));
807 assert(row_iter != ds->rows_.end());
808 if (row_iter == ds->rows_.end()) {
809 qDebug() << "Unexpected annotation: decoder = " << decc <<
810 ", format = " << a.format();
815 // Add the annotation
816 (*row_iter).second.push_annotation(a);
819 void DecodeSignal::on_capture_state_changed(int state)
821 // If a new acquisition was started, we need to start decoding from scratch
822 if (state == Session::Running)
826 void DecodeSignal::on_data_received()
828 logic_mux_cond_.notify_one();