EigerStream.cpp 14.9 KB
Newer Older
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//###########################################################################
// This file is part of LImA, a Library for Image Acquisition
//
// Copyright (C) : 2009-2015
// 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/>.
//###########################################################################
#include <fcntl.h>
#include <unistd.h>

#include <map>
#include <set>

#include <zmq.h>

30
#include <json/json.h>
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
31
32
33
34
35
36
37

#include <eigerapi/Requests.h>
#include <eigerapi/EigerDefines.h>

#include "lima/Exceptions.h"
#include "EigerStream.h"

38
39
40
#define _BSD_SOURCE
#include <endian.h>

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using namespace lima;
using namespace lima::Eiger;
using namespace eigerapi;
//			--- Message struct ---
struct Stream::Message
{
  Message()
  {
    zmq_msg_init(&msg);
  }
  ~Message()
  {
    zmq_msg_close(&msg);
  }
  zmq_msg_t* get_msg() {return &msg;}

  zmq_msg_t msg;
};
//		--- Compression buffer management ---
class Stream::_BufferCallback : public HwBufferCtrlObj::Callback
{
  DEB_CLASS_NAMESPC(DebModCamera,"Stream","_BufferCallback");
63
64
  typedef std::pair<std::shared_ptr<Stream::Message>,int> MessageNDepth;
  typedef std::map<void*,MessageNDepth> Data2Message;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  typedef std::multiset<void *> BufferList;
public:
  _BufferCallback() : HwBufferCtrlObj::Callback() {}
  virtual ~_BufferCallback() {releaseAll();}

  virtual void map(void* address)
  {
    DEB_MEMBER_FUNCT();
    DEB_PARAM() << DEB_VAR1(address);

    AutoMutex lock(m_mutex);
    m_buffer_in_use.insert(address);
  }
  virtual void release(void* address)
  {
    DEB_MEMBER_FUNCT();
    DEB_PARAM() << DEB_VAR1(address);

    AutoMutex lock(m_mutex);
    BufferList::iterator it = m_buffer_in_use.find(address);
    if(it == m_buffer_in_use.end())
      THROW_HW_ERROR(Error) << "Internal error: releasing buffer not in used list";
    
    m_buffer_in_use.erase(it++);
    if(it == m_buffer_in_use.end() || *it != address)
      m_data_2_msg.erase(address);
  }
  virtual void releaseAll()
  {
    DEB_MEMBER_FUNCT();
    
    AutoMutex lock(m_mutex);
    m_buffer_in_use.clear();
    m_data_2_msg.clear();
  }
  
101
  void register_new_msg(std::shared_ptr<Stream::Message>& msg,void* aDataBuffer,int depth)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
102
103
104
105
106
  {
    DEB_MEMBER_FUNCT();
    DEB_PARAM() << DEB_VAR1(aDataBuffer);

    AutoMutex lock(m_mutex);
107
    m_data_2_msg[aDataBuffer] = MessageNDepth(msg,depth);
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
108
  }
109
  bool get_msg(void* aDataBuffer,void*& msg_data,size_t& msg_size,int& depth)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
110
111
112
113
114
115
116
117
  {
    DEB_MEMBER_FUNCT();
    DEB_PARAM() << DEB_VAR1(aDataBuffer);

    AutoMutex lock(m_mutex);
    Data2Message::iterator it = m_data_2_msg.find(aDataBuffer);
    if(it == m_data_2_msg.end())
      return false;
118
119
120
121
    
    MessageNDepth message_depth = it->second;
    std::shared_ptr<Stream::Message> message = message_depth.first;
    depth = message_depth.second;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    msg_data = zmq_msg_data(message->get_msg());
    msg_size = zmq_msg_size(message->get_msg());
    DEB_RETURN() << DEB_VAR2(msg_data,msg_size);
    return true;
  }
private:
  Mutex m_mutex;
  Data2Message m_data_2_msg;
  BufferList m_buffer_in_use;
};
//		      --- buffer management ---
class Stream::_BufferCtrlObj : public SoftBufferCtrlObj
{
  DEB_CLASS_NAMESPC(DebModCamera,"Stream","_BufferCtrlObj");
public:
  _BufferCtrlObj(Stream& stream) : 
    m_stream(stream)
  {
  }
  virtual HwBufferCtrlObj::Callback* getBufferCallback()
  {
    return m_stream.m_buffer_cbk;
  }
private:
  Stream&	m_stream;
};

