SlsDetectorCamera.cpp 33.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//###########################################################################
// This file is part of LImA, a Library for Image Acquisition
//
// Copyright (C) : 2009-2011
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//###########################################################################

23
#include "SlsDetectorCamera.h"
24

25
#include <limits.h>
26
#include <algorithm>
27
#include <numeric>
28
#include <cmath>
29
30
#include <iostream>
#include <fstream>
31

32
33
34
35
using namespace std;
using namespace lima;
using namespace lima::SlsDetector;

36

37
Camera::AppInputData::AppInputData(string cfg_fname) 
38
	: config_file_name(cfg_fname)
39
{
40
	DEB_CONSTRUCTOR();
41
42
43
	parseConfigFile();
}

44
void Camera::AppInputData::parseConfigFile()
45
{
46
47
	DEB_MEMBER_FUNCT();

48
	ifstream config_file(config_file_name);
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
	while (config_file) {
		string s;
		config_file >> s;
		RegEx re;
		FullMatch full_match;
		MatchList match_list;
		MatchListIt lit, lend;

		re = "hostname";
		if (re.match(s, full_match)) {
			string host_name;
			config_file >> host_name;
			RegEx re("([A-Za-z0-9]+)\\+?");
			re.multiSearch(host_name, match_list);
			lend = match_list.end();
			for (lit = match_list.begin(); lit != lend; ++lit) {
				const FullMatch& full_match = *lit;
				const SingleMatch& single_match = full_match[1];
				host_name_list.push_back(single_match);
			}
69
			DEB_TRACE() << DEB_VAR1(host_name_list);
70
71
72
			continue;
		}

73
		re = "(([0-9]+):)?rx_tcpport";
74
		if (re.match(s, full_match)) {
75
76
77
78
79
80
81
82
			int id = 0;
			if (full_match[2].found()) {
				istringstream is(full_match[2]);
				is >> id;
				if (id < 0)
					THROW_HW_FATAL(InvalidValue) << 
						"Invalid detector id: " << id;
			}
83
84
85
86
87
88
89
90
			int rx_tcpport;
			config_file >> rx_tcpport;
			recv_port_map[id] = rx_tcpport;
			continue;
		}
	}
}

91
92
93
Camera::AcqThread::ExceptionCleanUp::ExceptionCleanUp(AcqThread& thread,
						      AutoMutex& l)
	: Thread::ExceptionCleanUp(thread), m_lock(l)
94
95
96
97
98
99
100
101
{
	DEB_CONSTRUCTOR();
}

Camera::AcqThread::ExceptionCleanUp::~ExceptionCleanUp()
{
	DEB_DESTRUCTOR();
	AcqThread *thread = static_cast<AcqThread *>(&m_thread);
102
	thread->cleanUp(m_lock);
103
104
}

105
Camera::AcqThread::AcqThread(Camera *cam)
106
107
	: m_cam(cam), m_cond(m_cam->m_cond), m_state(m_cam->m_state),
	  m_acq_stopped(false)
108
109
{
	DEB_CONSTRUCTOR();
110
111
}

112
void Camera::AcqThread::start(AutoMutex& l)
113
114
115
{
	DEB_MEMBER_FUNCT();

116
117
118
	if ((&l.mutex() != &m_cond.mutex()) || !l.locked())
		THROW_HW_ERROR(Error) << "Invalid AutoMutex";

119
	m_state = Starting;
120
	Thread::start();
121
122

	struct sched_param param;
123
	param.sched_priority = sched_get_priority_min(SCHED_RR);
124
125
	int ret = pthread_setschedparam(m_thread, SCHED_RR, &param);
	if (ret != 0)
126
		DEB_ERROR() << "Could not set AcqThread real-time priority!!";
127

128
	while (m_state == Starting)
129
130
131
		m_cond.wait();
}

132
void Camera::AcqThread::stop(AutoMutex& l, bool wait)
133
134
{
	DEB_MEMBER_FUNCT();
135
136
137
	if ((&l.mutex() != &m_cond.mutex()) || !l.locked())
		THROW_HW_ERROR(Error) << "Invalid AutoMutex";

138
139
	m_state = StopReq;
	m_cond.broadcast();
140
141
142
143
144
145

	{
		AutoMutexUnlock u(l);
		stopAcq();
	}

146
	while (wait && (m_state != Stopped) && (m_state != Idle))
147
148
149
		m_cond.wait();
}

