/* qcam.c -- routines for accessing the Connectix QuickCam */

/* Version 0.4b, May 21, 1996 */
/* Version 0.5, August 24, 1996 */
/* Version 0.9, November 17, 1996 */


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

Copyright (C) 1996 by Scott Laird

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL SCOTT LAIRD BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/time.h>
#include "qcam.h"
#include "qcamip.h"

/* Include for JPEG processing */
#include <jpeglib.h>
#include "writejpeg.h"

void usage(void)
{
  fprintf(stderr,"Usage:\n");
  fprintf(stderr,"  qcam [options]\n");
  fprintf(stderr,"    Options:\n");
  fprintf(stderr,"      -x width   Set width\n");
  fprintf(stderr,"      -y height  Set height\n");
  fprintf(stderr,"      -p port    Set port\n");
  fprintf(stderr,"      -B bpp     Set bits per pixel\n");

  fprintf(stderr,"      -c val     Set contrast\n");
  fprintf(stderr,"      -w val     Set white balance\n");
  fprintf(stderr,"      -W         Auto-set white balance\n");
  fprintf(stderr,"      -b val     Set brightness\n");
  fprintf(stderr,"      -E \"vals\"  Autoexposure mode, parameters required\n");
  fprintf(stderr,"      -D         Remove dark speckling\n");
  fprintf(stderr,"      -e         Perform edge detection\n");

  fprintf(stderr,"      -H         Display Histogram\n");
  fprintf(stderr,"      -s val     Set scaling factor (1, 2, or 4)\n");
  fprintf(stderr,"      -t val     Set top line of scan\n");
  fprintf(stderr,"      -l val     Set left column of scan\n");
  fprintf(stderr,"      -f file    Select configuration file\n");
  fprintf(stderr,"      -u         Force unidirectional mode\n");
  fprintf(stderr,"      -V         Show version information\n");
  fprintf(stderr,"      -j         Output in JPEG format\n");
  fprintf(stderr,"      -J file    Output to file in JPEG format\n");
  fprintf(stderr,"      -q val     JPEG compression quality - default=50\n");
  fprintf(stderr,"      -L         Loop continuously (jpeg only)\n");
  fprintf(stderr,"      -d file    Dump cam information to file\n");
}


void modegripe(struct qcam *q)
{
  fprintf(stderr,"Unsupported resolution/bit depth!\n");
  fprintf(stderr,"This program only supports 320x240, 160x120, and 80x60.\n");
  fprintf(stderr,"You specified %d x %d.  Try again.\n",q->width,q->height);
  exit(1);
}

