]> sigrok.org Git - pulseview.git/blame_incremental - pv/data/decodesignal.cpp
DecodeSignal: Process late annotations which are sent upon EOF
[pulseview.git] / pv / data / decodesignal.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2017 Soeren Apel <soeren@apelpie.net>
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
20#include "config.h"
21
22#include <cstring>
23#include <forward_list>
24#include <limits>
25
26#include <QDebug>
27
28#include "logic.hpp"
29#include "logicsegment.hpp"
30#include "decodesignal.hpp"
31#include "signaldata.hpp"
32
33#include <pv/data/decode/decoder.hpp>
34#include <pv/data/decode/row.hpp>
35#include <pv/globalsettings.hpp>
36#include <pv/session.hpp>
37
38using std::dynamic_pointer_cast;
39using std::lock_guard;
40using std::make_shared;
41using std::min;
42using std::out_of_range;
43using std::shared_ptr;
44using std::unique_lock;
45using pv::data::decode::AnnotationClass;
46using pv::data::decode::DecodeChannel;
47
48namespace pv {
49namespace data {
50
51const double DecodeSignal::DecodeMargin = 1.0;
52const double DecodeSignal::DecodeThreshold = 0.2;
53const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
54
55
56DecodeSignal::DecodeSignal(pv::Session &session) :
57 SignalBase(nullptr, SignalBase::DecodeChannel),
58 session_(session),
59 srd_session_(nullptr),
60 logic_mux_data_invalid_(false),
61 stack_config_changed_(true),
62 current_segment_id_(0)
63{
64 connect(&session_, SIGNAL(capture_state_changed(int)),
65 this, SLOT(on_capture_state_changed(int)));
66}
67
68DecodeSignal::~DecodeSignal()
69{
70 reset_decode(true);
71}
72
73void DecodeSignal::set_name(QString name)
74{
75 SignalBase::set_name(name);
76
77 update_output_signals();
78}
79
80void DecodeSignal::set_color(QColor color)
81{
82 SignalBase::set_color(color);
83
84 update_output_signals();
85}
86
87const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
88{
89 return stack_;
90}
91
92void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
93{
94 assert(decoder);
95
96 // Set name if this decoder is the first in the list or the name is unchanged
97 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
98 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
99
100 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
101 set_name(QString::fromUtf8(decoder->name));
102
103 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder, stack_.size());
104 stack_.push_back(dec);
105
106 connect(dec.get(), SIGNAL(annotation_visibility_changed()),
107 this, SLOT(on_annotation_visibility_changed()));
108
109 // Include the newly created decode channels in the channel lists
110 update_channel_list();
111
112 stack_config_changed_ = true;
113 auto_assign_signals(dec);
114 commit_decoder_channels();
115 update_output_signals();
116
117 decoder_stacked((void*)dec.get());
118
119 if (restart_decode)
120 begin_decode();
121}
122
123void DecodeSignal::remove_decoder(int index)
124{
125 assert(index >= 0);
126 assert(index < (int)stack_.size());
127
128 // Find the decoder in the stack
129 auto iter = stack_.begin() + index;
130 assert(iter != stack_.end());
131
132 shared_ptr<Decoder> dec = *iter;
133
134 decoder_removed(dec.get());
135
136 // Delete the element
137 stack_.erase(iter);
138
139 // Update channels and decoded data
140 stack_config_changed_ = true;
141 update_channel_list();
142 begin_decode();
143}
144
145bool DecodeSignal::toggle_decoder_visibility(int index)
146{
147 auto iter = stack_.cbegin();
148 for (int i = 0; i < index; i++, iter++)
149 assert(iter != stack_.end());
150
151 shared_ptr<Decoder> dec = *iter;
152
153 // Toggle decoder visibility
154 bool state = false;
155 if (dec) {
156 state = !dec->visible();
157 dec->set_visible(state);
158 }
159
160 return state;
161}
162
163void DecodeSignal::reset_decode(bool shutting_down)
164{
165 resume_decode(); // Make sure the decode thread isn't blocked by pausing
166
167 if (stack_config_changed_ || shutting_down)
168 stop_srd_session();
169 else
170 terminate_srd_session();
171
172 if (decode_thread_.joinable()) {
173 decode_interrupt_ = true;
174 decode_input_cond_.notify_one();
175 decode_thread_.join();
176 }
177
178 if (logic_mux_thread_.joinable()) {
179 logic_mux_interrupt_ = true;
180 logic_mux_cond_.notify_one();
181 logic_mux_thread_.join();
182 }
183
184 current_segment_id_ = 0;
185 segments_.clear();
186
187 for (const shared_ptr<decode::Decoder>& dec : stack_)
188 if (dec->has_logic_output())
189 output_logic_[dec->get_srd_decoder()]->clear();
190
191 logic_mux_data_.reset();
192 logic_mux_data_invalid_ = true;
193
194 if (!error_message_.isEmpty()) {
195 error_message_.clear();
196 // TODO Emulate noquote()
197 qDebug().nospace() << name() << ": Error cleared";
198 }
199
200 decode_reset();
201}
202
203void DecodeSignal::begin_decode()
204{
205 if (decode_thread_.joinable()) {
206 decode_interrupt_ = true;
207 decode_input_cond_.notify_one();
208 decode_thread_.join();
209 }
210
211 if (logic_mux_thread_.joinable()) {
212 logic_mux_interrupt_ = true;
213 logic_mux_cond_.notify_one();
214 logic_mux_thread_.join();
215 }
216
217 reset_decode();
218
219 if (stack_.size() == 0) {
220 set_error_message(tr("No decoders"));
221 return;
222 }
223
224 assert(channels_.size() > 0);
225
226 if (get_assigned_signal_count() == 0) {
227 set_error_message(tr("There are no channels assigned to this decoder"));
228 return;
229 }
230
231 // Make sure that all assigned channels still provide logic data
232 // (can happen when a converted signal was assigned but the
233 // conversion removed in the meanwhile)
234 for (decode::DecodeChannel& ch : channels_)
235 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
236 ch.assigned_signal = nullptr;
237
238 // Check that all decoders have the required channels
239 for (const shared_ptr<Decoder>& dec : stack_)
240 if (!dec->have_required_channels()) {
241 set_error_message(tr("One or more required channels "
242 "have not been specified"));
243 return;
244 }
245
246 // Free the logic data and its segment(s) if it needs to be updated
247 if (logic_mux_data_invalid_)
248 logic_mux_data_.reset();
249
250 if (!logic_mux_data_) {
251 const uint32_t ch_count = get_assigned_signal_count();
252 logic_mux_unit_size_ = (ch_count + 7) / 8;
253 logic_mux_data_ = make_shared<Logic>(ch_count);
254 }
255
256 if (get_input_segment_count() == 0)
257 set_error_message(tr("No input data"));
258
259 // Make sure the logic output data is complete and up-to-date
260 logic_mux_interrupt_ = false;
261 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
262
263 // Decode the muxed logic data
264 decode_interrupt_ = false;
265 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
266}
267
268void DecodeSignal::pause_decode()
269{
270 decode_paused_ = true;
271}
272
273void DecodeSignal::resume_decode()
274{
275 // Manual unlocking is done before notifying, to avoid waking up the
276 // waiting thread only to block again (see notify_one for details)
277 decode_pause_mutex_.unlock();
278 decode_pause_cond_.notify_one();
279 decode_paused_ = false;
280}
281
282bool DecodeSignal::is_paused() const
283{
284 return decode_paused_;
285}
286
287const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
288{
289 return channels_;
290}
291
292void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
293{
294 bool new_assignment = false;
295
296 // Disconnect all input signal notifications so we don't have duplicate connections
297 disconnect_input_notifiers();
298
299 // Try to auto-select channels that don't have signals assigned yet
300 for (decode::DecodeChannel& ch : channels_) {
301 // If a decoder is given, auto-assign only its channels
302 if (dec && (ch.decoder_ != dec))
303 continue;
304
305 if (ch.assigned_signal)
306 continue;
307
308 QString ch_name = ch.name.toLower();
309 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
310
311 shared_ptr<data::SignalBase> match;
312 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
313 if (!s->enabled())
314 continue;
315
316 QString s_name = s->name().toLower();
317 s_name = s_name.replace(QRegExp("[-_.]"), " ");
318
319 if (s->logic_data() &&
320 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
321 if (!match)
322 match = s;
323 else {
324 // Only replace an existing match if it matches more characters
325 int old_unmatched = ch_name.length() - match->name().length();
326 int new_unmatched = ch_name.length() - s->name().length();
327 if (abs(new_unmatched) < abs(old_unmatched))
328 match = s;
329 }
330 }
331 }
332
333 // Prevent using a signal more than once as D1 would match e.g. D1 and D10
334 bool signal_not_already_used = true;
335 for (decode::DecodeChannel& ch : channels_)
336 if (ch.assigned_signal && (ch.assigned_signal == match))
337 signal_not_already_used = false;
338
339 if (match && signal_not_already_used) {
340 ch.assigned_signal = match;
341 new_assignment = true;
342 }
343 }
344
345 if (new_assignment) {
346 // Receive notifications when new sample data is available
347 connect_input_notifiers();
348
349 logic_mux_data_invalid_ = true;
350 stack_config_changed_ = true;
351 commit_decoder_channels();
352 channels_updated();
353 }
354}
355
356void DecodeSignal::assign_signal(const uint16_t channel_id, shared_ptr<const SignalBase> signal)
357{
358 // Disconnect all input signal notifications so we don't have duplicate connections
359 disconnect_input_notifiers();
360
361 for (decode::DecodeChannel& ch : channels_)
362 if (ch.id == channel_id) {
363 ch.assigned_signal = signal;
364 logic_mux_data_invalid_ = true;
365 }
366
367 // Receive notifications when new sample data is available
368 connect_input_notifiers();
369
370 stack_config_changed_ = true;
371 commit_decoder_channels();
372 channels_updated();
373 begin_decode();
374}
375
376int DecodeSignal::get_assigned_signal_count() const
377{
378 // Count all channels that have a signal assigned to them
379 return count_if(channels_.begin(), channels_.end(),
380 [](decode::DecodeChannel ch) { return ch.assigned_signal.get(); });
381}
382
383void DecodeSignal::update_output_signals()
384{
385 for (const shared_ptr<decode::Decoder>& dec : stack_) {
386 assert(dec);
387
388 if (dec->has_logic_output()) {
389 const vector<decode::DecoderLogicOutputChannel> logic_channels =
390 dec->logic_output_channels();
391
392 // All signals of a decoder share the same LogicSegment, so it's
393 // sufficient to check for only the first channel
394 const decode::DecoderLogicOutputChannel& first_ch = logic_channels[0];
395
396 bool ch_exists = false;
397 for (const shared_ptr<SignalBase>& signal : output_signals_)
398 if (signal->internal_name() == first_ch.id)
399 ch_exists = true;
400
401 if (!ch_exists) {
402 shared_ptr<Logic> logic_data = make_shared<Logic>(logic_channels.size());
403 logic_data->set_samplerate(get_samplerate());
404 output_logic_[dec->get_srd_decoder()] = logic_data;
405 output_logic_muxed_data_[dec->get_srd_decoder()] = vector<uint8_t>();
406
407 shared_ptr<LogicSegment> logic_segment = make_shared<data::LogicSegment>(
408 *logic_data, 0, (logic_data->num_channels() + 7) / 8, get_samplerate());
409 logic_data->push_segment(logic_segment);
410
411 uint index = 0;
412 for (const decode::DecoderLogicOutputChannel& logic_ch : logic_channels) {
413 shared_ptr<data::SignalBase> signal =
414 make_shared<data::SignalBase>(nullptr, LogicChannel);
415 signal->set_internal_name(logic_ch.id);
416 signal->set_index(index);
417 signal->set_data(logic_data);
418 output_signals_.push_back(signal);
419 session_.add_generated_signal(signal);
420 index++;
421 }
422 } else {
423 shared_ptr<Logic> logic_data = output_logic_[dec->get_srd_decoder()];
424 logic_data->set_samplerate(get_samplerate());
425 for (shared_ptr<LogicSegment>& segment : logic_data->logic_segments())
426 segment->set_samplerate(get_samplerate());
427 }
428 }
429 }
430
431 for (shared_ptr<SignalBase> s : output_signals_) {
432 s->set_name(s->internal_name() + " (" + name() + ")");
433 s->set_color(color());
434 }
435
436 // TODO Assert that all sample rates are the same as the session's
437}
438
439void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
440{
441 for (decode::DecodeChannel& ch : channels_)
442 if (ch.id == channel_id)
443 ch.initial_pin_state = init_state;
444
445 stack_config_changed_ = true;
446 channels_updated();
447 begin_decode();
448}
449
450double DecodeSignal::get_samplerate() const
451{
452 double result = 0;
453
454 // TODO For now, we simply return the first samplerate that we have
455 if (segments_.size() > 0)
456 result = segments_.front().samplerate;
457
458 return result;
459}
460
461const pv::util::Timestamp DecodeSignal::start_time() const
462{
463 pv::util::Timestamp result;
464
465 // TODO For now, we simply return the first start time that we have
466 if (segments_.size() > 0)
467 result = segments_.front().start_time;
468
469 return result;
470}
471
472int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
473{
474 // The working sample count is the highest sample number for
475 // which all used signals have data available, so go through all
476 // channels and use the lowest overall sample count of the segment
477
478 int64_t count = std::numeric_limits<int64_t>::max();
479 bool no_signals_assigned = true;
480
481 for (const decode::DecodeChannel& ch : channels_)
482 if (ch.assigned_signal) {
483 if (!ch.assigned_signal->logic_data())
484 return 0;
485
486 no_signals_assigned = false;
487
488 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
489 if (logic_data->logic_segments().empty())
490 return 0;
491
492 if (segment_id >= logic_data->logic_segments().size())
493 return 0;
494
495 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
496 if (segment)
497 count = min(count, (int64_t)segment->get_sample_count());
498 }
499
500 return (no_signals_assigned ? 0 : count);
501}
502
503int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
504 bool include_processing) const
505{
506 lock_guard<mutex> decode_lock(output_mutex_);
507
508 int64_t result = 0;
509
510 if (segment_id >= segments_.size())
511 return result;
512
513 if (include_processing)
514 result = segments_[segment_id].samples_decoded_incl;
515 else
516 result = segments_[segment_id].samples_decoded_excl;
517
518 return result;
519}
520
521vector<Row*> DecodeSignal::get_rows(bool visible_only)
522{
523 vector<Row*> rows;
524
525 for (const shared_ptr<Decoder>& dec : stack_) {
526 assert(dec);
527 if (visible_only && !dec->visible())
528 continue;
529
530 for (Row* row : dec->get_rows())
531 rows.push_back(row);
532 }
533
534 return rows;
535}
536
537vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
538{
539 vector<const Row*> rows;
540
541 for (const shared_ptr<Decoder>& dec : stack_) {
542 assert(dec);
543 if (visible_only && !dec->visible())
544 continue;
545
546 for (const Row* row : dec->get_rows())
547 rows.push_back(row);
548 }
549
550 return rows;
551}
552
553uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
554{
555 if (segment_id >= segments_.size())
556 return 0;
557
558 const DecodeSegment* segment = &(segments_.at(segment_id));
559
560 auto row_it = segment->annotation_rows.find(row);
561
562 const RowData* rd;
563 if (row_it == segment->annotation_rows.end())
564 return 0;
565 else
566 rd = &(row_it->second);
567
568 return rd->get_annotation_count();
569}
570
571void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
572 const Row* row, uint32_t segment_id, uint64_t start_sample,
573 uint64_t end_sample) const
574{
575 lock_guard<mutex> lock(output_mutex_);
576
577 if (segment_id >= segments_.size())
578 return;
579
580 const DecodeSegment* segment = &(segments_.at(segment_id));
581
582 auto row_it = segment->annotation_rows.find(row);
583
584 const RowData* rd;
585 if (row_it == segment->annotation_rows.end())
586 return;
587 else
588 rd = &(row_it->second);
589
590 rd->get_annotation_subset(dest, start_sample, end_sample);
591}
592
593void DecodeSignal::get_annotation_subset(deque<const Annotation*> &dest,
594 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
595{
596 for (const Row* row : get_rows())
597 get_annotation_subset(dest, row, segment_id, start_sample, end_sample);
598}
599
600uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
601 const Decoder* dec, uint32_t bin_class_id) const
602{
603 if ((segments_.size() == 0) || (segment_id >= segments_.size()))
604 return 0;
605
606 const DecodeSegment *segment = &(segments_[segment_id]);
607
608 for (const DecodeBinaryClass& bc : segment->binary_classes)
609 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
610 return bc.chunks.size();
611
612 return 0;
613}
614
615void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
616 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
617 const vector<uint8_t> **dest, uint64_t *size)
618{
619 if (segment_id >= segments_.size())
620 return;
621
622 const DecodeSegment *segment = &(segments_[segment_id]);
623
624 for (const DecodeBinaryClass& bc : segment->binary_classes)
625 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
626 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
627 if (size) *size = bc.chunks.at(chunk_id).data.size();
628 return;
629 }
630}
631
632void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
633 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
634 uint64_t end_sample, vector<uint8_t> *dest) const
635{
636 assert(dest != nullptr);
637
638 if (segment_id >= segments_.size())
639 return;
640
641 const DecodeSegment *segment = &(segments_[segment_id]);
642
643 const DecodeBinaryClass* bin_class = nullptr;
644 for (const DecodeBinaryClass& bc : segment->binary_classes)
645 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
646 bin_class = &bc;
647
648 // Determine overall size before copying to resize dest vector only once
649 uint64_t size = 0;
650 uint64_t matches = 0;
651 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
652 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
653 size += chunk.data.size();
654 matches++;
655 }
656 dest->resize(size);
657
658 uint64_t offset = 0;
659 uint64_t matches2 = 0;
660 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
661 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
662 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
663 offset += chunk.data.size();
664 matches2++;
665
666 // Make sure we don't overwrite memory if the array grew in the meanwhile
667 if (matches2 == matches)
668 break;
669 }
670}
671
672void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
673 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
674 vector<uint8_t> *dest) const
675{
676 assert(dest != nullptr);
677
678 if (segment_id >= segments_.size())
679 return;
680
681 const DecodeSegment *segment = &(segments_[segment_id]);
682
683 const DecodeBinaryClass* bin_class = nullptr;
684 for (const DecodeBinaryClass& bc : segment->binary_classes)
685 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
686 bin_class = &bc;
687
688 // Determine overall size before copying to resize dest vector only once
689 uint64_t size = 0;
690 uint64_t offset = 0;
691 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
692 if (offset >= start)
693 size += chunk.data.size();
694 offset += chunk.data.size();
695 if (offset >= end)
696 break;
697 }
698 dest->resize(size);
699
700 offset = 0;
701 uint64_t dest_offset = 0;
702 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
703 if (offset >= start) {
704 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
705 dest_offset += chunk.data.size();
706 }
707 offset += chunk.data.size();
708 if (offset >= end)
709 break;
710 }
711}
712
713const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
714 const Decoder* dec, uint32_t bin_class_id) const
715{
716 if (segment_id >= segments_.size())
717 return nullptr;
718
719 const DecodeSegment *segment = &(segments_[segment_id]);
720
721 for (const DecodeBinaryClass& bc : segment->binary_classes)
722 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
723 return &bc;
724
725 return nullptr;
726}
727
728const deque<const Annotation*>* DecodeSignal::get_all_annotations_by_segment(
729 uint32_t segment_id) const
730{
731 if (segment_id >= segments_.size())
732 return nullptr;
733
734 const DecodeSegment *segment = &(segments_[segment_id]);
735
736 return &(segment->all_annotations);
737}
738
739void DecodeSignal::save_settings(QSettings &settings) const
740{
741 SignalBase::save_settings(settings);
742
743 settings.setValue("decoders", (int)(stack_.size()));
744
745 // Save decoder stack
746 int decoder_idx = 0;
747 for (const shared_ptr<Decoder>& decoder : stack_) {
748 settings.beginGroup("decoder" + QString::number(decoder_idx++));
749
750 settings.setValue("id", decoder->get_srd_decoder()->id);
751 settings.setValue("visible", decoder->visible());
752
753 // Save decoder options
754 const map<string, GVariant*>& options = decoder->options();
755
756 settings.setValue("options", (int)options.size());
757
758 // Note: Decoder::options() returns only the options
759 // that differ from the default. See binding::Decoder::getter()
760 int i = 0;
761 for (auto& option : options) {
762 settings.beginGroup("option" + QString::number(i));
763 settings.setValue("name", QString::fromStdString(option.first));
764 GlobalSettings::store_gvariant(settings, option.second);
765 settings.endGroup();
766 i++;
767 }
768
769 // Save row properties
770 i = 0;
771 for (const Row* row : decoder->get_rows()) {
772 settings.beginGroup("row" + QString::number(i));
773 settings.setValue("visible", row->visible());
774 settings.endGroup();
775 i++;
776 }
777
778 // Save class properties
779 i = 0;
780 for (const AnnotationClass* ann_class : decoder->ann_classes()) {
781 settings.beginGroup("ann_class" + QString::number(i));
782 settings.setValue("visible", ann_class->visible());
783 settings.endGroup();
784 i++;
785 }
786
787 settings.endGroup();
788 }
789
790 // Save channel mapping
791 settings.setValue("channels", (int)channels_.size());
792
793 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
794 auto channel = find_if(channels_.begin(), channels_.end(),
795 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
796
797 if (channel == channels_.end()) {
798 qDebug() << "ERROR: Gap in channel index:" << channel_id;
799 continue;
800 }
801
802 settings.beginGroup("channel" + QString::number(channel_id));
803
804 settings.setValue("name", channel->name); // Useful for debugging
805 settings.setValue("initial_pin_state", channel->initial_pin_state);
806
807 if (channel->assigned_signal)
808 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
809
810 settings.endGroup();
811 }
812
813 // TODO Save logic output signal settings
814}
815
816void DecodeSignal::restore_settings(QSettings &settings)
817{
818 SignalBase::restore_settings(settings);
819
820 // Restore decoder stack
821 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
822
823 int decoders = settings.value("decoders").toInt();
824
825 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
826 settings.beginGroup("decoder" + QString::number(decoder_idx));
827
828 QString id = settings.value("id").toString();
829
830 for (GSList *entry = dec_list; entry; entry = entry->next) {
831 const srd_decoder *dec = (srd_decoder*)entry->data;
832 if (!dec)
833 continue;
834
835 if (QString::fromUtf8(dec->id) == id) {
836 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec, stack_.size());
837
838 connect(decoder.get(), SIGNAL(annotation_visibility_changed()),
839 this, SLOT(on_annotation_visibility_changed()));
840
841 stack_.push_back(decoder);
842 decoder->set_visible(settings.value("visible", true).toBool());
843
844 // Restore decoder options that differ from their default
845 int options = settings.value("options").toInt();
846
847 for (int i = 0; i < options; i++) {
848 settings.beginGroup("option" + QString::number(i));
849 QString name = settings.value("name").toString();
850 GVariant *value = GlobalSettings::restore_gvariant(settings);
851 decoder->set_option(name.toUtf8(), value);
852 settings.endGroup();
853 }
854
855 // Include the newly created decode channels in the channel lists
856 update_channel_list();
857
858 // Restore row properties
859 int i = 0;
860 for (Row* row : decoder->get_rows()) {
861 settings.beginGroup("row" + QString::number(i));
862 row->set_visible(settings.value("visible", true).toBool());
863 settings.endGroup();
864 i++;
865 }
866
867 // Restore class properties
868 i = 0;
869 for (AnnotationClass* ann_class : decoder->ann_classes()) {
870 settings.beginGroup("ann_class" + QString::number(i));
871 ann_class->set_visible(settings.value("visible", true).toBool());
872 settings.endGroup();
873 i++;
874 }
875
876 break;
877 }
878 }
879
880 settings.endGroup();
881 channels_updated();
882 }
883
884 // Restore channel mapping
885 unsigned int channels = settings.value("channels").toInt();
886
887 const vector< shared_ptr<data::SignalBase> > signalbases =
888 session_.signalbases();
889
890 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
891 auto channel = find_if(channels_.begin(), channels_.end(),
892 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
893
894 if (channel == channels_.end()) {
895 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
896 continue;
897 }
898
899 settings.beginGroup("channel" + QString::number(channel_id));
900
901 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
902
903 for (const shared_ptr<data::SignalBase>& signal : signalbases)
904 if ((signal->name() == assigned_signal_name) && (signal->type() != SignalBase::DecodeChannel))
905 channel->assigned_signal = signal;
906
907 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
908
909 settings.endGroup();
910 }
911
912 connect_input_notifiers();
913
914 // Update the internal structures
915 stack_config_changed_ = true;
916 update_channel_list();
917 commit_decoder_channels();
918 update_output_signals();
919
920 // TODO Restore logic output signal settings
921
922 begin_decode();
923}
924
925bool DecodeSignal::all_input_segments_complete(uint32_t segment_id) const
926{
927 bool all_complete = true;
928
929 for (const decode::DecodeChannel& ch : channels_)
930 if (ch.assigned_signal) {
931 if (!ch.assigned_signal->logic_data())
932 continue;
933
934 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
935 if (logic_data->logic_segments().empty())
936 return false;
937
938 if (segment_id >= logic_data->logic_segments().size())
939 return false;
940
941 const shared_ptr<const LogicSegment> segment = logic_data->logic_segments()[segment_id]->get_shared_ptr();
942 if (segment && !segment->is_complete())
943 all_complete = false;
944 }
945
946 return all_complete;
947}
948
949uint32_t DecodeSignal::get_input_segment_count() const
950{
951 uint64_t count = std::numeric_limits<uint64_t>::max();
952 bool no_signals_assigned = true;
953
954 for (const decode::DecodeChannel& ch : channels_)
955 if (ch.assigned_signal) {
956 no_signals_assigned = false;
957
958 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
959 if (!logic_data || logic_data->logic_segments().empty())
960 return 0;
961
962 // Find the min value of all segment counts
963 if ((uint64_t)(logic_data->logic_segments().size()) < count)
964 count = logic_data->logic_segments().size();
965 }
966
967 return (no_signals_assigned ? 0 : count);
968}
969
970double DecodeSignal::get_input_samplerate(uint32_t segment_id) const
971{
972 double samplerate = 0;
973
974 for (const decode::DecodeChannel& ch : channels_)
975 if (ch.assigned_signal) {
976 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
977 if (!logic_data || logic_data->logic_segments().empty())
978 continue;
979
980 try {
981 const shared_ptr<const LogicSegment> segment =
982 logic_data->logic_segments().at(segment_id)->get_shared_ptr();
983 if (segment)
984 samplerate = segment->samplerate();
985 } catch (out_of_range&) {
986 // Do nothing
987 }
988 break;
989 }
990
991 return samplerate;
992}
993
994Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
995{
996 for (shared_ptr<Decoder>& d : stack_)
997 if (d->get_srd_decoder() == srd_dec)
998 return d.get();
999
1000 return nullptr;
1001}
1002
1003void DecodeSignal::update_channel_list()
1004{
1005 vector<decode::DecodeChannel> prev_channels = channels_;
1006 channels_.clear();
1007
1008 uint16_t id = 0;
1009
1010 // Copy existing entries, create new as needed
1011 for (shared_ptr<Decoder>& decoder : stack_) {
1012 const srd_decoder* srd_dec = decoder->get_srd_decoder();
1013 const GSList *l;
1014
1015 // Mandatory channels
1016 for (l = srd_dec->channels; l; l = l->next) {
1017 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
1018 bool ch_added = false;
1019
1020 // Copy but update ID if this channel was in the list before
1021 for (decode::DecodeChannel& ch : prev_channels)
1022 if (ch.pdch_ == pdch) {
1023 ch.id = id++;
1024 channels_.push_back(ch);
1025 ch_added = true;
1026 break;
1027 }
1028
1029 if (!ch_added) {
1030 // Create new entry without a mapped signal
1031 decode::DecodeChannel ch = {id++, 0, false, nullptr,
1032 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
1033 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
1034 channels_.push_back(ch);
1035 }
1036 }
1037
1038 // Optional channels
1039 for (l = srd_dec->opt_channels; l; l = l->next) {
1040 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
1041 bool ch_added = false;
1042
1043 // Copy but update ID if this channel was in the list before
1044 for (decode::DecodeChannel& ch : prev_channels)
1045 if (ch.pdch_ == pdch) {
1046 ch.id = id++;
1047 channels_.push_back(ch);
1048 ch_added = true;
1049 break;
1050 }
1051
1052 if (!ch_added) {
1053 // Create new entry without a mapped signal
1054 decode::DecodeChannel ch = {id++, 0, true, nullptr,
1055 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
1056 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
1057 channels_.push_back(ch);
1058 }
1059 }
1060 }
1061
1062 // Invalidate the logic output data if the channel assignment changed
1063 if (prev_channels.size() != channels_.size()) {
1064 // The number of channels changed, there's definitely a difference
1065 logic_mux_data_invalid_ = true;
1066 } else {
1067 // Same number but assignment may still differ, so compare all channels
1068 for (size_t i = 0; i < channels_.size(); i++) {
1069 const decode::DecodeChannel& p_ch = prev_channels[i];
1070 const decode::DecodeChannel& ch = channels_[i];
1071
1072 if ((p_ch.pdch_ != ch.pdch_) ||
1073 (p_ch.assigned_signal != ch.assigned_signal)) {
1074 logic_mux_data_invalid_ = true;
1075 break;
1076 }
1077 }
1078
1079 }
1080
1081 channels_updated();
1082}
1083
1084void DecodeSignal::commit_decoder_channels()
1085{
1086 // Submit channel list to every decoder, containing only the relevant channels
1087 for (shared_ptr<Decoder> dec : stack_) {
1088 vector<decode::DecodeChannel*> channel_list;
1089
1090 for (decode::DecodeChannel& ch : channels_)
1091 if (ch.decoder_ == dec)
1092 channel_list.push_back(&ch);
1093
1094 dec->set_channels(channel_list);
1095 }
1096
1097 // Channel bit IDs must be in sync with the channel's apperance in channels_
1098 int id = 0;
1099 for (decode::DecodeChannel& ch : channels_)
1100 if (ch.assigned_signal)
1101 ch.bit_id = id++;
1102}
1103
1104void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
1105{
1106 // Enforce end to be greater than start
1107 if (end <= start)
1108 return;
1109
1110 // Fetch the channel segments and their data
1111 vector<shared_ptr<const LogicSegment> > segments;
1112 vector<const uint8_t*> signal_data;
1113 vector<uint8_t> signal_in_bytepos;
1114 vector<uint8_t> signal_in_bitpos;
1115
1116 for (decode::DecodeChannel& ch : channels_)
1117 if (ch.assigned_signal) {
1118 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
1119
1120 shared_ptr<const LogicSegment> segment;
1121 if (segment_id < logic_data->logic_segments().size()) {
1122 segment = logic_data->logic_segments().at(segment_id)->get_shared_ptr();
1123 } else {
1124 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
1125 << "has no logic segment" << segment_id;
1126 logic_mux_interrupt_ = true;
1127 return;
1128 }
1129
1130 if (!segment)
1131 return;
1132
1133 segments.push_back(segment);
1134
1135 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
1136 segment->get_samples(start, end, data);
1137 signal_data.push_back(data);
1138
1139 const int bitpos = ch.assigned_signal->logic_bit_index();
1140 signal_in_bytepos.push_back(bitpos / 8);
1141 signal_in_bitpos.push_back(bitpos % 8);
1142 }
1143
1144 shared_ptr<LogicSegment> output_segment;
1145 try {
1146 output_segment = logic_mux_data_->logic_segments().at(segment_id);
1147 } catch (out_of_range&) {
1148 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1149 << segment_id << "in mux_logic_samples(), mux segments size is" \
1150 << logic_mux_data_->logic_segments().size();
1151 logic_mux_interrupt_ = true;
1152 return;
1153 }
1154
1155 // Perform the muxing of signal data into the output data
1156 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
1157 unsigned int signal_count = signal_data.size();
1158
1159 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1160 sample_cnt++) {
1161
1162 int bitpos = 0;
1163 uint8_t bytepos = 0;
1164
1165 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1166 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
1167 output[out_sample_pos + i] = 0;
1168
1169 for (unsigned int i = 0; i < signal_count; i++) {
1170 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1171 const uint8_t in_sample = 1 &
1172 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
1173
1174 const uint8_t out_sample = output[out_sample_pos + bytepos];
1175
1176 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1177
1178 bitpos++;
1179 if (bitpos > 7) {
1180 bitpos = 0;
1181 bytepos++;
1182 }
1183 }
1184 }
1185
1186 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
1187 delete[] output;
1188
1189 for (const uint8_t* data : signal_data)
1190 delete[] data;
1191}
1192
1193void DecodeSignal::logic_mux_proc()
1194{
1195 uint32_t input_segment_count;
1196 do {
1197 input_segment_count = get_input_segment_count();
1198 if (input_segment_count == 0) {
1199 // Wait for input data
1200 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1201 logic_mux_cond_.wait(logic_mux_lock);
1202 }
1203 } while ((!logic_mux_interrupt_) && (input_segment_count == 0));
1204
1205 if (logic_mux_interrupt_)
1206 return;
1207
1208 assert(logic_mux_data_);
1209
1210 uint32_t segment_id = 0;
1211
1212 // Create initial logic mux segment
1213 shared_ptr<LogicSegment> output_segment =
1214 make_shared<LogicSegment>(*logic_mux_data_, segment_id, logic_mux_unit_size_, 0);
1215 logic_mux_data_->push_segment(output_segment);
1216
1217 output_segment->set_samplerate(get_input_samplerate(0));
1218
1219 // Logic mux data is being updated
1220 logic_mux_data_invalid_ = false;
1221
1222 uint64_t samples_to_process;
1223 do {
1224 do {
1225 const uint64_t input_sample_count = get_working_sample_count(segment_id);
1226 const uint64_t output_sample_count = output_segment->get_sample_count();
1227
1228 samples_to_process =
1229 (input_sample_count > output_sample_count) ?
1230 (input_sample_count - output_sample_count) : 0;
1231
1232 if (samples_to_process > 0) {
1233 const uint64_t unit_size = output_segment->unit_size();
1234 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1235
1236 uint64_t processed_samples = 0;
1237 do {
1238 const uint64_t start_sample = output_sample_count + processed_samples;
1239 const uint64_t sample_count =
1240 min(samples_to_process - processed_samples, chunk_sample_count);
1241
1242 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
1243 processed_samples += sample_count;
1244
1245 // ...and process the newly muxed logic data
1246 decode_input_cond_.notify_one();
1247 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
1248 }
1249 } while (!logic_mux_interrupt_ && (samples_to_process > 0));
1250
1251 if (!logic_mux_interrupt_) {
1252 // samples_to_process is now 0, we've exhausted the currently available input data
1253
1254 // If the input segments are complete, we've completed this segment
1255 if (all_input_segments_complete(segment_id)) {
1256 if (!output_segment->is_complete())
1257 output_segment->set_complete();
1258
1259 if (segment_id < get_input_segment_count() - 1) {
1260
1261 // Process next segment
1262 segment_id++;
1263
1264 output_segment =
1265 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1266 logic_mux_unit_size_, 0);
1267 logic_mux_data_->push_segment(output_segment);
1268
1269 output_segment->set_samplerate(get_input_samplerate(segment_id));
1270 } else {
1271 // Wait for more input data if we're processing the currently last segment
1272 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1273 logic_mux_cond_.wait(logic_mux_lock);
1274 }
1275 } else {
1276 // Input segments aren't all complete yet but samples_to_process is 0, wait for more input data
1277 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1278 logic_mux_cond_.wait(logic_mux_lock);
1279 }
1280 }
1281 } while (!logic_mux_interrupt_);
1282}
1283
1284void DecodeSignal::decode_data(
1285 const int64_t abs_start_samplenum, const int64_t sample_count,
1286 const shared_ptr<const LogicSegment> input_segment)
1287{
1288 const int64_t unit_size = input_segment->unit_size();
1289 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
1290
1291 for (int64_t i = abs_start_samplenum;
1292 !decode_interrupt_ && (i < (abs_start_samplenum + sample_count));
1293 i += chunk_sample_count) {
1294
1295 const int64_t chunk_end = min(i + chunk_sample_count,
1296 abs_start_samplenum + sample_count);
1297
1298 {
1299 lock_guard<mutex> lock(output_mutex_);
1300 // Update the sample count showing the samples including currently processed ones
1301 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
1302 }
1303
1304 int64_t data_size = (chunk_end - i) * unit_size;
1305 uint8_t* chunk = new uint8_t[data_size];
1306 input_segment->get_samples(i, chunk_end, chunk);
1307
1308 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1309 data_size, unit_size) != SRD_OK) {
1310 set_error_message(tr("Decoder reported an error"));
1311 decode_interrupt_ = true;
1312 }
1313
1314 delete[] chunk;
1315
1316 {
1317 lock_guard<mutex> lock(output_mutex_);
1318 // Now that all samples are processed, the exclusive sample count catches up
1319 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1320 }
1321
1322 // Notify the frontend that we processed some data and
1323 // possibly have new annotations as well
1324 new_annotations();
1325
1326 if (decode_paused_) {
1327 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1328 decode_pause_cond_.wait(pause_wait_lock);
1329 }
1330 }
1331}
1332
1333void DecodeSignal::decode_proc()
1334{
1335 current_segment_id_ = 0;
1336
1337 // If there is no input data available yet, wait until it is or we're interrupted
1338 do {
1339 if (logic_mux_data_->logic_segments().size() == 0) {
1340 // Wait for input data
1341 unique_lock<mutex> input_wait_lock(input_mutex_);
1342 decode_input_cond_.wait(input_wait_lock);
1343 }
1344 } while ((!decode_interrupt_) && (logic_mux_data_->logic_segments().size() == 0));
1345
1346 if (decode_interrupt_)
1347 return;
1348
1349 shared_ptr<const LogicSegment> input_segment = logic_mux_data_->logic_segments().front()->get_shared_ptr();
1350 if (!input_segment)
1351 return;
1352
1353 // Create the initial segment and set its sample rate so that we can pass it to SRD
1354 create_decode_segment();
1355 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1356 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1357
1358 start_srd_session();
1359
1360 uint64_t samples_to_process = 0;
1361 uint64_t abs_start_samplenum = 0;
1362 do {
1363 // Keep processing new samples until we exhaust the input data
1364 do {
1365 samples_to_process = input_segment->get_sample_count() - abs_start_samplenum;
1366
1367 if (samples_to_process > 0) {
1368 decode_data(abs_start_samplenum, samples_to_process, input_segment);
1369 abs_start_samplenum += samples_to_process;
1370 }
1371 } while (!decode_interrupt_ && (samples_to_process > 0));
1372
1373 if (!decode_interrupt_) {
1374 // samples_to_process is now 0, we've exhausted the currently available input data
1375
1376 // If the input segment is complete, we've exhausted this segment
1377 if (input_segment->is_complete()) {
1378#if defined HAVE_SRD_SESSION_SEND_EOF && HAVE_SRD_SESSION_SEND_EOF
1379 // Tell protocol decoders about the end of
1380 // the input data, which may result in more
1381 // annotations being emitted
1382 (void)srd_session_send_eof(srd_session_);
1383 new_annotations();
1384#endif
1385
1386 if (current_segment_id_ < (logic_mux_data_->logic_segments().size() - 1)) {
1387 // Process next segment
1388 current_segment_id_++;
1389
1390 try {
1391 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
1392 } catch (out_of_range&) {
1393 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1394 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1395 << logic_mux_data_->logic_segments().size();
1396 decode_interrupt_ = true;
1397 return;
1398 }
1399 abs_start_samplenum = 0;
1400
1401 // Create the next segment and set its metadata
1402 create_decode_segment();
1403 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
1404 segments_.at(current_segment_id_).start_time = input_segment->start_time();
1405
1406 // Reset decoder state but keep the decoder stack intact
1407 terminate_srd_session();
1408 } else {
1409 // All segments have been processed
1410 if (!decode_interrupt_)
1411 decode_finished();
1412
1413 // Wait for more input data
1414 unique_lock<mutex> input_wait_lock(input_mutex_);
1415 decode_input_cond_.wait(input_wait_lock);
1416 }
1417 } else {
1418 // Input segment isn't complete yet but samples_to_process is 0, wait for more input data
1419 unique_lock<mutex> input_wait_lock(input_mutex_);
1420 decode_input_cond_.wait(input_wait_lock);
1421 }
1422
1423 }
1424 } while (!decode_interrupt_);
1425}
1426
1427void DecodeSignal::start_srd_session()
1428{
1429 // If there were stack changes, the session has been destroyed by now, so if
1430 // it hasn't been destroyed, we can just reset and re-use it
1431 if (srd_session_) {
1432 // When a decoder stack was created before, re-use it
1433 // for the next stream of input data, after terminating
1434 // potentially still executing operations, and resetting
1435 // internal state. Skip the rather expensive (teardown
1436 // and) construction of another decoder stack.
1437
1438 // TODO Reduce redundancy, use a common code path for
1439 // the meta/start sequence?
1440 terminate_srd_session();
1441
1442 // Metadata is cleared also, so re-set it
1443 uint64_t samplerate = 0;
1444 if (segments_.size() > 0)
1445 samplerate = segments_.at(current_segment_id_).samplerate;
1446 if (samplerate)
1447 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1448 g_variant_new_uint64(samplerate));
1449 for (const shared_ptr<Decoder>& dec : stack_)
1450 dec->apply_all_options();
1451 srd_session_start(srd_session_);
1452
1453 return;
1454 }
1455
1456 // Update the samplerates for the output logic channels
1457 update_output_signals();
1458
1459 // Create the session
1460 srd_session_new(&srd_session_);
1461 assert(srd_session_);
1462
1463 // Create the decoders
1464 srd_decoder_inst *prev_di = nullptr;
1465 for (const shared_ptr<Decoder>& dec : stack_) {
1466 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
1467
1468 if (!di) {
1469 set_error_message(tr("Failed to create decoder instance"));
1470 srd_session_destroy(srd_session_);
1471 srd_session_ = nullptr;
1472 return;
1473 }
1474
1475 if (prev_di)
1476 srd_inst_stack(srd_session_, prev_di, di);
1477
1478 prev_di = di;
1479 }
1480
1481 // Start the session
1482 if (segments_.size() > 0)
1483 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1484 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
1485
1486 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1487 DecodeSignal::annotation_callback, this);
1488
1489 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1490 DecodeSignal::binary_callback, this);
1491
1492 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_LOGIC,
1493 DecodeSignal::logic_output_callback, this);
1494
1495 srd_session_start(srd_session_);
1496
1497 // We just recreated the srd session, so all stack changes are applied now
1498 stack_config_changed_ = false;
1499}
1500
1501void DecodeSignal::terminate_srd_session()
1502{
1503 // Call the "terminate and reset" routine for the decoder stack
1504 // (if available). This does not harm those stacks which already
1505 // have completed their operation, and reduces response time for
1506 // those stacks which still are processing data while the
1507 // application no longer wants them to.
1508 if (srd_session_) {
1509#if defined HAVE_SRD_SESSION_SEND_EOF && HAVE_SRD_SESSION_SEND_EOF
1510 (void)srd_session_send_eof(srd_session_);
1511#endif
1512 srd_session_terminate_reset(srd_session_);
1513
1514 // Metadata is cleared also, so re-set it
1515 uint64_t samplerate = 0;
1516 if (segments_.size() > 0)
1517 samplerate = segments_.at(current_segment_id_).samplerate;
1518 if (samplerate)
1519 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1520 g_variant_new_uint64(samplerate));
1521 for (const shared_ptr<Decoder>& dec : stack_)
1522 dec->apply_all_options();
1523 }
1524}
1525
1526void DecodeSignal::stop_srd_session()
1527{
1528 if (srd_session_) {
1529 // Destroy the session
1530 srd_session_destroy(srd_session_);
1531 srd_session_ = nullptr;
1532
1533 // Mark the decoder instances as non-existant since they were deleted
1534 for (const shared_ptr<Decoder>& dec : stack_)
1535 dec->invalidate_decoder_inst();
1536 }
1537}
1538
1539void DecodeSignal::connect_input_notifiers()
1540{
1541 // Connect the currently used signals to our slot
1542 for (decode::DecodeChannel& ch : channels_) {
1543 if (!ch.assigned_signal)
1544 continue;
1545 const data::SignalBase *signal = ch.assigned_signal.get();
1546
1547 connect(signal, SIGNAL(samples_cleared()),
1548 this, SLOT(on_data_cleared()), Qt::UniqueConnection);
1549 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
1550 this, SLOT(on_data_received()), Qt::UniqueConnection);
1551
1552 if (signal->logic_data())
1553 connect(signal->logic_data().get(), SIGNAL(segment_completed()),
1554 this, SLOT(on_input_segment_completed()), Qt::UniqueConnection);
1555 }
1556}
1557
1558void DecodeSignal::disconnect_input_notifiers()
1559{
1560 // Disconnect the notification slot from the previous set of signals
1561 for (decode::DecodeChannel& ch : channels_) {
1562 if (!ch.assigned_signal)
1563 continue;
1564 const data::SignalBase *signal = ch.assigned_signal.get();
1565 disconnect(signal, nullptr, this, SLOT(on_data_cleared()));
1566 disconnect(signal, nullptr, this, SLOT(on_data_received()));
1567
1568 if (signal->logic_data())
1569 disconnect(signal->logic_data().get(), nullptr, this, SLOT(on_input_segment_completed()));
1570 }
1571}
1572
1573void DecodeSignal::create_decode_segment()
1574{
1575 // Create annotation segment
1576 segments_.emplace_back();
1577
1578 // Add annotation classes
1579 for (const shared_ptr<Decoder>& dec : stack_)
1580 for (Row* row : dec->get_rows())
1581 segments_.back().annotation_rows.emplace(row, RowData(row));
1582
1583 // Prepare our binary output classes
1584 for (const shared_ptr<Decoder>& dec : stack_) {
1585 uint32_t n = dec->get_binary_class_count();
1586
1587 for (uint32_t i = 0; i < n; i++)
1588 segments_.back().binary_classes.push_back(
1589 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
1590 }
1591}
1592
1593void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1594{
1595 assert(pdata);
1596 assert(decode_signal);
1597
1598 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1599 assert(ds);
1600
1601 if (ds->decode_interrupt_)
1602 return;
1603
1604 if (ds->segments_.empty())
1605 return;
1606
1607 lock_guard<mutex> lock(ds->output_mutex_);
1608
1609 // Get the decoder and the annotation data
1610 assert(pdata->pdo);
1611 assert(pdata->pdo->di);
1612 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1613 assert(srd_dec);
1614
1615 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1616 assert(pda);
1617
1618 // Find the row
1619 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1620 assert(dec);
1621
1622 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1623 if (!ann_class) {
1624 qWarning() << "Decoder" << ds->display_name() << "wanted to add annotation" <<
1625 "with class ID" << pda->ann_class << "but there are only" <<
1626 dec->ann_classes().size() << "known classes";
1627 return;
1628 }
1629
1630 const Row* row = ann_class->row;
1631
1632 if (!row)
1633 row = dec->get_row_by_id(0);
1634
1635 RowData& row_data = ds->segments_[ds->current_segment_id_].annotation_rows.at(row);
1636
1637 // Add the annotation to the row
1638 const Annotation* ann = row_data.emplace_annotation(pdata);
1639
1640 // We insert the annotation into the global annotation list in a way so that
1641 // the annotation list is sorted by start sample and length. Otherwise, we'd
1642 // have to sort the model, which is expensive
1643 deque<const Annotation*>& all_annotations =
1644 ds->segments_[ds->current_segment_id_].all_annotations;
1645
1646 if (all_annotations.empty()) {
1647 all_annotations.emplace_back(ann);
1648 } else {
1649 const uint64_t new_ann_len = (pdata->end_sample - pdata->start_sample);
1650 bool ann_has_earlier_start = (pdata->start_sample < all_annotations.back()->start_sample());
1651 bool ann_is_longer = (new_ann_len >
1652 (all_annotations.back()->end_sample() - all_annotations.back()->start_sample()));
1653
1654 if (ann_has_earlier_start && ann_is_longer) {
1655 bool ann_has_same_start;
1656 auto it = all_annotations.end();
1657
1658 do {
1659 it--;
1660 ann_has_earlier_start = (pdata->start_sample < (*it)->start_sample());
1661 ann_has_same_start = (pdata->start_sample == (*it)->start_sample());
1662 ann_is_longer = (new_ann_len > (*it)->length());
1663 } while ((ann_has_earlier_start || (ann_has_same_start && ann_is_longer)) && (it != all_annotations.begin()));
1664
1665 // Allow inserting at the front
1666 if (it != all_annotations.begin())
1667 it++;
1668
1669 all_annotations.emplace(it, ann);
1670 } else
1671 all_annotations.emplace_back(ann);
1672 }
1673
1674 // When emplace_annotation() inserts instead of appends an annotation,
1675 // the pointers in all_annotations that follow the inserted annotation and
1676 // point to annotations for this row are off by one and must be updated
1677 if (&(row_data.annotations().back()) != ann) {
1678 // Search backwards until we find the annotation we just added
1679 auto row_it = row_data.annotations().end();
1680 auto all_it = all_annotations.end();
1681 do {
1682 all_it--;
1683 if ((*all_it)->row_data() == &row_data)
1684 row_it--;
1685 } while (&(*row_it) != ann);
1686
1687 // Update the annotation addresses for this row's annotations until the end
1688 do {
1689 if ((*all_it)->row_data() == &row_data) {
1690 *all_it = &(*row_it);
1691 row_it++;
1692 }
1693 all_it++;
1694 } while (all_it != all_annotations.end());
1695 }
1696}
1697
1698void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1699{
1700 assert(pdata);
1701 assert(decode_signal);
1702
1703 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1704 assert(ds);
1705
1706 if (ds->decode_interrupt_)
1707 return;
1708
1709 // Get the decoder and the binary data
1710 assert(pdata->pdo);
1711 assert(pdata->pdo->di);
1712 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1713 assert(srd_dec);
1714
1715 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1716 assert(pdb);
1717
1718 // Find the matching DecodeBinaryClass
1719 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1720
1721 DecodeBinaryClass* bin_class = nullptr;
1722 for (DecodeBinaryClass& bc : segment->binary_classes)
1723 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1724 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
1725 bin_class = &bc;
1726
1727 if (!bin_class) {
1728 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1729 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1730 ", segment only knows" << segment->binary_classes.size() << "classes";
1731 return;
1732 }
1733
1734 // Add the data chunk
1735 bin_class->chunks.emplace_back();
1736 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1737
1738 chunk->sample = pdata->start_sample;
1739 chunk->data.resize(pdb->size);
1740 memcpy(chunk->data.data(), pdb->data, pdb->size);
1741
1742 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1743
1744 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
1745}
1746
1747void DecodeSignal::logic_output_callback(srd_proto_data *pdata, void *decode_signal)
1748{
1749 assert(pdata);
1750 assert(decode_signal);
1751
1752 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1753 assert(ds);
1754
1755 if (ds->decode_interrupt_)
1756 return;
1757
1758 lock_guard<mutex> lock(ds->output_mutex_);
1759
1760 assert(pdata->pdo);
1761 assert(pdata->pdo->di);
1762 const srd_decoder *const decc = pdata->pdo->di->decoder;
1763 assert(decc);
1764
1765 const srd_proto_data_logic *const pdl = (const srd_proto_data_logic*)pdata->data;
1766 assert(pdl);
1767
1768 // FIXME Only one group supported for now
1769 if (pdl->logic_group > 0) {
1770 qWarning() << "Received logic output state change for group" << pdl->logic_group << "from decoder" \
1771 << QString::fromUtf8(decc->name) << "but only group 0 is currently supported";
1772 return;
1773 }
1774
1775 shared_ptr<Logic> output_logic = ds->output_logic_.at(decc);
1776
1777 vector< shared_ptr<Segment> > segments = output_logic->segments();
1778
1779 shared_ptr<LogicSegment> last_segment;
1780
1781 if (!segments.empty())
1782 last_segment = dynamic_pointer_cast<LogicSegment>(segments.back());
1783 else {
1784 // Happens when the data was cleared - all segments are gone then
1785 // segment_id is always 0 as it's the first segment
1786 last_segment = make_shared<data::LogicSegment>(
1787 *output_logic, 0, (output_logic->num_channels() + 7) / 8, output_logic->get_samplerate());
1788 output_logic->push_segment(last_segment);
1789 }
1790
1791 if (pdata->start_sample < pdata->end_sample) {
1792 vector<uint8_t> data;
1793 const unsigned int unit_size = last_segment->unit_size();
1794 data.resize(unit_size * (1 + pdl->repeat_count));
1795
1796 if (unit_size == 1)
1797 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1798 data.data()[i * unit_size] = *((uint8_t*)pdl->data);
1799 else if (unit_size == 2)
1800 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1801 data.data()[i * unit_size] = *((uint16_t*)pdl->data);
1802 else if (unit_size <= 4)
1803 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1804 data.data()[i * unit_size] = *((uint32_t*)pdl->data);
1805 else if (unit_size <= 8)
1806 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1807 data.data()[i * unit_size] = *((uint64_t*)pdl->data);
1808 else
1809 for (unsigned int i = 0; i <= pdl->repeat_count; i++)
1810 memcpy((void*)&data.data()[i * unit_size], (void*)pdl->data, unit_size);
1811
1812 last_segment->append_payload(data.data(), data.size());
1813 } else
1814 qWarning() << "Ignoring malformed logic output state change for group" << pdl->logic_group << "from decoder" \
1815 << QString::fromUtf8(decc->name) << "from" << pdata->start_sample << "to" << pdata->end_sample;
1816}
1817
1818void DecodeSignal::on_capture_state_changed(int state)
1819{
1820 // If a new acquisition was started, we need to start decoding from scratch
1821 if (state == Session::Running) {
1822 logic_mux_data_invalid_ = true;
1823 begin_decode();
1824 }
1825}
1826
1827void DecodeSignal::on_data_cleared()
1828{
1829 reset_decode();
1830}
1831
1832void DecodeSignal::on_data_received()
1833{
1834 // If we detected a lack of input data when trying to start decoding,
1835 // we have set an error message. Bail out if we still don't have data
1836 // to work with
1837 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1838 return;
1839
1840 if (!error_message_.isEmpty()) {
1841 error_message_.clear();
1842 // TODO Emulate noquote()
1843 qDebug().nospace() << name() << ": Input data available, error cleared";
1844 }
1845
1846 if (!logic_mux_thread_.joinable())
1847 begin_decode();
1848 else
1849 logic_mux_cond_.notify_one();
1850}
1851
1852void DecodeSignal::on_input_segment_completed()
1853{
1854 if (!logic_mux_thread_.joinable())
1855 logic_mux_cond_.notify_one();
1856}
1857
1858void DecodeSignal::on_annotation_visibility_changed()
1859{
1860 annotation_visibility_changed();
1861}
1862
1863} // namespace data
1864} // namespace pv