150
151
152
153
154
155
inline
Camera::AcqThread::Status Camera::AcqThread::newFrameReady(FrameType frame)
{
	DEB_MEMBER_FUNCT();
	HwFrameInfoType frame_info;
	frame_info.acq_frame_nb = frame;
156
	StdBufferCbMgr *cb_mgr = m_cam->m_buffer.getBufferCbMgr();
157
158
159
160
161
162
	bool cont_acq = cb_mgr->newFrameReady(frame_info);
	bool acq_end = (frame == m_cam->m_lima_nb_frames - 1);
	cont_acq &= !acq_end;
	return Status(cont_acq, acq_end);
}

163
164
165
166
167
void Camera::AcqThread::threadFunction()
{
	DEB_MEMBER_FUNCT();

	AutoMutex l = m_cam->lock();
168

169
170
171
172
	// cleanup is executed with lock, once state goes to Stopped
	// thread will be deleted in getEffectiveState without releasing lock
	ExceptionCleanUp cleanup(*this, l);

173
	GlobalCPUAffinityMgr& affinity_mgr = m_cam->m_global_cpu_affinity_mgr;
174
175
	{
		AutoMutexUnlock u(l);
176
177
		affinity_mgr.startAcq();
		startAcq();
178
179
	}
	m_state = Running;
180
	DEB_TRACE() << DEB_VAR1(m_state);
181
182
	m_cond.broadcast();

183
184
	Reconstruction *reconstruct = m_cam->m_model->getReconstruction();

185
	SeqFilter seq_filter;
186
	bool had_frames = false;
187
	bool cont_acq = true;
188
	bool acq_end = false;
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
	FrameType next_frame = 0;

	auto get_next_frame = [&]() {
		DetFrameImagePackets packets = readRecvPackets(next_frame++);
		FrameType frame = packets.first;
		reconstruct->addFramePackets(std::move(packets));
		return frame;
	};
	
	while ((m_state != StopReq) && cont_acq &&
	       (next_frame < m_cam->m_lima_nb_frames)) {
		FrameType frame;
		{
			AutoMutexUnlock u(l);
			frame = get_next_frame();
			DEB_TRACE() << DEB_VAR2(next_frame, frame);
205
		}
206
207
208
209
210
211
212
		m_cam->m_buffer.waitLimaFrame(frame, l);
		{
			AutoMutexUnlock u(l);
			Status status = newFrameReady(frame);
			cont_acq = status.first;
			acq_end = status.second;
			had_frames = true;
213
		}
214
215
	}

216
	AcqState prev_state = m_state;
217

218
219
220
221
222
	if (acq_end && m_cam->m_skip_frame_freq) {
		AutoMutexUnlock u(l);
		m_cam->waitLastSkippedFrame();
	}
		
223
	m_state = Stopping;
224
	DEB_TRACE() << DEB_VAR2(prev_state, m_state);
225
226
	{
		AutoMutexUnlock u(l);
227
		stopAcq();
228

229
230
231
232
233
		IntList bfl;
		m_cam->getSortedBadFrameList(bfl);
		DEB_ALWAYS() << "bad_frames=" << bfl.size() << ": "
			     << PrettyIntList(bfl);

234
235
236
		Stats stats;
		m_cam->getStats(stats);
		DEB_ALWAYS() << DEB_VAR1(stats);
237

238
		FrameMap& m = m_cam->m_frame_map;
239
240
241
242
		if (m.getNbItems() > 1) {
			XYStat::LinRegress delay_stat = m.calcDelayStat();
			DEB_ALWAYS() << DEB_VAR1(delay_stat);
		}
243

244
		if (had_frames) {
245
246
			affinity_mgr.recvFinished();
			affinity_mgr.waitLimaFinished();
247
		} else {
248
			affinity_mgr.cleanUp();
249
		}
250
	}
251

252
	m_state = Stopped;
253
	DEB_TRACE() << DEB_VAR1(m_state);
254
255
256
	m_cond.broadcast();
}

257
DetFrameImagePackets Camera::AcqThread::readRecvPackets(FrameType frame)
258
259
{
	DEB_MEMBER_FUNCT();
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297

	DetFrameImagePackets det_frame_packets{frame, {}};
	DetImagePackets& det_packets = det_frame_packets.second;
	FramePacketMap::iterator it = m_frame_packet_map.find(frame);
	if (it != m_frame_packet_map.end()) {
		det_packets = std::move(it->second);
		m_frame_packet_map.erase(it);
	}

	auto stopped = [&]() { return (m_cam->getAcqState() == StopReq); };

	int nb_recvs = m_cam->getNbRecvs();
	for (int i = 0; i < nb_recvs; ++i) {
		while ((det_packets.find(i) == det_packets.end()) &&
		       !stopped()) {
			Receiver::ImagePackets *image_packets;
			Receiver *recv = m_cam->m_recv_list[i];
			image_packets = recv->readImagePackets();
			if (!image_packets)
				break;
			typedef DetImagePackets::value_type MapEntry;
			FrameType f = image_packets->frame;
			if (f == frame)  {
				det_packets.emplace(MapEntry(i, image_packets));
				break;
			} else {
				DetImagePackets& other = m_frame_packet_map[f];
				other.emplace(MapEntry(i, image_packets));
			}
		}
	}

	if (stopped()) {
		det_frame_packets.second.clear();
		m_frame_packet_map.clear();
	}

	return det_frame_packets;
298
299
}

