CIpassive.c

/*****************************************************************************

	CIpassive.c			Source for BitFlow CI lib passive example program

	Dec 20,		2012	CIW/SJT

	© Copyright 2012, BitFlow, Inc. All rights reserved.

	Tabstops are 4

	$Author: steve $

	$Date: 2020/10/02 23:30:12 $

	$Id: CIpassive.c,v 1.9 2020/10/02 23:30:12 steve Exp $

*****************************************************************************/

/*==========================================================================*/
/*
**	For access to command line display.
*/
#include	<stdio.h>
#include	<stdarg.h>
#include	<string.h>
/*
**	For checking for keypress
*/
#include	<sys/time.h>
#include	<sys/types.h>
#include	<unistd.h>
/*
**	For access to BitFlow camera interface library.
*/
#include	"BFciLib.h"
/*==========================================================================*/
static int sExitAns = 0;		/* program exit code */
static int sLibDebug = 0;		/* enable library display */
static tCIp sCIp = NULL;		/* device open token */
static int sNdx = 0;			/* device index */
static int sMaxFrames = 0;		/* total frames to display */
static int sSkipFrames = 0;		/* skip between display */
static int sDidFrames = 0;		/* total frames handled */
static int sTimeout = -1;		/* timeout for new frames */
static int sBGok = 0;			/* ok to be in background */
static int sPixShow = -1;		/* size of display */
static int sLinShow = 1;		/* size of display */
static int sPixToSkip = 0;		/* left is default */
static int sLinToSkip = 0;		/* top is default */
/*--------------------------------------------------------------------------*/
#define	SHOW(x)	{ (void)printf x ; (void)fflush(stdout); }
#define	ERR(x)	{ SHOW(("ERR: ")); SHOW(x); }

static char *sArgv0 = NULL;		/* name of executable */
static void ShowHelp(void)
{
	SHOW(("%s of " __DATE__ " at " __TIME__ "\n", sArgv0));
	SHOW(("   -h           display this message and exit\n"));
	SHOW(("\n"));
	SHOW(("   -x ndx       choose available device ndx (default 0)\n"));
	SHOW(("   -m maxFrames max frames to display (default infinite)\n"));
	SHOW(("   -s skipFr    frames to skip between display (default 0)\n"));
	SHOW(("   -t msec      timeout (msec) for new data (default infinite)\n"));
	SHOW(("   -W nPixShow  show this many pixels (default auto size)\n"));
	SHOW(("   -L nLinShow  show this many lines/frame (default 1)\n"));
	SHOW(("   -w pixToSkip skip this many pixels at start of each line\n"));
	SHOW(("   -l linToSkip skip this many lines at start of each frame\n"));
	SHOW(("   -b           program is backgrounded (no newline exit)\n"));
	SHOW(("   -D           display library debug info ('LDB' prefix)\n"));
	SHOW(("\n"));
	SHOW(("  CIpassive: attach to running VFG and display pixels\n"));
	SHOW(("      display ends with newline\n"));
	SHOW(("\n"));
}

/*==========================================================================*/
static void LDBdisplay(char *format, ...)
/*
**	Library debug display function.
**
**	This will display progress/information/error strings from BFciLib
*/
{
	va_list val;
	char buff[8192];

	va_start(val, format);
	(void)vsprintf(buff, format, val);
	va_end(val);
	/*
	 ** buff now contains the library display string
	 **
	 ** This function simply prints it to the console.
	 */
	(void)printf("LDB: %s\n", buff);
	(void)fflush(stdout);
}

/*--------------------------------------------------------------------------*/
#include	<time.h>
#include	<sys/timeb.h>
static tCIDOUBLE GetTime(void)
/*
**	Return fractional seconds
*/
{
	tCIDOUBLE ans = 0.0;

#ifdef _POSIX_TIMERS

	struct timespec tp;

	(void)clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
	ans = (tCIDOUBLE) tp.tv_sec;
	ans += ((tCIDOUBLE) tp.tv_nsec) / 1000000000.0;

#else

	struct timeb tb;

	(void)ftime(&tb);
	ans = tb.millitm;
	ans /= 1000.0;
	ans += tb.time;

#endif

	return (ans);
}

