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