300
void Camera::AcqThread::cleanUp(AutoMutex& l)
301
302
303
304
305
306
{
	DEB_MEMBER_FUNCT();

	if ((m_state == Stopped) || (m_state == Idle))
		return;

307
	AcqState prev_state = m_state;
308
309
310
311
312
313
314
315
	if ((m_state == Running) || (m_state == StopReq)) {
		m_state = Stopping;
		AutoMutexUnlock u(l);
		stopAcq();
	}

	{
		AutoMutexUnlock u(l);
316
317
318
		ostringstream err_msg;
		err_msg << "AcqThread: exception thrown: "
			<< "m_state=" << prev_state;
319
320
		Event::Code err_code = Event::CamFault;
		Event *event = new Event(Hardware, Event::Error, Event::Camera, 
321
					 err_code, err_msg.str());
322
323
324
325
326
327
328
329
330
331
332
		DEB_EVENT(*event) << DEB_VAR1(*event);
		m_cam->reportEvent(event);
	}

	m_state = Stopped;
	m_cond.broadcast();
}

void Camera::AcqThread::startAcq()
{
	DEB_MEMBER_FUNCT();
333
	sls::Detector *det = m_cam->m_det;
334
	DEB_TRACE() << "calling startReceiver";
335
	det->startReceiver();
336
337
	DEB_TRACE() << "calling Model::startAcq";
	m_cam->m_model->startAcq();
338
339
	DEB_TRACE() << "calling startDetector";
	det->startDetector();
340
341
342
343
344
}

void Camera::AcqThread::stopAcq()
{
	DEB_MEMBER_FUNCT();
345
346
347
348
349
350
351
352

	{
		AutoMutex l(m_cam->lock());
		if (m_acq_stopped)
			return;
		m_acq_stopped = true;
	}

353
	sls::Detector *det = m_cam->m_det;
354
355
356
357
	DetStatus det_status = m_cam->getDetStatus();
	bool xfer_active = m_cam->m_model->isXferActive();
	DEB_ALWAYS() << DEB_VAR2(det_status, xfer_active);
	if ((det_status == Defs::Running) || xfer_active) {
358
359
		DEB_TRACE() << "calling stopDetector";
		det->stopDetector();
360
		Timestamp t0 = Timestamp::now();
361
		while (m_cam->m_model->isAcqActive())
362
363
364
365
366
367
			Sleep(m_cam->m_abort_sleep_time);
		double milli_sec = (Timestamp::now() - t0) * 1e3;
		DEB_TRACE() << "Abort -> Idle: " << DEB_VAR1(milli_sec);
	}
	DEB_TRACE() << "calling stopReceiver";
	det->stopReceiver();
368
369
	DEB_TRACE() << "calling Model::stopAcq";
	m_cam->m_model->stopAcq();
370
371
}

372
373
374
Camera::Camera(string config_fname, int det_id) 
	: m_det_id(det_id),
	  m_model(NULL),
375
	  m_frame_map(this),
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
376
377
378
	  m_lima_nb_frames(1),
	  m_det_nb_frames(1),
	  m_skip_frame_freq(0),
379
	  m_last_skipped_frame_timeout(0.5),
380
	  m_lat_time(0),
381
	  m_buffer(this),
382
	  m_pixel_depth(PixelDepth16), 
383
	  m_image_type(Bpp16), 
384
	  m_raw_mode(false),
385
	  m_state(Idle),
386
	  m_new_frame_timeout(0.5),
387
	  m_abort_sleep_time(0.1),
388
	  m_tol_lost_packets(true),
389
	  m_time_ranges_cb(NULL),
390
	  m_global_cpu_affinity_mgr(this)