/*--------------------------------------------------------------------------*/
static int DecodeArgs(int argc, char **argv)
/*
**	Parse the input arguments.
*/
{
	char *str;

	argv += 1;
	argc -= 1;					/* skip program name */

	while (argc-- > 0)
	{
		str = *argv++;
		if (str[0] != '-')
		{
			ERR(("Do not know '%s' arg\n", str));
			ShowHelp();
			sExitAns = 1;
			return (sExitAns);
		}
		switch (str[1])
		{
		case 'h':
			ShowHelp();
			return (1);
		case 'x':
			(void)sscanf(*argv, "%d", &sNdx);
			argv += 1;
			argc -= 1;
			break;
		case 'W':
			(void)sscanf(*argv, "%d", &sPixShow);
			argv += 1;
			argc -= 1;
			break;
		case 'L':
			(void)sscanf(*argv, "%d", &sLinShow);
			argv += 1;
			argc -= 1;
			break;
		case 'w':
			(void)sscanf(*argv, "%d", &sPixToSkip);
			argv += 1;
			argc -= 1;
			break;
		case 'l':
			(void)sscanf(*argv, "%d", &sLinToSkip);
			argv += 1;
			argc -= 1;
			break;
		case 'b':
			sBGok = 1;
			break;
		case 'D':
			sLibDebug = 1;
			break;
		case 'm':
			(void)sscanf(*argv, "%d", &sMaxFrames);
			argv += 1;
			argc -= 1;
			break;
		case 't':
			(void)sscanf(*argv, "%d", &sTimeout);
			argv += 1;
			argc -= 1;
			break;
		case 's':
			(void)sscanf(*argv, "%d", &sSkipFrames);
			argv += 1;
			argc -= 1;
			break;
		default:
			ERR(("Do not know arg '%s' arg\n", str));
			ShowHelp();
			sExitAns = 1;
			return (sExitAns);
		}
	}

	return (kCIEnoErr);
}

/*--------------------------------------------------------------------------*/
static int CheckForKeyboardInput(void)
/*
**	Return 0 if no input available from stdin, 1 else
**
**	Note: the console needs a newline in order to post input.
*/
{
	fd_set exceptfds, readfds, writefds;
	struct timeval tv;
	int ans;
	char buff[1024];

	FD_ZERO(&exceptfds);
	FD_ZERO(&readfds);
	FD_ZERO(&writefds);
	FD_SET(fileno(stdin), &readfds);
	(void)memset(&tv, '\0', sizeof(struct timeval));

	ans = select(1, &readfds, &writefds, &exceptfds, &tv);

	if ((ans == 1) && FD_ISSET(fileno(stdin), &readfds))
	{
		/*
		 **   Consume the line.
		 */
		(void)fgets(buff, 1024, stdin);
		return (1);
	}

	return (0);
}