//			 --- Stream class ---
Stream::Stream(Camera& cam) : 
  m_cam(cam),
  m_active(false),
  m_header_detail(OFF),
  m_dirty_flag(true),
  m_wait(true),
  m_running(false),
  m_stop(false),
  m_buffer_cbk(new Stream::_BufferCallback()),
  m_buffer_ctrl_obj(new Stream::_BufferCtrlObj(*this))
{
  DEB_CONSTRUCTOR();

163
164
165
  bool is_le = (htole16(0x1234) == 0x1234);
  m_endianess = (is_le ? '<' : '>');

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
  m_zmq_context = zmq_ctx_new();
  if(pipe(m_pipes))
    THROW_HW_ERROR(Error) << "Can't open pipe";

  pthread_create(&m_thread_id,NULL,_runFunc,this);
}

Stream::~Stream()
{
  AutoMutex aLock(m_cond.mutex());
  m_stop = true;
  m_cond.broadcast();
  aLock.unlock();
  _send_synchro();

  if(m_thread_id > 0)
    pthread_join(m_thread_id,NULL);

  close(m_pipes[0]),close(m_pipes[1]);
  zmq_ctx_destroy(m_zmq_context);

  delete m_buffer_cbk;
  delete m_buffer_ctrl_obj;
}

void Stream::start()
{
  m_buffer_ctrl_obj->getBuffer().setStartTimestamp(Timestamp::now());
}

void Stream::stop()
{
  setActive(false);

  AutoMutex aLock(m_cond.mutex());
  m_wait = true;
  m_cond.broadcast();
  _send_synchro();

  while(m_running)
    m_cond.wait();
}

void Stream::_send_synchro()
{
  DEB_MEMBER_FUNCT();

  if(write(m_pipes[1],"|",1) == -1)
    DEB_ERROR() << "Something wrong happened!";
}

bool Stream::isRunning() const
{
  AutoMutex aLock(m_cond.mutex());
  return m_running;
}

223
224
225
226
227
void Stream::getCompressionType(Camera::CompressionType& type) const
{
  m_cam.getCompressionType(type);
}

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
void Stream::getHeaderDetail(Stream::HeaderDetail& detail) const
{
  AutoMutex lock(m_cond.mutex());
  detail = m_header_detail;
}

void Stream::setHeaderDetail(Stream::HeaderDetail detail)
{
  AutoMutex lock(m_cond.mutex());
  m_header_detail = detail,m_dirty_flag = true;
}

void Stream::setActive(bool active)
{
  DEB_MEMBER_FUNCT();
  DEB_PARAM() << DEB_VAR1(active);

  AutoMutex lock(m_cond.mutex());
  //Don't resend parameters if not changed
  if(active != m_active || m_dirty_flag)
    {

      const char* header_detail_str;
      switch(m_header_detail)
	{
	case ALL:
	  header_detail_str = "all";break;
	case BASIC:
	  header_detail_str = "basic";break;
	default:
	  header_detail_str = "none";break;
	}

      std::shared_ptr<Requests::Param> header_detail_req = 
	m_cam.m_requests->set_param(Requests::STREAM_HEADER_DETAIL,header_detail_str);
      DEB_TRACE() << "STREAM_HEADER_DETAIL:" << DEB_VAR1(header_detail_str);
      header_detail_req->wait();

      const char* active_str = active ? "enabled" : "disabled";
      std::shared_ptr<Requests::Param> active_req = 
	m_cam.m_requests->set_param(Requests::STREAM_MODE,active_str);
      DEB_TRACE() << "STREAM_MODE:" << DEB_VAR1(active_str);
      active_req->wait();
    }
  m_active = active,m_dirty_flag = false;

  m_wait = !active;
  if(active)
    {
      m_cond.broadcast();
      while(!m_running)
	m_cond.wait();
    }
}

HwBufferCtrlObj* Stream::getBufferCtrlObj()
{
  DEB_MEMBER_FUNCT();
  return m_buffer_ctrl_obj;
}

289
bool Stream::get_msg(void* aDataBuffer,void*& msg_data,size_t& msg_size,int &depth)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
290
{
291
  return m_buffer_cbk->get_msg(aDataBuffer,msg_data,msg_size,depth);
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
}

void* Stream::_runFunc(void *streamPt)
{
  ((Stream*)streamPt)->_run();
  return NULL;
}

#define _CHECK_RETURN(funct)			\
  if(funct == -1)					\
    {						\
      if(errno == EAGAIN)				\
	{								\
	  DEB_TRACE() << "zmq EAGAIN";					\
	  break;							\
	}								\
									\
      continue_flag = false;						\
      char errno_buffer[256];						\
      char* errno_msg = strerror_r(errno,errno_buffer,sizeof(errno_buffer)); \
      DEB_ERROR() << "Something bad appends stream reading will stop (errno: " \
		  << errno_msg << ")";					\
      DEB_ERROR() << "After rx " << pending_messages.size() << " message(s)"; \
      break;								\
    }