391
{
392
393
	DEB_CONSTRUCTOR();

394
	CPUAffinity::getNbSystemCPUs();
395

396
397
	m_input_data = new AppInputData(config_fname);

398
399
400
	bool remove_shmem = false;
	if (remove_shmem)
		removeSharedMem();
401
402
	createReceivers();

403
404
	DEB_TRACE() << "Creating the sls::Detector object";
	m_det = new sls::Detector(m_det_id);
405
	DEB_TRACE() << "Reading configuration file";
406
	const char *fname = m_input_data->config_file_name.c_str();
407
	EXC_CHECK(m_det->loadConfig(fname));
408

409
410
411
	EXC_CHECK(m_det->setRxSilentMode(1));
	EXC_CHECK(m_det->setRxFrameDiscardPolicy(
				  slsDetectorDefs::DISCARD_PARTIAL_FRAMES));
412
	setReceiverFifoDepth(128);
413

414
415
416
	sls::Result<int> dr_res;
	EXC_CHECK(dr_res = m_det->getDynamicRange());
	m_pixel_depth = PixelDepth(dr_res.squash(-1));
417

418
	setTrigMode(Defs::Auto);
419
420
421
	setNbFrames(1);
	setExpTime(0.99);
	setFramePeriod(1.0);
422
423
}

424
Camera::~Camera()
425
{
426
	DEB_DESTRUCTOR();
427

428
429
430
	if (m_time_ranges_cb)
		unregisterTimeRangesChangedCallback(*m_time_ranges_cb);

431
432
433
	if (!m_model)
		return;

434
	stopAcq();
435
436
437
	m_model->m_cam = NULL;
}

438
Type Camera::getType()
439
440
{
	DEB_MEMBER_FUNCT();
441
442
443
444
445
446
	slsDetectorDefs::detectorType sls_type;
	const char *err_msg = "Detector types are different";
	EXC_CHECK(sls_type = m_det->getDetectorType().tsquash(err_msg));
	Type det_type;
	switch (sls_type) {
	case slsDetectorDefs::GENERIC:
447
		det_type = GenericDet;
448
449
		break;
	case slsDetectorDefs::EIGER:
450
		det_type = EigerDet;
451
452
		break;
	case slsDetectorDefs::JUNGFRAU:
453
		det_type = JungfrauDet;
454
455
456
		break;
	default:
		det_type = UnknownDet;
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
	}
	DEB_RETURN() << DEB_VAR1(det_type);
	return det_type;
}

void Camera::setModel(Model *model)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR2(model, m_model);
	
	if (model && (model->getType() != getType()))
		THROW_HW_ERROR(InvalidValue) << DEB_VAR2(getType(), 
							 model->getType());
	if (m_model == model)
		return;
	if (m_model)
		m_model->m_cam = NULL;
	m_model = model;
475
476
477
	if (!m_model)
		return;

478
479
480
481
482
483
	int nb_udp_ifaces;
	m_model->getNbUDPInterfaces(nb_udp_ifaces);
	DEB_ALWAYS() << "Using " << m_model->getName()
		     << " with " << getNbDetModules() << "x" << nb_udp_ifaces
		     << " UDP interfaces";

484
485
486
	int nb_items = m_model->getNbFrameMapItems();
	m_frame_map.setNbItems(nb_items);
	m_model->updateFrameMapItems(&m_frame_map);
487

488
	setPixelDepth(m_pixel_depth);
489
490
}

491
492
493
void Camera::removeSharedMem()
{
	DEB_MEMBER_FUNCT();
494
495
	ostringstream cmd;
	cmd << "sls_detector_get " << m_det_id << "-free";
496
497
498
499
	string cmd_str = cmd.str();
	int ret = system(cmd_str.c_str());
	if (ret != 0)
		THROW_HW_ERROR(Error) << "Error executing " << DEB_VAR1(cmd_str);
500
501
}

502
void Camera::createReceivers()
503
{
504
505
	DEB_MEMBER_FUNCT();

506
	DEB_TRACE() << "Receivers:";
507
508
509
510
511
	const RecvPortMap& recv_port_map = m_input_data->recv_port_map;
	RecvPortMap::const_iterator mit, mend = recv_port_map.end();
	int idx = 0;
	for (mit = recv_port_map.begin(); mit != mend; ++mit, ++idx) {
		unsigned int id = mit->first;
512
513
514
		if (id >= m_input_data->host_name_list.size())
			THROW_HW_FATAL(InvalidValue) << DEB_VAR1(id) 
						     << "too high";
515
516
		const string& host_name = m_input_data->host_name_list[id];
		int rx_port = mit->second;
517
		DEB_TRACE() << "  " << host_name << ": " << DEB_VAR1(rx_port);
518

519
		AutoPtr<Receiver> recv_obj = new Receiver(this, idx, rx_port);
520
521
522
523
		m_recv_list.push_back(recv_obj);
	}
}

