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;
50 const unsigned int DecodeSignal::DecodeNotifyPeriod = 1024;
52 mutex DecodeSignal::global_srd_mutex_;
55 DecodeSignal::DecodeSignal(pv::Session &session) :
56 SignalBase(nullptr, SignalBase::DecodeChannel),
58 logic_mux_data_invalid_(false),
63 frame_complete_(false)
65 connect(&session_, SIGNAL(capture_state_changed(int)),
66 this, SLOT(on_capture_state_changed(int)));
67 connect(&session_, SIGNAL(data_received()),
68 this, SLOT(on_data_received()));
69 connect(&session_, SIGNAL(frame_ended()),
70 this, SLOT(on_frame_ended()));
72 set_name(tr("Empty decoder signal"));
75 DecodeSignal::~DecodeSignal()
77 if (decode_thread_.joinable()) {
78 decode_interrupt_ = true;
79 decode_input_cond_.notify_one();
80 decode_thread_.join();
83 if (logic_mux_thread_.joinable()) {
84 logic_mux_interrupt_ = true;
85 logic_mux_cond_.notify_one();
86 logic_mux_thread_.join();
90 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
95 void DecodeSignal::stack_decoder(srd_decoder *decoder)
98 stack_.push_back(make_shared<decode::Decoder>(decoder));
100 // Set name if this decoder is the first in the list
101 if (stack_.size() == 1)
102 set_name(QString::fromUtf8(decoder->name));
104 // Include the newly created decode channels in the channel lists
105 update_channel_list();
107 auto_assign_signals();
108 commit_decoder_channels();
112 void DecodeSignal::remove_decoder(int index)
115 assert(index < (int)stack_.size());
117 // Find the decoder in the stack
118 auto iter = stack_.begin();
119 for (int i = 0; i < index; i++, iter++)
120 assert(iter != stack_.end());
122 // Delete the element
125 // Update channels and decoded data
126 update_channel_list();
130 bool DecodeSignal::toggle_decoder_visibility(int index)
132 auto iter = stack_.cbegin();
133 for (int i = 0; i < index; i++, iter++)
134 assert(iter != stack_.end());
136 shared_ptr<Decoder> dec = *iter;
138 // Toggle decoder visibility
141 state = !dec->shown();
148 void DecodeSignal::reset_decode()
150 annotation_count_ = 0;
151 frame_complete_ = false;
152 samples_decoded_ = 0;
153 error_message_ = QString();
158 void DecodeSignal::begin_decode()
160 if (decode_thread_.joinable()) {
161 decode_interrupt_ = true;
162 decode_input_cond_.notify_one();
163 decode_thread_.join();
166 if (logic_mux_thread_.joinable()) {
167 logic_mux_interrupt_ = true;
168 logic_mux_cond_.notify_one();
169 logic_mux_thread_.join();
174 if (stack_.size() == 0) {
175 error_message_ = tr("No decoders");
179 assert(channels_.size() > 0);
181 if (get_assigned_signal_count() == 0) {
182 error_message_ = tr("There are no channels assigned to this decoder");
186 // Check that all decoders have the required channels
187 for (const shared_ptr<decode::Decoder> &dec : stack_)
188 if (!dec->have_required_channels()) {
189 error_message_ = tr("One or more required channels "
190 "have not been specified");
194 // Add annotation classes
195 for (const shared_ptr<decode::Decoder> &dec : stack_) {
197 const srd_decoder *const decc = dec->decoder();
198 assert(dec->decoder());
200 // Add a row for the decoder if it doesn't have a row list
201 if (!decc->annotation_rows)
202 rows_[Row(decc)] = decode::RowData();
204 // Add the decoder rows
205 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
206 const srd_decoder_annotation_row *const ann_row =
207 (srd_decoder_annotation_row *)l->data;
210 const Row row(decc, ann_row);
212 // Add a new empty row data object
213 rows_[row] = decode::RowData();
215 // Map out all the classes
216 for (const GSList *ll = ann_row->ann_classes;
218 class_rows_[make_pair(decc,
219 GPOINTER_TO_INT(ll->data))] = row;
223 // TODO Currently we assume all channels have the same sample rate
224 auto any_channel = find_if(channels_.begin(), channels_.end(),
225 [](data::DecodeChannel ch) { return ch.assigned_signal; });
226 shared_ptr<LogicSegment> first_segment =
227 any_channel->assigned_signal->logic_data()->logic_segments().front();
228 samplerate_ = first_segment->samplerate();
230 // Free the logic data and its segment(s) if it needs to be updated
231 if (logic_mux_data_invalid_)
232 logic_mux_data_.reset();
234 if (!logic_mux_data_) {
235 const int64_t ch_count = get_assigned_signal_count();
236 const int64_t unit_size = (ch_count + 7) / 8;
237 logic_mux_data_ = make_shared<Logic>(ch_count);
238 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
239 logic_mux_data_->push_segment(segment_);
242 // Update the samplerate and start time
243 start_time_ = segment_->start_time();
244 samplerate_ = segment_->samplerate();
245 if (samplerate_ == 0.0)
248 // Make sure the logic output data is complete and up-to-date
249 logic_mux_interrupt_ = false;
250 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
252 // Decode the muxed logic data
253 decode_interrupt_ = false;
254 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
257 QString DecodeSignal::error_message() const
259 lock_guard<mutex> lock(output_mutex_);
260 return error_message_;
263 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
268 void DecodeSignal::auto_assign_signals()
270 bool new_assignment = false;
272 // Try to auto-select channels that don't have signals assigned yet
273 for (data::DecodeChannel &ch : channels_) {
274 if (ch.assigned_signal)
277 for (shared_ptr<data::SignalBase> s : session_.signalbases())
278 if (s->logic_data() && (ch.name.toLower().contains(s->name().toLower()))) {
279 ch.assigned_signal = s.get();
280 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 uint64_t DecodeSignal::inc_annotation_count()
424 return (annotation_count_++);
427 void DecodeSignal::update_channel_list()
429 vector<data::DecodeChannel> prev_channels = channels_;
434 // Copy existing entries, create new as needed
435 for (shared_ptr<Decoder> decoder : stack_) {
436 const srd_decoder* srd_d = decoder->decoder();
439 // Mandatory channels
440 for (l = srd_d->channels; l; l = l->next) {
441 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
442 bool ch_added = false;
444 // Copy but update ID if this channel was in the list before
445 for (data::DecodeChannel &ch : prev_channels)
446 if (ch.pdch_ == pdch) {
448 channels_.push_back(ch);
454 // Create new entry without a mapped signal
455 data::DecodeChannel ch = {id++, false, nullptr,
456 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
457 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
458 channels_.push_back(ch);
463 for (l = srd_d->opt_channels; l; l = l->next) {
464 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
465 bool ch_added = false;
467 // Copy but update ID if this channel was in the list before
468 for (data::DecodeChannel &ch : prev_channels)
469 if (ch.pdch_ == pdch) {
471 channels_.push_back(ch);
477 // Create new entry without a mapped signal
478 data::DecodeChannel ch = {id++, true, nullptr,
479 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
480 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
481 channels_.push_back(ch);
486 // Invalidate the logic output data if the channel assignment changed
487 if (prev_channels.size() != channels_.size()) {
488 // The number of channels changed, there's definitely a difference
489 logic_mux_data_invalid_ = true;
491 // Same number but assignment may still differ, so compare all channels
492 for (size_t i = 0; i < channels_.size(); i++) {
493 const data::DecodeChannel &p_ch = prev_channels[i];
494 const data::DecodeChannel &ch = channels_[i];
496 if ((p_ch.pdch_ != ch.pdch_) ||
497 (p_ch.assigned_signal != ch.assigned_signal)) {
498 logic_mux_data_invalid_ = true;
508 void DecodeSignal::commit_decoder_channels()
510 // Submit channel list to every decoder, containing only the relevant channels
511 for (shared_ptr<decode::Decoder> dec : stack_) {
512 vector<data::DecodeChannel*> channel_list;
514 for (data::DecodeChannel &ch : channels_)
515 if (ch.decoder_ == dec)
516 channel_list.push_back(&ch);
518 dec->set_channels(channel_list);
522 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
524 // Enforce end to be greater than start
528 // Fetch all segments and their data
529 // TODO Currently, we assume only a single segment exists
530 vector<shared_ptr<LogicSegment> > segments;
531 vector<const uint8_t*> signal_data;
532 vector<uint8_t> signal_in_bytepos;
533 vector<uint8_t> signal_in_bitpos;
535 for (data::DecodeChannel &ch : channels_)
536 if (ch.assigned_signal) {
537 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
538 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
539 segments.push_back(segment);
540 signal_data.push_back(segment->get_samples(start, end));
542 const int bitpos = ch.assigned_signal->logic_bit_index();
543 signal_in_bytepos.push_back(bitpos / 8);
544 signal_in_bitpos.push_back(bitpos % 8);
547 // Perform the muxing of signal data into the output data
548 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
549 unsigned int signal_count = signal_data.size();
551 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
555 const int out_sample_pos = sample_cnt * segment_->unit_size();
556 for (unsigned int i = 0; i < segment_->unit_size(); i++)
557 output[out_sample_pos + i] = 0;
559 for (unsigned int i = 0; i < signal_count; i++) {
560 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
561 const uint8_t in_sample = 1 &
562 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
564 const uint8_t out_sample = output[out_sample_pos + bytepos];
566 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
576 segment_->append_payload(output, (end - start) * segment_->unit_size());
579 for (const uint8_t* data : signal_data)
583 void DecodeSignal::logic_mux_proc()
587 const uint64_t input_sample_count = get_working_sample_count();
588 const uint64_t output_sample_count = segment_->get_sample_count();
590 const uint64_t samples_to_process =
591 (input_sample_count > output_sample_count) ?
592 (input_sample_count - output_sample_count) : 0;
594 // Process the samples if necessary...
595 if (samples_to_process > 0) {
596 const uint64_t unit_size = segment_->unit_size();
597 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
599 uint64_t processed_samples = 0;
601 const uint64_t start_sample = output_sample_count + processed_samples;
602 const uint64_t sample_count =
603 min(samples_to_process - processed_samples, chunk_sample_count);
605 mux_logic_samples(start_sample, start_sample + sample_count);
606 processed_samples += sample_count;
608 // ...and process the newly muxed logic data
609 decode_input_cond_.notify_one();
610 } while (processed_samples < samples_to_process);
613 if (session_.get_capture_state() != Session::Stopped) {
614 // Wait for more input
615 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
616 logic_mux_cond_.wait(logic_mux_lock);
618 } while ((session_.get_capture_state() != Session::Stopped) && !logic_mux_interrupt_);
620 // No more input data and session is stopped, let the decode thread
621 // process any pending data, terminate and release the global SRD mutex
622 // in order to let other decoders run
623 decode_input_cond_.notify_one();
626 void DecodeSignal::decode_data(
627 const int64_t abs_start_samplenum, const int64_t sample_count,
628 srd_session *const session)
630 const int64_t unit_size = segment_->unit_size();
631 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
633 for (int64_t i = abs_start_samplenum;
634 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
635 i += chunk_sample_count) {
637 const int64_t chunk_end = min(i + chunk_sample_count,
638 abs_start_samplenum + sample_count);
640 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
642 if (srd_session_send(session, i, chunk_end, chunk,
643 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
644 error_message_ = tr("Decoder reported an error");
651 lock_guard<mutex> lock(output_mutex_);
652 samples_decoded_ = chunk_end;
657 void DecodeSignal::decode_proc()
659 srd_session *session;
660 srd_decoder_inst *prev_di = nullptr;
662 // Prevent any other decode threads from accessing libsigrokdecode
663 lock_guard<mutex> srd_lock(global_srd_mutex_);
665 // Create the session
666 srd_session_new(&session);
669 // Create the decoders
670 for (const shared_ptr<decode::Decoder> &dec : stack_) {
671 srd_decoder_inst *const di = dec->create_decoder_inst(session);
674 error_message_ = tr("Failed to create decoder instance");
675 srd_session_destroy(session);
680 srd_inst_stack(session, prev_di, di);
686 srd_session_metadata_set(session, SRD_CONF_SAMPLERATE,
687 g_variant_new_uint64(samplerate_));
689 srd_pd_output_callback_add(session, SRD_OUTPUT_ANN,
690 DecodeSignal::annotation_callback, this);
692 srd_session_start(session);
694 uint64_t sample_count;
695 uint64_t abs_start_samplenum = 0;
697 // Keep processing new samples until we exhaust the input data
700 lock_guard<mutex> input_lock(input_mutex_);
701 sample_count = segment_->get_sample_count() - abs_start_samplenum;
704 if (sample_count > 0) {
705 decode_data(abs_start_samplenum, sample_count, session);
706 abs_start_samplenum += sample_count;
708 } while (error_message_.isEmpty() && (sample_count > 0));
710 // Terminate if we exhausted the input data
711 if ((int64_t)segment_->get_sample_count() == get_working_sample_count())
714 if (error_message_.isEmpty()) {
715 // Wait for new input data or an interrupt request
716 unique_lock<mutex> input_wait_lock(input_mutex_);
717 decode_input_cond_.wait(input_wait_lock);
719 } while (error_message_.isEmpty() && !decode_interrupt_);
721 // Make sure all annotations are known to the frontend
724 // Destroy the session
725 srd_session_destroy(session);
728 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
733 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
736 lock_guard<mutex> lock(ds->output_mutex_);
738 const decode::Annotation a(pdata);
742 assert(pdata->pdo->di);
743 const srd_decoder *const decc = pdata->pdo->di->decoder;
746 auto row_iter = ds->rows_.end();
748 // Try looking up the sub-row of this class
749 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
750 if (r != ds->class_rows_.end())
751 row_iter = ds->rows_.find((*r).second);
753 // Failing that, use the decoder as a key
754 row_iter = ds->rows_.find(Row(decc));
757 assert(row_iter != ds->rows_.end());
758 if (row_iter == ds->rows_.end()) {
759 qDebug() << "Unexpected annotation: decoder = " << decc <<
760 ", format = " << a.format();
765 // Add the annotation
766 (*row_iter).second.push_annotation(a);
768 // Notify the frontend every DecodeNotifyPeriod annotations
769 if (ds->inc_annotation_count() % DecodeNotifyPeriod == 0)
770 ds->new_annotations();
773 void DecodeSignal::on_capture_state_changed(int state)
775 // If a new acquisition was started, we need to start decoding from scratch
776 if (state == Session::Running)
780 void DecodeSignal::on_data_received()
782 logic_mux_cond_.notify_one();
785 void DecodeSignal::on_frame_ended()
787 logic_mux_cond_.notify_one();