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 srd_session_(nullptr),
59 logic_mux_data_invalid_(false),
64 frame_complete_(false)
66 connect(&session_, SIGNAL(capture_state_changed(int)),
67 this, SLOT(on_capture_state_changed(int)));
68 connect(&session_, SIGNAL(data_received()),
69 this, SLOT(on_data_received()));
70 connect(&session_, SIGNAL(frame_ended()),
71 this, SLOT(on_frame_ended()));
73 set_name(tr("Empty decoder signal"));
76 DecodeSignal::~DecodeSignal()
78 if (decode_thread_.joinable()) {
79 decode_interrupt_ = true;
80 decode_input_cond_.notify_one();
81 decode_thread_.join();
84 if (logic_mux_thread_.joinable()) {
85 logic_mux_interrupt_ = true;
86 logic_mux_cond_.notify_one();
87 logic_mux_thread_.join();
93 const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
98 void DecodeSignal::stack_decoder(srd_decoder *decoder)
101 stack_.push_back(make_shared<decode::Decoder>(decoder));
103 // Set name if this decoder is the first in the list
104 if (stack_.size() == 1)
105 set_name(QString::fromUtf8(decoder->name));
107 // Include the newly created decode channels in the channel lists
108 update_channel_list();
110 auto_assign_signals();
111 commit_decoder_channels();
115 void DecodeSignal::remove_decoder(int index)
118 assert(index < (int)stack_.size());
120 // Find the decoder in the stack
121 auto iter = stack_.begin();
122 for (int i = 0; i < index; i++, iter++)
123 assert(iter != stack_.end());
125 // Delete the element
128 // Update channels and decoded data
129 update_channel_list();
133 bool DecodeSignal::toggle_decoder_visibility(int index)
135 auto iter = stack_.cbegin();
136 for (int i = 0; i < index; i++, iter++)
137 assert(iter != stack_.end());
139 shared_ptr<Decoder> dec = *iter;
141 // Toggle decoder visibility
144 state = !dec->shown();
151 void DecodeSignal::reset_decode()
155 annotation_count_ = 0;
156 frame_complete_ = false;
157 samples_decoded_ = 0;
158 error_message_ = QString();
163 void DecodeSignal::begin_decode()
165 if (decode_thread_.joinable()) {
166 decode_interrupt_ = true;
167 decode_input_cond_.notify_one();
168 decode_thread_.join();
171 if (logic_mux_thread_.joinable()) {
172 logic_mux_interrupt_ = true;
173 logic_mux_cond_.notify_one();
174 logic_mux_thread_.join();
179 if (stack_.size() == 0) {
180 error_message_ = tr("No decoders");
184 assert(channels_.size() > 0);
186 if (get_assigned_signal_count() == 0) {
187 error_message_ = tr("There are no channels assigned to this decoder");
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 // TODO Currently we assume all channels have the same sample rate
229 auto any_channel = find_if(channels_.begin(), channels_.end(),
230 [](data::DecodeChannel ch) { return ch.assigned_signal; });
231 shared_ptr<LogicSegment> first_segment =
232 any_channel->assigned_signal->logic_data()->logic_segments().front();
233 samplerate_ = first_segment->samplerate();
235 // Free the logic data and its segment(s) if it needs to be updated
236 if (logic_mux_data_invalid_)
237 logic_mux_data_.reset();
239 if (!logic_mux_data_) {
240 const int64_t ch_count = get_assigned_signal_count();
241 const int64_t unit_size = (ch_count + 7) / 8;
242 logic_mux_data_ = make_shared<Logic>(ch_count);
243 segment_ = make_shared<LogicSegment>(*logic_mux_data_, unit_size, samplerate_);
244 logic_mux_data_->push_segment(segment_);
247 // Update the samplerate and start time
248 start_time_ = segment_->start_time();
249 samplerate_ = segment_->samplerate();
250 if (samplerate_ == 0.0)
253 // Make sure the logic output data is complete and up-to-date
254 logic_mux_interrupt_ = false;
255 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
257 // Decode the muxed logic data
258 decode_interrupt_ = false;
259 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
262 QString DecodeSignal::error_message() const
264 lock_guard<mutex> lock(output_mutex_);
265 return error_message_;
268 const vector<data::DecodeChannel> DecodeSignal::get_channels() const
273 void DecodeSignal::auto_assign_signals()
275 bool new_assignment = false;
277 // Try to auto-select channels that don't have signals assigned yet
278 for (data::DecodeChannel &ch : channels_) {
279 if (ch.assigned_signal)
282 for (shared_ptr<data::SignalBase> s : session_.signalbases())
283 if (s->logic_data() && (ch.name.toLower().contains(s->name().toLower()))) {
284 ch.assigned_signal = s.get();
285 new_assignment = true;
289 if (new_assignment) {
290 logic_mux_data_invalid_ = true;
291 commit_decoder_channels();
296 void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
298 for (data::DecodeChannel &ch : channels_)
299 if (ch.id == channel_id) {
300 ch.assigned_signal = signal;
301 logic_mux_data_invalid_ = true;
304 commit_decoder_channels();
309 int DecodeSignal::get_assigned_signal_count() const
311 // Count all channels that have a signal assigned to them
312 return count_if(channels_.begin(), channels_.end(),
313 [](data::DecodeChannel ch) { return ch.assigned_signal; });
316 void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
318 for (data::DecodeChannel &ch : channels_)
319 if (ch.id == channel_id)
320 ch.initial_pin_state = init_state;
327 double DecodeSignal::samplerate() const
332 const pv::util::Timestamp& DecodeSignal::start_time() const
337 int64_t DecodeSignal::get_working_sample_count() const
339 // The working sample count is the highest sample number for
340 // which all used signals have data available, so go through
341 // all channels and use the lowest overall sample count of the
344 // TODO Currently, we assume only a single segment exists
346 int64_t count = std::numeric_limits<int64_t>::max();
347 bool no_signals_assigned = true;
349 for (const data::DecodeChannel &ch : channels_)
350 if (ch.assigned_signal) {
351 no_signals_assigned = false;
353 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
354 if (!logic_data || logic_data->logic_segments().empty())
357 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
358 count = min(count, (int64_t)segment->get_sample_count());
361 return (no_signals_assigned ? 0 : count);
364 int64_t DecodeSignal::get_decoded_sample_count() const
366 lock_guard<mutex> decode_lock(output_mutex_);
367 return samples_decoded_;
370 vector<Row> DecodeSignal::visible_rows() const
372 lock_guard<mutex> lock(output_mutex_);
376 for (const shared_ptr<decode::Decoder> &dec : stack_) {
381 const srd_decoder *const decc = dec->decoder();
382 assert(dec->decoder());
384 // Add a row for the decoder if it doesn't have a row list
385 if (!decc->annotation_rows)
386 rows.emplace_back(decc);
388 // Add the decoder rows
389 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
390 const srd_decoder_annotation_row *const ann_row =
391 (srd_decoder_annotation_row *)l->data;
393 rows.emplace_back(decc, ann_row);
400 void DecodeSignal::get_annotation_subset(
401 vector<pv::data::decode::Annotation> &dest,
402 const decode::Row &row, uint64_t start_sample,
403 uint64_t end_sample) const
405 lock_guard<mutex> lock(output_mutex_);
407 const auto iter = rows_.find(row);
408 if (iter != rows_.end())
409 (*iter).second.get_annotation_subset(dest,
410 start_sample, end_sample);
413 void DecodeSignal::save_settings(QSettings &settings) const
415 SignalBase::save_settings(settings);
417 // TODO Save decoder stack, channel mapping and decoder options
420 void DecodeSignal::restore_settings(QSettings &settings)
422 SignalBase::restore_settings(settings);
424 // TODO Restore decoder stack, channel mapping and decoder options
427 uint64_t DecodeSignal::inc_annotation_count()
429 return (annotation_count_++);
432 void DecodeSignal::update_channel_list()
434 vector<data::DecodeChannel> prev_channels = channels_;
439 // Copy existing entries, create new as needed
440 for (shared_ptr<Decoder> decoder : stack_) {
441 const srd_decoder* srd_d = decoder->decoder();
444 // Mandatory channels
445 for (l = srd_d->channels; l; l = l->next) {
446 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
447 bool ch_added = false;
449 // Copy but update ID if this channel was in the list before
450 for (data::DecodeChannel &ch : prev_channels)
451 if (ch.pdch_ == pdch) {
453 channels_.push_back(ch);
459 // Create new entry without a mapped signal
460 data::DecodeChannel ch = {id++, false, nullptr,
461 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
462 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
463 channels_.push_back(ch);
468 for (l = srd_d->opt_channels; l; l = l->next) {
469 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
470 bool ch_added = false;
472 // Copy but update ID if this channel was in the list before
473 for (data::DecodeChannel &ch : prev_channels)
474 if (ch.pdch_ == pdch) {
476 channels_.push_back(ch);
482 // Create new entry without a mapped signal
483 data::DecodeChannel ch = {id++, true, nullptr,
484 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
485 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
486 channels_.push_back(ch);
491 // Invalidate the logic output data if the channel assignment changed
492 if (prev_channels.size() != channels_.size()) {
493 // The number of channels changed, there's definitely a difference
494 logic_mux_data_invalid_ = true;
496 // Same number but assignment may still differ, so compare all channels
497 for (size_t i = 0; i < channels_.size(); i++) {
498 const data::DecodeChannel &p_ch = prev_channels[i];
499 const data::DecodeChannel &ch = channels_[i];
501 if ((p_ch.pdch_ != ch.pdch_) ||
502 (p_ch.assigned_signal != ch.assigned_signal)) {
503 logic_mux_data_invalid_ = true;
513 void DecodeSignal::commit_decoder_channels()
515 // Submit channel list to every decoder, containing only the relevant channels
516 for (shared_ptr<decode::Decoder> dec : stack_) {
517 vector<data::DecodeChannel*> channel_list;
519 for (data::DecodeChannel &ch : channels_)
520 if (ch.decoder_ == dec)
521 channel_list.push_back(&ch);
523 dec->set_channels(channel_list);
527 void DecodeSignal::mux_logic_samples(const int64_t start, const int64_t end)
529 // Enforce end to be greater than start
533 // Fetch all segments and their data
534 // TODO Currently, we assume only a single segment exists
535 vector<shared_ptr<LogicSegment> > segments;
536 vector<const uint8_t*> signal_data;
537 vector<uint8_t> signal_in_bytepos;
538 vector<uint8_t> signal_in_bitpos;
540 for (data::DecodeChannel &ch : channels_)
541 if (ch.assigned_signal) {
542 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
543 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().front();
544 segments.push_back(segment);
545 signal_data.push_back(segment->get_samples(start, end));
547 const int bitpos = ch.assigned_signal->logic_bit_index();
548 signal_in_bytepos.push_back(bitpos / 8);
549 signal_in_bitpos.push_back(bitpos % 8);
552 // Perform the muxing of signal data into the output data
553 uint8_t* output = new uint8_t[(end - start) * segment_->unit_size()];
554 unsigned int signal_count = signal_data.size();
556 for (int64_t sample_cnt = 0; sample_cnt < (end - start); sample_cnt++) {
560 const int out_sample_pos = sample_cnt * segment_->unit_size();
561 for (unsigned int i = 0; i < segment_->unit_size(); i++)
562 output[out_sample_pos + i] = 0;
564 for (unsigned int i = 0; i < signal_count; i++) {
565 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
566 const uint8_t in_sample = 1 &
567 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
569 const uint8_t out_sample = output[out_sample_pos + bytepos];
571 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
581 segment_->append_payload(output, (end - start) * segment_->unit_size());
584 for (const uint8_t* data : signal_data)
588 void DecodeSignal::logic_mux_proc()
592 const uint64_t input_sample_count = get_working_sample_count();
593 const uint64_t output_sample_count = segment_->get_sample_count();
595 const uint64_t samples_to_process =
596 (input_sample_count > output_sample_count) ?
597 (input_sample_count - output_sample_count) : 0;
599 // Process the samples if necessary...
600 if (samples_to_process > 0) {
601 const uint64_t unit_size = segment_->unit_size();
602 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
604 uint64_t processed_samples = 0;
606 const uint64_t start_sample = output_sample_count + processed_samples;
607 const uint64_t sample_count =
608 min(samples_to_process - processed_samples, chunk_sample_count);
610 mux_logic_samples(start_sample, start_sample + sample_count);
611 processed_samples += sample_count;
613 // ...and process the newly muxed logic data
614 decode_input_cond_.notify_one();
615 } while (processed_samples < samples_to_process);
618 if (session_.get_capture_state() != Session::Stopped) {
619 // Wait for more input
620 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
621 logic_mux_cond_.wait(logic_mux_lock);
623 } while ((session_.get_capture_state() != Session::Stopped) && !logic_mux_interrupt_);
625 // No more input data and session is stopped, let the decode thread
626 // process any pending data, terminate and release the global SRD mutex
627 // in order to let other decoders run
628 decode_input_cond_.notify_one();
631 void DecodeSignal::decode_data(
632 const int64_t abs_start_samplenum, const int64_t sample_count)
634 const int64_t unit_size = segment_->unit_size();
635 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
637 for (int64_t i = abs_start_samplenum;
638 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
639 i += chunk_sample_count) {
641 const int64_t chunk_end = min(i + chunk_sample_count,
642 abs_start_samplenum + sample_count);
644 const uint8_t* chunk = segment_->get_samples(i, chunk_end);
646 if (srd_session_send(srd_session_, i, chunk_end, chunk,
647 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
648 error_message_ = tr("Decoder reported an error");
655 lock_guard<mutex> lock(output_mutex_);
656 samples_decoded_ = chunk_end;
661 void DecodeSignal::decode_proc()
665 uint64_t sample_count;
666 uint64_t abs_start_samplenum = 0;
668 // Keep processing new samples until we exhaust the input data
670 // Prevent any other decode threads from accessing libsigrokdecode
671 lock_guard<mutex> srd_lock(global_srd_mutex_);
674 lock_guard<mutex> input_lock(input_mutex_);
675 sample_count = segment_->get_sample_count() - abs_start_samplenum;
678 if (sample_count > 0) {
679 decode_data(abs_start_samplenum, sample_count);
680 abs_start_samplenum += sample_count;
682 } while (error_message_.isEmpty() && (sample_count > 0));
684 if (error_message_.isEmpty()) {
685 // Make sure all annotations are known to the frontend
688 // Wait for new input data or an interrupt request
689 unique_lock<mutex> input_wait_lock(input_mutex_);
690 decode_input_cond_.wait(input_wait_lock);
692 } while (error_message_.isEmpty() && !decode_interrupt_);
695 void DecodeSignal::start_srd_session()
698 // Create the session
699 srd_session_new(&srd_session_);
700 assert(srd_session_);
702 // Create the decoders
703 srd_decoder_inst *prev_di = nullptr;
704 for (const shared_ptr<decode::Decoder> &dec : stack_) {
705 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
708 error_message_ = tr("Failed to create decoder instance");
709 srd_session_destroy(srd_session_);
714 srd_inst_stack(srd_session_, prev_di, di);
720 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
721 g_variant_new_uint64(samplerate_));
723 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
724 DecodeSignal::annotation_callback, this);
726 srd_session_start(srd_session_);
730 void DecodeSignal::stop_srd_session()
733 // Destroy the session
734 srd_session_destroy(srd_session_);
735 srd_session_ = nullptr;
739 void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
744 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
747 lock_guard<mutex> lock(ds->output_mutex_);
749 const decode::Annotation a(pdata);
753 assert(pdata->pdo->di);
754 const srd_decoder *const decc = pdata->pdo->di->decoder;
757 auto row_iter = ds->rows_.end();
759 // Try looking up the sub-row of this class
760 const auto r = ds->class_rows_.find(make_pair(decc, a.format()));
761 if (r != ds->class_rows_.end())
762 row_iter = ds->rows_.find((*r).second);
764 // Failing that, use the decoder as a key
765 row_iter = ds->rows_.find(Row(decc));
768 assert(row_iter != ds->rows_.end());
769 if (row_iter == ds->rows_.end()) {
770 qDebug() << "Unexpected annotation: decoder = " << decc <<
771 ", format = " << a.format();
776 // Add the annotation
777 (*row_iter).second.push_annotation(a);
779 // Notify the frontend every DecodeNotifyPeriod annotations
780 if (ds->inc_annotation_count() % DecodeNotifyPeriod == 0)
781 ds->new_annotations();
784 void DecodeSignal::on_capture_state_changed(int state)
786 // If a new acquisition was started, we need to start decoding from scratch
787 if (state == Session::Running)
791 void DecodeSignal::on_data_received()
793 logic_mux_cond_.notify_one();
796 void DecodeSignal::on_frame_ended()
798 logic_mux_cond_.notify_one();