524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
string Camera::execCmd(const string& s, bool put, int idx)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << "s=\"" << s << "\", " << DEB_VAR2(put, idx);

	string prog_name = string("sls_detector_") + (put ? "put" : "get");
	ostringstream os;
	os << prog_name << " ";
	if (idx >= 0)
		os << idx << ':';
	os << s;
	SystemCmdPipe cmd(os.str(), prog_name, false);
	cmd.setPipe(SystemCmdPipe::StdOut, SystemCmdPipe::DoPipe);
	cmd.setPipe(SystemCmdPipe::StdErr, SystemCmdPipe::DoPipe);
	StringList out, err;
	int ret = cmd.execute(out, err);
	DEB_TRACE() << DEB_VAR3(ret, out, err);
	string err_str = accumulate(err.begin(), err.end(), string());
	if ((ret != 0) || (err_str.find("ERROR") != string::npos))
		THROW_HW_ERROR(Error) << prog_name << "(" << ret << "): "
				      << err_str;
	else if (!err_str.empty())
		cerr << err_str;
	string out_str = accumulate(out.begin(), out.end(), string());
	DEB_RETURN() << DEB_VAR1(out_str);
	return out_str;
}

552
void Camera::putCmd(const string& s, int idx)
553
{
554
	DEB_MEMBER_FUNCT();
555
	execCmd(s, true, idx);
556
557
}

558
string Camera::getCmd(const string& s, int idx)
559
{
560
	DEB_MEMBER_FUNCT();
561
562
563
564
	string r = execCmd(s, false, idx);
	string::size_type p = s.find(':');
	string raw_s = s.substr((p == string::npos) ? 0 : (p + 1));
	DEB_TRACE() << DEB_VAR2(s, raw_s);
565
566
567
568
569
570
571
572
	bool multi_line = ((s == "list") || (s == "versions"));
	if (!multi_line) {
		if (r.find(raw_s + ' ') != 0)
			THROW_HW_ERROR(Error) << "Invalid response: " << r;
		string::size_type e = raw_s.size() + 1;
		p = r.find('\n', e);
		r = r.substr(e, (p == string::npos) ? p : (p - e));
	}
573
	DEB_RETURN() << DEB_VAR1(r);
574
	return r;
575
576
}

577
578
579
580
void Camera::setTrigMode(TrigMode trig_mode)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR1(trig_mode);
581
	waitAcqState(Idle);
582
583
584
	TrigMode cam_trig_mode = trig_mode;
	if (trig_mode == Defs::SoftTriggerExposure)
		cam_trig_mode = Defs::TriggerExposure;
585
586
587
	typedef slsDetectorDefs::timingMode TimingMode;
	TimingMode mode = static_cast<TimingMode>(cam_trig_mode);
	EXC_CHECK(m_det->setTimingMode(mode));
588
	m_trig_mode = trig_mode;
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
589
	setNbFrames(m_lima_nb_frames);
590
591
592
593
594
595
596
597
598
}

void Camera::getTrigMode(TrigMode& trig_mode)
{
	DEB_MEMBER_FUNCT();
	trig_mode = m_trig_mode;
	DEB_RETURN() << DEB_VAR1(trig_mode);
}

599
void Camera::setNbFrames(FrameType nb_frames)
600
{
601
	DEB_MEMBER_FUNCT();
602
	DEB_PARAM() << DEB_VAR1(nb_frames);
603
604
605
606
607
608
609

	// Lima frame numbers are (signed) int
	const FrameType MaxFrames = INT_MAX;
	if (nb_frames >= MaxFrames)
		THROW_HW_ERROR(InvalidValue) << "too high " 
					     <<	DEB_VAR2(nb_frames, MaxFrames);

610
	waitAcqState(Idle);
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
611
612
613
	FrameType det_nb_frames = nb_frames;
	if (m_skip_frame_freq)
		det_nb_frames += nb_frames / m_skip_frame_freq;
614
	bool trig_exp = (m_trig_mode == Defs::TriggerExposure);
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
615
616
	int cam_frames = trig_exp ? 1 : det_nb_frames;
	int cam_triggers = trig_exp ? det_nb_frames : 1;
617
618
	EXC_CHECK(m_det->setNumberOfFrames(cam_frames));
	EXC_CHECK(m_det->setNumberOfTriggers(cam_triggers));
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
619
620
	m_lima_nb_frames = nb_frames;
	m_det_nb_frames = det_nb_frames;
621
}
622

623
void Camera::getNbFrames(FrameType& nb_frames)
624
625
{
	DEB_MEMBER_FUNCT();
Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
626
	nb_frames = m_lima_nb_frames;
627
	DEB_RETURN() << DEB_VAR1(nb_frames);
628
}
629

Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
void Camera::setSkipFrameFreq(FrameType skip_frame_freq)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR1(skip_frame_freq);
	m_skip_frame_freq = skip_frame_freq;
	setNbFrames(m_lima_nb_frames);
}

