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

#include "BasicUsageEnvironment.hh"
#include "pthread.h"
#include "WAVSource.hh"


// To convert 16-bit samples to 8-bit u-law ("u" is the Greek letter "mu")
// encoding, before streaming, uncomment the following line:
#define CONVERT_TO_ULAW 1

UsageEnvironment* env;

void play(); // forward

pthread_t ThreadID;
TaskScheduler* scheduler;
WAVSource* wavSource;
unsigned char audioFormat;
unsigned char bitsPerSample;
unsigned samplingFrequency;
unsigned char numChannels;
unsigned bitsPerSecond;
char const* mimeType="PCMU";
 unsigned char payloadFormatCode;
uLawFromPCMAudioSource* uLawsource;

struct sessionState_t {
  FramedSource* source;
  RTPSink* sink;
  RTCPInstance* rtcpInstance;
  Groupsock* rtpGroupsock;
  Groupsock* rtcpGroupsock;
  RTSPServer* rtspServer;
} sessionState;

void triggerLive555Scheduler(void) {
	scheduler->triggerEvent(WAVSource::s_frameReceivedTrigger, sessionState.source);

}

/**
Thread function to read the PCM samples from teh device & trigger live555 thread.
**/
void* StartStreaming(void* p)
{
	static bool s_bFirstInstance = true;
	// Start the streaming:
	*env << "Beginning streaming...\n";

	//play();

	s_bFirstInstance = false;

	bool m_bStreamingEnable = true;
	while(true == m_bStreamingEnable)
	{
		/* get encoded the frames from the camera */
		if(true == wavSource->doReadFromDriver())
		{
			/* if capture frame is success, trigger the live555 thread for initiate transfer */
			triggerLive555Scheduler();

		}
		else
		{
			printf("Source Capture frame failed....Go back to Wait state\r\n");
			/* Disable streaming on error conditions */
			m_bStreamingEnable = false;
			/* Signal the main routine to re-initiate the session */
			break;
		}
        usleep(33333);
	}
}

int main(int argc, char** argv) {
  // Begin by setting up our usage environment:
  scheduler = BasicTaskScheduler::createNew();
  env = BasicUsageEnvironment::createNew(*scheduler);
 // Get attributes of the audio source:
  audioFormat = WAVSource::getAudioFormat();
  printf("audioFormat:%d",audioFormat);
  bitsPerSample = WAVSource::bitsPerSample();

   samplingFrequency = WAVSource::samplingFrequency();
  numChannels = WAVSource::numChannels();
  bitsPerSecond = samplingFrequency*bitsPerSample*numChannels/2;
  *env << "Audio source parameters:\n\t" << samplingFrequency << " Hz, ";
  *env << bitsPerSample << " bits-per-sample, ";
  *env << numChannels << " channels => ";
  *env << bitsPerSecond << " bits-per-second\n";
 
      
  payloadFormatCode = 96; // by default, unless a static RTP payload type can be used

  // Create (and start) a 'RTCP instance' for this RTP sink:
  const unsigned estimatedSessionBandwidth = (bitsPerSecond + 500)/1000; // 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
struct in_addr destinationAddress;
  destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env);
  // Note: This is a multicast address.  If you wish instead to stream
  // using unicast, then you should use the "testOnDemandRTSPServer" demo application,
  // or the "LIVE555 Media Server" - not this application - as a model.

  const unsigned short rtpPortNum = 2222;
  const unsigned short rtcpPortNum = rtpPortNum+1;
  const unsigned char ttl = 255;

  const Port rtpPort(rtpPortNum);
  const Port rtcpPort(rtcpPortNum);

  sessionState.rtpGroupsock
    = new Groupsock(*env, destinationAddress, rtpPort, ttl);
  sessionState.rtpGroupsock->multicastSendOnly(); // we're a SSM source
  sessionState.rtcpGroupsock
    = new Groupsock(*env, destinationAddress, rtcpPort, ttl);
  sessionState.rtcpGroupsock->multicastSendOnly(); // we're a SSM source
