/*
 * DV Player plugin for VDR
 *
 * Copyright (C) 2003, 2004 Erich Bachl <erich.bachl@vr-web.de>
 *
 * This code is distributed under the terms and conditions of the
 * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details.
 *
 */

#include <stdio.h>
#include <signal.h>

#include "device.h"
#include "shellthread.h"
#include "i18n.h"


cDVDevice::cDVDevice(void) { // 4. VDR call
  m_TSBuffer = NULL;
  pShellThread = NULL;
}

cDVDevice::~cDVDevice()
{
}

bool cDVDevice::SetPid(cPidHandle *Handle, int Type, bool On)
{
  dx(3, "cDVDevice::SetPid(Pid=%d, handle=%d, used=%d, Type=%d, On=%d)",
    Handle->pid, Handle->handle, Handle->used, Type, On);
  return true;
}

bool cDVDevice::OpenDvr(void)
{
  dx(3, "cDVDevice::OpenDvr()");

  mknod(FIFO, S_IFIFO|S_IRUSR|S_IWUSR, 0);

  if((fd_pvr = open(FIFO, O_RDONLY | O_NONBLOCK)) >= 0)
  {
    printf("Data detected...\n");
    m_TSBuffer = new cTSBuffer(fd_pvr, KILOBYTE(256), CardIndex() + 1);
    pShellThread = new cShellThread;
  }
  return true;
}

void cDVDevice::CloseDvr(void)
{
  dx(3, "cDVDevice::CloseDvr()");

  pShellThread->m_Loop = 0;
  delete pShellThread;
  pShellThread  = NULL;

  if(m_TSBuffer)  delete m_TSBuffer;
  m_TSBuffer = NULL;

  if(fd_pvr >= 0)
  {
    int r;
	unsigned char buffer[2048];
	sleep(2);
    while((r = read(fd_pvr, buffer, sizeof(buffer))) >= 0)
	{
		//printf("(%d)", r);
	}
    close(fd_pvr);
  }
  fd_pvr = -1;
}

bool cDVDevice::GetTSPacket(uchar *&Data)
{
  if(m_TSBuffer)
  {
#if VDRVERSNUM < 10300
    int r = m_TSBuffer->Read();
    if(r >= 0)
    {
#endif
      Data = m_TSBuffer->Get();
      return true;
#if VDRVERSNUM < 10300
    }
    else if(FATALERRNO)
    {
      LOG_ERROR;
      return false;
    }
    return true;
#endif
  }
  return false;
}

bool cDVDevice::ProvidesChannel(const cChannel *Channel, int Priority, bool *NeedsDetachReceivers) const
{
  dx(1, "ProvidesChannel");
  return !strcasecmp(Channel->Name(), "Camcorder");
}

bool cDVDevice::SetChannelDevice(const cChannel *Channel, bool LiveView)
{
  dx(1, "SetChannelDevice");
  return true;
}