void Camera::getSkipFrameFreq(FrameType& skip_frame_freq)
{
	DEB_MEMBER_FUNCT();
	skip_frame_freq = m_skip_frame_freq;
	DEB_RETURN() << DEB_VAR1(skip_frame_freq);
}

645
646
647
void Camera::setExpTime(double exp_time)
{
	DEB_MEMBER_FUNCT();
648
	DEB_PARAM() << DEB_VAR1(exp_time);
649
	waitAcqState(Idle);
650
	EXC_CHECK(m_det->setExptime(NSec(exp_time)));
651
652
	m_exp_time = exp_time;
}
653

654
655
656
657
void Camera::getExpTime(double& exp_time)
{ 
	DEB_MEMBER_FUNCT();
	exp_time = m_exp_time;
658
	DEB_RETURN() << DEB_VAR1(exp_time);
659
}
660

661
662
663
664
665
666
667
668
669
670
671
672
673
674
void Camera::setLatTime(double lat_time)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR1(lat_time);
	m_lat_time = lat_time;
}

void Camera::getLatTime(double& lat_time)
{ 
	DEB_MEMBER_FUNCT();
	lat_time = m_lat_time;
	DEB_RETURN() << DEB_VAR1(lat_time);
}

675
676
677
void Camera::setFramePeriod(double frame_period)
{
	DEB_MEMBER_FUNCT();
678
	DEB_PARAM() << DEB_VAR1(frame_period);
679
680
681

	if (m_model) {
		TimeRanges time_ranges;
682
		double e = 1e-6;
683
		m_model->getTimeRanges(time_ranges);
684
685
686
687
688
689
		if ((frame_period < time_ranges.min_frame_period - e) ||
		    (frame_period > time_ranges.max_frame_period + e))
			THROW_HW_ERROR(InvalidValue) 
				<< DEB_VAR3(frame_period,
					    time_ranges.min_frame_period, 
					    time_ranges.max_frame_period);
690
691
	}

692
	waitAcqState(Idle);
693
	EXC_CHECK(m_det->setPeriod(NSec(frame_period)));
694
695
	m_frame_period = frame_period;
}
696

697
698
699
700
void Camera::getFramePeriod(double& frame_period)
{
	DEB_MEMBER_FUNCT();
	frame_period = m_frame_period;
701
	DEB_RETURN() << DEB_VAR1(frame_period);
702
}
703

704
705
706
void Camera::updateImageSize()
{
	DEB_MEMBER_FUNCT();
707
708
709
	RecvList::iterator it, end = m_recv_list.end();
	for (it = m_recv_list.begin(); it != end; ++it)
		(*it)->setGapPixelsEnable(!m_raw_mode);
710
711
712
713
714
715
716
	m_model->updateImageSize();
	FrameDim frame_dim;
	getFrameDim(frame_dim, m_raw_mode);
	DEB_TRACE() << "MaxImageSizeChanged: " << DEB_VAR1(frame_dim);
	maxImageSizeChanged(frame_dim.getSize(), frame_dim.getImageType());
}

717
718
719
720
721
void Camera::updateTimeRanges()
{
	DEB_MEMBER_FUNCT();
	TimeRanges time_ranges;
	m_model->getTimeRanges(time_ranges);
722
723
	m_exp_time = max(m_exp_time, time_ranges.min_exp_time);
	m_frame_period = max(m_frame_period, time_ranges.min_frame_period);
724
725
726
727
728
729
730
	DEB_TRACE() << "TimeRangesChanged: " 
		    << DEB_VAR6(time_ranges.min_exp_time, 
				time_ranges.max_exp_time,
				time_ranges.min_lat_time,
				time_ranges.max_lat_time,
				time_ranges.min_frame_period,
				time_ranges.max_frame_period);
731
732
	if (m_time_ranges_cb)
		m_time_ranges_cb->timeRangesChanged(time_ranges);
733
734
}

735
736
737
738
739
740
void Camera::updateCPUAffinity(bool recv_restarted)
{
	DEB_MEMBER_FUNCT();

	// receiver threads are restarted after DR change
	if (recv_restarted)
741
		m_global_cpu_affinity_mgr.updateRecvRestart();
742

743
744
745
	// apply the corresponding GlobalCPUAffinity
	GlobalCPUAffinity global_affinity = m_cpu_affinity_map[m_pixel_depth];
	m_global_cpu_affinity_mgr.applyAndSet(global_affinity);
746
747
}

