/*
 * Copyright (C) 2002-2003 Fhg Fokus
 *
 * This file is part of SEMS, a free SIP media server.
 *
 * SEMS 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. This program is released under
 * the GPL with the additional exemption that compiling, linking,
 * and/or using OpenSSL is allowed.
 *
 * For a license to use the SEMS software under conditions
 * other than those described here, or to purchase support for this
 * software, please contact iptel.org by e-mail at the following addresses:
 *    info@iptel.org
 *
 * SEMS 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 this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "AmRtpReceiver.h"
#include "AmRtpStream.h"
#include "AmRtpPacket.h"
#include "log.h"
#include "AmConfig.h"

#include <errno.h>

// Not on Solaris!
#if !defined (__SVR4) && !defined (__sun)
#include <strings.h>
#endif

AmRtpReceiver::AmRtpReceiver()
{
  n_receivers = AmConfig::RTPReceiverThreads;
  receivers = new AmRtpReceiverThread[n_receivers];
}

AmRtpReceiver::~AmRtpReceiver()
{
  for(unsigned int i=0; i<n_receivers; i++){
    receivers[i].stop();
    receivers[i].join();
  }
  delete [] receivers;
}

AmRtpReceiverThread::AmRtpReceiverThread()
{
  // libevent event base
  ev_base = event_base_new();
}

AmRtpReceiverThread::~AmRtpReceiverThread()
{
  event_base_free(ev_base);
  INFO("RTP receiver has been recycled.\n");
}

void AmRtpReceiverThread::on_stop()
{
  INFO("requesting RTP receiver to stop.\n");
  event_base_loopbreak(ev_base);
}


void AmRtpReceiverThread::run()
{
  // fake event to prevent the event loop from exiting
  struct event* ev_default =
    event_new(ev_base,-1,EV_READ|EV_PERSIST,NULL,NULL);
  event_add(ev_default,NULL);

  // run the event loop
  DBG("RTP receiver running");
  event_base_loop(ev_base,0);
  DBG("RTP receiver stopped");

  // clean-up fake event
  event_free(ev_default);
}

struct event_base* AmRtpReceiverThread::getBase() {
  return ev_base;
}

void AmRtpReceiver::start()
{
  for(unsigned int i=0; i<n_receivers; i++)
    receivers[i].start();
}

struct event_base* AmRtpReceiver::getBase(int sd)
{
  unsigned int i = sd % n_receivers;
  return receivers[i].getBase();
}
