]> sigrok.org Git - pulseview.git/blame - pv/data/decodesignal.cpp
Rework decoder infrastructure
[pulseview.git] / pv / data / decodesignal.cpp
CommitLineData
ad908057
SA
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
c0c3e62a 20#include <cstring>
5a914348 21#include <forward_list>
0c5fe73e
SA
22#include <limits>
23
47747218
SA
24#include <QDebug>
25
ad908057
SA
26#include "logic.hpp"
27#include "logicsegment.hpp"
28#include "decodesignal.hpp"
29#include "signaldata.hpp"
30
ad908057 31#include <pv/data/decode/decoder.hpp>
ecd07c20 32#include <pv/data/decode/row.hpp>
d3feec23 33#include <pv/globalsettings.hpp>
ad908057
SA
34#include <pv/session.hpp>
35
5a914348 36using std::forward_list;
47747218
SA
37using std::lock_guard;
38using std::make_pair;
ad908057 39using std::make_shared;
0c5fe73e 40using std::min;
5ecf957f 41using std::out_of_range;
ad908057 42using std::shared_ptr;
47747218
SA
43using std::unique_lock;
44using pv::data::decode::Annotation;
6a26fc44 45using pv::data::decode::AnnotationClass;
a82325d1 46using pv::data::decode::DecodeChannel;
ad908057 47using pv::data::decode::Decoder;
ecd07c20 48using pv::data::decode::Row;
ad908057
SA
49
50namespace pv {
51namespace data {
52
47747218
SA
53const double DecodeSignal::DecodeMargin = 1.0;
54const double DecodeSignal::DecodeThreshold = 0.2;
3fbddf7f 55const int64_t DecodeSignal::DecodeChunkLength = 256 * 1024;
ad908057 56
ad908057 57
47747218
SA
58DecodeSignal::DecodeSignal(pv::Session &session) :
59 SignalBase(nullptr, SignalBase::DecodeChannel),
60 session_(session),
e91883bb 61 srd_session_(nullptr),
47747218 62 logic_mux_data_invalid_(false),
e3202557 63 stack_config_changed_(true),
8a603e13 64 current_segment_id_(0)
ad908057 65{
47747218
SA
66 connect(&session_, SIGNAL(capture_state_changed(int)),
67 this, SLOT(on_capture_state_changed(int)));
ad908057
SA
68}
69
47747218 70DecodeSignal::~DecodeSignal()
ad908057 71{
8ce0e732 72 reset_decode(true);
ad908057
SA
73}
74
47747218 75const vector< shared_ptr<Decoder> >& DecodeSignal::decoder_stack() const
ecd07c20 76{
47747218 77 return stack_;
ecd07c20
SA
78}
79
ed75426f 80void DecodeSignal::stack_decoder(const srd_decoder *decoder, bool restart_decode)
ad908057
SA
81{
82 assert(decoder);
762ab7a4 83
b9591f3a 84 // Set name if this decoder is the first in the list or the name is unchanged
6a26fc44
SA
85 const srd_decoder* prev_dec = stack_.empty() ? nullptr : stack_.back()->get_srd_decoder();
86 const QString prev_dec_name = prev_dec ? QString::fromUtf8(prev_dec->name) : QString();
47747218 87
b9591f3a 88 if ((stack_.empty()) || ((stack_.size() > 0) && (name() == prev_dec_name)))
47747218 89 set_name(QString::fromUtf8(decoder->name));
132a5c6d 90
6a26fc44 91 const shared_ptr<Decoder> dec = make_shared<Decoder>(decoder);
b9591f3a
SA
92 stack_.push_back(dec);
93
27a3f09b 94 // Include the newly created decode channels in the channel lists
9f97b357 95 update_channel_list();
132a5c6d 96
e3202557 97 stack_config_changed_ = true;
762ab7a4 98 auto_assign_signals(dec);
27a3f09b 99 commit_decoder_channels();
e77de61f
SA
100
101 decoder_stacked((void*)dec.get());
102
ed75426f
SA
103 if (restart_decode)
104 begin_decode();
ad908057
SA
105}
106
107void DecodeSignal::remove_decoder(int index)
108{
47747218
SA
109 assert(index >= 0);
110 assert(index < (int)stack_.size());
111
112 // Find the decoder in the stack
113 auto iter = stack_.begin();
114 for (int i = 0; i < index; i++, iter++)
115 assert(iter != stack_.end());
116
e77de61f
SA
117 decoder_removed(iter->get());
118
47747218
SA
119 // Delete the element
120 stack_.erase(iter);
121
122 // Update channels and decoded data
e3202557 123 stack_config_changed_ = true;
9f97b357 124 update_channel_list();
47747218 125 begin_decode();
ad908057
SA
126}
127
128bool DecodeSignal::toggle_decoder_visibility(int index)
129{
47747218 130 auto iter = stack_.cbegin();
ad908057 131 for (int i = 0; i < index; i++, iter++)
47747218 132 assert(iter != stack_.end());
ad908057
SA
133
134 shared_ptr<Decoder> dec = *iter;
135
136 // Toggle decoder visibility
137 bool state = false;
138 if (dec) {
139 state = !dec->shown();
140 dec->show(state);
141 }
142
143 return state;
144}
145
8ce0e732 146void DecodeSignal::reset_decode(bool shutting_down)
47747218 147{
8ce0e732 148 if (stack_config_changed_ || shutting_down)
e3202557
SA
149 stop_srd_session();
150 else
151 terminate_srd_session();
ce0b6a40 152
1b56c646
SA
153 if (decode_thread_.joinable()) {
154 decode_interrupt_ = true;
155 decode_input_cond_.notify_one();
156 decode_thread_.join();
157 }
158
159 if (logic_mux_thread_.joinable()) {
160 logic_mux_interrupt_ = true;
161 logic_mux_cond_.notify_one();
162 logic_mux_thread_.join();
163 }
164
dda88657 165 resume_decode(); // Make sure the decode thread isn't blocked by pausing
556259d2 166
8a603e13 167 current_segment_id_ = 0;
72435789 168 segments_.clear();
1b56c646
SA
169
170 logic_mux_data_.reset();
171 logic_mux_data_invalid_ = true;
eee3eab9 172
403c3e87
SA
173 if (!error_message_.isEmpty()) {
174 error_message_ = QString();
fe060a48
SA
175 // TODO Emulate noquote()
176 qDebug().nospace() << name() << ": Error cleared";
403c3e87 177 }
72435789 178
eee3eab9 179 decode_reset();
47747218
SA
180}
181
946b52e1
SA
182void DecodeSignal::begin_decode()
183{
47747218
SA
184 if (decode_thread_.joinable()) {
185 decode_interrupt_ = true;
186 decode_input_cond_.notify_one();
187 decode_thread_.join();
188 }
189
190 if (logic_mux_thread_.joinable()) {
191 logic_mux_interrupt_ = true;
192 logic_mux_cond_.notify_one();
193 logic_mux_thread_.join();
194 }
195
196 reset_decode();
197
27a3f09b 198 if (stack_.size() == 0) {
403c3e87 199 set_error_message(tr("No decoders"));
27a3f09b
SA
200 return;
201 }
202
203 assert(channels_.size() > 0);
204
205 if (get_assigned_signal_count() == 0) {
403c3e87 206 set_error_message(tr("There are no channels assigned to this decoder"));
27a3f09b
SA
207 return;
208 }
209
04627946
SA
210 // Make sure that all assigned channels still provide logic data
211 // (can happen when a converted signal was assigned but the
212 // conversion removed in the meanwhile)
a82325d1 213 for (decode::DecodeChannel& ch : channels_)
04627946
SA
214 if (ch.assigned_signal && !(ch.assigned_signal->logic_data() != nullptr))
215 ch.assigned_signal = nullptr;
216
47747218 217 // Check that all decoders have the required channels
6a26fc44 218 for (const shared_ptr<Decoder>& dec : stack_)
47747218 219 if (!dec->have_required_channels()) {
403c3e87
SA
220 set_error_message(tr("One or more required channels "
221 "have not been specified"));
47747218
SA
222 return;
223 }
224
27a3f09b
SA
225 // Free the logic data and its segment(s) if it needs to be updated
226 if (logic_mux_data_invalid_)
227 logic_mux_data_.reset();
228
229 if (!logic_mux_data_) {
72435789 230 const uint32_t ch_count = get_assigned_signal_count();
ed535cd7 231 logic_mux_unit_size_ = (ch_count + 7) / 8;
27a3f09b 232 logic_mux_data_ = make_shared<Logic>(ch_count);
27a3f09b 233 }
47747218 234
ed535cd7
SA
235 // Receive notifications when new sample data is available
236 connect_input_notifiers();
237
8a603e13 238 if (get_input_segment_count() == 0) {
403c3e87 239 set_error_message(tr("No input data"));
ed535cd7
SA
240 return;
241 }
242
27a3f09b
SA
243 // Make sure the logic output data is complete and up-to-date
244 logic_mux_interrupt_ = false;
245 logic_mux_thread_ = std::thread(&DecodeSignal::logic_mux_proc, this);
246
247 // Decode the muxed logic data
47747218
SA
248 decode_interrupt_ = false;
249 decode_thread_ = std::thread(&DecodeSignal::decode_proc, this);
946b52e1
SA
250}
251
556259d2
SA
252void DecodeSignal::pause_decode()
253{
254 decode_paused_ = true;
255}
256
257void DecodeSignal::resume_decode()
258{
259 // Manual unlocking is done before notifying, to avoid waking up the
260 // waiting thread only to block again (see notify_one for details)
261 decode_pause_mutex_.unlock();
262 decode_pause_cond_.notify_one();
263 decode_paused_ = false;
264}
265
266bool DecodeSignal::is_paused() const
267{
268 return decode_paused_;
269}
270
ecd07c20
SA
271QString DecodeSignal::error_message() const
272{
47747218
SA
273 lock_guard<mutex> lock(output_mutex_);
274 return error_message_;
ecd07c20
SA
275}
276
a82325d1 277const vector<decode::DecodeChannel> DecodeSignal::get_channels() const
9f97b357
SA
278{
279 return channels_;
280}
281
762ab7a4 282void DecodeSignal::auto_assign_signals(const shared_ptr<Decoder> dec)
132a5c6d 283{
47747218
SA
284 bool new_assignment = false;
285
132a5c6d 286 // Try to auto-select channels that don't have signals assigned yet
a82325d1 287 for (decode::DecodeChannel& ch : channels_) {
762ab7a4
SA
288 // If a decoder is given, auto-assign only its channels
289 if (dec && (ch.decoder_ != dec))
290 continue;
291
132a5c6d
SA
292 if (ch.assigned_signal)
293 continue;
294
c526a8fd
SA
295 QString ch_name = ch.name.toLower();
296 ch_name = ch_name.replace(QRegExp("[-_.]"), " ");
a8030bb0
SA
297
298 shared_ptr<data::SignalBase> match;
f4ab4b5c 299 for (const shared_ptr<data::SignalBase>& s : session_.signalbases()) {
f9ebf303
SA
300 if (!s->enabled())
301 continue;
302
c526a8fd
SA
303 QString s_name = s->name().toLower();
304 s_name = s_name.replace(QRegExp("[-_.]"), " ");
692f6093
SA
305
306 if (s->logic_data() &&
307 ((ch_name.contains(s_name)) || (s_name.contains(ch_name)))) {
a8030bb0
SA
308 if (!match)
309 match = s;
310 else {
311 // Only replace an existing match if it matches more characters
312 int old_unmatched = ch_name.length() - match->name().length();
313 int new_unmatched = ch_name.length() - s->name().length();
314 if (abs(new_unmatched) < abs(old_unmatched))
315 match = s;
316 }
47747218 317 }
692f6093 318 }
a8030bb0
SA
319
320 if (match) {
321 ch.assigned_signal = match.get();
322 new_assignment = true;
323 }
47747218
SA
324 }
325
326 if (new_assignment) {
327 logic_mux_data_invalid_ = true;
e3202557 328 stack_config_changed_ = true;
27a3f09b 329 commit_decoder_channels();
47747218 330 channels_updated();
132a5c6d
SA
331 }
332}
333
9f97b357
SA
334void DecodeSignal::assign_signal(const uint16_t channel_id, const SignalBase *signal)
335{
a82325d1 336 for (decode::DecodeChannel& ch : channels_)
47747218 337 if (ch.id == channel_id) {
9f97b357 338 ch.assigned_signal = signal;
47747218
SA
339 logic_mux_data_invalid_ = true;
340 }
9f97b357 341
e3202557 342 stack_config_changed_ = true;
27a3f09b 343 commit_decoder_channels();
9f97b357 344 channels_updated();
47747218 345 begin_decode();
9f97b357
SA
346}
347
27a3f09b
SA
348int DecodeSignal::get_assigned_signal_count() const
349{
350 // Count all channels that have a signal assigned to them
351 return count_if(channels_.begin(), channels_.end(),
a82325d1 352 [](decode::DecodeChannel ch) { return ch.assigned_signal; });
27a3f09b
SA
353}
354
9f97b357
SA
355void DecodeSignal::set_initial_pin_state(const uint16_t channel_id, const int init_state)
356{
a82325d1 357 for (decode::DecodeChannel& ch : channels_)
9f97b357
SA
358 if (ch.id == channel_id)
359 ch.initial_pin_state = init_state;
360
e3202557 361 stack_config_changed_ = true;
9f97b357 362 channels_updated();
47747218 363 begin_decode();
9f97b357
SA
364}
365
ff83d980
SA
366double DecodeSignal::samplerate() const
367{
72435789
SA
368 double result = 0;
369
370 // TODO For now, we simply return the first samplerate that we have
8a603e13
SA
371 if (segments_.size() > 0)
372 result = segments_.front().samplerate;
72435789
SA
373
374 return result;
ff83d980
SA
375}
376
72435789 377const pv::util::Timestamp DecodeSignal::start_time() const
ff83d980 378{
72435789
SA
379 pv::util::Timestamp result;
380
381 // TODO For now, we simply return the first start time that we have
8a603e13
SA
382 if (segments_.size() > 0)
383 result = segments_.front().start_time;
72435789
SA
384
385 return result;
ff83d980
SA
386}
387
5ecf957f 388int64_t DecodeSignal::get_working_sample_count(uint32_t segment_id) const
0c5fe73e
SA
389{
390 // The working sample count is the highest sample number for
ed535cd7
SA
391 // which all used signals have data available, so go through all
392 // channels and use the lowest overall sample count of the segment
0c5fe73e 393
0c5fe73e
SA
394 int64_t count = std::numeric_limits<int64_t>::max();
395 bool no_signals_assigned = true;
396
a82325d1 397 for (const decode::DecodeChannel& ch : channels_)
0c5fe73e
SA
398 if (ch.assigned_signal) {
399 no_signals_assigned = false;
400
401 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
402 if (!logic_data || logic_data->logic_segments().empty())
403 return 0;
404
5ecf957f
SA
405 try {
406 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
407 count = min(count, (int64_t)segment->get_sample_count());
30677c13 408 } catch (out_of_range&) {
5ecf957f
SA
409 return 0;
410 }
0c5fe73e
SA
411 }
412
413 return (no_signals_assigned ? 0 : count);
414}
415
b82908ab
SA
416int64_t DecodeSignal::get_decoded_sample_count(uint32_t segment_id,
417 bool include_processing) const
ff83d980 418{
47747218 419 lock_guard<mutex> decode_lock(output_mutex_);
5ecf957f
SA
420
421 int64_t result = 0;
422
c8a6db0e
SA
423 if (segment_id >= segments_.size())
424 return result;
425
426 if (include_processing)
427 result = segments_[segment_id].samples_decoded_incl;
428 else
429 result = segments_[segment_id].samples_decoded_excl;
5ecf957f
SA
430
431 return result;
ff83d980
SA
432}
433
6a26fc44 434vector<Row*> DecodeSignal::get_rows(bool visible_only)
ecd07c20 435{
6a26fc44 436 vector<Row*> rows;
47747218 437
6a26fc44 438 for (const shared_ptr<Decoder>& dec : stack_) {
47747218 439 assert(dec);
cbb2e4da
SA
440 if (visible_only && !dec->shown())
441 continue;
442
6a26fc44
SA
443 for (Row* row : dec->get_rows())
444 rows.push_back(row);
445 }
47747218 446
6a26fc44
SA
447 return rows;
448}
47747218 449
6a26fc44
SA
450vector<const Row*> DecodeSignal::get_rows(bool visible_only) const
451{
452 vector<const Row*> rows;
453
454 for (const shared_ptr<Decoder>& dec : stack_) {
455 assert(dec);
456 if (visible_only && !dec->shown())
457 continue;
458
459 for (const Row* row : dec->get_rows())
460 rows.push_back(row);
47747218
SA
461 }
462
463 return rows;
ecd07c20
SA
464}
465
6a26fc44
SA
466
467uint64_t DecodeSignal::get_annotation_count(const Row* row, uint32_t segment_id) const
f994f496
SA
468{
469 if (segment_id >= segments_.size())
470 return 0;
471
6a26fc44 472 const DecodeSegment* segment = &(segments_.at(segment_id));
f994f496 473
6a26fc44 474 auto row_it = segment->annotation_rows.find(row);
f994f496 475
6a26fc44
SA
476 const RowData* rd;
477 if (row_it == segment->annotation_rows.end()) {
478 // FIXME Use the fallback row, but how?
479 assert(false);
480 return 0;
481 } else
482 rd = &(row_it->second);
483
484 return rd->get_annotation_count();
f994f496
SA
485}
486
6a26fc44
SA
487void DecodeSignal::get_annotation_subset(vector<Annotation> &dest,
488 const Row* row, uint32_t segment_id, uint64_t start_sample,
ecd07c20
SA
489 uint64_t end_sample) const
490{
47747218
SA
491 lock_guard<mutex> lock(output_mutex_);
492
c8a6db0e
SA
493 if (segment_id >= segments_.size())
494 return;
72435789 495
6a26fc44
SA
496 const DecodeSegment* segment = &(segments_.at(segment_id));
497
498 auto row_it = segment->annotation_rows.find(row);
c8a6db0e 499
6a26fc44
SA
500 const RowData* rd;
501 if (row_it == segment->annotation_rows.end()) {
502 // FIXME Use the fallback row, but how?
503 assert(false);
504 return;
505 } else
506 rd = &(row_it->second);
507
508 rd->get_annotation_subset(dest, start_sample, end_sample);
47747218
SA
509}
510
6a26fc44 511void DecodeSignal::get_annotation_subset(vector<Annotation> &dest,
5a914348
SA
512 uint32_t segment_id, uint64_t start_sample, uint64_t end_sample) const
513{
5a914348
SA
514 // Use forward_lists for faster merging
515 forward_list<Annotation> *all_ann_list = new forward_list<Annotation>();
516
6a26fc44
SA
517 vector<const Row*> rows = get_rows();
518 for (const Row* row : rows) {
5a914348
SA
519 vector<Annotation> *ann_vector = new vector<Annotation>();
520 get_annotation_subset(*ann_vector, row, segment_id, start_sample, end_sample);
521
522 forward_list<Annotation> *ann_list =
523 new forward_list<Annotation>(ann_vector->begin(), ann_vector->end());
524 delete ann_vector;
525
526 all_ann_list->merge(*ann_list);
527 delete ann_list;
528 }
529
530 move(all_ann_list->begin(), all_ann_list->end(), back_inserter(dest));
531 delete all_ann_list;
532}
533
e77de61f 534uint32_t DecodeSignal::get_binary_data_chunk_count(uint32_t segment_id,
ac9494ef 535 const Decoder* dec, uint32_t bin_class_id) const
c0c3e62a 536{
c8a6db0e
SA
537 if (segments_.size() == 0)
538 return 0;
539
c0c3e62a
SA
540 try {
541 const DecodeSegment *segment = &(segments_.at(segment_id));
e77de61f
SA
542
543 for (const DecodeBinaryClass& bc : segment->binary_classes)
544 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
545 return bc.chunks.size();
c0c3e62a
SA
546 } catch (out_of_range&) {
547 // Do nothing
548 }
549
e77de61f 550 return 0;
c0c3e62a
SA
551}
552
e77de61f 553void DecodeSignal::get_binary_data_chunk(uint32_t segment_id,
ac9494ef 554 const Decoder* dec, uint32_t bin_class_id, uint32_t chunk_id,
c0c3e62a
SA
555 const vector<uint8_t> **dest, uint64_t *size)
556{
557 try {
558 const DecodeSegment *segment = &(segments_.at(segment_id));
e77de61f
SA
559
560 for (const DecodeBinaryClass& bc : segment->binary_classes)
561 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id)) {
562 if (dest) *dest = &(bc.chunks.at(chunk_id).data);
563 if (size) *size = bc.chunks.at(chunk_id).data.size();
564 return;
565 }
c0c3e62a
SA
566 } catch (out_of_range&) {
567 // Do nothing
568 }
569}
570
13b726cd 571void DecodeSignal::get_merged_binary_data_chunks_by_sample(uint32_t segment_id,
ac9494ef 572 const Decoder* dec, uint32_t bin_class_id, uint64_t start_sample,
e77de61f 573 uint64_t end_sample, vector<uint8_t> *dest) const
c0c3e62a
SA
574{
575 assert(dest != nullptr);
576
577 try {
578 const DecodeSegment *segment = &(segments_.at(segment_id));
579
e77de61f
SA
580 const DecodeBinaryClass* bin_class = nullptr;
581 for (const DecodeBinaryClass& bc : segment->binary_classes)
582 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
583 bin_class = &bc;
584
c0c3e62a
SA
585 // Determine overall size before copying to resize dest vector only once
586 uint64_t size = 0;
163f3499 587 uint64_t matches = 0;
e77de61f
SA
588 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
589 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
590 size += chunk.data.size();
4b97fe09
SA
591 matches++;
592 }
593 dest->resize(size);
c0c3e62a 594
163f3499
SA
595 uint64_t offset = 0;
596 uint64_t matches2 = 0;
e77de61f
SA
597 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks)
598 if ((chunk.sample >= start_sample) && (chunk.sample < end_sample)) {
599 memcpy(dest->data() + offset, chunk.data.data(), chunk.data.size());
600 offset += chunk.data.size();
163f3499
SA
601 matches2++;
602
603 // Make sure we don't overwrite memory if the array grew in the meanwhile
604 if (matches2 == matches)
605 break;
c0c3e62a
SA
606 }
607 } catch (out_of_range&) {
608 // Do nothing
609 }
610}
611
13b726cd 612void DecodeSignal::get_merged_binary_data_chunks_by_offset(uint32_t segment_id,
6a26fc44
SA
613 const Decoder* dec, uint32_t bin_class_id, uint64_t start, uint64_t end,
614 vector<uint8_t> *dest) const
13b726cd
SA
615{
616 assert(dest != nullptr);
617
618 try {
619 const DecodeSegment *segment = &(segments_.at(segment_id));
620
621 const DecodeBinaryClass* bin_class = nullptr;
622 for (const DecodeBinaryClass& bc : segment->binary_classes)
623 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
624 bin_class = &bc;
625
626 // Determine overall size before copying to resize dest vector only once
627 uint64_t size = 0;
628 uint64_t offset = 0;
629 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
630 if (offset >= start)
631 size += chunk.data.size();
632 offset += chunk.data.size();
633 if (offset >= end)
634 break;
635 }
636 dest->resize(size);
637
638 offset = 0;
639 uint64_t dest_offset = 0;
640 for (const DecodeBinaryDataChunk& chunk : bin_class->chunks) {
641 if (offset >= start) {
642 memcpy(dest->data() + dest_offset, chunk.data.data(), chunk.data.size());
643 dest_offset += chunk.data.size();
644 }
645 offset += chunk.data.size();
646 if (offset >= end)
647 break;
648 }
649 } catch (out_of_range&) {
650 // Do nothing
651 }
652}
653
628b45cc 654const DecodeBinaryClass* DecodeSignal::get_binary_data_class(uint32_t segment_id,
6a26fc44 655 const Decoder* dec, uint32_t bin_class_id) const
628b45cc
SA
656{
657 try {
658 const DecodeSegment *segment = &(segments_.at(segment_id));
659
660 for (const DecodeBinaryClass& bc : segment->binary_classes)
661 if ((bc.decoder == dec) && (bc.info->bin_class_id == bin_class_id))
662 return &bc;
663 } catch (out_of_range&) {
664 // Do nothing
665 }
666
667 return nullptr;
668}
c0c3e62a 669
47747218
SA
670void DecodeSignal::save_settings(QSettings &settings) const
671{
672 SignalBase::save_settings(settings);
673
c8e60bdf
SA
674 settings.setValue("decoders", (int)(stack_.size()));
675
8b5ea5a1 676 // Save decoder stack
c8e60bdf 677 int decoder_idx = 0;
6a26fc44 678 for (const shared_ptr<Decoder>& decoder : stack_) {
c8e60bdf
SA
679 settings.beginGroup("decoder" + QString::number(decoder_idx++));
680
6a26fc44 681 settings.setValue("id", decoder->get_srd_decoder()->id);
722c7624 682 settings.setValue("shown", decoder->shown());
c8e60bdf 683
d3feec23
SA
684 // Save decoder options
685 const map<string, GVariant*>& options = decoder->options();
686
687 settings.setValue("options", (int)options.size());
688
6a26fc44 689 // Note: Decoder::options() returns only the options
d3feec23
SA
690 // that differ from the default. See binding::Decoder::getter()
691 int i = 0;
f4ab4b5c 692 for (auto& option : options) {
d3feec23
SA
693 settings.beginGroup("option" + QString::number(i));
694 settings.setValue("name", QString::fromStdString(option.first));
695 GlobalSettings::store_gvariant(settings, option.second);
696 settings.endGroup();
697 i++;
698 }
699
c8e60bdf
SA
700 settings.endGroup();
701 }
702
8b5ea5a1
SA
703 // Save channel mapping
704 settings.setValue("channels", (int)channels_.size());
705
706 for (unsigned int channel_id = 0; channel_id < channels_.size(); channel_id++) {
707 auto channel = find_if(channels_.begin(), channels_.end(),
a82325d1 708 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
8b5ea5a1
SA
709
710 if (channel == channels_.end()) {
711 qDebug() << "ERROR: Gap in channel index:" << channel_id;
712 continue;
713 }
714
715 settings.beginGroup("channel" + QString::number(channel_id));
716
717 settings.setValue("name", channel->name); // Useful for debugging
718 settings.setValue("initial_pin_state", channel->initial_pin_state);
719
720 if (channel->assigned_signal)
721 settings.setValue("assigned_signal_name", channel->assigned_signal->name());
722
723 settings.endGroup();
724 }
47747218
SA
725}
726
727void DecodeSignal::restore_settings(QSettings &settings)
728{
729 SignalBase::restore_settings(settings);
730
8b5ea5a1 731 // Restore decoder stack
c8e60bdf
SA
732 GSList *dec_list = g_slist_copy((GSList*)srd_decoder_list());
733
734 int decoders = settings.value("decoders").toInt();
735
736 for (int decoder_idx = 0; decoder_idx < decoders; decoder_idx++) {
737 settings.beginGroup("decoder" + QString::number(decoder_idx));
738
739 QString id = settings.value("id").toString();
740
741 for (GSList *entry = dec_list; entry; entry = entry->next) {
742 const srd_decoder *dec = (srd_decoder*)entry->data;
743 if (!dec)
744 continue;
745
746 if (QString::fromUtf8(dec->id) == id) {
6a26fc44 747 shared_ptr<Decoder> decoder = make_shared<Decoder>(dec);
d3feec23
SA
748
749 stack_.push_back(decoder);
722c7624 750 decoder->show(settings.value("shown", true).toBool());
d3feec23
SA
751
752 // Restore decoder options that differ from their default
753 int options = settings.value("options").toInt();
754
755 for (int i = 0; i < options; i++) {
756 settings.beginGroup("option" + QString::number(i));
757 QString name = settings.value("name").toString();
758 GVariant *value = GlobalSettings::restore_gvariant(settings);
759 decoder->set_option(name.toUtf8(), value);
760 settings.endGroup();
761 }
c8e60bdf
SA
762
763 // Include the newly created decode channels in the channel lists
764 update_channel_list();
765 break;
766 }
767 }
768
769 settings.endGroup();
4ca06ec3 770 channels_updated();
c8e60bdf
SA
771 }
772
8b5ea5a1
SA
773 // Restore channel mapping
774 unsigned int channels = settings.value("channels").toInt();
775
776 const unordered_set< shared_ptr<data::SignalBase> > signalbases =
777 session_.signalbases();
778
779 for (unsigned int channel_id = 0; channel_id < channels; channel_id++) {
780 auto channel = find_if(channels_.begin(), channels_.end(),
a82325d1 781 [&](decode::DecodeChannel ch) { return ch.id == channel_id; });
8b5ea5a1
SA
782
783 if (channel == channels_.end()) {
784 qDebug() << "ERROR: Non-existant channel index:" << channel_id;
785 continue;
786 }
787
788 settings.beginGroup("channel" + QString::number(channel_id));
789
790 QString assigned_signal_name = settings.value("assigned_signal_name").toString();
791
f4ab4b5c 792 for (const shared_ptr<data::SignalBase>& signal : signalbases)
8b5ea5a1
SA
793 if (signal->name() == assigned_signal_name)
794 channel->assigned_signal = signal.get();
795
796 channel->initial_pin_state = settings.value("initial_pin_state").toInt();
797
798 settings.endGroup();
799 }
800
aa71890d 801 // Update the internal structures
e3202557 802 stack_config_changed_ = true;
aa71890d
SA
803 update_channel_list();
804 commit_decoder_channels();
805
8b5ea5a1 806 begin_decode();
47747218
SA
807}
808
403c3e87
SA
809void DecodeSignal::set_error_message(QString msg)
810{
811 error_message_ = msg;
fe060a48
SA
812 // TODO Emulate noquote()
813 qDebug().nospace() << name() << ": " << msg;
403c3e87
SA
814}
815
8a603e13
SA
816uint32_t DecodeSignal::get_input_segment_count() const
817{
818 uint64_t count = std::numeric_limits<uint64_t>::max();
819 bool no_signals_assigned = true;
820
a82325d1 821 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
822 if (ch.assigned_signal) {
823 no_signals_assigned = false;
824
825 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
826 if (!logic_data || logic_data->logic_segments().empty())
827 return 0;
828
829 // Find the min value of all segment counts
830 if ((uint64_t)(logic_data->logic_segments().size()) < count)
831 count = logic_data->logic_segments().size();
832 }
833
834 return (no_signals_assigned ? 0 : count);
835}
836
837uint32_t DecodeSignal::get_input_samplerate(uint32_t segment_id) const
838{
839 double samplerate = 0;
840
a82325d1 841 for (const decode::DecodeChannel& ch : channels_)
8a603e13
SA
842 if (ch.assigned_signal) {
843 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
844 if (!logic_data || logic_data->logic_segments().empty())
845 continue;
846
847 try {
848 const shared_ptr<LogicSegment> segment = logic_data->logic_segments().at(segment_id);
849 samplerate = segment->samplerate();
30677c13 850 } catch (out_of_range&) {
8a603e13
SA
851 // Do nothing
852 }
853 break;
854 }
855
856 return samplerate;
857}
858
6a26fc44
SA
859Decoder* DecodeSignal::get_decoder_by_instance(const srd_decoder *const srd_dec)
860{
861 for (shared_ptr<Decoder>& d : stack_)
862 if (d->get_srd_decoder() == srd_dec)
863 return d.get();
864
865 return nullptr;
866}
867
9f97b357
SA
868void DecodeSignal::update_channel_list()
869{
a82325d1 870 vector<decode::DecodeChannel> prev_channels = channels_;
9f97b357
SA
871 channels_.clear();
872
873 uint16_t id = 0;
874
875 // Copy existing entries, create new as needed
f4ab4b5c 876 for (shared_ptr<Decoder>& decoder : stack_) {
6a26fc44 877 const srd_decoder* srd_dec = decoder->get_srd_decoder();
9f97b357
SA
878 const GSList *l;
879
880 // Mandatory channels
6a26fc44 881 for (l = srd_dec->channels; l; l = l->next) {
9f97b357
SA
882 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
883 bool ch_added = false;
884
885 // Copy but update ID if this channel was in the list before
a82325d1 886 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
887 if (ch.pdch_ == pdch) {
888 ch.id = id++;
889 channels_.push_back(ch);
890 ch_added = true;
891 break;
892 }
893
894 if (!ch_added) {
895 // Create new entry without a mapped signal
a82325d1 896 decode::DecodeChannel ch = {id++, 0, false, nullptr,
9f97b357
SA
897 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
898 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
899 channels_.push_back(ch);
900 }
901 }
902
903 // Optional channels
6a26fc44 904 for (l = srd_dec->opt_channels; l; l = l->next) {
9f97b357
SA
905 const struct srd_channel *const pdch = (struct srd_channel *)l->data;
906 bool ch_added = false;
907
908 // Copy but update ID if this channel was in the list before
a82325d1 909 for (decode::DecodeChannel& ch : prev_channels)
9f97b357
SA
910 if (ch.pdch_ == pdch) {
911 ch.id = id++;
912 channels_.push_back(ch);
913 ch_added = true;
914 break;
915 }
916
917 if (!ch_added) {
918 // Create new entry without a mapped signal
a82325d1 919 decode::DecodeChannel ch = {id++, 0, true, nullptr,
9f97b357
SA
920 QString::fromUtf8(pdch->name), QString::fromUtf8(pdch->desc),
921 SRD_INITIAL_PIN_SAME_AS_SAMPLE0, decoder, pdch};
922 channels_.push_back(ch);
923 }
924 }
925 }
926
47747218
SA
927 // Invalidate the logic output data if the channel assignment changed
928 if (prev_channels.size() != channels_.size()) {
929 // The number of channels changed, there's definitely a difference
930 logic_mux_data_invalid_ = true;
931 } else {
932 // Same number but assignment may still differ, so compare all channels
933 for (size_t i = 0; i < channels_.size(); i++) {
a82325d1
SA
934 const decode::DecodeChannel& p_ch = prev_channels[i];
935 const decode::DecodeChannel& ch = channels_[i];
47747218
SA
936
937 if ((p_ch.pdch_ != ch.pdch_) ||
938 (p_ch.assigned_signal != ch.assigned_signal)) {
939 logic_mux_data_invalid_ = true;
940 break;
941 }
942 }
943
944 }
945
9f97b357
SA
946 channels_updated();
947}
948
27a3f09b 949void DecodeSignal::commit_decoder_channels()
ad908057 950{
27a3f09b 951 // Submit channel list to every decoder, containing only the relevant channels
6a26fc44 952 for (shared_ptr<Decoder> dec : stack_) {
a82325d1 953 vector<decode::DecodeChannel*> channel_list;
27a3f09b 954
a82325d1 955 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
956 if (ch.decoder_ == dec)
957 channel_list.push_back(&ch);
47747218 958
27a3f09b
SA
959 dec->set_channels(channel_list);
960 }
aa71890d
SA
961
962 // Channel bit IDs must be in sync with the channel's apperance in channels_
963 int id = 0;
a82325d1 964 for (decode::DecodeChannel& ch : channels_)
aa71890d
SA
965 if (ch.assigned_signal)
966 ch.bit_id = id++;
47747218
SA
967}
968
ed535cd7 969void DecodeSignal::mux_logic_samples(uint32_t segment_id, const int64_t start, const int64_t end)
47747218 970{
27a3f09b
SA
971 // Enforce end to be greater than start
972 if (end <= start)
973 return;
974
ed535cd7 975 // Fetch the channel segments and their data
27a3f09b
SA
976 vector<shared_ptr<LogicSegment> > segments;
977 vector<const uint8_t*> signal_data;
978 vector<uint8_t> signal_in_bytepos;
979 vector<uint8_t> signal_in_bitpos;
980
a82325d1 981 for (decode::DecodeChannel& ch : channels_)
27a3f09b
SA
982 if (ch.assigned_signal) {
983 const shared_ptr<Logic> logic_data = ch.assigned_signal->logic_data();
ed535cd7
SA
984
985 shared_ptr<LogicSegment> segment;
986 try {
987 segment = logic_data->logic_segments().at(segment_id);
30677c13 988 } catch (out_of_range&) {
ed535cd7
SA
989 qDebug() << "Muxer error for" << name() << ":" << ch.assigned_signal->name() \
990 << "has no logic segment" << segment_id;
991 return;
992 }
27a3f09b 993 segments.push_back(segment);
b82243f7
SA
994
995 uint8_t* data = new uint8_t[(end - start) * segment->unit_size()];
996 segment->get_samples(start, end, data);
997 signal_data.push_back(data);
27a3f09b
SA
998
999 const int bitpos = ch.assigned_signal->logic_bit_index();
1000 signal_in_bytepos.push_back(bitpos / 8);
1001 signal_in_bitpos.push_back(bitpos % 8);
1002 }
1003
ed535cd7
SA
1004
1005 shared_ptr<LogicSegment> output_segment;
1006 try {
1007 output_segment = logic_mux_data_->logic_segments().at(segment_id);
30677c13 1008 } catch (out_of_range&) {
ed535cd7
SA
1009 qDebug() << "Muxer error for" << name() << ": no logic mux segment" \
1010 << segment_id << "in mux_logic_samples(), mux segments size is" \
1011 << logic_mux_data_->logic_segments().size();
1012 return;
1013 }
1014
27a3f09b 1015 // Perform the muxing of signal data into the output data
8a603e13 1016 uint8_t* output = new uint8_t[(end - start) * output_segment->unit_size()];
27a3f09b
SA
1017 unsigned int signal_count = signal_data.size();
1018
3b5282a2
SA
1019 for (int64_t sample_cnt = 0; !logic_mux_interrupt_ && (sample_cnt < (end - start));
1020 sample_cnt++) {
1021
27a3f09b
SA
1022 int bitpos = 0;
1023 uint8_t bytepos = 0;
1024
8a603e13
SA
1025 const int out_sample_pos = sample_cnt * output_segment->unit_size();
1026 for (unsigned int i = 0; i < output_segment->unit_size(); i++)
27a3f09b 1027 output[out_sample_pos + i] = 0;
47747218 1028
27a3f09b
SA
1029 for (unsigned int i = 0; i < signal_count; i++) {
1030 const int in_sample_pos = sample_cnt * segments[i]->unit_size();
1031 const uint8_t in_sample = 1 &
1032 ((signal_data[i][in_sample_pos + signal_in_bytepos[i]]) >> (signal_in_bitpos[i]));
47747218 1033
27a3f09b
SA
1034 const uint8_t out_sample = output[out_sample_pos + bytepos];
1035
1036 output[out_sample_pos + bytepos] = out_sample | (in_sample << bitpos);
1037
1038 bitpos++;
1039 if (bitpos > 7) {
1040 bitpos = 0;
1041 bytepos++;
1042 }
1043 }
47747218
SA
1044 }
1045
8a603e13 1046 output_segment->append_payload(output, (end - start) * output_segment->unit_size());
27a3f09b
SA
1047 delete[] output;
1048
1049 for (const uint8_t* data : signal_data)
1050 delete[] data;
1051}
1052
1053void DecodeSignal::logic_mux_proc()
1054{
ed535cd7
SA
1055 uint32_t segment_id = 0;
1056
8a603e13
SA
1057 assert(logic_mux_data_);
1058
65efd025
SA
1059 // Create initial logic mux segment
1060 shared_ptr<LogicSegment> output_segment =
85a70280
SA
1061 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1062 logic_mux_unit_size_, 0);
65efd025 1063 logic_mux_data_->push_segment(output_segment);
8a603e13
SA
1064
1065 output_segment->set_samplerate(get_input_samplerate(0));
ed535cd7 1066
27a3f09b 1067 do {
ed535cd7 1068 const uint64_t input_sample_count = get_working_sample_count(segment_id);
8a603e13 1069 const uint64_t output_sample_count = output_segment->get_sample_count();
27a3f09b
SA
1070
1071 const uint64_t samples_to_process =
1072 (input_sample_count > output_sample_count) ?
1073 (input_sample_count - output_sample_count) : 0;
1074
1075 // Process the samples if necessary...
1076 if (samples_to_process > 0) {
8a603e13 1077 const uint64_t unit_size = output_segment->unit_size();
27a3f09b
SA
1078 const uint64_t chunk_sample_count = DecodeChunkLength / unit_size;
1079
1080 uint64_t processed_samples = 0;
1081 do {
1082 const uint64_t start_sample = output_sample_count + processed_samples;
1083 const uint64_t sample_count =
1084 min(samples_to_process - processed_samples, chunk_sample_count);
1085
ed535cd7 1086 mux_logic_samples(segment_id, start_sample, start_sample + sample_count);
27a3f09b
SA
1087 processed_samples += sample_count;
1088
1089 // ...and process the newly muxed logic data
1090 decode_input_cond_.notify_one();
3b5282a2 1091 } while (!logic_mux_interrupt_ && (processed_samples < samples_to_process));
27a3f09b
SA
1092 }
1093
1ec191ed 1094 if (samples_to_process == 0) {
ed535cd7
SA
1095 // TODO Optimize this by caching the input segment count and only
1096 // querying it when the cached value was reached
1097 if (segment_id < get_input_segment_count() - 1) {
1098 // Process next segment
1099 segment_id++;
1100
65efd025 1101 output_segment =
85a70280
SA
1102 make_shared<LogicSegment>(*logic_mux_data_, segment_id,
1103 logic_mux_unit_size_, 0);
65efd025 1104 logic_mux_data_->push_segment(output_segment);
ba5f2186 1105
8a603e13
SA
1106 output_segment->set_samplerate(get_input_samplerate(segment_id));
1107
ed535cd7
SA
1108 } else {
1109 // All segments have been processed
1110 logic_mux_data_invalid_ = false;
1111
1112 // Wait for more input
1113 unique_lock<mutex> logic_mux_lock(logic_mux_mutex_);
1114 logic_mux_cond_.wait(logic_mux_lock);
1115 }
27a3f09b 1116 }
1ae18301 1117
1ec191ed 1118 } while (!logic_mux_interrupt_);
47747218
SA
1119}
1120
1121void DecodeSignal::decode_data(
8a603e13
SA
1122 const int64_t abs_start_samplenum, const int64_t sample_count,
1123 const shared_ptr<LogicSegment> input_segment)
47747218 1124{
8a603e13 1125 const int64_t unit_size = input_segment->unit_size();
27a3f09b 1126 const int64_t chunk_sample_count = DecodeChunkLength / unit_size;
47747218
SA
1127
1128 for (int64_t i = abs_start_samplenum;
1ae18301
SA
1129 error_message_.isEmpty() && !decode_interrupt_ &&
1130 (i < (abs_start_samplenum + sample_count));
47747218
SA
1131 i += chunk_sample_count) {
1132
1133 const int64_t chunk_end = min(i + chunk_sample_count,
1134 abs_start_samplenum + sample_count);
1135
e06cf18d
SA
1136 {
1137 lock_guard<mutex> lock(output_mutex_);
b82908ab
SA
1138 // Update the sample count showing the samples including currently processed ones
1139 segments_.at(current_segment_id_).samples_decoded_incl = chunk_end;
e06cf18d
SA
1140 }
1141
b82243f7
SA
1142 int64_t data_size = (chunk_end - i) * unit_size;
1143 uint8_t* chunk = new uint8_t[data_size];
8a603e13 1144 input_segment->get_samples(i, chunk_end, chunk);
47747218 1145
e91883bb 1146 if (srd_session_send(srd_session_, i, chunk_end, chunk,
1ae18301 1147 data_size, unit_size) != SRD_OK)
403c3e87 1148 set_error_message(tr("Decoder reported an error"));
a3ebd556 1149
47747218
SA
1150 delete[] chunk;
1151
b82908ab
SA
1152 {
1153 lock_guard<mutex> lock(output_mutex_);
1154 // Now that all samples are processed, the exclusive sample count catches up
1155 segments_.at(current_segment_id_).samples_decoded_excl = chunk_end;
1156 }
1157
1b56c646
SA
1158 // Notify the frontend that we processed some data and
1159 // possibly have new annotations as well
1160 new_annotations();
556259d2
SA
1161
1162 if (decode_paused_) {
1163 unique_lock<mutex> pause_wait_lock(decode_pause_mutex_);
1164 decode_pause_cond_.wait(pause_wait_lock);
1165 }
47747218
SA
1166 }
1167}
1168
1169void DecodeSignal::decode_proc()
1170{
65efd025
SA
1171 current_segment_id_ = 0;
1172
1173 // If there is no input data available yet, wait until it is or we're interrupted
1174 if (logic_mux_data_->logic_segments().size() == 0) {
1175 unique_lock<mutex> input_wait_lock(input_mutex_);
1176 decode_input_cond_.wait(input_wait_lock);
1177 }
a3ebd556
SA
1178
1179 if (decode_interrupt_)
1180 return;
1181
8a603e13 1182 shared_ptr<LogicSegment> input_segment = logic_mux_data_->logic_segments().front();
8a603e13 1183 assert(input_segment);
65efd025
SA
1184
1185 // Create the initial segment and set its sample rate so that we can pass it to SRD
1186 create_decode_segment();
8a603e13 1187 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 1188 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 1189
65efd025
SA
1190 start_srd_session();
1191
1192 uint64_t sample_count = 0;
27a3f09b 1193 uint64_t abs_start_samplenum = 0;
47747218 1194 do {
27a3f09b
SA
1195 // Keep processing new samples until we exhaust the input data
1196 do {
767bf4e7 1197 lock_guard<mutex> input_lock(input_mutex_);
8a603e13 1198 sample_count = input_segment->get_sample_count() - abs_start_samplenum;
27a3f09b
SA
1199
1200 if (sample_count > 0) {
8a603e13 1201 decode_data(abs_start_samplenum, sample_count, input_segment);
27a3f09b
SA
1202 abs_start_samplenum += sample_count;
1203 }
1b56c646
SA
1204 } while (error_message_.isEmpty() && (sample_count > 0) && !decode_interrupt_);
1205
8a603e13
SA
1206 if (error_message_.isEmpty() && !decode_interrupt_ && sample_count == 0) {
1207 if (current_segment_id_ < logic_mux_data_->logic_segments().size() - 1) {
1208 // Process next segment
1209 current_segment_id_++;
1210
1211 try {
1212 input_segment = logic_mux_data_->logic_segments().at(current_segment_id_);
30677c13 1213 } catch (out_of_range&) {
8a603e13
SA
1214 qDebug() << "Decode error for" << name() << ": no logic mux segment" \
1215 << current_segment_id_ << "in decode_proc(), mux segments size is" \
1216 << logic_mux_data_->logic_segments().size();
1217 return;
1218 }
1219 abs_start_samplenum = 0;
1220
65efd025
SA
1221 // Create the next segment and set its metadata
1222 create_decode_segment();
8a603e13 1223 segments_.at(current_segment_id_).samplerate = input_segment->samplerate();
65efd025 1224 segments_.at(current_segment_id_).start_time = input_segment->start_time();
8a603e13 1225
90ca4cc8
SA
1226 // Reset decoder state but keep the decoder stack intact
1227 terminate_srd_session();
8a603e13
SA
1228 } else {
1229 // All segments have been processed
1b56c646 1230 decode_finished();
27a3f09b 1231
8a603e13
SA
1232 // Wait for new input data or an interrupt was requested
1233 unique_lock<mutex> input_wait_lock(input_mutex_);
1234 decode_input_cond_.wait(input_wait_lock);
1235 }
27a3f09b
SA
1236 }
1237 } while (error_message_.isEmpty() && !decode_interrupt_);
ce0b6a40
GS
1238
1239 // Potentially reap decoders when the application no longer is
1240 // interested in their (pending) results.
1241 if (decode_interrupt_)
1242 terminate_srd_session();
e91883bb
SA
1243}
1244
1245void DecodeSignal::start_srd_session()
1246{
8ce0e732
SA
1247 // If there were stack changes, the session has been destroyed by now, so if
1248 // it hasn't been destroyed, we can just reset and re-use it
ce0b6a40
GS
1249 if (srd_session_) {
1250 // When a decoder stack was created before, re-use it
1251 // for the next stream of input data, after terminating
1252 // potentially still executing operations, and resetting
1253 // internal state. Skip the rather expensive (teardown
1254 // and) construction of another decoder stack.
1255
1256 // TODO Reduce redundancy, use a common code path for
72486b78 1257 // the meta/start sequence?
ce0b6a40 1258 terminate_srd_session();
72486b78
SA
1259
1260 // Metadata is cleared also, so re-set it
ba5b52e1 1261 uint64_t samplerate = 0;
7dd518b8 1262 if (segments_.size() > 0)
ba5b52e1
GS
1263 samplerate = segments_.at(current_segment_id_).samplerate;
1264 if (samplerate)
7dd518b8 1265 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1266 g_variant_new_uint64(samplerate));
6a26fc44 1267 for (const shared_ptr<Decoder>& dec : stack_)
72486b78 1268 dec->apply_all_options();
ce0b6a40 1269 srd_session_start(srd_session_);
72486b78 1270
ce0b6a40
GS
1271 return;
1272 }
e91883bb 1273
a3ebd556
SA
1274 // Create the session
1275 srd_session_new(&srd_session_);
1276 assert(srd_session_);
47747218 1277
a3ebd556
SA
1278 // Create the decoders
1279 srd_decoder_inst *prev_di = nullptr;
6a26fc44 1280 for (const shared_ptr<Decoder>& dec : stack_) {
a3ebd556 1281 srd_decoder_inst *const di = dec->create_decoder_inst(srd_session_);
e91883bb 1282
a3ebd556 1283 if (!di) {
403c3e87 1284 set_error_message(tr("Failed to create decoder instance"));
a3ebd556 1285 srd_session_destroy(srd_session_);
c5f9553c 1286 srd_session_ = nullptr;
a3ebd556
SA
1287 return;
1288 }
e91883bb 1289
a3ebd556
SA
1290 if (prev_di)
1291 srd_inst_stack(srd_session_, prev_di, di);
e91883bb 1292
a3ebd556 1293 prev_di = di;
e91883bb 1294 }
a3ebd556
SA
1295
1296 // Start the session
7dd518b8
SA
1297 if (segments_.size() > 0)
1298 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
1299 g_variant_new_uint64(segments_.at(current_segment_id_).samplerate));
a3ebd556
SA
1300
1301 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_ANN,
1302 DecodeSignal::annotation_callback, this);
1303
c0c3e62a
SA
1304 srd_pd_output_callback_add(srd_session_, SRD_OUTPUT_BINARY,
1305 DecodeSignal::binary_callback, this);
1306
a3ebd556 1307 srd_session_start(srd_session_);
e3202557
SA
1308
1309 // We just recreated the srd session, so all stack changes are applied now
1310 stack_config_changed_ = false;
e91883bb 1311}
47747218 1312
ce0b6a40
GS
1313void DecodeSignal::terminate_srd_session()
1314{
1315 // Call the "terminate and reset" routine for the decoder stack
1316 // (if available). This does not harm those stacks which already
1317 // have completed their operation, and reduces response time for
1318 // those stacks which still are processing data while the
1319 // application no longer wants them to.
72486b78 1320 if (srd_session_) {
ce0b6a40 1321 srd_session_terminate_reset(srd_session_);
72486b78
SA
1322
1323 // Metadata is cleared also, so re-set it
ba5b52e1 1324 uint64_t samplerate = 0;
7dd518b8 1325 if (segments_.size() > 0)
ba5b52e1
GS
1326 samplerate = segments_.at(current_segment_id_).samplerate;
1327 if (samplerate)
7dd518b8 1328 srd_session_metadata_set(srd_session_, SRD_CONF_SAMPLERATE,
ba5b52e1 1329 g_variant_new_uint64(samplerate));
6a26fc44 1330 for (const shared_ptr<Decoder>& dec : stack_)
72486b78
SA
1331 dec->apply_all_options();
1332 }
ce0b6a40
GS
1333}
1334
e91883bb
SA
1335void DecodeSignal::stop_srd_session()
1336{
1337 if (srd_session_) {
1338 // Destroy the session
1339 srd_session_destroy(srd_session_);
1340 srd_session_ = nullptr;
8ce0e732
SA
1341
1342 // Mark the decoder instances as non-existant since they were deleted
6a26fc44 1343 for (const shared_ptr<Decoder>& dec : stack_)
8ce0e732 1344 dec->invalidate_decoder_inst();
e91883bb 1345 }
47747218
SA
1346}
1347
a8a9222d
SA
1348void DecodeSignal::connect_input_notifiers()
1349{
1350 // Disconnect the notification slot from the previous set of signals
1b56c646 1351 disconnect(this, SLOT(on_data_cleared()));
a8a9222d
SA
1352 disconnect(this, SLOT(on_data_received()));
1353
1354 // Connect the currently used signals to our slot
a82325d1 1355 for (decode::DecodeChannel& ch : channels_) {
a8a9222d
SA
1356 if (!ch.assigned_signal)
1357 continue;
1358
1b56c646
SA
1359 const data::SignalBase *signal = ch.assigned_signal;
1360 connect(signal, SIGNAL(samples_cleared()),
1361 this, SLOT(on_data_cleared()));
b10b58f4 1362 connect(signal, SIGNAL(samples_added(uint64_t, uint64_t, uint64_t)),
a8a9222d
SA
1363 this, SLOT(on_data_received()));
1364 }
1365}
1366
65efd025 1367void DecodeSignal::create_decode_segment()
4913560f 1368{
65efd025
SA
1369 // Create annotation segment
1370 segments_.emplace_back(DecodeSegment());
72435789 1371
65efd025 1372 // Add annotation classes
6a26fc44
SA
1373 for (const shared_ptr<Decoder> dec : stack_)
1374 for (Row* row : dec->get_rows())
1375 segments_.back().annotation_rows.emplace(row, RowData(row));
e77de61f
SA
1376
1377 // Prepare our binary output classes
6a26fc44 1378 for (const shared_ptr<Decoder>& dec : stack_) {
ac9494ef 1379 uint32_t n = dec->get_binary_class_count();
e77de61f 1380
ac9494ef 1381 for (uint32_t i = 0; i < n; i++)
e77de61f 1382 segments_.back().binary_classes.push_back(
c8a6db0e 1383 {dec.get(), dec->get_binary_class(i), deque<DecodeBinaryDataChunk>()});
e77de61f 1384 }
4913560f
SA
1385}
1386
47747218
SA
1387void DecodeSignal::annotation_callback(srd_proto_data *pdata, void *decode_signal)
1388{
1389 assert(pdata);
b21501d6 1390 assert(decode_signal);
47747218
SA
1391
1392 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1393 assert(ds);
1394
3b5282a2
SA
1395 if (ds->decode_interrupt_)
1396 return;
1397
47747218
SA
1398 lock_guard<mutex> lock(ds->output_mutex_);
1399
c0c3e62a 1400 // Get the decoder and the annotation data
47747218
SA
1401 assert(pdata->pdo);
1402 assert(pdata->pdo->di);
6a26fc44
SA
1403 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1404 assert(srd_dec);
47747218 1405
c0c3e62a 1406 const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data;
1becee23
UH
1407 assert(pda);
1408
c0c3e62a 1409 // Find the row
6a26fc44
SA
1410 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
1411 assert(dec);
47747218 1412
6a26fc44
SA
1413 AnnotationClass* ann_class = dec->get_ann_class_by_id(pda->ann_class);
1414 assert(ann_class);
1415
1416 const Row* row = ann_class->row;
1417
1418 if (!row)
1419 row = dec->get_row_by_id(0);
47747218
SA
1420
1421 // Add the annotation
6a26fc44 1422 ds->segments_[ds->current_segment_id_].annotation_rows.at(row).emplace_annotation(pdata);
47747218
SA
1423}
1424
c0c3e62a
SA
1425void DecodeSignal::binary_callback(srd_proto_data *pdata, void *decode_signal)
1426{
1427 assert(pdata);
1428 assert(decode_signal);
1429
1430 DecodeSignal *const ds = (DecodeSignal*)decode_signal;
1431 assert(ds);
1432
1433 if (ds->decode_interrupt_)
1434 return;
1435
e77de61f
SA
1436 // Get the decoder and the binary data
1437 assert(pdata->pdo);
1438 assert(pdata->pdo->di);
6a26fc44
SA
1439 const srd_decoder *const srd_dec = pdata->pdo->di->decoder;
1440 assert(srd_dec);
e77de61f 1441
c0c3e62a
SA
1442 const srd_proto_data_binary *const pdb = (const srd_proto_data_binary*)pdata->data;
1443 assert(pdb);
1444
e77de61f 1445 // Find the matching DecodeBinaryClass
c0c3e62a
SA
1446 DecodeSegment* segment = &(ds->segments_.at(ds->current_segment_id_));
1447
e77de61f
SA
1448 DecodeBinaryClass* bin_class = nullptr;
1449 for (DecodeBinaryClass& bc : segment->binary_classes)
6a26fc44
SA
1450 if ((bc.decoder->get_srd_decoder() == srd_dec) &&
1451 (bc.info->bin_class_id == (uint32_t)pdb->bin_class))
e77de61f 1452 bin_class = &bc;
c0c3e62a 1453
e77de61f
SA
1454 if (!bin_class) {
1455 qWarning() << "Could not find valid DecodeBinaryClass in segment" <<
1456 ds->current_segment_id_ << "for binary class ID" << pdb->bin_class <<
1457 ", segment only knows" << segment->binary_classes.size() << "classes";
1458 return;
1459 }
c0c3e62a 1460
e77de61f
SA
1461 // Add the data chunk
1462 bin_class->chunks.emplace_back();
1463 DecodeBinaryDataChunk* chunk = &(bin_class->chunks.back());
1464
1465 chunk->sample = pdata->start_sample;
1466 chunk->data.resize(pdb->size);
1467 memcpy(chunk->data.data(), pdb->data, pdb->size);
1468
6a26fc44 1469 Decoder* dec = ds->get_decoder_by_instance(srd_dec);
b2b18d3a
SA
1470
1471 ds->new_binary_data(ds->current_segment_id_, (void*)dec, pdb->bin_class);
c0c3e62a
SA
1472}
1473
47747218
SA
1474void DecodeSignal::on_capture_state_changed(int state)
1475{
1476 // If a new acquisition was started, we need to start decoding from scratch
ba5f2186
SA
1477 if (state == Session::Running) {
1478 logic_mux_data_invalid_ = true;
47747218 1479 begin_decode();
ba5f2186 1480 }
47747218
SA
1481}
1482
1b56c646
SA
1483void DecodeSignal::on_data_cleared()
1484{
1485 reset_decode();
1486}
1487
47747218
SA
1488void DecodeSignal::on_data_received()
1489{
5620539c
SA
1490 // If we detected a lack of input data when trying to start decoding,
1491 // we have set an error message. Only try again if we now have data
1492 // to work with
1493 if ((!error_message_.isEmpty()) && (get_input_segment_count() == 0))
1494 return;
1495
1b56c646
SA
1496 if (!logic_mux_thread_.joinable())
1497 begin_decode();
1498 else
1499 logic_mux_cond_.notify_one();
47747218
SA
1500}
1501
ad908057
SA
1502} // namespace data
1503} // namespace pv