sessionState.sink
    = SimpleRTPSink::createNew(*env, sessionState.rtpGroupsock,
			       payloadFormatCode, samplingFrequency,
			       "audio", mimeType, numChannels);
 sessionState.rtcpInstance
    = RTCPInstance::createNew(*env, sessionState.rtcpGroupsock,
			      estimatedSessionBandwidth, CNAME,
			      sessionState.sink, NULL /* we're a server */,
			      True /* we're a SSM source*/);
  // Create an appropriate audio RTP sink (using "SimpleRTPSink") from the RTP 'groupsock':
  
  // Create and start a RTSP server to serve this stream:
  sessionState.rtspServer = RTSPServer::createNew(*env, 8554);
  if (sessionState.rtspServer == NULL) {
    *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
    exit(1);
  }
 
  ServerMediaSession* sms
    = ServerMediaSession::createNew(*env, "testStream", "PCMStreamer",
	   "Session streamed by \"RanjithWaveStreamer\"", True/*SSM*/);
  sms->addSubsession(PassiveServerMediaSubsession::createNew(*sessionState.sink, sessionState.rtcpInstance));
  sessionState.rtspServer->addServerMediaSession(sms);

  char* url = sessionState.rtspServer->rtspURL(sms);
  *env << "Play this stream using the URL \"" << url << "\"\n";
  delete[] url;

  // Note: This starts RTCP running automatically

  
  play();

  pthread_create(&ThreadID, NULL,StartStreaming, NULL);
  
  

  env->taskScheduler().doEventLoop(); // does not return
  return 0; // only to prevent compiler warnings
}


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.


void play() {
  // Open the file as a 'WAV' file:
   wavSource = WAVSource::createNew(*env);
  if (wavSource == NULL) {
    *env << "Wav Source is NULL " << "\n";
    exit(1);
  }
   sessionState.source = wavSource; // by default
  if (audioFormat == WA_PCM) {
    if (bitsPerSample == 16) {
      // Note that samples in the WAV audio file are in little-endian order.
#ifdef CONVERT_TO_ULAW
      // Add a filter that converts from raw 16-bit PCM audio (in little-endian order) to 8-bit u-law audio:
     uLawsource = uLawFromPCMAudioSource::createNew(*env, wavSource, 1/*little-endian*/);
   sessionState.source = uLawsource;
      if (sessionState.source == NULL) {
	*env << "Unable to create a u-law filter from the PCM audio source: " << env->getResultMsg() << "\n";
	exit(1);
      }
      bitsPerSecond /= 2;
      *env << "Converting to 8-bit u-law audio for streaming => " << bitsPerSecond << " bits-per-second\n";
      mimeType = "PCMU";
      if (samplingFrequency == 8000 && numChannels == 1) {
	payloadFormatCode = 0; // a static RTP payload type
      printf("payloadFormatCode:0 in PCMU\n");
      }
#else
      // Add a filter that converts from little-endian to network (big-endian) order: 
      sessionState.source = EndianSwap16::createNew(*env, wavSource);
      if (sessionState.source == NULL) {
	*env << "Unable to create a little->bit-endian order filter from the PCM audio source: " << env->getResultMsg() << "\n";
	exit(1);
      }
      *env << "Converting to network byte order for streaming\n";
      mimeType = "L16";
      if (samplingFrequency == 44100 && numChannels == 2) {
	payloadFormatCode = 10; // a static RTP payload type
        printf("payloadFormatCode:10\n");
      } else if (samplingFrequency == 44100 && numChannels == 1) {
	payloadFormatCode = 11; // a static RTP payload type
printf("payloadFormatCode:11\n");
      }
#endif
    }  else { // bitsPerSample == 8 (we assume that bitsPerSample == 4 is only for WA_IMA_ADPCM)
      // Don't do any transformation; send the 8-bit PCM data 'as is':
      mimeType = "L8";
    }
  } else if (audioFormat == WA_PCMU) {
    mimeType = "PCMU";
    if (samplingFrequency == 8000 && numChannels == 1) {
      payloadFormatCode = 0; // a static RTP payload type    
printf("payloadFormatCode:0\n");                                                                      
    }
  } else if (audioFormat == WA_PCMA) {
    mimeType = "PCMA";
    if (samplingFrequency == 8000 && numChannels == 1) {
      payloadFormatCode = 8; // a static RTP payload type    
printf("payloadFormatCode:8\n");                                                                      
    } 
  } else { //unknown format                                                                                                        
    *env << "Unknown audio format code \"" << audioFormat << "\" in WAV file header\n";
    exit(1);
  }
  // Finally, start the streaming:
  *env << "Beginning streaming11111...\n";
  sessionState.sink->startPlaying(*sessionState.source, afterPlaying,sessionState.sink);
}


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

  // End by closing the media:
  Medium::close(sessionState.rtspServer);
  Medium::close(sessionState.rtcpInstance);
  Medium::close(sessionState.sink);
  delete sessionState.rtpGroupsock;
  Medium::close(sessionState.source);
  delete sessionState.rtcpGroupsock;

  // We're done:
  exit(0);
}




