main.cxx
上传用户:wzkunzhan
上传日期:2022-04-23
资源大小:2618k
文件大小:64k
- /*
- * main.cxx
- *
- * Main source for H323BeaconServer
- *
- *
- * Copyright (c) 1993-2001 Equivalence Pty. Ltd.
- *
- * The contents of this file are subject to the Mozilla Public License
- * Version 1.0 (the "License"); you may not use this file except in
- * compliance with the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
- * the License for the specific language governing rights and limitations
- * under the License.
- *
- * The Original Code is Portable Windows Library.
- *
- * The Initial Developer of the Original Code is Equivalence Pty. Ltd.
- *
- * Portions are Copyright (C) 1993 Free Software Foundation, Inc.
- * All Rights Reserved.
- *
- * Portions are Copyright (C) 2002 ITEC-Ohio.
- * All Rights Reserved.
- *
- */
- #include <ptlib.h>
- //#include <sys/types.h>
- //#include <socket.h>
- //#include <string.h>
- //#include <arpa/inet.h>
- //#include <unistd.h>
- //#include <netinet/in.h>
- #include <ptlib/pipechan.h>
- #include "version.h"
- #include "lpc10codec.h"
- #include "speexcodec.h"
- #include "mscodecs.h"
- #include "opalvxml.h"
- #include "main.h"
- #include "callermain.h"
- PCREATE_PROCESS(H323BeaconServer);
- #define new PNEW
- #define DEFAULT_MSG_LIMIT 60
- #define DEFAULT_TESTS_LOG "tests_log.txt"
- #define G7231_BLOCK_SIZE 24
- #define G7231_SAMPLES_PER_BLOCK 240
- #define G7231_BANDWIDTH 63
- #define G7231_SILENCE_FLAG 0x02
- #define G7231_SILENCE_LENGTH 0x04
- #define CHECK_PCM 1
- #define CHECK_G7231 2
- #define YES '1'
- #define NO '0'
- #define MENU_PREFIX "UserMenu-"
- //log-server defines
- //#define SOCKET_ERROR -1
- #define SRVPORT 5050
- #define LOG_H323 "sideB.H323"
- static PMutex logMutex;
- static PTextFile logFile;
- static PFilePath logFilename = DEFAULT_TESTS_LOG;
- PString G7231Ext = ".g723";
- PString WAVExt = ".wav";
- PString PCMExt = ".sw";
- PString receivedDTMFMessage;
- PString dtmfTrigger = NO;
- PString recordDTMFTrigger = NO;
- PString stopRecordDTMFTrigger = NO;
- PString startPlayingDTMFTrigger = NO;
- int playedFlag = 0; //to make sure that the message has already been played before flushing the queue
- PString fn_tmp = "";
- PString fnAgain = "";
- PString IPAddress ; // stores IP address
- PString tmpDir;
- unsigned int tmpCallLimit;
- BOOL playedOnce = FALSE;
- int countwavefiles;
- char buffercountwavefiles[100];
- PString junkwave = "";
- BOOL recordStartedNext = FALSE;
- PString fn_original = "";
- PFilePath fn;
- PFilePath _fn;
- PFile *fileclass;
- PFile *fileclass_tmp;
- PCM_RecordFile * recordFile;
- PCM_RecordFile * recordFilejunkwave;
- MyH323Connection * tmpConn;
- //Caller * caller;
- static void LogMessage(const PString & str)
- {
- PTime now;
- PString msg = now.AsString("hh:mm:ss dd/MM/yyyy") & str;
- logMutex.Wait();
- if (!logFile.IsOpen()) {
- logFile.Open(logFilename, PFile::ReadWrite);
- logFile.SetPosition(0, PFile::End);
- }
- logFile.WriteLine(msg);
- logFile.Close();
-
- logMutex.Signal();
- }
- static void LogCall(const PFilePath & fn,
- const PString & from,
- const PString & user,
- unsigned len,
- const PString & codec,
- const PString & product)
- {
- PString addr = from;
- LogMessage(addr & """ + user + """ & PString(PString::Unsigned, len) & codec & """ + product + """ & """ + fn + """);
- }
- ///////////////////////////////////////////////////////////////
- H323BeaconServer::H323BeaconServer()
- : PProcess("H.323 Beacon Project", "H.323 Beacon Server",
- MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
- {
- }
- H323BeaconServer::~H323BeaconServer()
- {
- }
- void H323BeaconServer::Main()
- {
-
-
- cout << "*************************************************************n";
- cout << GetName() << " Version 1.4 built using the librariesn";
- cout << "available at http://www.openh323.orgn";
- cout << "(C)Copyright ITEC-Ohio,2004.n";
- cout << "http://www.itecohio.org/beaconn";
- cout << "*************************************************************n";
- cout << "NOTE: For more options, Example usage:" << endl;
- cout << ""C:\Program Files\H.323 Beacon Server\H323BeaconServer -h"" << endl;
- PConfigArgs args(GetArguments());
- args.Parse(
- "D-disable:"
- "a-acceptor:"
- "r-result:"
- "d-directory:"
- "g-gatekeeper:" "n-no-gatekeeper."
- "-g711-ulaw." "-no-g711-ulaw."
- "-g711-alaw." "-no-g711-alaw."
- "-g711message:" "-no-g711message."
- "-g7231." "-no-g7231."
- "-g7231message:" "-no-g7231message."
- "-gsm." "-no-gsm."
- "-gsmmessage:" "-no-gsmmessage."
- "h-help."
- "H-hangup." "-no-hangup."
- "i-interface:" "-no-interface."
- "k-kill." "-no-kill."
- "l-limit:" "-no-limit."
- "-listenport:" "-no-listenport."
- "-lpc10message:" "-no-lpc10message."
- "-speexmessage:" "-no-speexmessage."
- "m-message:" "-no-message."
- "-no-recordg7231."
- #if PTRACING
- "o-output:"
- #endif
- "P-prefer:"
- "-pcm." "-no-pcm."
- "-pcmmessage:" "-no-pcmmessage."
- "-port:"
- "q-quicknet:" "-no-quicknet:"
- "r-run:" "-no-run."
- "-recordraw."
- "-require-gatekeeper." "-no-require-gatekeeper."
- "-save."
- #if PMEMORY_CHECK
- "-setallocationbreakpoint:"
- #endif
- #if PTRACING
- "t-trace."
- #endif
- "u-username:" "-no-username."
- , FALSE);
- #if PMEMORY_CHECK
- if (args.HasOption("setallocationbreakpoint"))
- PMemoryHeap::SetAllocationBreakpoint(args.GetOptionString("setallocationbreakpoint").AsInteger());
- #endif
- //#if PTRACING
- PTrace::Initialise(args.GetOptionCount('t'),
- args.HasOption('o') ? (const char *)args.GetOptionString('o') : NULL);
- //#endif
- if (args.HasOption('h')) {
- cout << "Usage : H323BeaconServer [options]n"
- "Options:n"
- " -a --acceptor IPaddress : Connect to the Acceptor IP in Initiator moden" //WM
- " -r --result option : 'html' or 'text'n"
- " -md --directory dir : Put recorded mesages into dirn" //WM
- " -l --limit secs : Limit recorded messages to secs duration (default " << DEFAULT_MSG_LIMIT << ")n"
- " -m --pcmmessage fn : Set outgoing message for PCM derived codecs (G.711/GSM) to fnn"
- " --g7231message fn : Set outgoing message for G723.1 codec to fnn"
- " --g711message fn : Set outgoing message for G711 codec to fnn"
- " --gsmmessage fn : Set outgoing message for GSM codec to fnn"
- " --lpc10message fn : Set outgoing message for LPC10 codec to fnn"
- " --speexmessage fn : Set outgoing message for Speex codec to fnn"
- " --recordraw : Record PCM audo in raw files (.sw) instead of .wavn"
- " -r --run cmd : Run this command after each recorded messagen"
- " -k --kill : Kill recorded files after user commandn"
- " -H --hangup : hangup after playing messagen"
- " -u --username str : Set the local endpoint name to strn"
- " -i --interface ip : Bind to a specific interfacen"
- " --listenport port : Listen on a specific portn"
- " -g --gatekeeper host: Specify gatekeeper host.n"
- " -n --no-gatekeeper : Disable gatekeeper discovery.n"
- " --require-gatekeeper: Exit if gatekeeper discovery fails.n"
- " -D --disable codec : Disable the specified codec (may be used multiple times)n"
- " -P --prefer codec : Prefer the specified codec (may be used multiple times)n"
- #if PTRACING
- " -t --trace : Enable trace, use multiple times for more detailn"
- " -o --output : File for trace output, default is stderrn"
- #endif
- " --save : Save arguments in configuration filen"
- " -h --help : Display this help messagen";
- return;
- }
- args.Save("save");
- #if HAS_IXJ
- if (args.GetCount() > 0) {
- if (args[0] *= "record")
- RecordFile(args);
- else if (args[0] *= "play")
- PlayFile(args);
- else
- cerr << "unknown command "" << args[0] << """ << endl;
- return;
- }
- #endif
- unsigned callLimit = DEFAULT_MSG_LIMIT;
- if (args.HasOption('l')) {
- callLimit = args.GetOptionString('l').AsInteger();
- if (callLimit > 3600) {
- cout << "warning: maximum call length " << callLimit << " is out of range. Using " << DEFAULT_MSG_LIMIT << " insteadn";
- callLimit = DEFAULT_MSG_LIMIT;
- } else if (callLimit == 0)
- cout << "warning: recorded message call limit disabledn";
- }
- cout << "Maximum duration of audio-recording limited to " << callLimit << " seconds...n";
- PString runCmd;
- if (args.HasOption('r')) {
- runCmd = args.GetOptionString('r');
- cout << "Executing "" << runCmd << "" after each message" << endl;
- }
- ///////////////////////////////////////////////////////////////////
-
- PDirectory dir; //WM
- if (args.HasOption('d')) {
- dir = args.GetOptionString('d');
- }
- PString Carg;
- if (args.HasOption('a')) {
- Caller caller;
- PString CallerIP;
- CallerIP = args.GetOptionString('a');
- if (CallerIP==NULL){
- cout<<"Error: Acceptor IPaddress Missingn"<<
- "Usage:H323BeaconServer -a <AcceptorIPaddress>n";
- exit(0);
- }
-
- Carg = "-tttttt -o sideA.H323 -m media.wav " + CallerIP;
- PTime theTime;
- PString date = theTime.GetTimeInSeconds();
- //cout <<"Test Start Date:"<<date<<"n";
- cout<< "Starting the Server in Test Session Initiator mode with noptions ""<<Carg <<""n";
- caller.CallerMain(Carg);
- PString option;
- PString command;
- if (args.HasOption('r')) {
- option = args.GetOptionString('r');
- if (option=="text"){
- command = "perl GO-text.pl " + CallerIP + " " + date;
- }
- else {
- command = "perl GO-html.pl " + CallerIP + " " + date;
- }
- }
- else {
- command ="perl GO-text.pl " + CallerIP + " " + date;
- }
- //call the E-model
-
-
- if(system(command)==0){
- }
- return;
- }
- /////////////////////////////////////////////////////////////////////
- int flags = 0;
- if (args.HasOption("no-recordg7231")) {
- cout << "Supressing recording of G723.1 messages" << endl;
- flags |= MyH323EndPoint::NoRecordG7231;
- }
- if (args.HasOption('k')) {
- cout << "Deleting recorded files after processing" << endl;
- if (runCmd.IsEmpty())
- flags |= MyH323EndPoint::DeleteAfterRecord;
- }
- if (args.HasOption('H'))
- flags |= MyH323EndPoint::HangupAfterPlay;
-
- cout << "Creating the H.323 endpoint for the test session...n";
- MyH323EndPoint endpoint(callLimit, runCmd, dir, flags);
- PString userName = "H323BeaconServer ver" + GetVersion();
- if (args.HasOption('u'))
- userName = args.GetOptionString('u');
- endpoint.SetLocalUserName(userName);
- cout << "Initializing Codecs.........n";
- if (!endpoint.Initialise(args))
- return;
-
- // start the H.323 listener
- H323ListenerTCP * listener;
- PIPSocket::Address interfaceAddress(INADDR_ANY);
- // WORD listenPort = H323ListenerTCP::DefaultSignalPort;
- WORD listenPort = H323EndPoint::DefaultTcpPort;
- PTRACE(1,"LISTENPORT: " <<listenPort);
- if (args.HasOption("listenport"))
- listenPort = (WORD)args.GetOptionString("listenport").AsInteger();
- if (args.HasOption('i'))
- interfaceAddress = PIPSocket::Address(args.GetOptionString('i'));
- cout << "Creating the H.323 TCP Listener...Listen Port: " << listenPort << endl;
- listener = new H323ListenerTCP(endpoint, interfaceAddress, listenPort);
- if (!endpoint.StartListener(listener)) {
- cout << "Could not open H.323 listener port on "
- << listener->GetListenerPort() << endl;
- delete listener;
- return;
- }
-
-
- cout << "H.323 Beacon Server IP Address: " << getLocalhostIPAddress() << endl;
- cout << "Waiting to accept incoming connections..." << endl;
- for (;;)
- PThread::Current()->Sleep(5000);
- }
- ///////////////////////////////////////////////////////////////
- // : H323AudioCapability(12*G7231_BLOCK_SIZE, 4*G7231_BLOCK_SIZE)
- G7231_File_Capability::G7231_File_Capability()
- : H323AudioCapability(8, 4)
- {
- }
- BOOL G7231_File_Capability::OnSendingPDU(H245_AudioCapability & cap, unsigned packetSize) const
- {
- // set the choice to the correct type
- cap.SetTag(GetSubType());
- // get choice data
- H245_AudioCapability_g7231 & g7231 = cap;
- // max number of audio frames per PDU we want to send
- g7231.m_maxAl_sduAudioFrames = packetSize;
- // no silence suppression
- g7231.m_silenceSuppression = FALSE;
- return TRUE;
- }
- BOOL G7231_File_Capability::OnReceivedPDU(const H245_AudioCapability & cap, unsigned & packetSize)
- {
- const H245_AudioCapability_g7231 & g7231 = cap;
- packetSize = g7231.m_maxAl_sduAudioFrames;
- return TRUE;
- }
- PObject * G7231_File_Capability::Clone() const
- {
- return new G7231_File_Capability(*this);
- }
- H323Codec * G7231_File_Capability::CreateCodec(H323Codec::Direction direction) const
- {
- return new G7231_File_Codec(direction);
- }
- ///////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////
- G7231_File_Codec::G7231_File_Codec(Direction dir)
- : H323AudioCodec(OPAL_G7231_6k3, dir)
- {
- }
- int G7231_File_Codec::GetFrameLen(int val)
- {
- static const int frameLen[] = { 24, 20, 4, 1 };
- return frameLen[val & 3];
- }
- BOOL G7231_File_Codec::Read(BYTE * buffer, unsigned & length, RTP_DataFrame &)
- {
- if (rawDataChannel == NULL)
- return FALSE;
-
- if (!rawDataChannel->Read(buffer, 1)) {
- cerr << "Read failed" << endl;
- return FALSE;
- }
- if (rawDataChannel->GetLastReadCount() == 0) {
- cerr << "Read count is zero" << endl;
- return FALSE;
- }
- int readLen = G7231_File_Codec::GetFrameLen(buffer[0]);
- if (readLen > 0) {
- if (!rawDataChannel->Read(buffer+1, readLen-1)) {
- cerr << "Read failed" << endl;
- return FALSE;
- }
- if (rawDataChannel->GetLastReadCount() == 0) {
- cerr << "Read count is zero" << endl;
- return FALSE;
- }
- }
- length = readLen;
- return TRUE;
- }
- BOOL G7231_File_Codec::Write(const BYTE * buffer, unsigned length, const RTP_DataFrame & /* rtp */, unsigned & writtenLength)
- {
- static const BYTE silence[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0};
- // If the length is zero, output silence to the file..
- if (length == 0) {
- PTRACE(1,"G.723.1 zero length frame");
- writtenLength = 0;
- return rawDataChannel->Write(silence, 24);
- }
- int writeLen;
- switch (buffer[0]&3) {
- case 0:
- writeLen = 24;
- break;
- case 1:
- writeLen = 20;
- break;
- case 2:
- // Windows Media Player cannot play 4 byte SID (silence) frames.
- // So write out a 24 byte frame of silence instead.
- PTRACE(1,"Replacing SID with 24 byte frame");
- writtenLength = 4;
- return rawDataChannel->Write(silence, 24);
- // writeLen = 4;
- // break;
- default :
- writeLen = 1;
- break;
- }
- PTRACE(1,"G.723.1 frame length = " <<writeLen);
- writtenLength = writeLen;
- return rawDataChannel->Write(buffer, writeLen);
- }
- unsigned G7231_File_Codec::GetBandwidth() const { return G7231_BANDWIDTH; }
-
- ///////////////////////////////////////////////////////////////
- MyH323EndPoint::MyH323EndPoint(unsigned _callLimit,
- const PString & _runCmd,
- const PDirectory & _dir,
- int _flags)
- : callLimit(_callLimit), runCmd(_runCmd), dir(_dir), flags(_flags)
- {
- }
- BOOL MyH323EndPoint::OnIncomingCall(H323Connection & _conn,
- const H323SignalPDU & setupPDU,
- H323SignalPDU &)
- {
- MyH323Connection & conn = (MyH323Connection &)_conn;
- // see if incoming call is to a getway address
- PString number;
- if (setupPDU.GetDestinationE164(number))
- conn.SetE164Number(number);
- return TRUE;
- }
- /*
- void MyH323EndPoint::OnConnectionEstablished( H323Connection & _conn , const PString & _token )
- {
- MyH323Connection & conn = (MyH323Connection &)_conn;
- RTP_Session * session = conn.GetSession(RTP_Session::DefaultAudioSessionID);
- session->SetReportTimeInterval(1000);
- }
- */
- H323Connection * MyH323EndPoint::CreateConnection(unsigned callReference)
- {
- return new MyH323Connection(*this, callReference);
- }
- BOOL MyH323EndPoint::Initialise(PConfigArgs & args)
- {
- // format for record files, raw or wav
- if (args.HasOption("recordraw"))
- SetRecordWav(FALSE);
- else
- SetRecordWav(TRUE);
- // get G723.1 OGM
- if (args.HasOption("g7231message"))
- g7231Ogm = args.GetOptionString("g7231message");
- else if (args.HasOption('m')) {
- if (PFile::Exists(args.GetOptionString('m') + "_g7231" + WAVExt)) {
- g7231Ogm = args.GetOptionString('m') + "_g7231" + WAVExt;
- }
- else if (PFile::Exists(args.GetOptionString('m') + PCMExt)) {
- g7231Ogm = args.GetOptionString('m') + G7231Ext;
- }
- }
- if (!g7231Ogm.IsEmpty()) {
- // check if the file exists. (do not check if filename contains %s)
- if ((g7231Ogm.Find("%s") == P_MAX_INDEX) && !PFile::Exists(g7231Ogm)) {
- cout << "warning: cannot open G723.1 OGM file "" << g7231Ogm << """ << endl;
- g7231Ogm = "";
- }
- }
- /*
- if (g7231Ogm.IsEmpty())
- cout << "No G.723.1 outgoing message setn";
- else {
- cout << "Using "" << g7231Ogm << "" as G.723.1 outgoing messagen";
- }
- */
- // Get the OGM message for the 'PCM' codecs
- // Check if the file specified exists. If it does, use it.
- // If it does not exist, try with .wav and .sw extensions.
- if (args.HasOption("pcmmessage")) {
- pcmOgm = args.GetOptionString("pcmmessage");
- }
- else if (args.HasOption('m')) {
- if (g7231Ogm.Find("%s") == P_MAX_INDEX) {
- pcmOgm = args.GetOptionString('m');
- } else {
- if (PFile::Exists(args.GetOptionString('m'))) {
- pcmOgm = args.GetOptionString('m');
- }
- else if (PFile::Exists(args.GetOptionString('m') + WAVExt)) {
- pcmOgm = args.GetOptionString('m') + WAVExt;
- }
- else if (PFile::Exists(args.GetOptionString('m') + PCMExt)) {
- pcmOgm = args.GetOptionString('m') + PCMExt;
- }
- }
- }
- // By default, use the pcmOgm for all the PCM codecs, but allow the user
- // to override them.
- gsmOgm = pcmOgm;
- g711Ogm = pcmOgm;
- lpc10Ogm = pcmOgm;
- speexOgm = pcmOgm;
- // We can set the filename for specific codecs.
- if (args.HasOption("gsmmessage"))
- gsmOgm = args.GetOptionString("gsmmessage");
- if (args.HasOption("g711message"))
- g711Ogm = args.GetOptionString("g711message");
- if (args.HasOption("lpc10message"))
- lpc10Ogm = args.GetOptionString("lpc10message");
- if (args.HasOption("speexmessage"))
- speexOgm = args.GetOptionString("speexmessage");
- // Check GSM OGM message
- if (!gsmOgm.IsEmpty()) {
- if ((gsmOgm.Find("%s") == P_MAX_INDEX) && !PFile::Exists(gsmOgm)) {
- cout << "warning: cannot open GSM OGM file "" << gsmOgm << """ << endl;
- gsmOgm = "";
- }
- }
- if (gsmOgm.IsEmpty()) {
- cout << "No outgoing message specified in the arguments...." <<endl;
- cout << "Shutting down H.323 Beacon Server!!!!!!!!" <<endl;
- cout << "Try, Example usage:" << endl;
- cout << ""C:\Program Files\C++ H.323 Beacon Server\H323BeaconServer -m message"" << endl;
- }
-
- else {
- cout << "Using "" << gsmOgm << "" as GSM outgoing messagen";
- }
- // Check G.711 OGM message
- if (!g711Ogm.IsEmpty()) {
- if ((g711Ogm.Find("%s") == P_MAX_INDEX) && !PFile::Exists(g711Ogm)) {
- cout << "warning: cannot open G711 OGM file "" << g711Ogm << """ << endl;
- g711Ogm = "";
- }
- }
- /*
- if (g711Ogm.IsEmpty())
- cout << "No G711 outgoing message setn";
- else {
- cout << "Using "" << g711Ogm << "" as G.711 outgoing messagen";
- }*/
- // Check LPC10 OGM message
- if (!lpc10Ogm.IsEmpty()) {
- if ((lpc10Ogm.Find("%s") == P_MAX_INDEX) && !PFile::Exists(lpc10Ogm)) {
- cout << "warning: cannot open LPC10 OGM file "" << lpc10Ogm << """ << endl;
- lpc10Ogm = "";
- }
- }
- if (lpc10Ogm.IsEmpty()) {
- // cout << "No LPC10 outgoing message setn";
- }
- else {
- // cout << "Using "" << lpc10Ogm << "" as LPC10 outgoing messagen";
- }
- // Check Speex OGM message
- if (!speexOgm.IsEmpty()) {
- // check if the file exists. (do not check if filename contains %s)
- if ((speexOgm.Find("%s") == P_MAX_INDEX) && !PFile::Exists(speexOgm)) {
- cout << "warning: cannot open Speex OGM file "" << speexOgm << """ << endl;
- speexOgm = "";
- }
- }
- if (speexOgm.IsEmpty()) {
- // cout << "No Speex outgoing message setn";
- }
- else {
- // cout << "Using "" << speexOgm << "" as Speex outgoing messagen";
- }
- if (g7231Ogm.IsEmpty() && gsmOgm.IsEmpty() && g711Ogm.IsEmpty()
- && lpc10Ogm.IsEmpty()
- && speexOgm.IsEmpty()
- ) {
- cerr << "Must specify at least one outgoing message" << endl;
- return FALSE;
- }
- if (!g7231Ogm.IsEmpty())
- SetCapability(0, 0, new G7231_File_Capability);
- if (!gsmOgm.IsEmpty())
- SetCapability(0, 0, new H323_GSM0610Capability);
- if (!gsmOgm.IsEmpty())
- SetCapability(0, 0, new MicrosoftGSMAudioCapability);
- if (!g711Ogm.IsEmpty())
- SetCapability(0, 0, new H323_G711Capability(H323_G711Capability::muLaw, H323_G711Capability::At64k));
- if (!g711Ogm.IsEmpty())
- SetCapability(0, 0, new H323_G711Capability(H323_G711Capability::ALaw, H323_G711Capability::At64k));
- if (!lpc10Ogm.IsEmpty())
- SetCapability(0, 0, new H323_LPC10Capability(*this));
- if (!speexOgm.IsEmpty())
- SetCapability(0, 0, new SpeexNarrow2AudioCapability());
- SetCapability(0, 0, new SpeexNarrow3AudioCapability());
- SetCapability(0, 0, new SpeexNarrow4AudioCapability());
- SetCapability(0, 0, new SpeexNarrow5AudioCapability());
- SetCapability(0, 0, new SpeexNarrow6AudioCapability());
- capabilities.Remove(args.GetOptionString('D').Lines());
- capabilities.Reorder(args.GetOptionString('P').Lines());
- //cout << "Codecs (in preference order):n" << setprecision(2) << capabilities << endl;
- return TRUE;
- }
- ///////////////////////////////////////////////////////////////
- PCM_RecordFile::PCM_RecordFile(MyH323Connection & _conn, const PFilePath & _fn, unsigned _callLimit)
- : conn(_conn), fn(_fn), callLimit(_callLimit)
- {
- //recordStarted = FALSE;
- recordStartedNext = FALSE;
- timeLimitExceeded = FALSE;
- closed = FALSE;
- dataWritten = FALSE;
- // If the file name ends in .wav then open the output as a WAV file.
- // Otherwise open it as a raw file.
- if ((_fn.Right(4)).ToLower() == ".wav")
- fileclass = new PWAVFile(_fn, PFile::WriteOnly,
- PFile::ModeDefault,PWAVFile::PCM_WavFile);
- else
- fileclass = new PFile(_fn, PFile::WriteOnly);
- }
- void PCM_RecordFile::StartRecording()
- {
- PWaitAndSignal mutex(pcmrecordMutex);
-
-
- //if (recordStarted)
- if (recordStartedNext)
- return;
- PTRACE(1, "Starting recording to " << junkwave);
-
- if (playedOnce)
- {
- fn_tmp = junkwave;
- fn = junkwave;
- playedOnce = FALSE;
- }
- else
- {
- fn_tmp = fn;
- }
-
- PTime now;
- //recordStarted = TRUE;
- recordStartedNext = TRUE;
- finishTime = now + (callLimit * 1000);
- }
- BOOL PCM_RecordFile::Close()
- {
- PWaitAndSignal mutex(pcmrecordMutex);
-
- closed = TRUE;
- return fileclass->Close();
- }
- BOOL PCM_RecordFile::Write(const void * buf, PINDEX len)
- {
- // Wait for the mutex, and Signal it at the end of this function
- PWaitAndSignal mutex(pcmrecordMutex);
- // If the record file has been closed, or if the time limit has
- // been exceeded, then return immediatly.
- if (closed || timeLimitExceeded)
- return TRUE;
- if (!recordStartedNext) {
- DelayFrame(len);
- return TRUE;
- }
-
-
- //To check for the finish DTMFMessage and not clear the call
- //if time exceeded or if the user stops recording...
- PTime now;
- if ((callLimit != 0) && ((now >= finishTime) || strcmp(stopRecordDTMFTrigger,"1") == 0 )) {
- //PTRACE(1, "Terminating call due to timeout..");
-
- if(now >= finishTime){
- cout << "Recording Stopped due to time out%%%%%%%%%" <<endl;
- PTRACE(1, "Closing recording due to time out...");
- }
- else{
- cout << "Recording Stopped%%%%%%%%%" <<endl;
- PTRACE(1, "Closing recording due to stopRecordDTMFTrigger.."<<stopRecordDTMFTrigger);
- }
- timeLimitExceeded = TRUE;
- //conn.ClearCall(); //to avoid disconnecting after finishing the recording from Client side..
- cout << "Waiting for "Start Playing" message from the H.323 Beacon Client..." <<endl;
- PTRACE(1, "Waiting for DTMF 3 Message******************");
- while(strcmp(startPlayingDTMFTrigger,"1") != 0 ){
- //
- PTRACE(1,"WM_A in while look");
- //return FALSE;
- return TRUE;
- }
- PTRACE(1, "Finished waiting for DTMF 3 Message*****************");
- //Play the file here..
- PTRACE(1, "Playing the recorded file>>>>>>>>>>>>>>>>>>>...."<<fn);
- /*
- PWAVFile *playSaved;
- playSaved = new PWAVFile(fn_tmp, PFile::ReadOnly);
- PTRACE(1," fn_tmp = " << fn_tmp);
- if (!playSaved->IsOpen()){
- PTRACE(1, "Cannot open file "" << playSaved->GetName() << """);
- delete playSaved;
- }
- else{
- PTRACE(1, "Playing file "" << playSaved->GetName() << """);
- SetReadChannel(playSaved, TRUE);
- /* doSilence = FALSE;
- if (!doSilence){
-
- if (ReadFrame(amount)){
- frameBoundary = AdjustFrame(buffer, amount);
- totalData += amount;
- }
- else{
- PTRACE(1, "Finished playing the recorded file having " << totalData << " bytes");
- PIndirectChannel::Close();
- silentCount = 5; // always do 5 frames of silence after every file
-
- // no silence
- doSilence = TRUE;
- }
- }*/
- /*
- }
- */
- PTRACE(1, "Terminating call ########################");
- conn.ClearCall();
- return TRUE;
- }
- DelayFrame(len);
- dataWritten = TRUE;
- return WriteFrame(buf, len);
- }
- BOOL PCM_RecordFile::WriteFrame(const void * buf, PINDEX len)
- {
- /*
- if(playedOnce){
- return fileclass_tmp->Write(buf, len);
- }
- */
- PTRACE(1,"In PCM_RecordFile::WriteFrame");
- return fileclass->Write(buf, len); //Place where Write() is actually called..
- }
- void PCM_RecordFile::DelayFrame(PINDEX len)
- {
- delay.Delay(len/16);
- }
- PCM_RecordFile::~PCM_RecordFile()
- {
- PWaitAndSignal mutex(pcmrecordMutex);
- if (!dataWritten) {
- if(playedOnce){
- PTRACE(1, "Deleting fn_tmp " << fn << " as no data recorded");
- fileclass_tmp->Remove(fn);
- delete fileclass_tmp;
- }
- PTRACE(1, "Deleting " << fn << " as no data recorded");
- fileclass->Remove(fn);
- }
- delete fileclass;
- }
- ///////////////////////////////////////////////////////////////
- // Override some of the PCM_RecordFile functions to write
- // G723.1 data instead of PCM data.
- G7231_RecordFile::G7231_RecordFile(MyH323Connection & _conn, const PFilePath & _fn, unsigned _callLimit)
- : PCM_RecordFile(_conn, _fn, _callLimit)
- {
- // If the record file is a .wav file, we need to close the file
- // that PCM_RecordFile will have opened, and reopen it as a G.723.1 Wav file.
- if ((_fn.Right(4)).ToLower() == ".wav") {
- fileclass->Remove(_fn);
- delete fileclass;
- fileclass = new PWAVFile(_fn, PFile::WriteOnly,
- PFile::ModeDefault,PWAVFile::G7231_WavFile);
- }
- }
- BOOL G7231_RecordFile::WriteFrame(const void * buf, PINDEX /*len*/)
- {
- int frameLen = G7231_File_Codec::GetFrameLen(*(BYTE *)buf);
- // cerr << "Writing G7231 " << frameLen << endl;
- return fileclass->Write(buf, frameLen);
- }
- void G7231_RecordFile::DelayFrame(PINDEX /*len*/)
- {
- // Ignore the len parameter as that is the compressed size.
- // We must delay by the actual sample time.
- delay.Delay((G7231_SAMPLES_PER_BLOCK*2)/16);
- }
- ///////////////////////////////////////////////////////////////
- static BOOL MatchString(const PString & str1, const PString str2)
- {
- if (str1.GetLength() != str2.GetLength())
- return FALSE;
- PINDEX len = str1.GetLength();
- PINDEX i;
- for (i = 0; i < len; i++)
- if ((str1[i] != '?') && (str2[i] != '?') && (str1[i] != str2[i]))
- return FALSE;
- return TRUE;
- }
- static PINDEX FindMatch(const PStringList & list, const PString & key)
- {
- PINDEX maxKeyLen = 0;
- PINDEX i;
- PINDEX keyLen = key.GetLength();
- PINDEX listLen = list.GetSize();
- for (i = 0; i < listLen; i++)
- maxKeyLen = PMAX(maxKeyLen, list[i].GetLength());
- if (keyLen == 0 || maxKeyLen == 0)
- return P_MAX_INDEX;
- if (keyLen > maxKeyLen)
- return P_MAX_INDEX;
- PINDEX len = 1;
- while (len <= keyLen) {
- PString subStr = key.Left(len);
- PINDEX matches = 0;
- PINDEX lastMatch = P_MAX_INDEX;
- PINDEX i;
- // look for a match to the substring
- for (i = 0; i < list.GetSize(); i++) {
- if ((list[i].GetLength() >= keyLen) && MatchString(list[i].Left(len), subStr)) {
- matches++;
- lastMatch = i;
- }
- }
- // if we got ONE match, we have a winner
- if (matches == 1)
- return lastMatch+1;
- // if we have no matches, then there is no point continuing
- if (matches == 0)
- return P_MAX_INDEX;
- // if we have more than one match, try the next char
- len++;
- }
- // too many matches
- return 0;
- }
- MyH323Connection::MyH323Connection(MyH323EndPoint & _ep, unsigned callReference)
- : H323Connection(_ep, callReference), ep(_ep)
- {
- basename = psprintf("%04i%02i%02i_%02i%02i%02i", callStartTime.GetYear(), callStartTime.GetMonth(), callStartTime.GetDay(),
- callStartTime.GetHour(), callStartTime.GetMinute(), callStartTime.GetSecond());
- recordFile = NULL;
- ogmChannel = NULL;
- receiveCodecName = transmitCodecName = "none";
- // SetMaxAudioDelayJitter(150);
- cout << "Opening Test Session...." << endl;
- currentMenu = 0;
- digits = "";
- PConfig config;
- PStringList sections = config.GetSections();
- PINDEX i;
- for (i = 0; i < sections.GetSize(); i++) {
- if (sections[i].Find(MENU_PREFIX) == 0)
- menuNames.AppendString(sections[i]);
- }
- }
- MyH323Connection::~MyH323Connection()
- {
- //cout << "Closing Test Session!!!!!!!" << endl;
- //cout << "Waiting to accept incoming calls....." << endl;
- //cout << "H.323 Beacon Server IP Address: " << IPAddress << endl;
- //PTRACE(1,"Closing connection###########################");
- PTime now;
- PTimeInterval interval = now - recordStartTime;
- PString addr = GetControlChannel().GetRemoteAddress();
- PString codecStr = receiveCodecName + "/" + transmitCodecName;
- unsigned duration = (unsigned)((interval.GetMilliSeconds()+999)/1000);
- LogCall(recordFn, addr, GetRemotePartyName(), duration, codecStr, product);
- if ((recordFile!= NULL) && (recordFile->WasRecordStarted()) && !ep.GetRunCmd().IsEmpty()) {
- PString cmdStr = ep.GetRunCmd() &
- recordFn &
- "'" + addr + "'" &
- """ + GetRemotePartyName() + """ &
- PString(PString::Unsigned, duration) &
- """ + codecStr + """ &
- """ + product + """;
- PTRACE(1, "Executing : " << cmdStr);
- system((const char *)cmdStr);
- } else {
- PTRACE(1, "No action to perform at end of record");
- }
- if (ogmChannel != NULL)
- {
- PTRACE(1, "Deleting OgmChannel ");
- delete ogmChannel;
- }
- if (recordFile != NULL)
- {
- PTRACE(1, "Deleting recordFile ");
- delete recordFile;
- }
- if (ep.GetDeleteAfterRecord()) {
- PTRACE(1, "Removing " << recordFn << " as requested by option");
- PString command = "ForceDel.exe ""+recordFn+"" > NUL";
- if(system(command)==0)
- PTRACE(1,"Removal of " << recordFn << " Successful!");
- else
- PTRACE(1,"Removal of " << recordFn << " Failure!");
- }
- for(int ii = 0; ii<countwavefiles+2; ii++)
- {
- junkwave = psprintf("junkwave%01i",ii);
- junkwave = tmpDir + (junkwave + ".wav");
- if(remove(junkwave) == -1)
- {
- PTRACE(1, "Removing JunkWave Failed**********" << junkwave);
- }
- else
- {
- PTRACE(1, "Removing JunkWave Success!!!!!!!");
- }
- }
- /* PString message =" This is the Trace Route Message From the Servern";
- if(SendTraceRtToClient(addr,&message)==1){
- cout<<"traceRT sent successfully"<<endl;
- PTRACE(1,"traceRT sent successfullyn");
- }
- else{
- cout<<"traceRT send unsuccessfull"<<endl;
- PTRACE(1,"traceRT send unsuccessfulln");
- }
- */
- cout << "Closing Test Session!!!!!!!" << endl;
- cout<<"Starting log_server...."<<endl;
- log_server();
- cout <<"Closing log_server...."<<endl;
- cout << "Waiting to accept incoming calls....." << endl;
- cout << "H.323 Beacon Server IP Address: " << IPAddress << endl;
- PTRACE(1,"Closing connection###########################");
- }
- H323Connection::AnswerCallResponse
- MyH323Connection::OnAnswerCall(const PString & caller,
- const H323SignalPDU & setupPDU,
- H323SignalPDU & /*connectPDU*/)
- {
- product = "Unknown";
- const H225_Setup_UUIE & setup = setupPDU.m_h323_uu_pdu.m_h323_message_body;
- const H225_EndpointType & epInfo = setup.m_sourceInfo;
- if (epInfo.HasOptionalField(H225_EndpointType::e_vendor)) {
- const H225_VendorIdentifier & vendorInfo = epInfo.m_vendor;
- if (vendorInfo.HasOptionalField(H225_VendorIdentifier::e_productId))
- product = vendorInfo.m_productId.AsString();
- if (vendorInfo.HasOptionalField(H225_VendorIdentifier::e_versionId))
- product = product + "/" + vendorInfo.m_versionId.AsString();
- }
-
- cout << "Accepting call from " << caller << " ...n";
- return AnswerCallNow;
- }
- BOOL MyH323Connection::OpenAudioChannel(BOOL isEncoding,
- unsigned /* bufferSize */,
- H323AudioCodec & codec)
- {
- if(playedFlag == 0){
- codec.SetSilenceDetectionMode(H323AudioCodec::NoSilenceDetection);
- PStringStream codecName;
- codecName << codec;
- PString ogm;
- BOOL isPCM = FALSE;
- if (codec.IsDescendant(G7231_File_Codec::Class())) {
- ogm = ep.GetG7231OGM();
- isPCM = FALSE;
- } else if (codec.IsDescendant(H323_GSM0610Codec::Class())) {
- ogm = ep.GetGSMOGM();
- isPCM = TRUE;
- } else if (codec.IsDescendant(MicrosoftGSMCodec::Class())) {
- ogm = ep.GetGSMOGM();
- isPCM = TRUE;
- } else if (codec.IsDescendant(H323_muLawCodec::Class())) {
- ogm = ep.GetG711OGM();
- isPCM = TRUE;
- } else if (codec.IsDescendant(H323_ALawCodec::Class())) {
- ogm = ep.GetG711OGM();
- isPCM = TRUE;
- } else if (codec.IsDescendant(H323_LPC10Codec::Class())) {
- ogm = ep.GetLPC10OGM();
- isPCM = TRUE;
- } else if (codec.IsDescendant(SpeexCodec::Class())) {
- ogm = ep.GetSPEEXOGM();
- isPCM = TRUE;
- } else {
- cerr << "Unknown codec "" << codecName << endl;
- return FALSE;
- }
- PWaitAndSignal mutex(connMutex);
- tmpDir = ep.GetDirectory();
- tmpCallLimit = ep.GetCallLimit();
- if ((recordFile == NULL) && (isEncoding == FALSE)) {
- if (isPCM) {
- if (ep.GetRecordWav() == TRUE)
- recordFn = ep.GetDirectory() + (basename + ".wav");
- else
- recordFn = ep.GetDirectory() + (basename + ".sw");
- recordFile = new PCM_RecordFile (*this, recordFn, ep.GetCallLimit());
- } else {
- if (ep.GetRecordWav() == TRUE)
- recordFn = ep.GetDirectory() + (basename + ".wav");
- else
- recordFn = ep.GetDirectory() + (basename + ".g723");
- recordFile = new G7231_RecordFile(*this, recordFn, ep.GetCallLimit());
- }
- }
- if ((ogmChannel == NULL) && (isEncoding == TRUE)) {
- if (isPCM)
- ogmChannel = new PCM_OGMChannel(*this);
- else
- ogmChannel = new G7231_OGMChannel(*this);
- }
- if (isEncoding) {
- if (ep.GetHangupAfterPlay())
- ogmChannel->SetPlayOnce();
- if (ogm.Find("%s"))
- ogm.Replace("%s", e164Number);
- transmitCodecName = codecName;
- if (!StartMenu(0)) {
- if (!PFile::Exists(ogm))
- cerr << "error: cannot find OGM "" << ogm << """ << endl;
- else
- ogmChannel->QueueFile(ogm); //being called!!
- if (!ep.GetNoRecordG7231())
- ogmChannel->SetRecordTrigger();
- }
- codec.AttachChannel(ogmChannel, FALSE);
- } else {
- receiveCodecName = codecName;
- codec.AttachChannel(recordFile, FALSE);
- }
- return TRUE;
- }
- else
- return TRUE;
-
- }
- BOOL MyH323Connection::OnStartLogicalChannel(H323Channel & channel)
- {
- if (!H323Connection::OnStartLogicalChannel(channel))
- return FALSE;
- cout << "Started logical channel: ";
- switch (channel.GetDirection()) {
- case H323Channel::IsTransmitter :
- cout << "Sending capability information->";
- break;
- case H323Channel::IsReceiver :
- cout << "Receiving capability information-> ";
- break;
- default :
- break;
- }
- cout << channel.GetCapability() << endl;
- return TRUE;
- }
- void MyH323Connection::StartRecording()
- {
- recordFile->StartRecording();
- }
- void MyH323Connection::OnUserInputString(const PString & value)
- {
- PINDEX i;
- for (i = 0; i < value.GetLength(); i++) {
- OnUserInputChar(value[i]);
- }
- }
- BOOL MyH323Connection::StartMenu(int menuNumber)
- {
- digits = "";
- currentMenu = menuNumber;
- PString menuName = psprintf("%s%i", MENU_PREFIX, menuNumber);
- if (menuNames.GetStringsIndex(menuName) == P_MAX_INDEX)
- return FALSE;
- PTRACE(1, "Starting menu " << menuNumber);
- PConfig menu(menuName);
- PString startCmd = menu.GetString("start");
- if (!startCmd.IsEmpty())
- ProcessMenuCmd(startCmd);
- return TRUE;
- }
- BOOL MyH323Connection::ProcessMenuCmd(const PString & cmdStr)
- {
- PTRACE(1, "Processing menu cmd " << cmdStr);
- PStringArray tokens = cmdStr.Tokenise(" ", FALSE);
- int len = tokens.GetSize();
- if (len == 0)
- return TRUE;
- PString cmd = tokens[0];
- if ((len >= 2) && (cmd *= "play")) {
- ogmChannel->QueueFile(tokens[1]);
- if (len > 2) {
- cmd = "menu";
- tokens[1] = tokens[2];
- }
- }
- if ((len >= 2) && (cmd *= "menu")) {
- int newMenu = tokens[1].AsInteger();
- if (newMenu != currentMenu)
- StartMenu(newMenu);
- }
- else if (cmd *= "hangup")
- ogmChannel->SetHangupTrigger();
- else if (cmd *= "record")
- ogmChannel->SetRecordTrigger();
- return TRUE;
- }
- void MyH323Connection::OnUserInputChar(char ch)
- {
- if (ch == '#')
- digits += '$';
- else
- digits += ch;
- PTRACE(1, "Processing digit string " << digits);
- //to change the state of receivedDTMFMessage
- receivedDTMFMessage = digits;
- if(strcmp(receivedDTMFMessage,"") != 0)
- dtmfTrigger = YES;
-
- PTRACE(1, "receivedDTMFMessage.........." << receivedDTMFMessage);
- if(strcmp(receivedDTMFMessage,"1") == 0){
- recordDTMFTrigger = YES;
- cout << "Start recording message received from H.323 Beacon Client..." <<endl;
- PTRACE(1,"recordDTMFTrigger TRUE is----"<<recordDTMFTrigger);
- }
- else if (strcmp(receivedDTMFMessage,"2") == 0){
- stopRecordDTMFTrigger = YES;
- cout << "Stop recording message received from H.323 Beacon Client..." <<endl;
- PTRACE(1,"stopRecordDTMFTrigger TRUE is----"<<stopRecordDTMFTrigger);
- }
- else if (strcmp(receivedDTMFMessage,"3") == 0){
- startPlayingDTMFTrigger = YES;
- cout << "Start playing message received from H.323 Beacon Client..." <<endl;
- cout << "Playing back the recorded file to the H.323 Beacon Client..." << endl;
- PTRACE(1,"startPlayingDTMFTrigger TRUE is----"<<startPlayingDTMFTrigger);
- }
- else if (strcmp(receivedDTMFMessage,"4") == 0){
- cout << "Hang up message received...Hanging up...Please Wait>>>>>>>>"<<endl;
- PTRACE(1,"Hang-up message from client@@@@@@@@@@@@@@@@@@");
- }
- else{
- recordDTMFTrigger = NO;
- stopRecordDTMFTrigger = NO;
- startPlayingDTMFTrigger = NO;
- PTRACE(1,"Not a valid DTMF Trigger.....");
- }
- if ((strcmp(receivedDTMFMessage,"1") == 0) && (playedFlag > 0)){
- ogmChannel->FlushQueue();
- recordDTMFTrigger = NO;
- stopRecordDTMFTrigger = NO;
- startPlayingDTMFTrigger = NO;
- playedFlag = 0;
- }
- PString menuName = psprintf("%s%i", MENU_PREFIX, currentMenu);
- if (menuNames.GetStringsIndex(menuName) == P_MAX_INDEX) {
- PTRACE(1, "Cannot find menu " << menuName);
- StartMenu(0);
- return;
- }
- PConfig menu(menuName);
- PStringList keys = menu.GetKeys();
- PINDEX keyMatch = FindMatch(keys, digits);
- // if key is still ambiguous, then keep collecting
- if (keyMatch == 0)
- return;
- PString cmd;
- if (keyMatch != P_MAX_INDEX) {
- PString key = keys[keyMatch-1];
- PTRACE(1, "Executing cmd for key " << key);
- cmd = menu.GetString(key);
- } else {
- PTRACE(1, "Cannot match cmd " << digits << " in menu " << menuName);
- cmd = menu.GetString("error", "menu 0");
- }
- if (!cmd.IsEmpty()) {
- ProcessMenuCmd(cmd);
- digits = "";
- }
-
- }
- ///////////////////////////////////////////////////////////////
- BOOL CheckWAVFileValid(PWAVFile *chan, int type) {
- // Check the wave file header
- if (!chan->IsValid()) {
- PTRACE(1, chan->GetName() << " wav file header invalid");
- return FALSE;
- }
- // Check the wave file format
- if ( (type == CHECK_PCM) && (chan->GetFormat() != 0x01) ){
- PTRACE(1, chan->GetName() << " is not a PCM format wav file");
- PTRACE(1, "It is format " << chan->GetFormat() );
- return FALSE;
- }
- if ( (type == CHECK_G7231) &&
- ((chan->GetFormat() != 0x42) && (chan->GetFormat() != 0x111)) ){
- PTRACE(1, chan->GetName() << " is not a G.723.1 format wav file");
- PTRACE(1, "It is format " << chan->GetFormat() );
- return FALSE;
- }
- // Check the sample rate for PCM wave files
- if ( (type == CHECK_PCM) &&
- ( (chan->GetSampleRate() != 8000)
- ||(chan->GetChannels() != 1)
- ||(chan->GetSampleSize() != 16) )
- ) {
- PTRACE(1, chan->GetName() << " is not a 16 Bit, Mono, 8000 Hz (8Khz) PCM wav file");
- PTRACE(1, "It is " << chan->GetSampleSize() << " bits, "
- << (chan->GetChannels()==1 ? "mono " : "stereo ")
- << chan->GetSampleRate() << " Hz");
- return FALSE;
- }
- return TRUE;
- }
- ///////////////////////////////////////////////////////////////
- PCM_OGMChannel::PCM_OGMChannel(MyH323Connection & _conn)
- : conn(_conn)
- {
- silentCount = 20; // wait 20 frames before playing the OGM
- recordTrigger = FALSE;
- hangupTrigger = FALSE;
- closed = FALSE;
- playOnce = FALSE;
- frameLen = frameOffs = 0;
- }
- void PCM_OGMChannel::PlayFile(PFile * chan)
- {
- PWaitAndSignal mutex(chanMutex);
- // if (IsOpen())
- // Close();
- if (!chan->Open(PFile::ReadOnly)) {
- PTRACE(1, "Cannot open file "" << chan->GetName() << """);
- return;
- }
- PTRACE(1, "Playing file "" << chan->GetName() << """);
- totalData = 0;
- SetReadChannel(chan, TRUE);
- }
- BOOL PCM_OGMChannel::IsWAVFileValid(PWAVFile *chan) {
- // Check that this is a PCM wave file
- return CheckWAVFileValid(chan, CHECK_PCM);
- }
- BOOL PCM_OGMChannel::Read(void * buffer, PINDEX amount)
- {
- PWaitAndSignal mutex(chanMutex);
- // if the channel is closed, then return error
- if (closed)
- return FALSE;
- // Create the frame buffer using the amount of bytes the codec wants to
- // read. Different codecs use different read sizes.
- frameBuffer.SetMinSize(1024);//amount);
- // assume we are returning silence
- BOOL doSilence = TRUE;
- BOOL frameBoundary = FALSE;
- if (strcmp(startPlayingDTMFTrigger,"1") != 0 && (playedOnce == FALSE)){
- // if still outputting a frame from last time, then keep doing it
- if (frameOffs < frameLen) {
- frameBoundary = AdjustFrame(buffer, amount);
- doSilence = FALSE;
- }
- else {
- // if we are returning silence frames, then
- if (silentCount > 0)
- silentCount--;
- // if a channel is already open, don't do silence
- else if (GetBaseReadChannel() != NULL)
- doSilence = FALSE;
- // If not in silence and no existing channel, open a new file.
- else {
- if (strcmp(receivedDTMFMessage,"1") == 0){
- PString * str = playQueue.Dequeue();
- if (str != NULL) {
- // check the file extension and open a .wav or a raw (.sw or .g723) file
- if (((*str).Right(4)).ToLower() == ".wav") {
- PWAVFile *chan;
- chan = new PWAVFile(*str, PFile::ReadOnly);
- if (!chan->IsOpen()) {
- PTRACE(1, "Cannot open file "" << chan->GetName() << """);
- delete chan;
- } else {
- if (!IsWAVFileValid(chan) ){
- PTRACE(1, chan->GetName() << " is not a valid wav file");
- delete chan;
- cerr << "wave file is invalid" << endl;
- } else {
- PTRACE(1, "Playing file "" << chan->GetName() << """);
- totalData = 0;
- SetReadChannel(chan, TRUE);
- doSilence = FALSE;
- }
- }
- } else { // raw file (eg .sw)
- PFile *chan;
- chan = new PFile(*str);
- if (!chan->Open(PFile::ReadOnly)) {
- PTRACE(1, "Cannot open file "" << chan->GetName() << """);
- delete chan;
- } else {
- cout << "Playing message file-> "" << chan->GetName() << """ <<endl;
- PTRACE(1, "Playing file "" << chan->GetName() << """); //actually playing here!
- fn_original = chan->GetName();
- totalData = 0;
- SetReadChannel(chan, TRUE);
- doSilence = FALSE;
- playedFlag++;
- }
- }
- delete str;
- }
- }
- }
- /*
- if (strcmp(receivedDTMFMessage,"1") == 0){
- doSilence = FALSE;
- }
- */
- // if not doing silence, try and read from the file
- if (!doSilence) {
-
- if (ReadFrame(amount)){
- PTRACE(1,"Amount origin file " << amount);
- frameBoundary = AdjustFrame(buffer, amount);
- PTRACE(1,"************** Original Frame Boundary " << frameBoundary);
- totalData += amount;
- }
- else {
- if (strcmp(receivedDTMFMessage,"1") == 0){
- cout << "Finished playing message file........." <<endl;
- PTRACE(1, "Finished playing " << totalData << " bytes");
- //closed = TRUE;
-
- PIndirectChannel::Close();
- silentCount = 5; // always do 5 frames of silence after every file
-
- // hangup if required
- if (hangupTrigger || playOnce)
- conn.ClearCall();
-
- // trigger record if required
- else if (recordTrigger) {
- if ((playQueue.GetSize() == 0) && (GetBaseReadChannel() == NULL))
- cout << "Recording Started%%%%%%%%%" << endl;
- PTRACE(1,"Starting to Record!!!!!!!!!!!!");
- conn.StartRecording();
- }
- }
-
- // no silence
- doSilence = TRUE;
- }
- }
- }
- }
- //if (strcmp(startPlayingDTMFTrigger,"1") == 0)
- else {
- if (strcmp(fn_tmp,"") != 0){
- PWAVFile *playSaved;
- playSaved = new PWAVFile(fn_tmp, PFile::ReadOnly);
- PTRACE(1,"fn_tmp = " << fn_tmp);
- if (!playSaved->IsOpen()){
- PTRACE(1, "Cannot open file "" << playSaved->GetName() << """);
- delete playSaved;
- }
- else{
- PTRACE(1, "Playing file "" << playSaved->GetName() << """);
- SetReadChannel(playSaved, TRUE);
- doSilence = FALSE;
- }
- if (!doSilence){
- if (ReadFrame(amount)){
- PTRACE(1,"buffer = " << buffer << " amount = " << amount);
- frameBoundary = AdjustFrame(buffer, amount);
- PTRACE(1, "*******************Recorded File " << frameBoundary);
- totalData += amount;
- }
- else{
- cout << "Finished playing back...." << endl;
- cout << "Test Session still active......." << endl;
- PTRACE(1, "Finished playing " << totalData << " bytes");
-
- // junkwave = psprintf("junkwave%01i",countwavefiles);
-
- //fn = tmpDir + (junkwave + ".wav");
- // junkwave = tmpDir + (junkwave + ".wav");
- //junkwave = fn;
- //_fn = fn;
- // fn = junkwave;
- // _fn = fn;
- // PTRACE(1,"*TEST* fn = " << junkwave);
-
- // if ((junkwave.Right(4)).ToLower() == ".wav"){
- //PTRACE(1,"Creating the Junk File****************!!!");
- //fileclass_tmp = new PWAVFile(junkwave, PFile::WriteOnly,
- //PFile::ModeDefault,PWAVFile::PCM_WavFile);
- //}
- //else
- // fileclass_tmp = new PFile(junkwave, PFile::WriteOnly);
- //recordFilejunkwave = new PCM_RecordFile (*((MyH323Connection *)tmpConn),junkwave,tmpCallLimit);
- //closed = TRUE;
- // Remove Temporary File
- // if (strcmp(fn_tmp,fn_original) != 0){
- //PTRACE(1,"Removing fn_tmp file " << fn_tmp);
- //PFile::Remove(fn_tmp);
- //if (remove(fn_tmp) == -1)
- /*
- if (PFile::Remove(fn_tmp,TRUE)){
- PTRACE(1,"Removing Complete");
- }
- else{
- PTRACE(1,"Removing NOT Complete");
- }
- */
- // }
-
- PIndirectChannel::Close();
- silentCount = 5; // always do 5 frames of silence after every file
-
- // no silence
- doSilence = TRUE;
- PTRACE(1,"WM_G");
- if ((strcmp(recordDTMFTrigger,"1") == 0) && playedOnce == TRUE){
- PTRACE(1,"Starting to Record Second Time!!!!!!!!!!!!^^^^^^^");
- if (recordTrigger){
- if ((playQueue.GetSize() == 0) && (GetBaseReadChannel() == NULL)){
- recordStartedNext = FALSE;
- playedOnce = TRUE;
-
- //fileclass_tmp->StartRecording();
- //conn.StartRecording();
- recordFilejunkwave->StartRecording();
-
- // PCM_RecordFile::Write(buffer,amount);
- countwavefiles++;
-
- //recordFile->StartRecording();
- }
- }
- doSilence = TRUE;
- if (doSilence){
- CreateSilenceFrame(amount);
- frameBoundary = AdjustFrame(buffer, amount);
- }
- // delay to synchronise to frame boundary
- if (frameBoundary){
- Synchronise(amount);
- doSilence = TRUE;
- startPlayingDTMFTrigger = NO;
- }
- return TRUE;
- }
-
- //to keep the record, stop, play cycle going without disconnecting..
- dtmfTrigger = NO;
- recordDTMFTrigger = NO;
- stopRecordDTMFTrigger = NO;
- startPlayingDTMFTrigger = NO;
- playedFlag = 0;
- receivedDTMFMessage = "";
-
- playedOnce = TRUE;
- PTRACE(1, "WAITING for recordDTMFTrigger" << recordDTMFTrigger);
- /*
- if ((strcmp(receivedDTMFMessage,"4") == 0)){
- PTRACE(1,"Clearing Call in Read function.........@@@@@@@@@@@@@@");
-
- H323Channel *tmpChan = tmpConn->FindChannel(RTP_Session::DefaultAudioSessionID,FALSE);
- dtmfTrigger = NO;
- recordDTMFTrigger = NO;
- stopRecordDTMFTrigger = NO;
- startPlayingDTMFTrigger = NO;
- playedFlag = 0;
- receivedDTMFMessage = "";
-
- playedOnce = FALSE;
-
- return FALSE;
- }
- */
- // This code is for Thread NOT Terminating
- for(;;){
- // This code is for Thread NOT Terminating
- doSilence = TRUE;
- if (doSilence) {
- CreateSilenceFrame(amount);
- frameBoundary = AdjustFrame(buffer, amount);
- }
- // delay to synchronise to frame boundary
- if (frameBoundary){
- Synchronise(amount);
- doSilence = TRUE;
- startPlayingDTMFTrigger = NO;
- }
- if ((strcmp(recordDTMFTrigger,"1") == 0) && playedOnce == TRUE){
- PTRACE(1,"Starting to play message for second time@@@@@@@@@@@@@@");
- fn_tmp = fn_original; // To make play the original message starting from seconnd record seq
- return TRUE;
- }
- if ((strcmp(stopRecordDTMFTrigger,"1") == 0) && playedOnce == TRUE){
- PTRACE(1,"This is Second STOP");
- fn_tmp = "";
- return TRUE;
- }
- if ((strcmp(startPlayingDTMFTrigger,"1") == 0) && playedOnce == TRUE){
- PTRACE(1,"This is Second time Playing");
- junkwave = psprintf("junkwave%01i",countwavefiles);
- //fn = tmpDir + (junkwave + ".wav");
- junkwave = tmpDir + (junkwave + ".wav");
- //junkwave = fn;
- //_fn = fn;
- PTRACE(1,"*TEST* fn = " << junkwave);
-
- if ((junkwave.Right(4)).ToLower() == ".wav"){
- PTRACE(1,"Creating the Junk File****************!!!");
- fileclass_tmp = new PWAVFile(junkwave, PFile::WriteOnly,
- PFile::ModeDefault,PWAVFile::PCM_WavFile);
- }
- else
- fileclass_tmp = new PFile(junkwave, PFile::WriteOnly);
- fn = junkwave;
- _fn = fn;
- recordFilejunkwave = new PCM_RecordFile (*((MyH323Connection *)tmpConn),junkwave,tmpCallLimit);
- return TRUE;
- }
- if ((strcmp(receivedDTMFMessage,"4") == 0) && playedOnce == TRUE){
- PTRACE(1,"Clearing call in Read function.........@@@@@@@@@@@@@@");
- //H323Channel *tmpChan = tmpConn->FindChannel(RTP_Session::DefaultAudioSessionID,FALSE);
-
- dtmfTrigger = NO;
- recordDTMFTrigger = NO;
- stopRecordDTMFTrigger = NO;
- startPlayingDTMFTrigger = NO;
- playedFlag = 0;
- receivedDTMFMessage = "";
- playedOnce = FALSE;
- fn = "";
- fn_tmp = "";
-
- /*
- switch (tmpChan->GetDirection()) {
- case H323Channel::IsTransmitter :
- //cout << "sending ";
- //PTRACE(1,"In Hangup, Channel is Trasnmitting");
- break;
- case H323Channel::IsReceiver :
- //cout << "receiving ";
- //PTRACE(1,"In Hangup, Channel is Receiving");
- break;
- default :
- break;
-
- }
- */
- /*
- conn.CloseLogicalChannel(RTP_Session::DefaultAudioSessionID,FALSE);
- //H323ChannelNumber num = tmpChan->GetSessionID();
- conn.CloseLogicalChannel(tmpChan->GetSessionID(),FALSE);
- conn.ClearCall();
- PIndirectChannel::Close();
- conn.~MyH323Connection();
- conn.CleanUpOnCallEnd();
- closed = TRUE; */
- //delete tmpChan;
- //delete tmpConn;
-
-
- return FALSE;
- }
- //return TRUE;
- }
- PTRACE(1, "FINISHED WAITINGGGGGGGGGGGGGGGGGGGGGGGGGGGG recordDTMFTrigger" << recordDTMFTrigger);
-
- //conn.ClearCall();
- return TRUE;
- }
- }
- }
- }
- // start silence frame if required
- if (doSilence) {
- CreateSilenceFrame(amount);
- frameBoundary = AdjustFrame(buffer, amount);
- }
- // delay to synchronise to frame boundary
- if (frameBoundary)
- Synchronise(amount);
- return TRUE;
- }
- BOOL PCM_OGMChannel::Close()
- {
- PWaitAndSignal mutex(chanMutex);
- closed = TRUE;
- PIndirectChannel::Close();
- return TRUE;
- }
- void PCM_OGMChannel::SetRecordTrigger()
- {
- PWaitAndSignal mutex(chanMutex);
- recordTrigger = TRUE;
- if ((playQueue.GetSize() == 0) && (GetBaseReadChannel() == NULL))
- conn.StartRecording();
- }
- void PCM_OGMChannel::SetHangupTrigger()
- {
- PWaitAndSignal mutex(chanMutex);
- hangupTrigger = TRUE;
- if (GetBaseReadChannel() == NULL)
- conn.ClearCall();
- }
- void PCM_OGMChannel::QueueFile(const PString & fn)
- {
- PWaitAndSignal mutex(chanMutex);
- PTRACE(1, "Enqueueing file " << fn << " for playing");
- fnAgain = fn;
- PTRACE(1, "Value of fnAgain.......######" <<fnAgain);
- playQueue.Enqueue(new PString(fn));
- }
- void PCM_OGMChannel::FlushQueue()
- {
- PWaitAndSignal mutex(chanMutex);
- if (GetBaseReadChannel() != NULL) {
- PIndirectChannel::Close();
- if (hangupTrigger)
- conn.ClearCall();
- else if (recordTrigger)
- conn.StartRecording();
- }
- PString * str;
- while ((str = playQueue.Dequeue()) != NULL)
- delete str;
- }
- BOOL PCM_OGMChannel::AdjustFrame(void * buffer, PINDEX amount)
- {
- if ((frameOffs + amount) > frameLen) {
- cerr << "Reading past end of frame:offs=" << frameOffs << ",amt=" << amount << ",len=" << frameLen << endl;
- return TRUE;
- }
- //PAssert((frameOffs + amount) <= frameLen, "Reading past end of frame");
- memcpy(buffer, frameBuffer.GetPointer()+frameOffs, amount);
- frameOffs += amount;
- lastReadCount = amount;
- return frameOffs == frameLen;
- }
- void PCM_OGMChannel::Synchronise(PINDEX amount)
- {
- ogm_delay.Delay(amount / 16);
- }
- BOOL PCM_OGMChannel::ReadFrame(PINDEX amount)
- {
- BOOL result;
- frameOffs = 0;
- frameLen = amount;
- result = PIndirectChannel::Read(frameBuffer.GetPointer(), frameLen); //This is the Read method being actually called..
- PTRACE(1, "result in ReadFrame is " << result);
- // if we did not read a full frame of audio, fill the end of the
- // frame with zeros.
- PINDEX count = GetLastReadCount();
- if (count < frameLen)
- {
- memset(frameBuffer.GetPointer()+count, 0, frameLen-count);
- PTRACE(1,"memset occured in ReadFrame");
- }
- return result;
- }
- void PCM_OGMChannel::CreateSilenceFrame(PINDEX amount)
- {
- frameOffs = 0;
- frameLen = amount;
- memset(frameBuffer.GetPointer(), 0, frameLen);
- }
-
- ///////////////////////////////////////////////////////////////
- G7231_OGMChannel::G7231_OGMChannel(MyH323Connection & conn)
- : PCM_OGMChannel(conn)
- {
- }
- void G7231_OGMChannel::Synchronise(PINDEX /*amount*/)
- {
- ogm_delay.Delay(30);
- }
- BOOL G7231_OGMChannel::ReadFrame(PINDEX /*amount*/)
- {
- if (!PIndirectChannel::Read(frameBuffer.GetPointer(), 1))
- return FALSE;
- frameOffs = 0;
- frameLen = G7231_File_Codec::GetFrameLen(frameBuffer[0]);
- return PIndirectChannel::Read(frameBuffer.GetPointer()+1, frameLen-1);
- }
- void G7231_OGMChannel::CreateSilenceFrame(PINDEX /*amount*/)
- {
- frameOffs = 0;
- frameLen = 4;
- frameBuffer[0] = 2;
- memset(frameBuffer.GetPointer()+1, 0, 3);
- }
- BOOL G7231_OGMChannel::IsWAVFileValid(PWAVFile *chan) {
- // Check that this is a G.723.1 wave file
- return CheckWAVFileValid(chan, CHECK_G7231);
- }
- ///////////////////////////////////////////////////////////////
- PString H323BeaconServer::getLocalhostIPAddress()
- {
- PString hostname ; // stores local host name
-
- //Get local host IP address
- hostent FAR *lpHostEnt = gethostbyname ( hostname ) ;
- if ( lpHostEnt == NULL )
- cout << "IPAddress not available";
- LPSTR lpAddr = lpHostEnt -> h_addr_list[0] ;
- if ( lpAddr )
- {
- in_addr inAddr ;
- memmove ( &inAddr, lpAddr, 4 ) ;
- IPAddress = inet_ntoa ( inAddr ) ;
- if ( IPAddress.IsEmpty( ) )
- cout << "IPAddress not available";
- }
- return IPAddress;
- }
- /*
- int MyH323Connection::SendTraceRtToClient(PString clientIP, PString *message)
- {
- // WORD nport=5050;
- int rt=0;
- // sock=new PSocket();
- //PChannel chan;
- //PIPXSocket sock(nport);
- //sock.port(nport);
- char temp[100];
- char *ip;
-
- strcpy(temp,clientIP);
- // cout<< "TEMP: "<<temp<<"n";
- ip=strtok(temp,"$");
- ip=strtok(NULL,":");
- char msg[2048]= "";
- PFile fp("ft_result",PFile::ReadOnly,PFile::ModeDefault);
- fp.read(msg,2048);
- SOCKET writeSocket;
- writeSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-
- sockaddr_in service;
- service.sin_family = AF_INET;
- service.sin_addr.s_addr = inet_addr(ip);
- service.sin_port = htons(5051);
-
- cout <<"Trying to Send the traceRT to client "<< ip<<"n";
- PTRACE(1,"Trying to Send the traceRT to clientn");
- PTRACE(1,ip);
- //char msg[1024] = "MSG FROM SERVER: TRACERT: 1 2 3 4 5 6 7 8 9 10n";
- if (connect (writeSocket, (SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR) {
- PTRACE(1,"Connection to client,failed for traceRT filen");
- }
- else {
- PTRACE(1,"Connection Established to client, sending traceRT filen");
- if(send(writeSocket,msg,sizeof(msg),0)>0) {
- rt=1;
- PTRACE(1,"TRACERT: Successfully writing to client....n");
- }else {
- PTRACE(1,"TRACERT: Send failed....n");
- }
- }
-
- closesocket (writeSocket);
- return rt;
- }
- */
- int MyH323Connection::log_server(){
-
- //----------------------
- // Initialize Winsock
- WSADATA wsaData;
- int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
- if (iResult != NO_ERROR)
- printf("Error at WSAStartup()n");
- //----------------------
-
-
- SOCKET ListenSocket;
- ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (ListenSocket == SOCKET_ERROR) {
- printf("Error at socket(): %ldn", WSAGetLastError());
- printf("Error at socket()n");
- WSACleanup();
- return 1;
- }
- //----------------------
- //----------------------
- // The sockaddr_in structure specifies the address family,
- // IP address, and port for the socket that is being bound.
- sockaddr_in service;
- service.sin_family = AF_INET;
- service.sin_addr.s_addr = inet_addr("0.0.0.0");
- service.sin_port = htons(SRVPORT);
-
- //create a structure for the client address
- //sockaddr_in clientaddr;
- //unsigned int clntLen;
- //Set the socket options to reuse the socket address to avoid bind failures
- //int opt=1;
- char optval[5] = "TRUE";
- //unsigned long optval =1;
- if(setsockopt(ListenSocket, SOL_SOCKET, SO_REUSEADDR, optval, sizeof(optval))==SOCKET_ERROR){
- cout<<"Error setting the reuse address optionn";
- }
-
- if (bind( ListenSocket,
- (struct sockaddr *) &service,
- sizeof(service)) != 0) {
- printf("bind() failed.n");
- close(ListenSocket);
- return 1;
- }
- //----------------------
- // Listen for incoming connection requests
- // on the created socket
- if (listen( ListenSocket, 1 ) != 0)
- printf("Error listening on socket.n");
- //----------------------
- // Create a SOCKET for accepting incoming requests.
- SOCKET AcceptSocket;
- //int AcceptSocket;
- printf("Waiting for client to connect...nWill timeout in 15 secsn");
- //printf("before forn");
- // int nLen = sizeof(struct sockaddr);
- char buf[1024];
- int line = 1;
- FILE *log;
- //printf("Making socket non-blockingn");
- //----------------------
- // Accept the connection.
- //fcntl(ListenSocket, F_SETFL, O_NONBLOCK);
- long par=1;
- if(ioctlsocket (ListenSocket, FIONBIO,(unsigned long *)&par)==SOCKET_ERROR){
- cout<<"Cant set socket to non-blocking moden";
- }
- //while(1) {
- //printf("before forn");
- AcceptSocket = INVALID_SOCKET;
- int i=0;
- //AcceptSocket = accept( ListenSocket, NULL, NULL );
- //printf("before forn");
- for (i=0;i<15;i++){
- //printf("just inside forn");
- if( AcceptSocket == INVALID_SOCKET ) {
- if (i==14) {
- printf("Client didnt connect Timed outn");
- shutdown (AcceptSocket,2);
- shutdown (ListenSocket,2);
- close (AcceptSocket);
- close (ListenSocket);
- return 0;
- }
- //printf("Sleeping for a second: %dn",i);
- Sleep(1000);
- AcceptSocket = accept( ListenSocket, NULL, NULL );
- }
- else {
- //printf("I am in elsen");
- //AcceptSocket = accept( ListenSocket, (struct sockaddr *) &clientaddr, &clntLen );
- //AcceptSocket = accept( ListenSocket, NULL, NULL );
- break;
- }
-
- }
- printf("nClient connected...");
- if(!(log=fopen(LOG_H323,"r")))
- {
- printf("nFailed on opening LOG_H323");
- }
- else
- {
- printf("nSending log file...");
- while(1)
- {
- fgets(buf,line,log);
- send( AcceptSocket, buf, strlen(buf), 0 );
- line++;
- if (feof(log)) break;
- }
- printf("nThe file log was sent!");
- fclose(log);
- }
-
- shutdown (AcceptSocket,2);
- shutdown (ListenSocket,2);
- close (AcceptSocket);
- close (ListenSocket);
- //}
- WSACleanup();
- return 1;
- }