/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "webcam.h"


extern uint32_t options;
extern char *video_base;


int
open_device(webcam_t *cam, const uint8_t try)
{
  struct stat st;
  gchar *dev_name = NULL;

  dev_name = g_strdup_printf("%s%d", video_base, cam->cam_no+try);

  if (-1 == stat(dev_name, &st)) {
    VERBOSE(printf("[!] Cannot identify '%s': %d, %s\n", dev_name, errno, strerror(errno)));
    g_free(dev_name);
    return -1;
  }

  if (!S_ISCHR(st.st_mode)) {
    VERBOSE(printf("[!] '%s' is not a character device\n", dev_name));
    g_free(dev_name);
    return -1;
  }
  cam->fd = open(dev_name, O_RDWR | O_NONBLOCK, 0);

  if (-1 == cam->fd) {
    VERBOSE(printf("[!] Cannot open '%s': %d, %s\n", dev_name, errno, strerror(errno)));
    g_free(dev_name);
    return -1;
  } else {
    VERBOSE(printf("[i] Successfully opened %s as a video device, fd= %d\n", dev_name, cam->fd));
  }
  g_free(dev_name);

  return 0;
}


void
close_device(const webcam_t *cam)
{
  if (-1 == close(cam->fd)) {
    fprintf(stderr, "[!] %s webcam %d: close failed\n", __func__, cam->cam_no);
  }
}