static inline bool _get_json_header(std::shared_ptr<Stream::Message> &msg,
				    Json::Value& header)
{
322
  DEB_GLOBAL_FUNCT();
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
323
324
  void* data = zmq_msg_data(msg->get_msg());
  size_t data_size = zmq_msg_size(msg->get_msg());
325
326
  DEB_TRACE() << "json_header=" << std::string((char *) data, data_size);
  
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
  const char* begin = (const char*)data;
  const char* end = begin + data_size;
  Json::Reader reader;
  return reader.parse(begin,end,header);
}

#ifdef READ_HEADER
static bool _get_header(const Json::Value& stream_header,
			int nb_messages,std::vector<zmq_msg_t> &pending_messages,
			Json::Value& header)
{
  std::string header_detail = stream_header.get("header_detail","").asString();
  int message_id;
  if(nb_messages > 1 && header_detail == "none")
    message_id = 1;
  else if(nb_messages > 2 && header_detail == "basic")
    message_id = 2;
  else if(nb_messages > 8 && header_detail == "all")
    message_id = 8;
  else				// Unknown header detail
    return false;

  return _get_json_header(pending_messages[message_id],header);
}
#endif

void Stream::_run()
{
  DEB_MEMBER_FUNCT();
  
  AutoMutex aLock(m_cond.mutex());
  StdBufferCbMgr& buffer_mgr = m_buffer_ctrl_obj->getBuffer();

  while(1)
    {
      void* stream_socket = NULL;
      while(m_wait && !m_stop)
	{
	  DEB_TRACE() << "Wait";
	  m_running = false;
	  m_cond.broadcast();
	  m_cond.wait();
	  m_running = true;
	  DEB_TRACE() << "Running";
	}
      if(m_stop) break;
373
374
375
376
377
      int nb_frames;
      m_cam.getNbFrames(nb_frames);
      TrigMode trigger_mode;
      m_cam.getTrigMode(trigger_mode);

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
      bool continue_flag = true;
      //open stream socket
      char stream_endpoint[256];
      snprintf(stream_endpoint,sizeof(stream_endpoint),
	       "tcp://%s:9999",m_cam.getDetectorIp().c_str());
      stream_socket = zmq_socket(m_zmq_context,ZMQ_PULL);

      if(!zmq_connect(stream_socket,stream_endpoint))
	{
	  m_cond.broadcast();
	  aLock.unlock();

	  DEB_TRACE() << "connected to " << stream_endpoint;
	  //  Initialize poll set
	  zmq_pollitem_t items [] = {
	    { NULL, m_pipes[0], ZMQ_POLLIN, 0 },
	    { stream_socket, 0, ZMQ_POLLIN, 0 }
	  };
	  while(continue_flag)		// reading loop
	    {
	      DEB_TRACE() << "Enter poll";
	      zmq_poll(items,2,-1);
	      DEB_TRACE() << "Exit poll";

	      if(items[0].revents & ZMQ_POLLIN)
		{
		  char buffer[1024];
		  if(read(m_pipes[0],buffer,sizeof(buffer)) == -1)
		    DEB_WARNING() << "Something strange happened!";

		  aLock.lock();
		  continue_flag = !m_wait && !m_stop;
		  aLock.unlock();
		}
	      if(items[1].revents & ZMQ_POLLIN) // reading stream
		{
		  std::vector<std::shared_ptr<Stream::Message>> pending_messages;
		  pending_messages.reserve(9);
		  int more;
		  do {
		    std::shared_ptr<Stream::Message> msg(new Stream::Message());
		    _CHECK_RETURN(zmq_msg_recv(msg->get_msg(),stream_socket,0));
		    more = zmq_msg_more(msg->get_msg());
		    pending_messages.emplace_back(msg);
		  } while(more);
		  int nb_messages = pending_messages.size();
		  DEB_TRACE() << DEB_VAR1(nb_messages);
		  if(nb_messages > 0)
		    {
		      Json::Value stream_header;
		      continue_flag = _get_json_header(pending_messages[0],stream_header);
		      if(continue_flag)
			{
			  std::string htype = stream_header.get("htype","").asString();
			  DEB_TRACE() << DEB_VAR1(htype);
#ifdef READ_HEADER
			  if(htype.find("dheader-") != std::string::npos)
			    {
			      Json::Value header;
			      continue_flag = _get_header(stream_header,nb_messages,
							  pending_messages,header);
			      
			    }
			  else 
#endif
			    if(htype.find("dimage-") != std::string::npos)
			    {
			      int frameid = stream_header.get("frame",-1).asInt();
			      DEB_TRACE() << DEB_VAR1(frameid);
			      //stream_header.get("hash","md5sum")
			      if(nb_messages < 3)
				{
				  DEB_ERROR() << "Should receive at least 3 messages part, only received " 
					      << nb_messages;
				  break;
				}

			      Json::Value data_header;
			      if(!_get_json_header(pending_messages[1],data_header)) break;
457

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
458
459
460
461
			      //Data size (width,height)
			      Json::Value shape = data_header.get("shape","");
			      if(!shape.isArray() || shape.size() != 2) break;
			      FrameDim anImageDim;
462
			      anImageDim.setSize(Size(shape[0u].asInt(),shape[1u].asInt()));
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
463
			      //data type
464
			      ImageType image_type;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
465
466
			      std::string dtype = data_header.get("type","none").asString();
			      if(dtype == "int32")
467
				image_type = Bpp32S;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
468
			      else if(dtype == "uint32")
469
				image_type = Bpp32;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
470
			      else if(dtype == "int16")
471
				image_type = Bpp16S;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
472
			      else if(dtype == "uint16")
473
				image_type = Bpp16;
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
474
475
			      else
				break;
476
			      anImageDim.setImageType(image_type);
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
477
			      DEB_TRACE() << DEB_VAR1(anImageDim);
478
479
480
481
482
483
484

			      if (frameid == 0) {
				std::string encoding = data_header.get("encoding", "").asString();
				Camera::CompressionType comp_type;
				_checkEncoding(encoding, image_type, comp_type);
			      }

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
485
486
487
			      HwFrameInfoType frame_info;
			      frame_info.acq_frame_nb = frameid;
			      void* buffer_ptr = buffer_mgr.getFrameBufferPtr(frameid);
488
489
			      m_buffer_cbk->register_new_msg(pending_messages[2],buffer_ptr,
							     anImageDim.getDepth());
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
490
491
492
493
494
495
496
497
498
#ifdef READ_HEADER
			      if(nb_messages == 5)
				{
				  zmq_msg_t& msg = pending_messages[4]->msg;
				  char* headerpt = (char*)zmq_msg_data(&msg);
				  size_t header_size = zmq_msg_size(&msg);
				}
#endif
			      continue_flag = buffer_mgr.newFrameReady(frame_info);
499
500
			      if(trigger_mode != IntTrig && trigger_mode != IntTrigMult && !--nb_frames)
				m_cam.disarm();
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
501
502
503
504
505
506
507
508
509
			    }
			    else if(htype.find("dseries_end-") != std::string::npos)
			      continue_flag = false;
			}
		    }
		}
	    }
	}
      else
510
511
512
513
	{
	  char error_buffer[256];
	  char* error_msg = strerror_r(errno,error_buffer,sizeof(error_buffer));
	  DEB_ERROR() << "Connection error: " << DEB_VAR2(errno,error_msg);
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
514
	aLock.unlock();
515
	}
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
516
517
518
519
520
521
522
523

      if(stream_socket) zmq_close(stream_socket);
      DEB_TRACE() << "disconnected from " << stream_endpoint;
      aLock.lock();
      m_wait = true;
    }
  m_running = false;
}
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565

