]> sigrok.org Git - pulseview.git/blob - pv/data/decoderstack.cpp
Fix clang warning: shifting a negative signed value is undefined
[pulseview.git] / pv / data / decoderstack.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <libsigrokdecode/libsigrokdecode.h>
22
23 #include <stdexcept>
24
25 #include <QDebug>
26
27 #include "decoderstack.hpp"
28
29 #include <pv/data/logic.hpp>
30 #include <pv/data/logicsegment.hpp>
31 #include <pv/data/decode/decoder.hpp>
32 #include <pv/data/decode/annotation.hpp>
33 #include <pv/session.hpp>
34 #include <pv/view/logicsignal.hpp>
35
36 using std::lock_guard;
37 using std::mutex;
38 using boost::optional;
39 using std::unique_lock;
40 using std::deque;
41 using std::make_pair;
42 using std::max;
43 using std::min;
44 using std::list;
45 using std::map;
46 using std::pair;
47 using std::shared_ptr;
48 using std::vector;
49
50 using namespace pv::data::decode;
51
52 namespace pv {
53 namespace data {
54
55 const double DecoderStack::DecodeMargin = 1.0;
56 const double DecoderStack::DecodeThreshold = 0.2;
57 const int64_t DecoderStack::DecodeChunkLength = 4096;
58 const unsigned int DecoderStack::DecodeNotifyPeriod = 65536;
59
60 mutex DecoderStack::global_decode_mutex_;
61
62 DecoderStack::DecoderStack(pv::Session &session,
63         const srd_decoder *const dec) :
64         session_(session),
65         start_time_(0),
66         samplerate_(0),
67         sample_count_(0),
68         frame_complete_(false),
69         samples_decoded_(0)
70 {
71         connect(&session_, SIGNAL(frame_began()),
72                 this, SLOT(on_new_frame()));
73         connect(&session_, SIGNAL(data_received()),
74                 this, SLOT(on_data_received()));
75         connect(&session_, SIGNAL(frame_ended()),
76                 this, SLOT(on_frame_ended()));
77
78         stack_.push_back(shared_ptr<decode::Decoder>(
79                 new decode::Decoder(dec)));
80 }
81
82 DecoderStack::~DecoderStack()
83 {
84         if (decode_thread_.joinable()) {
85                 interrupt_ = true;
86                 input_cond_.notify_one();
87                 decode_thread_.join();
88         }
89 }
90
91 const std::list< std::shared_ptr<decode::Decoder> >&
92 DecoderStack::stack() const
93 {
94         return stack_;
95 }
96
97 void DecoderStack::push(std::shared_ptr<decode::Decoder> decoder)
98 {
99         assert(decoder);
100         stack_.push_back(decoder);
101 }
102
103 void DecoderStack::remove(int index)
104 {
105         assert(index >= 0);
106         assert(index < (int)stack_.size());
107
108         // Find the decoder in the stack
109         auto iter = stack_.begin();
110         for (int i = 0; i < index; i++, iter++)
111                 assert(iter != stack_.end());
112
113         // Delete the element
114         stack_.erase(iter);
115 }
116
117 double DecoderStack::samplerate() const
118 {
119         return samplerate_;
120 }
121
122 const pv::util::Timestamp& DecoderStack::start_time() const
123 {
124         return start_time_;
125 }
126
127 int64_t DecoderStack::samples_decoded() const
128 {
129         lock_guard<mutex> decode_lock(output_mutex_);
130         return samples_decoded_;
131 }
132
133 std::vector<Row> DecoderStack::get_visible_rows() const
134 {
135         lock_guard<mutex> lock(output_mutex_);
136
137         vector<Row> rows;
138
139         for (const shared_ptr<decode::Decoder> &dec : stack_) {
140                 assert(dec);
141                 if (!dec->shown())
142                         continue;
143
144                 const srd_decoder *const decc = dec->decoder();
145                 assert(dec->decoder());
146
147                 // Add a row for the decoder if it doesn't have a row list
148                 if (!decc->annotation_rows)
149                         rows.push_back(Row(decc));
150
151                 // Add the decoder rows
152                 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
153                         const srd_decoder_annotation_row *const ann_row =
154                                 (srd_decoder_annotation_row *)l->data;
155                         assert(ann_row);
156                         rows.push_back(Row(decc, ann_row));
157                 }
158         }
159
160         return rows;
161 }
162
163 void DecoderStack::get_annotation_subset(
164         std::vector<pv::data::decode::Annotation> &dest,
165         const Row &row, uint64_t start_sample,
166         uint64_t end_sample) const
167 {
168         lock_guard<mutex> lock(output_mutex_);
169
170         const auto iter = rows_.find(row);
171         if (iter != rows_.end())
172                 (*iter).second.get_annotation_subset(dest,
173                         start_sample, end_sample);
174 }
175
176 QString DecoderStack::error_message()
177 {
178         lock_guard<mutex> lock(output_mutex_);
179         return error_message_;
180 }
181
182 void DecoderStack::clear()
183 {
184         sample_count_ = 0;
185         frame_complete_ = false;
186         samples_decoded_ = 0;
187         error_message_ = QString();
188         rows_.clear();
189         class_rows_.clear();
190 }
191
192 void DecoderStack::begin_decode()
193 {
194         shared_ptr<pv::view::LogicSignal> logic_signal;
195         shared_ptr<pv::data::Logic> data;
196
197         if (decode_thread_.joinable()) {
198                 interrupt_ = true;
199                 input_cond_.notify_one();
200                 decode_thread_.join();
201         }
202
203         clear();
204
205         // Check that all decoders have the required channels
206         for (const shared_ptr<decode::Decoder> &dec : stack_)
207                 if (!dec->have_required_channels()) {
208                         error_message_ = tr("One or more required channels "
209                                 "have not been specified");
210                         return;
211                 }
212
213         // Add classes
214         for (const shared_ptr<decode::Decoder> &dec : stack_) {
215                 assert(dec);
216                 const srd_decoder *const decc = dec->decoder();
217                 assert(dec->decoder());
218
219                 // Add a row for the decoder if it doesn't have a row list
220                 if (!decc->annotation_rows)
221                         rows_[Row(decc)] = decode::RowData();
222
223                 // Add the decoder rows
224                 for (const GSList *l = decc->annotation_rows; l; l = l->next) {
225                         const srd_decoder_annotation_row *const ann_row =
226                                 (srd_decoder_annotation_row *)l->data;
227                         assert(ann_row);
228
229                         const Row row(decc, ann_row);
230
231                         // Add a new empty row data object
232                         rows_[row] = decode::RowData();
233
234                         // Map out all the classes
235                         for (const GSList *ll = ann_row->ann_classes;
236                                 ll; ll = ll->next)
237                                 class_rows_[make_pair(decc,
238                                         GPOINTER_TO_INT(ll->data))] = row;
239                 }
240         }
241
242         // We get the logic data of the first channel in the list.
243         // This works because we are currently assuming all
244         // LogicSignals have the same data/segment
245         for (const shared_ptr<decode::Decoder> &dec : stack_)
246                 if (dec && !dec->channels().empty() &&
247                         ((logic_signal = (*dec->channels().begin()).second)) &&
248                         ((data = logic_signal->logic_data())))
249                         break;
250
251         if (!data)
252                 return;
253
254         // Check we have a segment of data
255         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
256                 data->logic_segments();
257         if (segments.empty())
258                 return;
259         segment_ = segments.front();
260
261         // Get the samplerate and start time
262         start_time_ = segment_->start_time();
263         samplerate_ = segment_->samplerate();
264         if (samplerate_ == 0.0)
265                 samplerate_ = 1.0;
266
267         interrupt_ = false;
268         decode_thread_ = std::thread(&DecoderStack::decode_proc, this);
269 }
270
271 uint64_t DecoderStack::max_sample_count() const
272 {
273         uint64_t max_sample_count = 0;
274
275         for (auto i = rows_.cbegin(); i != rows_.end(); i++)
276                 max_sample_count = max(max_sample_count,
277                         (*i).second.get_max_sample());
278
279         return max_sample_count;
280 }
281
282 optional<int64_t> DecoderStack::wait_for_data() const
283 {
284         unique_lock<mutex> input_lock(input_mutex_);
285         while (!interrupt_ && !frame_complete_ &&
286                 samples_decoded_ >= sample_count_)
287                 input_cond_.wait(input_lock);
288         return boost::make_optional(!interrupt_ &&
289                 (samples_decoded_ < sample_count_ || !frame_complete_),
290                 sample_count_);
291 }
292
293 void DecoderStack::decode_data(
294         const int64_t sample_count, const unsigned int unit_size,
295         srd_session *const session)
296 {
297         uint8_t chunk[DecodeChunkLength];
298
299         const unsigned int chunk_sample_count =
300                 DecodeChunkLength / segment_->unit_size();
301
302         for (int64_t i = 0; !interrupt_ && i < sample_count;
303                         i += chunk_sample_count) {
304                 lock_guard<mutex> decode_lock(global_decode_mutex_);
305
306                 const int64_t chunk_end = min(
307                         i + chunk_sample_count, sample_count);
308                 segment_->get_samples(chunk, i, chunk_end);
309
310                 if (srd_session_send(session, i, chunk_end, chunk,
311                                 (chunk_end - i) * unit_size, unit_size) != SRD_OK) {
312                         error_message_ = tr("Decoder reported an error");
313                         break;
314                 }
315
316                 {
317                         lock_guard<mutex> lock(output_mutex_);
318                         samples_decoded_ = chunk_end;
319                 }
320
321                 if (i % DecodeNotifyPeriod == 0)
322                         new_decode_data();
323         }
324
325         new_decode_data();
326 }
327
328 void DecoderStack::decode_proc()
329 {
330         optional<int64_t> sample_count;
331         srd_session *session;
332         srd_decoder_inst *prev_di = nullptr;
333
334         assert(segment_);
335
336         // Create the session
337         srd_session_new(&session);
338         assert(session);
339
340         // Create the decoders
341         const unsigned int unit_size = segment_->unit_size();
342
343         for (const shared_ptr<decode::Decoder> &dec : stack_) {
344                 srd_decoder_inst *const di = dec->create_decoder_inst(session);
345
346                 if (!di) {
347                         error_message_ = tr("Failed to create decoder instance");
348                         srd_session_destroy(session);
349                         return;
350                 }
351
352                 if (prev_di)
353                         srd_inst_stack (session, prev_di, di);
354
355                 prev_di = di;
356         }
357
358         // Get the intial sample count
359         {
360                 unique_lock<mutex> input_lock(input_mutex_);
361                 sample_count = sample_count_ = segment_->get_sample_count();
362         }
363
364         // Start the session
365         srd_session_metadata_set(session, SRD_CONF_SAMPLERATE,
366                 g_variant_new_uint64((uint64_t)samplerate_));
367
368         srd_pd_output_callback_add(session, SRD_OUTPUT_ANN,
369                 DecoderStack::annotation_callback, this);
370
371         srd_session_start(session);
372
373         do {
374                 decode_data(*sample_count, unit_size, session);
375         } while (error_message_.isEmpty() && (sample_count = wait_for_data()));
376
377         // Destroy the session
378         srd_session_destroy(session);
379 }
380
381 void DecoderStack::annotation_callback(srd_proto_data *pdata, void *decoder)
382 {
383         assert(pdata);
384         assert(decoder);
385
386         DecoderStack *const d = (DecoderStack*)decoder;
387         assert(d);
388
389         lock_guard<mutex> lock(d->output_mutex_);
390
391         const Annotation a(pdata);
392
393         // Find the row
394         assert(pdata->pdo);
395         assert(pdata->pdo->di);
396         const srd_decoder *const decc = pdata->pdo->di->decoder;
397         assert(decc);
398
399         auto row_iter = d->rows_.end();
400
401         // Try looking up the sub-row of this class
402         const auto r = d->class_rows_.find(make_pair(decc, a.format()));
403         if (r != d->class_rows_.end())
404                 row_iter = d->rows_.find((*r).second);
405         else {
406                 // Failing that, use the decoder as a key
407                 row_iter = d->rows_.find(Row(decc));    
408         }
409
410         assert(row_iter != d->rows_.end());
411         if (row_iter == d->rows_.end()) {
412                 qDebug() << "Unexpected annotation: decoder = " << decc <<
413                         ", format = " << a.format();
414                 assert(0);
415                 return;
416         }
417
418         // Add the annotation
419         (*row_iter).second.push_annotation(a);
420 }
421
422 void DecoderStack::on_new_frame()
423 {
424         begin_decode();
425 }
426
427 void DecoderStack::on_data_received()
428 {
429         {
430                 unique_lock<mutex> lock(input_mutex_);
431                 if (segment_)
432                         sample_count_ = segment_->get_sample_count();
433         }
434         input_cond_.notify_one();
435 }
436
437 void DecoderStack::on_frame_ended()
438 {
439         {
440                 unique_lock<mutex> lock(input_mutex_);
441                 if (segment_)
442                         frame_complete_ = true;
443         }
444         input_cond_.notify_one();
445 }
446
447 } // namespace data
448 } // namespace pv