/*--------------------------------------------------------------------------*/
static void InitAndGetDataUntilKeyPress(void)
/*
**	Illustrate a simple example board interaction sequence.
*/
{
	tCIRC circ;
	tCIDOUBLE a = -1.0, b, c, d;
	tCIU64 totalBytes = 0, totalLines = 0;
	tCIU32 i, offX, offY;
	tCIU32 nPtrs;
	tCIU8 **uPtrs = NULL;
	tCIU8 *p8;
	unsigned short *p16;
	tCIU32 *p32;
	tCIU32 frameID, value, value2, value3, pixToShow;
	tCIU8 *frameP;
	tCIU32 nFrames, bitsPerPix, hROIoffset, hROIsize, vROIoffset, vROIsize, stride;
	int nowLine;
	char *fmtStr;
	/*
	 ** Open the ndx'th frame grabber with read-only permission.
	 */
	circ = CiVFGopen(sNdx, kCIBO_readOnly, &sCIp);
	if (kCIEnoErr != circ)
	{
		ERR(("CiVFGopen gave '%s'\n", CiErrStr(circ)));
		sExitAns = 1;
		return;
	}
	circ = CiSetDebug(sCIp, -1, (0 == sLibDebug) ? NULL : LDBdisplay);
	if (kCIEnoErr != circ)
	{
		ERR(("CiSetDebug gave '%s'\n", CiErrStr(circ)));
	}
	/*
	 ** Determine buffer configuration.  We only need bitsPerPix and stride.
	 */
	circ = CiBufferInterrogate(sCIp, &nFrames, &bitsPerPix, &hROIoffset, &hROIsize, &vROIoffset, &vROIsize, &stride);
	if (kCIEnoErr != circ)
	{
		ERR(("CiBufferInterrogate gave '%s'\n", CiErrStr(circ)));
		sExitAns = 1;
		goto andOut;
	}
	/*
	 ** Get the buffer pointers for read only access to buffers.
	 */
	circ = CiMapFrameBuffers(sCIp, 0, &nPtrs, &uPtrs);
	if (kCIEnoErr != circ)
	{
		ERR(("CiMapFrameBuffers gave '%s'\n", CiErrStr(circ)));
		sExitAns = 1;
		goto andOut;
	}
	/*
	 ** Decide how many per line we show.
	 */
	switch (bitsPerPix)
	{
	case 64:
	case 8:
		pixToShow = 16;
		break;
	case 10:
	case 12:
		pixToShow = 12;
		break;
	case 14:
	case 16:
	case 24:
		pixToShow = 8;
		break;
	case 30:
	case 32:
	case 36:
	case 48:
		pixToShow = 6;
		break;
	default:
		ERR(("Do not know pixBitDepth of %d\n", bitsPerPix));
		sExitAns = 1;
		goto andOut;
	}
	if (0 < sPixShow)
	{
		pixToShow = sPixShow;
	}
	/*
	 ** Handle defaults for right/bottom: -1 is full-right/full-bottom
	 */
	if (0 == sPixToSkip)
	{
		offX = 0;
	}
	else if (0 < sPixToSkip)
	{
		offX = BYTES_PER_PIXEL(bitsPerPix) * sPixToSkip;
	}
	else
	{
		offX = ((hROIsize + (sPixToSkip + 1)) * BYTES_PER_PIXEL(bitsPerPix)) - (BYTES_PER_PIXEL(bitsPerPix) * pixToShow);
	}
	if (0 == sLinToSkip)
	{
		offY = 0;
	}
	else if (0 < sLinToSkip)
	{
		offY = stride * sLinToSkip;
	}
	else
	{
		offY = ((vROIsize + (sLinToSkip + 1)) * stride) - (stride * sLinShow);
	}
	/*
	 ** Tell the user how to stop this cleanly.
	 */
	(void)CiVFGinquire2(sCIp, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &fmtStr);

	if (0 == sBGok)
	{
		SHOW(("Will dump 1st line of frames (%d %d/%d %d/%d %d/%d (%s))"
			  " until newline (skip %d, ndx %d, to %d) (roi: %d/%d %d/%d)\n",
			  nFrames, hROIoffset, hROIsize, vROIoffset, vROIsize, bitsPerPix,
			  stride, fmtStr, sSkipFrames, sNdx, sTimeout, sPixToSkip,
			  pixToShow, sLinToSkip, sLinShow));
	}
	else
	{
		SHOW(("Will dump 1st line of frames (%d %d/%d %d/%d %d/%d (%s))"
			  " until %d (skip %d, ndx %d, to %d) (roi: %d/%d %d/%d)\n",
			  nFrames, hROIoffset, hROIsize, vROIoffset, vROIsize, bitsPerPix,
			  stride, fmtStr, sMaxFrames, sSkipFrames, sNdx, sTimeout,
			  sPixToSkip, pixToShow, sLinToSkip, sLinShow));
	}
	a = GetTime();
	/*
	 ** Display each acquired frame 1st line in a loop.  Stop at newline.
	 */
	while (1)
	{
		/*
		 ** Check to see if a frame is already available before waiting.
		 */
checkAgain:
		circ = CiGetOldestNotDeliveredFrame(sCIp, &frameID, &frameP);
		switch (circ)
		{
		case kCIEnoErr:
			/*
			 **   We have the frame.
			 */
			break;
		case kCIEnoNewData:
			/*
			 **   We need to wait for another frame.
			 */
			circ = CiWaitNextUndeliveredFrame(sCIp, sTimeout);
			if (kCIEnoErr != circ)
			{
				switch (circ)
				{
				case kCIEaqAbortedErr:
					SHOW(("CiWaitNextUndeliveredFrame gave '%s'\n", CiErrStr(circ)));
					break;
				default:
					ERR(("CiWaitNextUndeliveredFrame gave '%s'\n", CiErrStr(circ)));
					sExitAns = 1;
				}
				goto andOut;
			}
			goto checkAgain;
		default:
			ERR(("CiGetOldestNotDeliveredFrame gave '%s'\n", CiErrStr(circ)));
			sExitAns = 1;
			goto andOut;
		}
		/*
		 **   Allow skipping frames so display is not an issue.
		 */
		if ((0 != sSkipFrames) && (0 != (sDidFrames % (sSkipFrames + 1))))
		{
			goto skipHere;
		}
		/*
		 **   Display the frameID and the first line of frame data.
		 */
		nowLine = sLinShow;
		/*
		 **   Move to proper line in buffer.
		 */
		frameP += offY;
		/*
		 **   Move to proper pixel in buffer.
		 */
		frameP += offX;
		/*
		 **   Prepare for per-line increment.
		 */
		frameP -= stride;
anotherLine:
		frameP += stride;
		if (1 < sLinShow)
		{
			SHOW(("frameID %9d(%d):", frameID, (offY / stride) + sLinShow - nowLine));
		}
		else
		{
			SHOW(("frameID %9d:", frameID));
		}
		switch (bitsPerPix)
		{
		case 64:
		case 8:
			p8 = frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p8++;
				SHOW((" %02X", value));
			}
			break;
		case 10:
		case 12:
			p16 = (tCIU16 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p16++;
				SHOW((" %03X", value));
			}
			break;
		case 14:
		case 16:
			p16 = (tCIU16 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p16++;
				SHOW((" %04X", value));
			}
			break;
		case 24:
			p8 = (tCIU8 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p8++;
				value2 = *p8++;
				value3 = *p8++;
				SHOW((" %02X.%02X.%02X", value, value2, value3));
			}
			break;
		case 30:
			p32 = (tCIU32 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p32++;
				value2 = (value >> 10) & 0x3FF;
				value3 = (value >> 20) & 0x3FF;
				value &= 0x03FF;
				SHOW((" %03X.%03X.%03X", value, value2, value3));
			}
			break;
		case 32:
			p32 = (tCIU32 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p32++;
				SHOW((" %08X", value));
			}
			break;
		case 36:
			p16 = (tCIU16 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p16++;
				value2 = *p16++;
				value3 = *p16++;
				SHOW((" %03X.%03X.%03X", value, value2, value3));
			}
			break;
		case 48:
			p16 = (tCIU16 *) frameP;
			for (i = 0; i < pixToShow; i++)
			{
				value = *p16++;
				value2 = *p16++;
				value3 = *p16++;
				SHOW((" %04X.%04X.%04X", value, value2, value3));
			}
			break;
		default:
			ERR(("Do not know pixBitDepth of %d\n", bitsPerPix));
			sExitAns = 1;
			goto andOut;
		}
		SHOW(("\n"));
		if (0 < --nowLine)
		{
			goto anotherLine;
		}

skipHere:
		totalLines += vROIsize;
		totalBytes += ((bitsPerPix + 7) >> 3) * hROIsize * vROIsize;
		sDidFrames += 1;
		/*
		 **   Break out of this loop on newline
		 */
		if (0 == sBGok)
		{
			if (0 != CheckForKeyboardInput())
			{
				break;
			}
		}
		/*
		 **   Break out of loop if countdown hits zero
		 */
		if ((0 != sMaxFrames) && (--sMaxFrames == 0))
		{
			break;
		}
	}

