/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library 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 Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
**********/
// Copyright (c) 1996-2000, Live Networks, Inc.  All rights reserved
// A test program that receives a RTP/RTCP multicast MP3 stream,
// and outputs the resulting MP3 file stream to 'stdout'
// main program

#include "liveMedia.hh"
#include "GroupsockHelper.hh"

#include "BasicUsageEnvironment.hh"

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <assert.h>
#include <libgen.h>
#include <signal.h>

#include <linux/dvb/dmx.h>
#include <linux/dvb/frontend.h>

//#define VIDEOPID 0x1000 //iceage
//#define VIDEOPID 0x20 //equilibrium
//#define VIDEOPID 0x44 //lost in space
#define VIDEOPID 0x208 //footy
//#define PCRPID 0x1000 //iceage
//#define PCRPID 0x20 //equilibrium
//#define PCRPID 0x44 //lost in space
#define PCRPID 0x208 //footy
//#define AUDIOPID 0x1001 //iceage
//#define AUDIOPID 0x40 //equilibrium
#define AUDIOPID 0x209 //footy

/***********************************************
* LOCAL MACROS                                 *
************************************************/

#define ERROR(x...)                                                     \
        do {                                                            \
                fprintf(stderr, "ERROR: ");                             \
                fprintf(stderr, x);                                     \
                fprintf (stderr, "\n");                                 \
        } while (0)

#define PERROR(x...)                                                    \
        do {                                                            \
                fprintf(stderr, "ERROR: ");                             \
                fprintf(stderr, x);                                     \
                fprintf (stderr, " (%s)\n", strerror(errno));       \
        } while (0)


#define MAX_PATH_LENGTH     80

#define LIST_SIZE(x) sizeof(x)/sizeof(Param)

// To receive a stream of 'ADUs' rather than raw MP3 frames, uncomment this:
//#define STREAM_USING_ADUS 1
// (For more information about ADUs and interleaving,
//  see <http://www.live555.com/rtp-mp3/>)

// To receive a "source-specific multicast" (SSM) stream, uncomment this:
//#define USE_SSM 1

void afterPlaying(void* clientData); // forward

// A structure to hold the state of the current session.
// It is used in the "afterPlaying()" function to clean up the session.
struct sessionState_t {
  FramedSource* source;
  FileSink* sink;
  RTCPInstance* rtcpInstance;
} sessionState;

UsageEnvironment* env;

int setup_dvb(){


    struct dmx_pes_filter_params pesfilterv;
    struct dmx_pes_filter_params pesfiltera;
    struct dmx_pes_filter_params pesfilterp;

    int fdv, fda, fdp, ret;

    if ( (fdv = open ("/dev/dvb/adapter2/demux0", O_NONBLOCK)) < 0 )
    {
        perror ("open failed");
        return -1;
    }


    if ( (fdp = open ("/dev/dvb/adapter2/demux0", O_NONBLOCK)) < 0 )
    {
        perror ("open failed");
        return -1;
    }

    if ( (fda = open ("/dev/dvb/adapter2/demux0", O_NONBLOCK)) < 0 )
    {
        perror ("open failed");
        return -1;
    }


    pesfilterv.pid = VIDEOPID;
    pesfilterv.input = DMX_IN_DVR;
    pesfilterv.output = DMX_OUT_DECODER;
    pesfilterv.pes_type = DMX_PES_VIDEO;
    pesfilterv.flags = 0;

    pesfilterp.pid = PCRPID;
    pesfilterp.input = DMX_IN_DVR;
    pesfilterp.output = DMX_OUT_DECODER;
    pesfilterp.pes_type = DMX_PES_PCR;
    pesfilterp.flags = 0;

    pesfilterv.pid = AUDIOPID;
    pesfiltera.input = DMX_IN_DVR;
    pesfiltera.output = DMX_OUT_DECODER;
    pesfiltera.pes_type = DMX_PES_AUDIO;
    pesfiltera.flags = 0;

    ret = ioctl(fdv, DMX_SET_PES_FILTER, &pesfilterv);
    if (ret != 0)
    {

       PERROR("ioctl DMX_SET_PES_FILTER fdv failed");
       return ret;
    }

    ret = ioctl(fdp, DMX_SET_PES_FILTER, &pesfilterp);
    if (ret != 0)
    {
       PERROR("ioctl DMX_SET_PES_FILTER fdp failed");
       return ret;
    }

    ret = ioctl(fda, DMX_SET_PES_FILTER, &pesfiltera);
    if (ret != 0)
    {
       PERROR("ioctl DMX_SET_PES_FILTER fda failed");
       return ret;
    }

    ret = ioctl(fdv, DMX_START);
    if (ret != 0)
    {
       PERROR("ioctl DMX_START fdv failed");
       return ret;
    }

    ret = ioctl(fda, DMX_START);
    if (ret != 0)
    {
       PERROR("ioctl DMX_START fda failed");
       return ret;
    }

    ret = ioctl(fdp, DMX_START);
    if (ret != 0)
    {
        PERROR("ioctl DMX_START fdp failed");
        return ret;
    }
}

