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