]> sigrok.org Git - pulseview.git/blob - pv/storesession.cpp
f8ab2e69bc78c1a2ed985e86d176c662b56084d3
[pulseview.git] / pv / storesession.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2014 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 <cassert>
22
23 #ifdef _WIN32
24 // Windows: Avoid boost/thread namespace pollution (which includes windows.h).
25 #define NOGDI
26 #define NORESOURCE
27 #endif
28 #include <boost/thread/locks.hpp>
29 #include <boost/thread/shared_mutex.hpp>
30
31 #include "storesession.hpp"
32
33 #include <pv/devicemanager.hpp>
34 #include <pv/session.hpp>
35 #include <pv/data/analog.hpp>
36 #include <pv/data/analogsegment.hpp>
37 #include <pv/data/logic.hpp>
38 #include <pv/data/logicsegment.hpp>
39 #include <pv/data/signalbase.hpp>
40 #include <pv/devices/device.hpp>
41 #include <pv/view/signal.hpp>
42
43 #include <libsigrokcxx/libsigrokcxx.hpp>
44
45 using boost::shared_lock;
46 using boost::shared_mutex;
47
48 using std::deque;
49 using std::dynamic_pointer_cast;
50 using std::ios_base;
51 using std::lock_guard;
52 using std::make_pair;
53 using std::map;
54 using std::min;
55 using std::mutex;
56 using std::pair;
57 using std::set;
58 using std::shared_ptr;
59 using std::string;
60 using std::thread;
61 using std::unordered_set;
62 using std::vector;
63
64 using Glib::VariantBase;
65
66 using sigrok::ConfigKey;
67 using sigrok::Error;
68 using sigrok::OutputFormat;
69 using sigrok::OutputFlag;
70
71 namespace pv {
72
73 const size_t StoreSession::BlockSize = 1024 * 1024;
74
75 StoreSession::StoreSession(const std::string &file_name,
76         const shared_ptr<OutputFormat> &output_format,
77         const map<string, VariantBase> &options,
78         const std::pair<uint64_t, uint64_t> sample_range,
79         const Session &session) :
80         file_name_(file_name),
81         output_format_(output_format),
82         options_(options),
83         sample_range_(sample_range),
84         session_(session),
85         interrupt_(false),
86         units_stored_(0),
87         unit_count_(0)
88 {
89 }
90
91 StoreSession::~StoreSession()
92 {
93         wait();
94 }
95
96 pair<int, int> StoreSession::progress() const
97 {
98         return make_pair(units_stored_.load(), unit_count_.load());
99 }
100
101 const QString& StoreSession::error() const
102 {
103         lock_guard<mutex> lock(mutex_);
104         return error_;
105 }
106
107 bool StoreSession::start()
108 {
109         const unordered_set< shared_ptr<view::Signal> > sigs(session_.signals());
110
111         shared_ptr<data::Segment> any_segment;
112         shared_ptr<data::LogicSegment> lsegment;
113         vector< shared_ptr<data::SignalBase> > achannel_list;
114         vector< shared_ptr<data::AnalogSegment> > asegment_list;
115
116         for (shared_ptr<view::Signal> signal : sigs) {
117                 if (!signal->enabled())
118                         continue;
119
120                 shared_ptr<data::SignalData> data = signal->data();
121
122                 if (dynamic_pointer_cast<data::Logic>(data)) {
123                         // All logic channels share the same data segments
124                         shared_ptr<data::Logic> ldata = dynamic_pointer_cast<data::Logic>(data);
125
126                         const deque< shared_ptr<data::LogicSegment> > &lsegments =
127                                 ldata->logic_segments();
128
129                         if (lsegments.empty()) {
130                                 error_ = tr("Can't save logic channel without data.");
131                                 return false;
132                         }
133
134                         lsegment = lsegments.front();
135                         any_segment = lsegment;
136                 }
137
138                 if (dynamic_pointer_cast<data::Analog>(data)) {
139                         // Each analog channel has its own segments
140                         shared_ptr<data::Analog> adata =
141                                 dynamic_pointer_cast<data::Analog>(data);
142
143                         const deque< shared_ptr<data::AnalogSegment> > &asegments =
144                                 adata->analog_segments();
145
146                         if (asegments.empty()) {
147                                 error_ = tr("Can't save analog channel without data.");
148                                 return false;
149                         }
150
151                         asegment_list.push_back(asegments.front());
152                         any_segment = asegments.front();
153
154                         achannel_list.push_back(signal->channel());
155                 }
156         }
157
158         if (!any_segment) {
159                 error_ = tr("No channels enabled.");
160                 return false;
161         }
162
163         // Check whether the user wants to export a certain sample range
164         uint64_t end_sample;
165
166         if (sample_range_.first == sample_range_.second) {
167                 start_sample_ = 0;
168                 sample_count_ = any_segment->get_sample_count();
169         } else {
170                 if (sample_range_.first > sample_range_.second) {
171                         start_sample_ = sample_range_.second;
172                         end_sample = min(sample_range_.first, any_segment->get_sample_count());
173                         sample_count_ = end_sample - start_sample_;
174                 } else {
175                         start_sample_ = sample_range_.first;
176                         end_sample = min(sample_range_.second, any_segment->get_sample_count());
177                         sample_count_ = end_sample - start_sample_;
178                 }
179         }
180
181         // Begin storing
182         try {
183                 const auto context = session_.device_manager().context();
184                 auto device = session_.device()->device();
185
186                 map<string, Glib::VariantBase> options = options_;
187
188                 if (!output_format_->test_flag(OutputFlag::INTERNAL_IO_HANDLING))
189                         output_stream_.open(file_name_, ios_base::binary |
190                                         ios_base::trunc | ios_base::out);
191
192                 output_ = output_format_->create_output(file_name_, device, options);
193                 auto meta = context->create_meta_packet(
194                         {{ConfigKey::SAMPLERATE, Glib::Variant<guint64>::create(
195                                 any_segment->samplerate())}});
196                 output_->receive(meta);
197         } catch (Error error) {
198                 error_ = tr("Error while saving: ") + error.what();
199                 return false;
200         }
201
202         thread_ = std::thread(&StoreSession::store_proc, this,
203                 achannel_list, asegment_list, lsegment);
204         return true;
205 }
206
207 void StoreSession::wait()
208 {
209         if (thread_.joinable())
210                 thread_.join();
211 }
212
213 void StoreSession::cancel()
214 {
215         interrupt_ = true;
216 }
217
218 void StoreSession::store_proc(vector< shared_ptr<data::SignalBase> > achannel_list,
219         vector< shared_ptr<data::AnalogSegment> > asegment_list,
220         shared_ptr<data::LogicSegment> lsegment)
221 {
222         unsigned progress_scale = 0;
223
224         /// TODO: Wrap this in a std::unique_ptr when we transition to C++11
225         uint8_t *const ldata = new uint8_t[BlockSize];
226         assert(ldata);
227
228         int aunit_size = 0;
229         int lunit_size = 0;
230         unsigned int lsamples_per_block = INT_MAX;
231         unsigned int asamples_per_block = INT_MAX;
232
233         if (!asegment_list.empty()) {
234                 // We assume all analog channels use the sample unit size
235                 aunit_size = asegment_list.front()->unit_size();
236                 asamples_per_block = BlockSize / aunit_size;
237         }
238         if (lsegment) {
239                 lunit_size = lsegment->unit_size();
240                 lsamples_per_block = BlockSize / lunit_size;
241         }
242
243         // Qt needs the progress values to fit inside an int. If they would
244         // not, scale the current and max values down until they do.
245         while ((sample_count_ >> progress_scale) > INT_MAX)
246                 progress_scale ++;
247
248         unit_count_ = sample_count_ >> progress_scale;
249
250         const unsigned int samples_per_block =
251                 std::min(asamples_per_block, lsamples_per_block);
252
253         while (!interrupt_ && sample_count_) {
254                 progress_updated();
255
256                 const uint64_t packet_len =
257                         std::min((uint64_t)samples_per_block, sample_count_);
258
259                 try {
260                         const auto context = session_.device_manager().context();
261
262                         for (unsigned int i = 0; i < achannel_list.size(); i++) {
263                                 shared_ptr<sigrok::Channel> achannel = (achannel_list.at(i))->channel();
264                                 shared_ptr<data::AnalogSegment> asegment = asegment_list.at(i);
265
266                                 const float *adata =
267                                         asegment->get_samples(start_sample_, start_sample_ + packet_len);
268
269                                 // The srzip format currently only supports packets with one
270                                 // analog channel. See zip_append_analog() in srzip.c
271                                 auto analog = context->create_analog_packet(
272                                         vector<shared_ptr<sigrok::Channel> >{achannel},
273                                         (float *)adata, packet_len,
274                                         sigrok::Quantity::VOLTAGE, sigrok::Unit::VOLT,
275                                         vector<const sigrok::QuantityFlag *>());
276                                 const string adata_str = output_->receive(analog);
277
278                                 if (output_stream_.is_open())
279                                         output_stream_ << adata_str;
280
281                                 delete[] adata;
282                         }
283
284                         if (lsegment) {
285                                 lsegment->get_samples(ldata, start_sample_, start_sample_ + packet_len);
286
287                                 const size_t length = packet_len * lunit_size;
288                                 auto logic = context->create_logic_packet(ldata, length, lunit_size);
289                                 const string ldata_str = output_->receive(logic);
290
291                                 if (output_stream_.is_open())
292                                         output_stream_ << ldata_str;
293                         }
294                 } catch (Error error) {
295                         error_ = tr("Error while saving: ") + error.what();
296                         break;
297                 }
298
299                 sample_count_ -= packet_len;
300                 start_sample_ += packet_len;
301                 units_stored_ = unit_count_ - (sample_count_ >> progress_scale);
302         }
303
304         // Zeroing the progress variables indicates completion
305         units_stored_ = unit_count_ = 0;
306
307         progress_updated();
308
309         output_.reset();
310         output_stream_.close();
311
312         delete[] ldata;
313 }
314
315 } // pv