andOut:
	/*
	 ** Unmap the frame buffers.
	 */
	if ((NULL != uPtrs) && (kCIEnoErr != (circ = CiUnmapFrameBuffers(sCIp))))
	{
		ERR(("CiUnmapFrameBuffers gave '%s'\n", CiErrStr(circ)));
	}
	/*
	 ** Close the access.
	 */
	if ((NULL != sCIp) && (kCIEnoErr != (circ = CiVFGclose(sCIp))))
	{
		ERR(("CiVFGclose gave '%s'\n", CiErrStr(circ)));
	}
	/*
	 ** Show data rate
	 */
	c = b = GetTime() - a;
	if ((a < 0.0) || (c < 0.001))
	{
		a = 0.0;
		b = 0.0;
		c = 0.0;
		d = 0.0;
	}
	else
	{
		a = ((tCIDOUBLE) totalBytes) / c;
		b = ((tCIDOUBLE) totalLines) / c;
		d = ((tCIDOUBLE) sDidFrames) / c;
	}
	SHOW(("%d:Data rate %.1lf ln/s (%.1lf b/s) (%.1lf FPS) (%.1lf sec) after %d frames\n", sNdx, b, a, d, c, sDidFrames));

	return;
}

/*==========================================================================*/
int main(int argc, char **argv)
/*
**	Decode command line and acquire/display frames until EOF
*/
{
	sArgv0 = *argv;

	if (kCIEnoErr == DecodeArgs(argc, argv))
	{
		InitAndGetDataUntilKeyPress();
	}

	return (sExitAns);
}

/*==========================================================================*/
/*
	$Log: CIpassive.c,v $
	Revision 1.9  2020/10/02 23:30:12  steve
	CLOCK_MONOTONIC is not always monotonic, so prefer CLOCK_MONOTONIC_RAW.

	Revision 1.8  2020/10/02 01:17:23  steve
	ftime is deprecated. Use clock_gettime.

	Revision 1.7  2018/01/23 10:43:07  steve
	Fix 32b mem issue

	Revision 1.6  2017/12/12 11:05:51  steve
	Fixes for axn+vivid

	Revision 1.5  2017/09/29 09:14:01  steve
	Now dump all camf

	Revision 1.4  2015/01/15 17:24:40  steve
	Cyton available

	Revision 1.3  2014-05-29 13:14:14  steve
	User lib c++ supporting Neon/Alta/Kbn/KbnCXP

	Revision 1.2  2013-03-07 15:23:05  steve
	Fix test details

	Revision 1.1  2013-03-03 18:58:11  steve
	Ready w/CXP

*/