748
void Camera::setRecvCPUAffinity(const RecvCPUAffinityList& recv_affinity_list)
749
750
{
	DEB_MEMBER_FUNCT();
751
	unsigned int nb_aff = recv_affinity_list.size();
752
	DEB_PARAM() << DEB_VAR1(nb_aff);
753
	RecvCPUAffinityList::const_iterator ait = recv_affinity_list.begin();
754
	RecvList::iterator rit = m_recv_list.begin();
755
756
	for (unsigned int i = 0; i < nb_aff; ++i, ++ait, ++rit)
		(*rit)->setCPUAffinity(*ait);
757
758
}

759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
void Camera::setModuleActive(int mod_idx, bool  active)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR2(mod_idx, active);

	if ((mod_idx < 0) || (mod_idx >= getNbDetModules()))
		THROW_HW_ERROR(InvalidValue) << DEB_VAR1(mod_idx);

	Positions pos = Idx2Pos(mod_idx);
	EXC_CHECK(m_det->setActive(active, pos));
}

void Camera::getModuleActive(int mod_idx, bool& active)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR1(mod_idx);

	if ((mod_idx < 0) || (mod_idx >= getNbDetModules()))
		THROW_HW_ERROR(InvalidValue) << DEB_VAR1(mod_idx);

	Positions pos = Idx2Pos(mod_idx);
	EXC_CHECK(active = m_det->getActive(pos).front());
	DEB_RETURN() << DEB_VAR1(active);
}

784
785
786
787
788
void Camera::setPixelDepth(PixelDepth pixel_depth)
{
	DEB_MEMBER_FUNCT();
	DEB_PARAM() << DEB_VAR1(pixel_depth);

789
	if (getAcqState() != Idle)
790
791
		THROW_HW_FATAL(Error) << "Camera is not idle";

792
	waitAcqState(Idle);
793
794
795
796
797
798
799
800
801
802
803
	switch (pixel_depth) {
	case PixelDepth4:
	case PixelDepth8:
		m_image_type = Bpp8;	break;
	case PixelDepth16:
		m_image_type = Bpp16;	break;
	case PixelDepth32:
		m_image_type = Bpp32;	break;
	default:
		THROW_HW_ERROR(InvalidValue) << DEB_VAR1(pixel_depth);
	}
804
	EXC_CHECK(m_det->setDynamicRange(pixel_depth));
805
806
	m_pixel_depth = pixel_depth;

807
	if (m_model) {
808
		updateImageSize();
809
		updateTimeRanges();
810
		updateCPUAffinity(true);
811
	}
812
813
814
815
816
817
818
819
820
}

void Camera::getPixelDepth(PixelDepth& pixel_depth)
{
	DEB_MEMBER_FUNCT();
	pixel_depth = m_pixel_depth; 
	DEB_RETURN() << DEB_VAR1(pixel_depth);
}

821
void Camera::setRawMode(bool raw_mode)
822
823
{
	DEB_MEMBER_FUNCT();
824
	DEB_PARAM() << DEB_VAR1(raw_mode);
825

826
	if (raw_mode == m_raw_mode)
827
		return;
828
	m_raw_mode = raw_mode;
829

830
	updateImageSize();
831
832
}

833
void Camera::getRawMode(bool& raw_mode)
834
835
{
	DEB_MEMBER_FUNCT();
836
837
	raw_mode = m_raw_mode; 
	DEB_RETURN() << DEB_VAR1(raw_mode);
838
839
}

840
AcqState Camera::getAcqState()
841
842
843
{
	DEB_MEMBER_FUNCT();
	AutoMutex l = lock();
844
	AcqState state = getEffectiveState();
845
846
	DEB_RETURN() << DEB_VAR1(state);
	return state;
847
848
}

849
AcqState Camera::getEffectiveState()
850
851
852
853
854
855
856
857
{
	if (m_state == Stopped) {
		m_acq_thread = NULL;
		m_state = Idle;
	}
	return m_state;
}

858
void Camera::waitAcqState(AcqState state)
859
860
{
	DEB_MEMBER_FUNCT();
861
	DEB_PARAM() << DEB_VAR1(state);
862
863
864
865
866
	AutoMutex l = lock();
	while (getEffectiveState() != state)
		m_cond.wait();
}

867
AcqState Camera::waitNotAcqState(AcqState state)
868
869
{
	DEB_MEMBER_FUNCT();
870
	DEB_PARAM() << DEB_VAR1(state);
871
872
873
	AutoMutex l = lock();
	while (getEffectiveState() == state)
		m_cond.wait();
874
875
876
	state = getEffectiveState();
	DEB_RETURN() << DEB_VAR1(state);
	return state;
877
878
}

