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