int main(int argc, char **argv)
{
  scanbuf *scan=0;
  int arg;
  extern char *optarg;
  extern int optind;
  struct qcam *q;
  int width,height;
  int autocalibrate = 0;
  int autoexposure = 0;
  int ae_arg_cnt;
  int ae_mode, ae_lum_target, ae_lum_tolerance;
  int ae_lum_std_target, ae_lum_std_tolerance;
  int dark = 0;
  int dump = 0;
  char dumpfile[BUFSIZ];
  int edge = 0;
  int histogram = 0;
  int snapshots = 0;
  char jpegfile[BUFSIZ];
  int maxsnaps = 11;
  static char *getargs = "hx:y:p:b:B:c:w:s:t:l:f:E:HVWuDd:eJ:jLq:";
  int found;
  /* Added for jpeg */
  int jfile = 0;
  int jpeg = 0;
  int looping = 0;
  extern int image_width, image_height, image_quality;
  int j,gridsize,shift;
  FILE *out;
  /* End of jpeg initialization additions */
#ifdef DEBUG
  struct timeval start, end;
  double microseconds;
#endif
	
  image_quality = 50;

  if(geteuid()) {
    fprintf(stderr,"%s: Not installed SUID or run as root.  Exiting.\n",
	    argv[0]);
    exit(1);
  }

  q=qc_init();

  /* unpleasant pre-search for -f option */
  found = 0;
  while ((arg = getopt(argc, argv, getargs)) > 0) {
    if (arg == 'f' && !found) {
      qc_initfile(q, optarg);
      found = 1;
    }
  }
  if (!found) qc_initfile(q, 0); /* use default */

  qc_getresolution(q,&width,&height);

  /* Read command line */

  optind = 0;
  while((arg=getopt(argc,argv,getargs))>0) { 
    switch (arg) {
    case 'x':
      width=atoi(optarg);
      break;
    case 'y':
      height=atoi(optarg);
      break;
    case 'p':
      if (!getuid())
	q->port=strtol(optarg,NULL,0);
      break;
    case 'B':
      qc_setbitdepth(q,atoi(optarg));
      break;
    case 'b':
      qc_setbrightness(q,atoi(optarg));
      break;
    case 'c':
      qc_setcontrast(q,atoi(optarg));
      break;
    case 'w':
      qc_setwhitebal(q,atoi(optarg));
      break;
    case 's':
      if (qc_settransfer_scale(q, atoi(optarg)))
	fprintf(stderr, "Bad scaling factor, valid values are 1, 2 or 4\n");
      break;
    case 't':
      if (qc_settop(q, atoi(optarg)))
	fprintf(stderr, "Bad top line, valid values are 1 - 243\n");
      break;
    case 'l':
      if (qc_setleft(q, atoi(optarg)))
	fprintf(stderr, "Bad left column, valid values are 2 - 336, and must be even\n");
      break;
    case 'f':
      /* already handled */
      break;
    case 'V':
      fprintf(stderr,"%s: Version %s\n",argv[0], VERSION);
      exit(0);
      break;
    case 'W':
      autocalibrate = 1;
      break;
    case 'E':
      autoexposure = 1;
      ae_arg_cnt = sscanf(optarg, "%d %d %d %d %d", &ae_mode,
			  &ae_lum_target, &ae_lum_tolerance,
			  &ae_lum_std_target, &ae_lum_std_tolerance);
      switch (ae_arg_cnt) {
      case 5:
	if (qcip_set_luminance_std_tolerance(q, ae_lum_std_tolerance))
	  fprintf(stderr, "Invalid luminance std tolerance.\n");
      case 4:
	if (qcip_set_luminance_std_target(q, ae_lum_std_target))
	  fprintf(stderr, "Invalid luminance std target.\n");
      case 3:
	if (qcip_set_luminance_tolerance(q, ae_lum_tolerance))
	  fprintf(stderr, "Invalid luminance tolerance.\n");
      case 2:
	if (qcip_set_luminance_target(q, ae_lum_target))
	  fprintf(stderr, "Invalid luminance target.\n");
      case 1:
	if (qcip_set_autoexposure_mode(ae_mode))
	  fprintf(stderr, "Invalid autoexposure mode.\n");
	break;
      default:
	  fprintf(stderr, "Invalid arguments for auto exposure.\n");
	  exit(1);
	break;
      }
      break;
    case 'H':
      histogram = 1;
      break;
    case 'u':
      qc_forceunidir(q);
      break;
    case 'D':
      dark = 1;
      break;
    case 'e':
      edge = 1;
      break;
    case 'd':
      dump = 1;
      strncpy(dumpfile, optarg, BUFSIZ);
      break;
    case 'j':
      jpeg = 1;
      break;
    case 'J':
      jfile = 1;
      strncpy(jpegfile, optarg, BUFSIZ);
      break;
    case 'L':
      looping = 1;
      break;
    case 'q':
      image_quality = atoi(optarg);
      if (image_quality > 100) image_quality = 100;
      if (image_quality < 1) image_quality = 1;
      break;
    case 'h':
      usage();
      exit(0);
      break;
    default:
      fprintf(stderr,"%s: Unknown option or error in option\n",argv[0]);
      usage();
      exit(1);
      break;
    }
  }

  if(qc_setresolution(q,width,height)) {
    fprintf(stderr,"Invalid resolution.  Exiting.\n");
    exit(1);
  }

  /* Attempt to get permission to access IO ports.  Must be root */

  if (qc_open(q)) {
    fprintf(stderr,"Cannot open QuickCam; exiting.\n");
    exit(1);
  }

  setuid(getuid());

  do {

    /* Program the QuickCam */

    qc_set(q);

    if (autocalibrate) {
      qc_calibrate(q);
    }

    /* Scan one image */

#ifdef DEBUG
    if (gettimeofday(&start, NULL))
      perror("get start time");
#endif

    scan=qc_scan(q);
    if (dark) {
      fixdark(q, scan);
    }

#ifdef DEBUG
    if (gettimeofday(&end, NULL))
      perror("get end time");

    microseconds = end.tv_usec - start.tv_usec;
    microseconds += 1000000.0 * (end.tv_sec - start.tv_sec);  
    fprintf(stderr, "%.0f ms to scan image", microseconds/1000.0);
    if (microseconds != 0)
      fprintf(stderr, " (%.1f fps)\n", 1000000.0/microseconds);
    else
      fprintf(stderr, "\n");
#endif

    snapshots++;
  } while (autoexposure && qcip_autoexposure(q, scan) && snapshots < maxsnaps);

  if (edge)
    qc_edge_detect(q, scan, -1);

  if (histogram)
    qcip_display_histogram(q, scan);

  /* Output the image to stdout or a file */

  if (jpeg || jfile) {
	image_width = qc_getwidth(q)/qc_gettransfer_scale(q);
	image_height = qc_getheight(q)/qc_gettransfer_scale(q);

	/* This weird gridsize and shift stuff is necessary to compensate
	   for a darkened image when using jpeg */

	gridsize = image_height * image_width;
	shift = BITS_IN_JSAMPLE - qc_getbitdepth(q);
	
loopflag:

	/* Compress the image & output */
	    for(j=0;j<gridsize;j++)
	      scan[j] = scan[j] << shift;

	if (jfile) {
		out = fopen("grab.jpg","wb");
		write_JPEG_file((JSAMPLE *) scan, out);
		fclose(out);

		/* rename is necessary for looping, at least for a webcam */

		rename("grab.jpg", jpegfile);
	} else {
		write_JPEG_file((JSAMPLE *) scan, stdout);
	}
	
	if (looping) {
		free(scan);
		scan=qc_scan(q);

		/* Other scan operators could be added here. I just added
		    edge detection because it's cool :) */

 		if (edge)
			qc_edge_detect(q, scan, -1);

		/* I know, it's ugly (goto), but the easiest quick hack */
		goto loopflag;
	}

	free(scan);

  } else {
  	qc_writepgm(q,stdout,scan);
  	free(scan);
  }

  if (dump)
    qc_dump(q, dumpfile);

  /* Release IO privileges */
  qc_close(q);

  return 0;
}