void Stream::_checkEncoding(const std::string& encoding,
			    ImageType image_type,
			    Camera::CompressionType& comp_type)
{
  DEB_MEMBER_FUNCT();
  DEB_PARAM() << DEB_VAR3(encoding, image_type, m_endianess);

  char endianess = *encoding.rbegin();
  if (endianess != m_endianess)
    THROW_HW_ERROR(Error) << "Endianess mismatch: "
			  << "got " << endianess << ", "
			  << "expected " << m_endianess;

  if (encoding == std::string(1, m_endianess)) {
    comp_type = Camera::NoCompression;
  } else {
    const std::string lz4 = std::string("lz4") + m_endianess;
    if (encoding == lz4) {
      comp_type = Camera::LZ4;
    } else {
      const char *bs;
      switch (image_type) {
      case Bpp32S: case Bpp32: bs = "bs32-"; break;
      case Bpp16S: case Bpp16: bs = "bs16-"; break;
      case Bpp8S:  case Bpp8:  bs = "bs8-";  break;
      }
      if (encoding == std::string(bs) + lz4)
	comp_type = Camera::BSLZ4;
      else
	THROW_HW_ERROR(Error) << "Unexpected encoding: " << encoding;
    }
  }

  Camera::CompressionType expected_comp_type;
  getCompressionType(expected_comp_type);
  if (comp_type != expected_comp_type)
    THROW_HW_ERROR(Error) << "Unexpected compression type: " << comp_type;

  DEB_RETURN() << DEB_VAR1(comp_type);
}