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