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