int main(int argc, char** argv) {

  int ret;

  ret = setup_dvb();

  if ( ret != 0 )
  {
      PERROR("Setting up DVB failed.. Exiting\n");
      return ret;
  }

  // Begin by setting up our usage environment:
  TaskScheduler* scheduler = BasicTaskScheduler::createNew();
  env = BasicUsageEnvironment::createNew(*scheduler);

  // Create the data sink for 'stdout':
  sessionState.sink = FileSink::createNew(*env, "/dev/dvb/adapter2/dvr0", 3*1024*1024); //7*188 appears to be the minimum

  //FileSink::createNew(UsageEnvironment& env, char const* fileName,
  //		      unsigned bufferSize, Boolean oneFilePerFrame)
  //sessionState.sink = FileSink::createNew(*env, "/mnt/hd1/received.ts");
  // Note: The string "stdout" is handled as a special case.
  // A real file name could have been used instead.

  // Create 'groupsocks' for RTP and RTCP:
  char* sessionAddressStr
#ifdef USE_SSM
    = "232.255.42.42";
#else
    = "0.0.0.0";
  // Note: If the session is unicast rather than multicast,
  // then replace this string with "0.0.0.0"
#endif
  const unsigned short rtpPortNum = 1234;
  const unsigned short rtcpPortNum = rtpPortNum+1;
#ifndef USE_SSM
  const unsigned char ttl = 1; // low, in case routers don't admin scope
#endif

  struct in_addr sessionAddress;
  sessionAddress.s_addr = our_inet_addr(sessionAddressStr);
  const Port rtpPort(rtpPortNum);
  const Port rtcpPort(rtcpPortNum);

#ifdef USE_SSM
  char* sourceAddressStr = "aaa.bbb.ccc.ddd";
                           // replace this with the real source address
  struct in_addr sourceFilterAddress;
  sourceFilterAddress.s_addr = our_inet_addr(sourceAddressStr);

  Groupsock rtpGroupsock(*env, sessionAddress, sourceFilterAddress, rtpPort);
  Groupsock rtcpGroupsock(*env, sessionAddress, sourceFilterAddress, rtcpPort);
  rtcpGroupsock.changeDestinationParameters(sourceFilterAddress,0,~0);
      // our RTCP "RR"s are sent back using unicast
#else
  Groupsock rtpGroupsock(*env, sessionAddress, rtpPort, ttl);
  Groupsock rtcpGroupsock(*env, sessionAddress, rtcpPort, ttl);
#endif

  RTPSource* rtpSource;

  // Create the data source: a "MPEG Transport stream RTP source"
  rtpSource = SimpleRTPSource::createNew(*env, &rtpGroupsock, 33, 90000, "application/mp2t");

  // Create (and start) a 'RTCP instance' for the RTP source:
  const unsigned estimatedSessionBandwidth = 4000; // in kbps; for RTCP b/w share
  const unsigned maxCNAMElen = 100;
  unsigned char CNAME[maxCNAMElen+1];
  gethostname((char*)CNAME, maxCNAMElen);
  CNAME[maxCNAMElen] = '\0'; // just in case
  sessionState.rtcpInstance
    = RTCPInstance::createNew(*env, &rtcpGroupsock,
			      estimatedSessionBandwidth, CNAME,
			      NULL /* we're a client */, rtpSource);
  // Note: This starts RTCP running automatically

  sessionState.source = rtpSource;

  // Finally, start receiving the multicast stream:
  *env << "Beginning receiving unicast stream on port 1234...\n";
  sessionState.sink->startPlaying(*sessionState.source, afterPlaying, NULL);

  env->taskScheduler().doEventLoop(); // does not return

  return 0; // only to prevent compiler warning
}


void afterPlaying(void* /*clientData*/) {
  *env << "...done receiving\n";

  // End by closing the media:
  Medium::close(sessionState.rtcpInstance); // Note: Sends a RTCP BYE
  Medium::close(sessionState.sink);
  Medium::close(sessionState.source);
}