879
880
881
882
void Camera::prepareAcq()
{
	DEB_MEMBER_FUNCT();

883
	StdBufferCbMgr *cb_mgr = m_buffer.getBufferCbMgr();
884
	if (!cb_mgr)
885
		THROW_HW_ERROR(Error) << "No Acq BufferCbMgr defined";
886
	if (!m_model)
887
		THROW_HW_ERROR(Error) << "No Model defined";
888

889
890
	m_buffer.prepareAcq();

891
892
	waitNotAcqState(Stopping);
	if (getAcqState() != Idle)
893
894
		THROW_HW_ERROR(Error) << "Camera is not idle";

Alejandro Homs Puron's avatar
Alejandro Homs Puron committed
895
	bool need_period = !m_lima_nb_frames || (m_lima_nb_frames > 1);
896
897
898
	need_period &= ((m_trig_mode == Defs::Auto) || 
			(m_trig_mode == Defs::BurstTrigger));
	if (need_period && (m_lat_time > 0))
899
900
		setFramePeriod(m_exp_time + m_lat_time);

901
	int nb_buffers;
902
	cb_mgr->getNbBuffers(nb_buffers);
903

904
905
	{
		AutoMutex l = lock();
906
		m_frame_map.setBufferSize(nb_buffers);
907
		m_frame_map.clear();
908
		m_prev_ifa.clear();
909
910
911
		RecvList::iterator it, end = m_recv_list.end();
		for (it = m_recv_list.begin(); it != end; ++it)
			(*it)->prepareAcq();
912
913
914

		m_missing_last_skipped_frame.clear();
		if (m_skip_frame_freq)
915
			for (int i = 0; i < getNbRecvs(); ++i)
916
				m_missing_last_skipped_frame.insert(i);
917
918

		m_next_ready_ts = Timestamp();
919
	}
920

921
922
923
924
	RecvList::iterator rit, rend = m_recv_list.end();
	for (rit = m_recv_list.begin(); rit != rend; ++rit)
		(*rit)->prepareAcq();

925
	m_model->prepareAcq();
926
	m_global_cpu_affinity_mgr.prepareAcq();
927
	m_model->getReconstruction()->prepare();
928

929
	resetFramesCaught();
930
931
	EXC_CHECK(m_det->setFileWrite(0));
	EXC_CHECK(m_det->setNextFrameNumber(1));
932
933
}

934
void Camera::startAcq()
935
{
936
	DEB_MEMBER_FUNCT();
937

938
939
940
	AutoMutex l = lock();
	if (m_acq_thread)
		THROW_HW_ERROR(Error) << "Must call prepareAcq first";
941

942
	StdBufferCbMgr *cb_mgr = m_buffer.getBufferCbMgr();
943
	cb_mgr->setStartTimestamp(Timestamp::now());
944
945

	m_acq_thread = new AcqThread(this);
946
	m_acq_thread->start(l);
947
948
}

949
void Camera::stopAcq()
950
{
951
952
	DEB_MEMBER_FUNCT();

953
954
955
	Reconstruction *r = m_model ? m_model->getReconstruction() : NULL;
	if (r)
		r->cleanUp();
956
	m_global_cpu_affinity_mgr.stopAcq();
957

958
959
	AutoMutex l = lock();
	if (getEffectiveState() != Running)
960
961
		return;

962
	m_acq_thread->stop(l, true);
963
964
	if (getEffectiveState() != Idle)
		THROW_HW_ERROR(Error) << "Camera not Idle";
965
966
}

967
968
969
970
971
972
973
974
975
976
977
void Camera::triggerFrame()
{
	DEB_MEMBER_FUNCT();

	if (m_trig_mode != Defs::SoftTriggerExposure)
		THROW_HW_ERROR(InvalidValue) << "Wrong trigger mode";

	AutoMutex l = lock();
	if (getEffectiveState() != Running)
		THROW_HW_ERROR(Error) << "Camera not Running";

978
	EXC_CHECK(m_det->sendSoftwareTrigger());
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
	m_next_ready_ts = Timestamp::now();
	m_next_ready_ts += m_exp_time;
}

Camera::DetStatus Camera::getDetTrigStatus()
{
	DEB_MEMBER_FUNCT();

	if (m_trig_mode != Defs::SoftTriggerExposure)
		THROW_HW_ERROR(InvalidValue) << "Wrong trigger mode";

	Timestamp t = Timestamp::now();

	AutoMutex l = lock();
	bool ready = !m_next_ready_ts.isSet() || (m_next_ready_ts < t);
	DetStatus trig_status = ready ? Defs::Waiting : Defs::Running;
	DEB_RETURN() << DEB_VAR1(trig_status);
	return trig_status;
997
998
}

999
1000
void Camera::assemblePackets(DetFrameImagePackets&& det_frame_packets)
{