#ifndef __HELPFUNC_H
#define __HELPFUNC_H

#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <asm/types.h>
#include "v4l2.h"

#ifdef __PTV__C
#define _EXTERN
#else
#define _EXTERN extern
#endif

#undef DEBUG

#define	VIDEO	          1
#define	AUDIO		  2
#define BUFFSIZE       4096 * 16
#define NUM_BUFS         16
#define MAX_DEV_NAME     64
#define PRIORITY        -15
#define USLEEP          200  //20050823: 40000 -> 20000 -w.
#define PVRSLEEP     500000
#define MAXSOURCES       10
#define STDOUT            1
#define SYSLOG            2
#define TOUCH(x) x = x
#define MAX_DEV_NUM       8

#define IOCTL(fd, cmd, data)                         \
({ int __result; do __result = ioctl(fd, cmd, data); \
   while (__result == -1L && errno == EINTR); __result; })

#define saveIOCTL(fd, cmd, data)                                        \
({                                                                      \
  register int cc;                                                      \
  auto 	   int numRetries = 20, retries = 0, wait = 100000;             \
  d(0, "saveIOCTL(fd, cmd, data)");                                     \
  do {                                                                  \
    cc = IOCTL(fd, cmd, data);                                          \
    if (cc) {                                                       	\
      if (retries++ < numRetries) {                                     \
        d(1, "saveIOCTL: try number %2d)\033[K\r", retries);            \
	usleep(wait);  	  		      	   	      		\
        }                                                               \
      else {                                                            \
        d(0, "saveIOCTL: %d retries reached, giving up.", retries - 1); \
        break;                                                          \
        }                                                               \
      }                                                                 \
  } while (cc);                                                     	\
  cc;                                                                   \
})

typedef struct
  {
  /* generic properties */
  int  linuxver;
  int  debug;
  int  logger;
  int  cardnum;
  /* device independend properties */
  int  brightness;
  int  contrast;
  int  color;
  int  hue;
  int  aspect;
  int  pulldown;
  int  dnr_spatial;
  int  dnr_temporal;
  int  volume;
  int  videonorm;
  } SETUP;

typedef struct
  {
  int    freq;
  char  *channelname;
  } CHANNELNAMES;


_EXTERN SETUP ptvsetup, tmpsetup;

_EXTERN char video_device[MAX_DEV_NAME];

extern const char *tvnorms[];
extern const char *inputs[];

_EXTERN void *(* fast_memcpy)(void *to, const void *from, size_t len);

#if defined(__cplusplus)
extern "C" {
#endif

void  d                        (int level, const char *fmt, ...);
char *Freq2Channelname         (int frequency);

#if defined(__cplusplus)
}
#endif

#endif // __HELPFUNC_H
