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()
75 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
80 void DecodeSignal::stack_decoder(srd_decoder *decoder)
83 stack_.push_back(make_shared<decode::Decoder>(decoder));
85 // Set name if this decoder is the first in the list
86 if (stack_.size() == 1)
87 set_name(QString::fromUtf8(decoder->name));
89 // Include the newly created decode channels in the channel lists
90 update_channel_list();
92 auto_assign_signals();
93 commit_decoder_channels();
97 void DecodeSignal::remove_decoder(int index)
100 assert(index < (int)stack_.size());
102 // Find the decoder in the stack
103 auto iter = stack_.begin();
104 for (int i = 0; i < index; i++, iter++)
105 assert(iter != stack_.end());
107 // Delete the element
110 // Update channels and decoded data
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()
135 if (decode_thread_.joinable()) {
136 decode_interrupt_ = true;
137 decode_input_cond_.notify_one();
138 decode_thread_.join();
141 if (logic_mux_thread_.joinable()) {
142 logic_mux_interrupt_ = true;
143 logic_mux_cond_.notify_one();
144 logic_mux_thread_.join();
149 frame_complete_ = false;
150 samples_decoded_ = 0;
151 error_message_ = QString();
156 logic_mux_data_.reset();
157 logic_mux_data_invalid_ = true;
160 void DecodeSignal::begin_decode()
162 if (decode_thread_.joinable()) {
163 decode_interrupt_ = true;
164 decode_input_cond_.notify_one();
165 decode_thread_.join();
168 if (logic_mux_thread_.joinable()) {
169 logic_mux_interrupt_ = true;
170 logic_mux_cond_.notify_one();
171 logic_mux_thread_.join();
176 if (stack_.size() == 0) {
177 error_message_ = tr("No decoders");
181 assert(channels_.size() > 0);
183 if (get_assigned_signal_count() == 0) {
184 error_message_ = tr("There are no channels assigned to this decoder");
188 // Make sure that all assigned channels still provide logic data
189 // (can happen when a converted signal was assigned but the
190 // conversion removed in the meanwhile)
191 for (data::DecodeChannel &ch : channels_)
192 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
193 ch.assigned_signal = nullptr;
195 // Check that all decoders have the required channels
196 for (const shared_ptr<decode::Decoder> &dec : stack_)
197 if (!dec->have_required_channels()) {
198 error_message_ = tr("One or more required channels "
199 "have not been specified");
203 // Add annotation classes
204 for (const shared_ptr<decode::Decoder> &dec : stack_) {
206 const srd_decoder *const decc = dec->decoder();
207 assert(dec->decoder());
209 // Add a row for the decoder if it doesn't have a row list
210 if (!decc->annotation_rows)
211 rows_[Row(decc)] = decode::RowData();
213 // Add the decoder rows
214 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
215 const srd_decoder_annotation_row *const ann_row =
216 (srd_decoder_annotation_row *)l->data;
219 const Row row(decc, ann_row);
221 // Add a new empty row data object
222 rows_[row] = decode::RowData();
224 // Map out all the classes
225 for (const GSList *ll = ann_row->ann_classes;
227 class_rows_[make_pair(decc,
228 GPOINTER_TO_INT(ll->data))] = row;
232 // Free the logic data and its segment(s) if it needs to be updated
233 if (logic_mux_data_invalid_)
234 logic_mux_data_.reset();
236 if (!logic_mux_data_) {
237 const int64_t ch_count = get_assigned_signal_count();
238 const int64_t unit_size = (ch_count + 7) / 8;
239 logic_mux_data_ = make_shared<Logic>(ch_count);
240 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
241 logic_mux_data_->push_segment(segment_);
244 // Make sure the logic output data is complete and up-to-date
245 logic_mux_interrupt_ = false;
246 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
248 // Decode the muxed logic data
249 decode_interrupt_ = false;
250 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
252 // Receive notifications when new sample data is available
253 connect_input_notifiers();
256 QString DecodeSignal::error_message() const
258 lock_guard<mutex> lock(output_mutex_);
259 return error_message_;
262 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
267 void DecodeSignal::auto_assign_signals()
269 bool new_assignment = false;
271 // Try to auto-select channels that don't have signals assigned yet
272 for (data::DecodeChannel &ch : channels_) {
273 if (ch.assigned_signal)
276 for (shared_ptr<data::SignalBase> s : session_.signalbases()) {
277 const QString ch_name = ch.name.toLower();
278 const QString s_name = s->name().toLower();
280 if (s->logic_data() &&
281 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
282 ch.assigned_signal = s.get();
283 new_assignment = true;
288 if (new_assignment) {
289 logic_mux_data_invalid_ = true;
290 commit_decoder_channels();
295 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
297 for (data::DecodeChannel &ch : channels_)
298 if (ch.id == channel_id) {
299 ch.assigned_signal = signal;
300 logic_mux_data_invalid_ = true;
303 commit_decoder_channels();
308 int DecodeSignal::get_assigned_signal_count() const
310 // Count all channels that have a signal assigned to them
311 return count_if(channels_.begin(), channels_.end(),
312 [](data::DecodeChannel ch) { return ch.assigned_signal; });
315 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
317 for (data::DecodeChannel &ch : channels_)
318 if (ch.id == channel_id)
319 ch.initial_pin_state = init_state;
326 double DecodeSignal::samplerate() const
331 const pv::util::Timestamp& DecodeSignal::start_time() const
336 int64_t DecodeSignal::get_working_sample_count() const
338 // The working sample count is the highest sample number for
339 // which all used signals have data available, so go through
340 // all channels and use the lowest overall sample count of the
343 // TODO Currently, we assume only a single segment exists
345 int64_t count = std::numeric_limits<int64_t>::max();
346 bool no_signals_assigned = true;
348 for (const data::DecodeChannel &ch : channels_)
349 if (ch.assigned_signal) {
350 no_signals_assigned = false;
352 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
353 if (!logic_data || logic_data->logic_segments().empty())
356 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
357 count = min(count, (int64_t)segment->get_sample_count());
360 return (no_signals_assigned ? 0 : count);
363 int64_t DecodeSignal::get_decoded_sample_count() const
365 lock_guard<mutex> decode_lock(output_mutex_);
366 return samples_decoded_;
369 vector<Row> DecodeSignal::visible_rows() const
371 lock_guard<mutex> lock(output_mutex_);
375 for (const shared_ptr<decode::Decoder> &dec : stack_) {
380 const srd_decoder *const decc = dec->decoder();
381 assert(dec->decoder());
383 // Add a row for the decoder if it doesn't have a row list
384 if (!decc->annotation_rows)
385 rows.emplace_back(decc);
387 // Add the decoder rows
388 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
389 const srd_decoder_annotation_row *const ann_row =
390 (srd_decoder_annotation_row *)l->data;
392 rows.emplace_back(decc, ann_row);
399 void DecodeSignal::get_annotation_subset(
400 vector<pv::data::decode::Annotation> &dest,
401 const decode::Row &row, uint64_t start_sample,
402 uint64_t end_sample) const
404 lock_guard<mutex> lock(output_mutex_);
406 const auto iter = rows_.find(row);
407 if (iter != rows_.end())
408 (*iter).second.get_annotation_subset(dest,
409 start_sample, end_sample);
412 void DecodeSignal::save_settings(QSettings &settings) const
414 SignalBase::save_settings(settings);
416 // TODO Save decoder stack, channel mapping and decoder options
419 void DecodeSignal::restore_settings(QSettings &settings)
421 SignalBase::restore_settings(settings);
423 // TODO Restore decoder stack, channel mapping and decoder options
426 void DecodeSignal::update_channel_list()
428 vector<data::DecodeChannel> prev_channels = channels_;
433 // Copy existing entries, create new as needed
434 for (shared_ptr<Decoder> decoder : stack_) {
435 const srd_decoder* srd_d = decoder->decoder();
438 // Mandatory channels
439 for (l = srd_d->channels; l; l = l->next) {
440 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
441 bool ch_added = false;
443 // Copy but update ID if this channel was in the list before
444 for (data::DecodeChannel &ch : prev_channels)
445 if (ch.pdch_ == pdch) {
447 channels_.push_back(ch);
453 // Create new entry without a mapped signal
454 data::DecodeChannel ch = {id++, false, nullptr,
455 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
456 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
457 channels_.push_back(ch);
462 for (l = srd_d->opt_channels; l; l = l->next) {
463 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
464 bool ch_added = false;
466 // Copy but update ID if this channel was in the list before
467 for (data::DecodeChannel &ch : prev_channels)
468 if (ch.pdch_ == pdch) {
470 channels_.push_back(ch);
476 // Create new entry without a mapped signal
477 data::DecodeChannel ch = {id++, true, nullptr,
478 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
479 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
480 channels_.push_back(ch);
485 // Invalidate the logic output data if the channel assignment changed
486 if (prev_channels.size() != channels_.size()) {
487 // The number of channels changed, there's definitely a difference
488 logic_mux_data_invalid_ = true;
490 // Same number but assignment may still differ, so compare all channels
491 for (size_t i = 0; i < channels_.size(); i++) {
492 const data::DecodeChannel &p_ch = prev_channels[i];
493 const data::DecodeChannel &ch = channels_[i];
495 if ((p_ch.pdch_ != ch.pdch_) ||
496 (p_ch.assigned_signal != ch.assigned_signal)) {
497 logic_mux_data_invalid_ = true;
507 void DecodeSignal::commit_decoder_channels()
509 // Submit channel list to every decoder, containing only the relevant channels
510 for (shared_ptr<decode::Decoder> dec : stack_) {
511 vector<data::DecodeChannel*> channel_list;
513 for (data::DecodeChannel &ch : channels_)
514 if (ch.decoder_ == dec)
515 channel_list.push_back(&ch);
517 dec->set_channels(channel_list);
521 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
523 // Enforce end to be greater than start
527 // Fetch all segments and their data
528 // TODO Currently, we assume only a single segment exists
529 vector<shared_ptr<LogicSegment> > segments;
530 vector<const uint8_t*> signal_data;
531 vector<uint8_t> signal_in_bytepos;
532 vector<uint8_t> signal_in_bitpos;
534 for (data::DecodeChannel &ch : channels_)
535 if (ch.assigned_signal) {
536 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
537 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
538 segments.push_back(segment);
539 signal_data.push_back(segment->get_samples(start, end));
541 const int bitpos = ch.assigned_signal->logic_bit_index();
542 signal_in_bytepos.push_back(bitpos / 8);
543 signal_in_bitpos.push_back(bitpos % 8);
546 // Perform the muxing of signal data into the output data
547 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
548 unsigned int signal_count = signal_data.size();
550 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
554 const int out_sample_pos = sample_cnt * segment_->unit_size();
555 for (unsigned int i = 0; i < segment_->unit_size(); i++)
556 output[out_sample_pos + i] = 0;
558 for (unsigned int i = 0; i < signal_count; i++) {
559 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
560 const uint8_t in_sample = 1 &
561 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
563 const uint8_t out_sample = output[out_sample_pos + bytepos];
565 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
575 segment_->append_payload(output, (end - start) * segment_->unit_size());
578 for (const uint8_t* data : signal_data)
582 void DecodeSignal::logic_mux_proc()
585 const uint64_t input_sample_count = get_working_sample_count();
586 const uint64_t output_sample_count = segment_->get_sample_count();
588 const uint64_t samples_to_process =
589 (input_sample_count > output_sample_count) ?
590 (input_sample_count - output_sample_count) : 0;
592 // Process the samples if necessary...
593 if (samples_to_process > 0) {
594 const uint64_t unit_size = segment_->unit_size();
595 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
597 uint64_t processed_samples = 0;
599 const uint64_t start_sample = output_sample_count + processed_samples;
600 const uint64_t sample_count =
601 min(samples_to_process - processed_samples, chunk_sample_count);
603 mux_logic_samples(start_sample, start_sample + sample_count);
604 processed_samples += sample_count;
606 // ...and process the newly muxed logic data
607 decode_input_cond_.notify_one();
608 } while (processed_samples < samples_to_process);
611 if (samples_to_process == 0) {
612 // Wait for more input
613 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
614 logic_mux_cond_.wait(logic_mux_lock);
616 } while (!logic_mux_interrupt_);
618 // No more input data and session is stopped, let the decode thread
619 // process any pending data, terminate and release the global SRD mutex
620 // in order to let other decoders run
621 decode_input_cond_.notify_one();
624 void DecodeSignal::query_input_metadata()
626 // Update the samplerate and start time because we cannot start
627 // the libsrd session without the current samplerate
629 // TODO Currently we assume all channels have the same sample rate
631 bool samplerate_valid = false;
633 auto any_channel = find_if(channels_.begin(), channels_.end(),
634 [](data::DecodeChannel ch) { return ch.assigned_signal; });
636 shared_ptr<Logic> logic_data =
637 any_channel->assigned_signal->logic_data();
640 if (!logic_data->logic_segments().empty()) {
641 shared_ptr<LogicSegment> first_segment =
642 any_channel->assigned_signal->logic_data()->logic_segments().front();
643 start_time_ = first_segment->start_time();
644 samplerate_ = first_segment->samplerate();
646 samplerate_valid = true;
649 if (!samplerate_valid) {
650 // Wait until input data is available or an interrupt was requested
651 unique_lock<mutex> input_wait_lock(input_mutex_);
652 decode_input_cond_.wait(input_wait_lock);
654 } while (!samplerate_valid && !decode_interrupt_);
657 void DecodeSignal::decode_data(
658 const int64_t abs_start_samplenum, const int64_t sample_count)
660 const int64_t unit_size = segment_->unit_size();
661 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
663 for (int64_t i = abs_start_samplenum;
664 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
665 i += chunk_sample_count) {
667 const int64_t chunk_end = min(i + chunk_sample_count,
668 abs_start_samplenum + sample_count);
670 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
672 if (srd_session_send(srd_session_, i, chunk_end, chunk,
673 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
674 error_message_ = tr("Decoder reported an error");
682 lock_guard<mutex> lock(output_mutex_);
683 samples_decoded_ = chunk_end;
686 // Notify the frontend that we processed some data and
687 // possibly have new annotations as well
692 void DecodeSignal::decode_proc()
694 query_input_metadata();
696 if (decode_interrupt_)
701 uint64_t sample_count;
702 uint64_t abs_start_samplenum = 0;
704 // Keep processing new samples until we exhaust the input data
706 // Prevent any other decode threads from accessing libsigrokdecode
707 lock_guard<mutex> srd_lock(global_srd_mutex_);
710 lock_guard<mutex> input_lock(input_mutex_);
711 sample_count = segment_->get_sample_count() - abs_start_samplenum;
714 if (sample_count > 0) {
715 decode_data(abs_start_samplenum, sample_count);
716 abs_start_samplenum += sample_count;
718 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
720 if (error_message_.isEmpty() && !decode_interrupt_) {
721 if (sample_count == 0)
724 // Wait for new input data or an interrupt was requested
725 unique_lock<mutex> input_wait_lock(input_mutex_);
726 decode_input_cond_.wait(input_wait_lock);
728 } while (error_message_.isEmpty() && !decode_interrupt_);
731 void DecodeSignal::start_srd_session()
736 // Create the session
737 srd_session_new(&srd_session_);
738 assert(srd_session_);
740 // Create the decoders
741 srd_decoder_inst *prev_di = nullptr;
742 for (const shared_ptr<decode::Decoder> &dec : stack_) {
743 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
746 error_message_ = tr("Failed to create decoder instance");
747 srd_session_destroy(srd_session_);
752 srd_inst_stack(srd_session_, prev_di, di);
758 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
759 g_variant_new_uint64(samplerate_));
761 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
762 DecodeSignal::annotation_callback, this);
764 srd_session_start(srd_session_);
767 void DecodeSignal::stop_srd_session()
770 // Destroy the session
771 srd_session_destroy(srd_session_);
772 srd_session_ = nullptr;
776 void DecodeSignal::connect_input_notifiers()
778 // Disconnect the notification slot from the previous set of signals
779 disconnect(this, SLOT(on_data_cleared()));
780 disconnect(this, SLOT(on_data_received()));
782 // Connect the currently used signals to our slot
783 for (data::DecodeChannel &ch : channels_) {
784 if (!ch.assigned_signal)
787 const data::SignalBase *signal = ch.assigned_signal;
788 connect(signal, SIGNAL(samples_cleared()),
789 this, SLOT(on_data_cleared()));
790 connect(signal, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
791 this, SLOT(on_data_received()));
795 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
800 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
803 lock_guard<mutex> lock(ds->output_mutex_);
805 const decode::Annotation a(pdata);
809 assert(pdata->pdo->di);
810 const srd_decoder *const decc = pdata->pdo->di->decoder;
813 auto row_iter = ds->rows_.end();
815 // Try looking up the sub-row of this class
816 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
817 if (r != ds->class_rows_.end())
818 row_iter = ds->rows_.find((*r).second);
820 // Failing that, use the decoder as a key
821 row_iter = ds->rows_.find(Row(decc));
824 assert(row_iter != ds->rows_.end());
825 if (row_iter == ds->rows_.end()) {
826 qDebug() << "Unexpected annotation: decoder = " << decc <<
827 ", format = " << a.format();
832 // Add the annotation
833 (*row_iter).second.push_annotation(a);
836 void DecodeSignal::on_capture_state_changed(int state)
838 // If a new acquisition was started, we need to start decoding from scratch
839 if (state == Session::Running)
843 void DecodeSignal::on_data_cleared()
848 void DecodeSignal::on_data_received()
850 if (!logic_mux_thread_.joinable())
853 logic_mux_cond_.notify_one();