Code/Resource
Windows Develop
Linux-Unix program
Internet-Socket-Network
Web Server
Browser Client
Ftp Server
Ftp Client
Browser Plugins
Proxy Server
Email Server
Email Client
WEB Mail
Firewall-Security
Telnet Server
Telnet Client
ICQ-IM-Chat
Search Engine
Sniffer Package capture
Remote Control
xml-soap-webservice
P2P
WEB(ASP,PHP,...)
TCP/IP Stack
SNMP
Grid Computing
SilverLight
DNS
Cluster Service
Network Security
Communication-Mobile
Game Program
Editor
Multimedia program
Graph program
Compiler program
Compress-Decompress algrithms
Crypt_Decrypt algrithms
Mathimatics-Numerical algorithms
MultiLanguage
Disk/Storage
Java Develop
assembly language
Applications
Other systems
Database system
Embeded-SCM Develop
FlashMX/Flex
source in ebook
Delphi VCL
OS Develop
MiddleWare
MPI
MacOS develop
LabView
ELanguage
Software/Tools
E-Books
Artical/Document
AppController.java
Package: SIP_soft_phone.zip [view]
Upload User: lizhi6181
Upload Date: 2014-10-02
Package Size: 8848k
Code Size: 138k
Category:
VOIP program
Development Platform:
Java
- /*
- * Open Source Exemplar Software
- *
- * Copyright (C) 2005 University of Wisconsin (Trace R&D Center)
- * Copyright (C) 2005 Omnitor AB
- *
- * This reference design was developed under funding from the National
- * Institute on Disability and Rehabilitation Research US Dept of Education
- * and the European Commission.
- *
- * This piece of software is a part of a package that was developed as a joint
- * effort of Omnitor AB and the Trace Center - University of Wisconsin and is
- * released to the public domain with only the following restrictions:
- *
- * 1) That the following acknowledgement be included in the source code and
- * documentation for the program or package that use this code
- *
- * "Parts of this program were based on reference designs developed by
- * Omnitor AB and the Trace Center, University of Wisconsin-Madison under
- * funding from the National Institute on Disability and Rehabilitation
- * Research US Dept of Education and the European Commission."
- *
- * 2) That this program not be modified unless it is plainly marked as
- * modified from the original distributed by Trace/Omnitor.
- *
- * (NOTE: This release applies only to the files that contain this notice -
- * not necesarily to any other code or libraries associated with this file.
- * Please check individual files and libraries for the rights to use each)
- *
- * THIS PIECE OF THE SOFTWARE PACKAGE IS EXPERIMENTAL/DEMONSTRATION IN NATURE.
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
- * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
- * BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
- * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
- * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
- * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
- * SOFTWARE.
- *
- */
- package se.omnitor.tipcon1;
- import ca.beq.util.win32.registry.RegistryKey;
- import ca.beq.util.win32.registry.RootKey;
- import ca.beq.util.win32.registry.RegistryValue;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.InputStreamReader;
- import java.io.IOException;
- import java.net.DatagramSocket;
- import java.net.DatagramPacket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- import java.net.SocketTimeoutException;
- import java.util.Collection;
- import java.util.Properties;
- import java.util.Random;
- import java.util.Vector;
- import java.util.Iterator;
- import java.awt.Color;
- import java.awt.Font;
- import javax.media.CaptureDeviceInfo;
- import javax.media.CaptureDeviceManager;
- import javax.media.Codec;
- import javax.media.ControllerClosedEvent;
- import javax.media.ControllerEvent;
- import javax.media.ControllerListener;
- import javax.media.Format;
- import javax.media.MediaLocator;
- import javax.media.NoProcessorException;
- import javax.media.PackageManager;
- import javax.media.PlugInManager;
- import javax.media.Processor;
- import javax.media.control.TrackControl;
- import javax.media.format.AudioFormat;
- import javax.media.format.VideoFormat;
- import javax.media.protocol.ContentDescriptor;
- import javax.media.protocol.DataSource;
- import javax.media.protocol.SourceCloneable;
- import javax.media.rtp.RTPManager;
- import javax.naming.NameNotFoundException;
- import javax.naming.NamingException;
- import javax.sound.sampled.AudioFileFormat;
- import javax.sound.sampled.AudioInputStream;
- import javax.sound.sampled.AudioSystem;
- import javax.sound.sampled.Clip;
- import javax.sound.sampled.Line;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- import se.omnitor.media.protocol.text.t140.TextFormat;
- import se.omnitor.tipcon1.gui.AudioVideoPlayer;
- import se.omnitor.tipcon1.gui.DialogFactory;
- import se.omnitor.tipcon1.gui.ProgramWindow;
- import se.omnitor.tipcon1.gui.SplashScreen;
- import se.omnitor.tipcon1.gui.ThreadedDialog;
- import se.omnitor.tipcon1.rtp.RTPPayloadConstants;
- import se.omnitor.tipcon1.sip.SipRegistrarInfo;
- import se.omnitor.protocol.rtp.text.SyncBuffer;
- import se.omnitor.protocol.t140.T140TextArea;
- import se.omnitor.protocol.t140.T140Panel;
- import se.omnitor.protocol.t140.T140Packetizer;
- import se.omnitor.protocol.t140.T140DePacketizer;
- import se.omnitor.util.FifoBuffer;
- import se.omnitor.protocol.sip.AuthInfo;
- import se.omnitor.protocol.sip.FromAddress;
- import se.omnitor.protocol.sip.SipControllerListener;
- import se.omnitor.protocol.sip.SipController;
- import se.omnitor.protocol.sip.call.IncomingCallDialog;
- import se.omnitor.protocol.sip.call.IncomingReferDialog;
- import se.omnitor.protocol.sip.call.OutgoingCallDialog;
- import se.omnitor.protocol.sip.call.CallProcessor;
- import se.omnitor.protocol.sip.register.RegisterProcessor;
- import se.omnitor.protocol.sip.register.RegisterDialog;
- import se.omnitor.protocol.sdp.SdpManager;
- import se.omnitor.protocol.sdp.SdpMedia;
- import se.omnitor.protocol.sdp.media.CustomMedia;
- import se.omnitor.protocol.sdp.format.CustomFormat;
- import se.omnitor.protocol.sdp.format.T140Format;
- import se.omnitor.protocol.sdp.format.RedFormat;
- import se.omnitor.protocol.stun.StunStack;
- import se.omnitor.protocol.stun.StunStackException;
- import javax.sdp.SdpException;
- // import LogClasses and Classes
- import java.util.logging.Level;
- import java.util.logging.Logger;
- //import net.sf.fmj.media.cdp.civil.CaptureDevicePlugger;
- import java.awt.Dimension;
- import javax.media.Control;
- /**
- * The main class for a multimedia SIP user client.
- *
- * This class connects RTP, SIP and GUI. How this program works is described
- * in a document at Omnitor AB.
- *
- * @author Andreas Piirimets, Omnitor AB
- * @author Erik Zetterstrom, Omnitor AB
- */
- public class AppController implements SipControllerListener {
- // A registrarion's status
- private static final int FAIL = 1;
- private static final int TRYING = 2;
- private static final int OK = 3;
- private static final int NOT_REG = 4;
- // Semaphore
- private Integer stateLock = new Integer(0);
- // The local video
- private AudioVideoPlayer avPlayer = null;
- // General RTP variables
- private boolean processorChangeFailed;
- private DataSource transmitVideoDataSource = null;
- private Vector supportedMedia;
- // RTP Text transmit variables
- private boolean firstRun = true;
- private boolean redFlagOutgoing = false;
- private int maxIncomingCps;
- //private int localTextPort;
- private boolean textIsActivated;
- private int nbrOfTextDevices = 1;
- // Video RTP transmit variables
- //private int localVideoPort;
- private VideoFormat[] videoFormat;
- //private VideoFormat videoFormatToUse;
- private Vector videoCodecs;
- private int videoDevice;
- private boolean videoIsActivated;
- private int nbrOfVideoDevices;
- private String[] videoLocator;
- private int videofps = 25;
- // Audio RTP transmit variables
- //private int localAudioPort;
- private AudioFormat[] audioFormat;
- private Vector audioCodecs;
- private int audioDevice;
- private boolean audioIsActivated;
- private int nbrOfAudioDevices;
- private String[] audioLocator;
- private boolean isMuted;
- // RTP Text receive variables
- private boolean redFlagIncoming = false;
- // GUI dialogs, windows and labels
- protected ProgramWindow gui;
- private ThreadedDialog incomingCallDialog;
- private ThreadedDialog outgoingCallDialog;
- // SIP variables
- protected SipController sc;
- private String remoteUserAddress;
- private RegisterProcessor[] registerProcessor;
- private CallProcessor callProcessor;
- private int[] sipRegistrarStatus;
- boolean sipCompatibleNatIsProbed = false;
- boolean isBehindSipCompatibleNat = false;
- Thread sipStarterThread = null;
- Integer sipStartStopMutex;
- boolean sipSystemIsRunning = false;
- boolean queuedSipSystemRestart;
- // SDP
- private SdpManager currentSdpManager;
- private Vector negotiatedMedia;
- private int sdpCallCounter;
- // Network
- private String localIpAddress = null;
- private String localHostAddress;
- private String dnsServer = null;
- private int nextFreePort = 1024;
- private boolean isSipCompatibleNatDetected = false;
- private String sipCompatibleNatName = null;
- // Runtime variables
- // These variables control system settings during runtime, these settings
- // may and should differ from settings saved to disk.
- private boolean runtimeIsStunActivated;
- private SyncBuffer txTextBuffer;
- private FifoBuffer rxTextBuffer;
- private T140Panel t140Panel;
- private T140Packetizer t140Packetizer;
- private T140DePacketizer t140DePacketizer;
- private String classRoot;
- private AppConstants appConstants;
- private Properties language;
- private MediaManager mediaManager;
- private boolean outgoingCallProgressReported;
- private boolean isEconf351 = false;
- private AppSettings appSettings;
- private StunStack stunStack;
- private boolean tipcon1Mode;
- private String configurationTypeString;
- //private static CertCallback certCallback = new CertCallback();
- //************************************************************************
- // declare package and classname
- public final static String CLASS_NAME = AppController.class.getName();
- // get an instance of Logger
- private static Logger logger = Logger.getLogger(CLASS_NAME);
- /**
- * Register a payload type to JMF.
- *
- * @param payloadType The payload type number to register
- * @param codec The codec to assign to this payload type number
- */
- private void registerPayloadType(int payloadType, String codec) {
- TextFormat textFormat = new TextFormat(codec);
- RTPManager rtpManager = RTPManager.newInstance();
- rtpManager.addFormat(textFormat, payloadType);
- }
- /**
- * Registers the text plug-in to JMF.
- *
- */
- private void registerTextPlugIn() {
- // Name of the new plugin
- String packageString = new String("se.omnitor.media.protocol.rtptext");
- // Add new package prefix
- Vector packagePrefix = PackageManager.getProtocolPrefixList();
- String myPackagePrefix = new String("se.omnitor");
- if (packagePrefix.indexOf(myPackagePrefix) == -1) {
- packagePrefix.addElement(myPackagePrefix);
- PackageManager.setProtocolPrefixList(packagePrefix);
- PackageManager.commitProtocolPrefixList();
- }
- // Add new content prefix
- Vector contentPrefix = PackageManager.getContentPrefixList();
- if (contentPrefix.indexOf(myPackagePrefix) == -1) {
- contentPrefix.addElement(myPackagePrefix);
- PackageManager.setContentPrefixList(contentPrefix);
- PackageManager.commitContentPrefixList();
- }
- // Save the changes to the plug-in registry
- try {
- PlugInManager.commit();
- } catch (java.io.IOException ioe) {
- ioe.printStackTrace();
- }
- // Register Packetizer
- /*
- TextPacketizer textPacketizer = new TextPacketizer(0,0);
- try {
- PlugInManager.removePlugIn(textPacketizer.getClass().getName(),
- PlugInManager.CODEC);
- PlugInManager.addPlugIn(textPacketizer.getClass().getName(),
- textPacketizer.getSupportedInputFormats(),
- textPacketizer.
- getSupportedOutputFormats(null),
- PlugInManager.CODEC);
- PlugInManager.commit();
- } catch (Exception e2) {
- if (DEBUG) {
- System.err.println("Cannot register TextPacketizer: " + e2);
- }
- }
- if (DEBUG) {
- System.out.println("TextPacketizer registered.");
- }
- */
- // Register DePacketizer
- /*
- TextDePacketizer textDePacketizer = new TextDePacketizer(0, false);
- try {
- PlugInManager.removePlugIn(textDePacketizer.getClass().getName(),
- PlugInManager.CODEC);
- PlugInManager.addPlugIn(textDePacketizer.getClass().getName(),
- textDePacketizer.
- getSupportedInputFormats(),
- textDePacketizer.
- getSupportedOutputFormats(null),
- PlugInManager.CODEC);
- PlugInManager.commit();
- } catch (Exception e2) {
- if (DEBUG) {
- System.err.println("Cannot register TextDePacketizer: " + e2);
- }
- }
- if (DEBUG) {
- System.out.println("TextDePacketizer registered.");
- }
- */
- // Register player
- /*
- TextPlayer textPlayer= new TextPlayer();
- try {
- PlugInManager.removePlugIn(textPlayer.getClass().getName(),
- PlugInManager.RENDERER);
- PlugInManager.addPlugIn(textPlayer.getClass().getName(),
- textPlayer.getSupportedInputFormats(),
- textPlayer.getSupportedOutputFormats(null),
- PlugInManager.RENDERER);
- PlugInManager.commit();
- } catch (Exception e2) {
- if (DEBUG) {
- System.err.println("Cannot register TextDePacketizer: " + e2);
- }
- }
- if (DEBUG) {
- System.out.println("TextPlayer registered.");
- }
- */
- }
- /**
- * Registers the H263 mode A effect to JMF.
- *
- */
- /*
- private void registerH263ModeAEffect() {
- H263ModeAEffect effect = new H263ModeAEffect();
- String name = effect.getClass().getName();
- try {
- PlugInManager.removePlugIn(name, PlugInManager.EFFECT);
- PlugInManager.addPlugIn(name,
- effect.getSupportedInputFormats(),
- effect.getSupportedOutputFormats(null),
- PlugInManager.EFFECT);
- PlugInManager.commit();
- }
- catch (Exception e2) {
- if (DEBUG) {
- System.err.println("Cannot register H263 mode A effect: " +
- e2);
- e2.printStackTrace();
- }
- }
- if (DEBUG) {
- System.out.println("H263 mode A effect registered.");
- }
- }
- */
- /**
- * Initializes text plugin, creates SipController, and creates GUI.
- * It also reports the status to the given splash screen through all the
- * tasks.
- *
- * @param splash The splash screen which should receive all the reports
- */
- public AppController(Properties aLanguage, SplashScreen splash,
- String classRoot,
- String customSettingsFile, String customHelpsetPath) {
- // write methodname
- final String METHOD =
- "AppController(Properties language, SplashScreen splash, String classRoot)";
- // log when entering a method
- logger.entering(CLASS_NAME, METHOD, new Object[] {aLanguage, splash,
- classRoot});
- try {
- appConstants =
- (AppConstants) Class.forName(classRoot + ".AppConstants").
- newInstance();
- appConstants.setConstants(customSettingsFile, customHelpsetPath);
- } catch (Exception e) {
- logger.throwing(this.getClass().getName(), "<init>", e);
- DialogFactory.showErrorMessageDialog
- (aLanguage.getProperty("se.omnitor.tipcon1.AppController." +
- "GUI_ERROR"));
- System.exit( -1);
- }
- this.classRoot = classRoot;
- sipStartStopMutex = new Integer(0);
- appSettings = new AppSettings(appConstants.SETTINGS_DATA_FILE_URL);
- if (appSettings.getLanguageCode() == AppConstants.ENGLISH) {
- language = new English();
- }
- else if (appSettings.getLanguageCode() == AppConstants.SWEDISH) {
- language = new Swedish();
- }
- tipcon1Mode = appSettings.getTipcon1Mode();
- configurationTypeString = appSettings.getConfigurationString();
- DialogFactory.registerLanguage(language);
- sdpCallCounter = 1;
- isMuted = false;
- // Initialize text plug-in
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController.INIT_TEXT"));
- registerTextPlugIn();
- // Initialize text plug-in
- /*
- splash.changeText("Initializing video transmission");
- registerH263ModeAEffect();
- */
- // Get the local IP address
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController.INIT_NETWORK"));
- if (!detectLocalIp()) {
- DialogFactory.showErrorMessageDialog
- (language.getProperty("se.omnitor.tipcon1.AppController." +
- "NETWORK_ERROR"));
- }
- /*
- catch (UnknownHostException uhe) {
- logger.throwing(this.getClass().getName(), "<init>", uhe);
- DialogFactory.showErrorMessageDialog
- (language.getProperty("se.omnitor.tipcon1.AppController." +
- "SIP_ERROR"));
- System.exit(-1);
- }
- */
- try {
- // Retrieve all supported media types of the local computer
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "INIT_CAPTURE"));
- supportedMedia = (Vector) initializeSupportedMedia();
- if (supportedMedia.isEmpty()) {
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "SETUP_NA"));
- detectDevices();
- supportedMedia = (Vector) initializeSupportedMedia();
- }
- } catch (Exception e1) {
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "DEVICE_CHANGE"));
- detectDevices();
- supportedMedia = (Vector) initializeSupportedMedia();
- }
- // Create text transport
- txTextBuffer = new SyncBuffer(appSettings.getRedundantRtpGenerations(),
- (int) appSettings.getBufferTime());
- logger.finer("buffertime is :" + appSettings.getBufferTime());
- // Initialize the GUI
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController.CREATE_GUI"));
- t140Packetizer = new T140Packetizer(0);
- t140Panel = new T140Panel(t140Packetizer,
- appSettings.isRealtimePreviewEnabled(),
- language.getProperty("se.omnitor.tipcon1.gui.t140.LOGWINDOW"),
- language.getProperty("se.omnitor.tipcon1.gui.t140.RECEIVEWINDOW"),
- language.getProperty("se.omnitor.tipcon1.gui.t140.SENDWINDOW"),
- language);
- t140Packetizer.setOutBuffer(txTextBuffer);
- rxTextBuffer = new FifoBuffer();
- t140DePacketizer = new T140DePacketizer(0);
- t140DePacketizer.setInBuffer(rxTextBuffer);
- t140DePacketizer.setEventHandler(t140Panel);
- t140DePacketizer.start();
- setupT140panel();
- // Get settings
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController.LOAD_SETTINGS"));
- restoreSavedSettings();
- try {
- Class cls = Class.forName(classRoot + ".gui.ProgramWindow");
- gui = (ProgramWindow) cls.newInstance();
- logger.logp(Level.FINER, CLASS_NAME, METHOD, "SipController sc is",
- sc);
- gui.init(sc, this, appSettings);
- deploySettings(); // to use don't use this line (here)
- gui.prepare();
- } catch (Exception cnfe) {
- logger.throwing(this.getClass().getName(), "<init>", cnfe);
- DialogFactory.showErrorMessageDialog
- (language.getProperty("se.omnitor.tipcon1.AppController." +
- "GUI_ERROR"));
- System.exit( -1);
- }
- // Initialize the SIP client
- splash.changeText(language.getProperty("se.omnitor.tipcon1." +
- "AppController.INIT_SIP"));
- threadedStartSipSystem();
- deploySettings();
- logger.exiting(CLASS_NAME, METHOD);
- }
- private void restoreSavedSettings() {
- appSettings.load();
- txTextBuffer.setRedGen(appSettings.getRedundantRtpGenerations());
- setTextBufferTime(appSettings.getBufferTime());
- t140Panel.useMsrpSmoother(appSettings.isMsrpSmootherActive());
- txTextBuffer.setSendOnCR(appSettings.useSendOnCR());
- txTextBuffer.setBufferTime(100);
- maxIncomingCps = 0;
- textIsActivated = true;
- videoIsActivated = true;
- //videoIsActivated = false;
- audioIsActivated = true;
- if(appSettings.getTipcon1Mode()) {
- restoreSavedVideoSettings();
- }
- restoreSavedAudioSettings();
- }
- private void createGui() {
- }
- /**
- * Gets the local IP address and the local host name. These values are
- * stored in a global variable in the system. If the local IP address is
- * 127.0.0.1, the function assumes that no network is present and false
- * will be returned.
- *
- * @return True if an address was retrieved, false if not.
- */
- private boolean detectLocalIp() {
- String oldLocalIp = localIpAddress;
- try {
- localIpAddress = InetAddress.getLocalHost().getHostAddress();
- localHostAddress = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException uhe) {
- return false;
- }
- if (!localIpAddress.equals(oldLocalIp) && oldLocalIp != null) {
- if (localIpAddress.equals("127.0.0.1")) {
- sc.stop();
- } else if (oldLocalIp.equals("127.0.0.1")) {
- try {
- sc.start();
- } catch (Exception e) {
- return false;
- }
- } else {
- try {
- sc.stop();
- sc.start();
- } catch (Exception e) {
- return false;
- }
- }
- }
- if (localIpAddress.equals("127.0.0.1")) {
- return false;
- }
- return true;
- }
- public void setupT140panel() {
- t140Panel.useMsrpSmoother(true);
- t140Panel.setTaFont
- (new Font(appSettings.getLocalFont(), Font.PLAIN,
- appSettings.getLocalTextSize()));
- /*
- t140Panel.setRemoteFont
- (new Font(remoteFont, Font.PLAIN, remoteTextSize));
- */
- try {
- t140Panel.setTaFontColor(appSettings.getLocalTextColor());
- } catch (NumberFormatException nfe) {
- }
- /*
- t140Panel.setRemoteFontColor
- (new Color(Integer.parseInt(remoteTextColor[0]),
- Integer.parseInt(remoteTextColor[1]),
- Integer.parseInt(remoteTextColor[2])));
- */
- try {
- t140Panel.setTaFontBackground(appSettings.getLocalBgColor());
- } catch (NumberFormatException nfe) {
- }
- /*
- t140Panel.setRemoteFontBackground
- (new Color(Integer.parseInt(remoteBgColor[0]),
- Integer.parseInt(remoteBgColor[1]),
- Integer.parseInt(remoteBgColor[2])));
- */
- /*
- if (dataCnt != pLength) {
- Object[][] correctedData = new Object[dataCnt][2];
- System.arraycopy(data, 0, correctedData, 0, dataCnt);
- data = correctedData;
- }
- */
- t140Panel.setTaFont
- (new Font("Arial Unicode MS", Font.PLAIN, 12));
- /*
- t140Panel.setRemoteFont
- (new Font("Arial Unicode MS", Font.PLAIN, 12));
- */
- t140Panel.setTaFontColor(new Color(0, 0, 0));
- //t140Panel.setRemoteFontColor(new Color(0, 0, 0));
- t140Panel.setTaFontBackground(new Color(255, 255, 255));
- //t140Panel.setRemoteFontBackground(new Color(255, 255, 255));
- }
- /**
- * Restores saved audio settings. At this moment, this function just
- * sets default settings for audio. Save and restore to harddrive has
- * not been implemented yet.
- *
- */
- public void restoreSavedAudioSettings() {
- int cnt;
- int fcnt;
- // Count devices
- audioCodecs = new Vector(0, 1);
- // Set formats and codecs
- audioFormat = new AudioFormat[nbrOfAudioDevices];
- audioLocator = new String[nbrOfAudioDevices];
- Format[] captureFormat;
- int audioCnt = 0;
- int videoCnt = 0;
- Vector outputFormats;
- DeviceContainer tempDc;
- int smSize;
- if (supportedMedia == null) {
- smSize = 0;
- } else {
- smSize = supportedMedia.size();
- }
- for (cnt = 0; cnt < smSize; cnt++) {
- tempDc = (DeviceContainer) supportedMedia.get(cnt);
- captureFormat = tempDc.getCaptureFormats();
- outputFormats = (Vector) tempDc.getOutputFormats();
- if (tempDc.getType().equals("audio")) {
- if (captureFormat != null) {
- for (fcnt = 0; fcnt < captureFormat.length; fcnt++) {
- if (audioFormat[audioCnt] == null) {
- audioFormat[audioCnt] =
- (AudioFormat) captureFormat[fcnt];
- } else {
- if (((AudioFormat) captureFormat[fcnt]).
- getSampleSizeInBits() >
- audioFormat[audioCnt].getSampleSizeInBits()) {
- audioFormat[audioCnt] =
- (AudioFormat) captureFormat[fcnt];
- }
- }
- }
- }
- if (outputFormats != null) {
- int ofSize = outputFormats.size();
- for (fcnt = 0; fcnt < ofSize; fcnt++) {
- if (!audioCodecs.contains
- ((String) outputFormats.get(fcnt))) {
- audioCodecs.add((String) outputFormats.get(fcnt));
- }
- }
- }
- audioLocator[audioCnt] = tempDc.getLocator();
- audioCnt++;
- }
- }
- }
- /**
- * Restores saved video settings.
- *
- */
- public void restoreSavedVideoSettings() {
- int cnt;
- int fcnt;
- // Count devices
- videoCodecs = new Vector(0, 1);
- // Set formats and codecs
- videoFormat = new VideoFormat[nbrOfVideoDevices];
- videoLocator = new String[nbrOfVideoDevices];
- Format[] captureFormat;
- int videoCnt = 0;
- Vector outputFormats;
- DeviceContainer tempDc;
- boolean vfIsSet = false;
- int smSize;
- if (supportedMedia == null) {
- smSize = 0;
- } else {
- smSize = supportedMedia.size();
- }
- for (cnt = 0; cnt < smSize; cnt++) {
- tempDc = (DeviceContainer) supportedMedia.get(cnt);
- captureFormat = tempDc.getCaptureFormats();
- outputFormats = (Vector) tempDc.getOutputFormats();
- if (tempDc.getType().equals("video")) {
- System.out.println("restoreSavedVideoSettings()");
- if (captureFormat != null) {
- for (fcnt = 0; fcnt < captureFormat.length; fcnt++) {
- if (videoFormat[videoCnt] == null) {
- videoFormat[videoCnt] = (VideoFormat) captureFormat[fcnt];
- //VideoFormat[] vf = new VideoFormat[1];
- //vf[0] = new VideoFormat("YUV", new Dimension(176,144),Format.NOT_SPECIFIED,null, 25.0F);
- //setVideoFormat(vf);
- } else {
- // 188 kbit/s is a suitable speed for video
- // transmission. Try to find a format as close as
- // possible to 188 kbit/s.
- //System.out.println(appSettings.getResolution() + ":" +formatToString(captureFormat[fcnt]));
- String resolution = appSettings.getResolution();
- //if (resolution.equals("176x144 (yuv)")) {
- // VideoFormat[] vf = new VideoFormat[1];
- // vf[0] = new VideoFormat("YUV", new Dimension(176,144),Format.NOT_SPECIFIED,null, 25.0F);
- // setVideoFormat(vf);
- // vfIsSet = true;
- //}
- //else
- if (resolution.equalsIgnoreCase(formatToString(captureFormat[fcnt]))) {
- VideoFormat[] vf = new VideoFormat[1];
- vf[0] = (VideoFormat) captureFormat[fcnt];
- setVideoFormat(vf);
- vfIsSet = true;
- } else if (Math.abs(((VideoFormat) captureFormat[fcnt]).
- getMaxDataLength()) <
- Math.abs(videoFormat[videoCnt].
- getMaxDataLength() - 316000) && !vfIsSet) {
- if (((VideoFormat) captureFormat[fcnt]).
- getEncoding().equals("yuv")) {
- VideoFormat[] vf = new VideoFormat[1];
- vf[0] = (VideoFormat) captureFormat[fcnt];
- setVideoFormat(vf);
- //videoFormat[videoCnt] = (VideoFormat) captureFormat[fcnt];
- }
- }
- }
- }
- }
- if (outputFormats != null) {
- int ofSize = outputFormats.size();
- for (fcnt = 0; fcnt < ofSize; fcnt++) {
- if (!videoCodecs.contains
- ((String) outputFormats.get(fcnt))) {
- videoCodecs.add((String) outputFormats.get(fcnt));
- }
- }
- }
- videoLocator[videoCnt] = tempDc.getLocator();
- videoCnt++;
- }
- }
- }
- /**
- * This function is aimed to be used after all settings has been entered
- * to this class. This function will insert all codecs into the SIP
- * controller and, if activated, restart the local video image.
- *
- */
- public void deploySettings() {
- // write methodname
- final String METHOD = "deploySettings()";
- // log when entering a method
- logger.entering(CLASS_NAME, METHOD);
- // Now, all SDP settings are deployed immediately before calling or
- // answering a call in order to allow STUN requests probe for port
- // mappings.
- //deploySdpSettings(true);
- if(appSettings.getTipcon1Mode()) {
- deployVideoSettings();
- }
- logger.exiting(CLASS_NAME, METHOD);
- }
- /**
- * Deploy video settings. The video is restarted.
- *
- */
- public void deployVideoSettings() {
- Thread t = new Thread() {
- public void run() {
- restartVideo();
- }
- };
- t.setName("Video restarter");
- t.start();
- }
- /**
- * Deploys the current SDP settings, which are read from the variables.
- * This function should be run after the variables has been read from the
- * settings XML file or after the user has committed changes.
- *
- */
- public void deploySdpSettings(boolean useTextIfActivated) {
- // write methodname
- final String METHOD = "deploySdpSettings(boolean useTextIfActivated)";
- // log when entering a method
- logger.entering(CLASS_NAME, METHOD);
- int plType;
- String plName;
- long plClockRate;
- RTPPayloadConstants constants = new RTPPayloadConstants();
- int cnt;
- String codecName;
- // Higher than 98 since Allan eC requires text to use 98
- int nextDynamicPayloadType = 99;
- SdpManager sdpm;
- try {
- logger.logp(Level.INFO, CLASS_NAME, METHOD, "userRealName is",
- appSettings.getUserRealName());
- if (isRuntimeStunActivated()) {
- sdpm = new SdpManager(appSettings.getUserRealName().replace(' ',
- '_'),
- "" + sdpCallCounter,
- "" + sdpCallCounter,
- "IN",
- "IP4",
- stunStack.getExternalIp());
- } else {
- sdpm = new SdpManager(appSettings.getUserRealName().replace(' ',
- '_'),
- "" + sdpCallCounter,
- "" + sdpCallCounter,
- "IN",
- "IP4",
- localIpAddress);
- }
- } catch (SdpException se) {
- logger.throwing(this.getClass().getName(), "deploySdpSettings",
- se);
- return;
- }
- SdpMedia sdpMedia;
- se.omnitor.protocol.sdp.Format format;
- Vector formats;
- // Video descriptors
- if (videoIsActivated && appSettings.getTipcon1Mode()) {
- if (videoCodecs != null &&
- videoCodecs.size() > 0) {
- int port = -1;
- if (isRuntimeStunActivated()) {
- int mappedPort = 1;
- try {
- // Do five attempts finding an even mapped port (as RTP should be sent from an even port)
- for (int mcnt=0; mcnt<5 && (mappedPort%2 == 1); mcnt++) {
- port = getFreePort();
- mappedPort = stunStack.getMappedPort(port);
- }
- sdpMedia = new CustomMedia("video",
- mappedPort,
- "RTP/AVP");
- // As the NAT often picks port numbers in series,
- // lets force it to hold a port open for the incoming
- // RTCP.
- stunStack.getMappedPort(port+1);
- } catch (StunStackException se) {
- sdpMedia = new CustomMedia("video", port, "RTP/AVP");
- setRuntimeStunActivated(false);
- DialogFactory.showErrorMessageDialog
- (language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "STUN_ERROR"));
- }
- } else {
- port = getFreePort();
- sdpMedia = new CustomMedia("video", port, "RTP/AVP");
- }
- sdpMedia.setPhysicalPort(port);
- formats = new Vector(0, 1);
- int vcSize = videoCodecs.size();
- for (cnt = 0; cnt < vcSize; cnt++) {
- codecName = (String) videoCodecs.get(cnt);
- plType = constants.getPayloadType(codecName);
- if (plType != -1) {
- if (plType == constants.DYNAMIC) {
- plType = nextDynamicPayloadType;
- nextDynamicPayloadType++;
- plClockRate = constants.getClockRate(codecName);
- if (plClockRate == constants.VARIABLE) {
- plClockRate = 8000; // Check this!?
- }
- plName = constants.getSdpName(codecName);
- format = new CustomFormat(plType,
- plName,
- (int) plClockRate);
- } else {
- format =
- se.omnitor.protocol.sdp.Format.
- getFormat(plType);
- }
- if (format != null) {
- formats.add(format);
- }
- }
- }
- sdpMedia.setFormats(formats);
- sdpm.addMedia(sdpMedia);
- }
- else {
- // TODO:
- // Set these to receive only!
- //formats.add(FOrmat.getFormat(34));
- //formats.add(Format.getFormat(26));
- }
- }
- // Audio descriptors
- if (audioIsActivated &&
- audioCodecs != null &&
- audioCodecs.size() > 0) {
- int port = -1;
- if (isRuntimeStunActivated()) {
- int mappedPort = 1;
- try {
- stunStack.getMappedPort(5059);
- // Do five attempts finding an even mapped port (as RTP should be sent from an even port)
- for (int mcnt=0; mcnt<5 && (mappedPort%2 == 1); mcnt++) {
- port = getFreePort();
- mappedPort = stunStack.getMappedPort(port);
- }
- sdpMedia = new CustomMedia("audio",
- mappedPort,
- "RTP/AVP");
- // As the NAT often picks port numbers in series,
- // lets force it to hold a port open for the incoming
- // RTCP.
- stunStack.getMappedPort(port+1);
- } catch (StunStackException se) {
- sdpMedia = new CustomMedia("audio", port, "RTP/AVP");
- setRuntimeStunActivated(false);
- DialogFactory.showErrorMessageDialog
- (language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "STUN_ERROR"));
- }
- } else {
- port = getFreePort();
- sdpMedia = new CustomMedia("audio", port, "RTP/AVP");
- }
- sdpMedia.setPhysicalPort(port);
- formats = new Vector(0, 1);
- int acSize = audioCodecs.size();
- for (cnt = 0; cnt < acSize; cnt++) {
- codecName = (String) audioCodecs.get(cnt);
- plType = constants.getPayloadType(codecName);
- if (plType != -1) {
- if (plType == constants.DYNAMIC) {
- plType = nextDynamicPayloadType;
- nextDynamicPayloadType++;
- plClockRate = constants.getClockRate(codecName);
- if (plClockRate == constants.VARIABLE) {
- plClockRate = 8000; // Check this!?
- }
- plName = constants.getSdpName(codecName);
- format = new CustomFormat(plType,
- plName,
- (int) plClockRate);
- } else {
- format =
- se.omnitor.protocol.sdp.Format.getFormat(plType);
- }
- if (format != null) {
- formats.add(format);
- }
- }
- }
- sdpMedia.setFormats(formats);
- sdpm.addMedia(sdpMedia);
- }
- // Text descriptors
- if (textIsActivated && useTextIfActivated) {
- int port = -1;
- if (isRuntimeStunActivated()) {
- int mappedPort = 1;
- try {
- // Do five attempts finding an even mapped port (as RTP should be sent from an even port)
- for (int mcnt=0; mcnt<5 && (mappedPort%2 == 1); mcnt++) {
- port = getFreePort();
- mappedPort = stunStack.getMappedPort(port);
- }
- sdpMedia = new CustomMedia("text",
- mappedPort,
- "RTP/AVP");
- // As the NAT often picks port numbers in series,
- // lets force it to hold a port open for the incoming
- // RTCP.
- stunStack.getMappedPort(port+1);
- } catch (StunStackException se) {
- sdpMedia = new CustomMedia("text", port, "RTP/AVP");
- setRuntimeStunActivated(false);
- DialogFactory.showErrorMessageDialog
- (language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "STUN_ERROR"));
- }
- } else {
- port = getFreePort();
- sdpMedia = new CustomMedia("text", port, "RTP/AVP");
- }
- sdpMedia.setPhysicalPort(port);
- formats = new Vector(0, 1);
- plType = constants.getPayloadType("T140");
- if (plType != -1) {
- if (plType == constants.DYNAMIC) {
- plType = nextDynamicPayloadType;
- nextDynamicPayloadType++;
- }
- T140Format tf = new T140Format(plType);
- RedFormat rf = null;
- if (appSettings.getRedundantRtpGenerations() > 0) {
- rf = new RedFormat(nextDynamicPayloadType);
- nextDynamicPayloadType++;
- rf.setGenerations(appSettings.getRedundantRtpGenerations());
- tf.setRedFormat(rf);
- rf.setFormat(tf);
- formats.add(rf);
- }
- formats.add(tf);
- /*
- plClockRate = constants.getClockRate("T140");
- if (plClockRate == constants.VARIABLE) {
- plClockRate = 1000; // Check this!?
- }
- plName = constants.getSdpName("T140");
- format = new T140Format(plType, (int)plClockRate);
- if (format != null) {
- formats.add(format);
- }
- */
- /*
- try {
- if (maxIncomingCps > 0) {
- sc.addMedia("",
- plName,
- "T140",
- "text",
- plType,
- plClockRate,
- redundantGenerations != 0,
- "cps=" + maxIncomingCps);
- }
- else {
- sc.addMedia("",
- plName,
- "T140",
- "text",
- plType,
- plClockRate,
- redundantGenerations != 0);
- }
- }
- catch (Exception e) {
- // Ignore any errors, as there is nothing to do about it.
- }
- */
- }
- sdpMedia.setFormats(formats);
- sdpm.addMedia(sdpMedia);
- }
- currentSdpManager = sdpm;
- logger.exiting(CLASS_NAME, METHOD);
- }
- private int getFreePort() {
- for (int cnt=nextFreePort; cnt<65535; cnt+=2) {
- try {
- DatagramSocket dgs = new DatagramSocket(cnt);
- dgs.close();
- dgs = new DatagramSocket(cnt+1);
- dgs.close();
- nextFreePort = cnt+2;
- return cnt;
- } catch (SocketException se) {
- // Try next port
- }
- }
- for (int cnt=1024; cnt<nextFreePort; cnt+=2) {
- try {
- DatagramSocket dgs = new DatagramSocket(cnt);
- dgs.close();
- nextFreePort = cnt+2;
- return cnt;
- } catch (SocketException se) {
- // Try next port
- }
- }
- return -1;
- }
- /**
- * Sets the number of redundant generations in the outgoing RTP Text
- * packets.
- *
- * @param red The number of generations.
- */
- /*
- public void xxsetTextRedundantGenerations(int red) {
- redundantRtpGenerations = red;
- txTextBuffer.setRedGen(red);
- }
- */
- /**
- * Activates the whole program. Shows the GUI and starts to listen for
- * incoming SIP packets.
- *
- */
- public void start() {
- // The program is ready for user input, show the GUI.
- gui.setVisible(true);
- }
- /**
- * Starts all SIP handing in a new thread (sipStarterThread).
- *
- */
- private void threadedStartSipSystem() {
- final Thread oldThread = sipStarterThread;
- sipStarterThread = new Thread() {
- public void run() {
- // Wait until last SIP starter thread stops, 20 seconds
- if (oldThread != null) {
- for (int cnt = 0; cnt < 30 && oldThread.isAlive(); cnt++) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) {
- // Do nothing
- }
- }
- // Finally, interrupt it if still not stopped after 20 secs
- if (oldThread.isAlive()) {
- oldThread.interrupt();
- }
- }
- startSipSystem();
- }
- };
- sipStarterThread.setName("SIP starter thread");
- sipStarterThread.start();
- }
- /**
- * Starts all SIP handing in a new thread (sipStarterThread).
- *
- */
- public void threadedRestartSipSystem() {
- final Thread oldThread = sipStarterThread;
- sipStarterThread = new Thread() {
- public void run() {
- // Wait until last SIP starter thread stops, 20 seconds
- if (oldThread != null) {
- for (int cnt = 0; cnt < 30 && oldThread.isAlive(); cnt++) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) {
- // Do nothing
- }
- }
- // Finally, interrupt it if still not stopped after 20 secs
- if (oldThread.isAlive()) {
- oldThread.interrupt();
- }
- }
- stopSipSystem();
- startSipSystem();
- }
- };
- sipStarterThread.setName("SIP restarter thread");
- sipStarterThread.start();
- }
- private void startSipSystem() {
- synchronized (sipStartStopMutex) {
- gui.setRegDetecting("Detecting SIP environment");
- int stunMode = appSettings.getStunMode();
- if (stunMode == AppSettings.STUN_DISABLED) {
- setRuntimeStunActivated(false);
- } else {
- setRuntimeStunActivated(true);
- }
- isSipCompatibleNatDetected = false;
- boolean possibleSipNat = false;
- // If STUN is activated, but no STUN server is chosen, try to find a
- // STUN server by looking att the register settings.
- if (isRuntimeStunActivated() &&
- (appSettings.getStunServerAddress() == null ||
- appSettings.getStunServerAddress().trim().equals(""))) {
- gui.setRegDetecting("Finding STUN server");
- boolean foundStunServer = false;
- if (appSettings.getSipRegistrarInfo() != null) {
- for (int cnt = 0;
- (cnt < appSettings.getSipRegistrarInfo().length) &&
- !foundStunServer;
- cnt++) {
- String host = appSettings.getSipRegistrarInfo()[cnt].
- getRegistrarHost();
- String stunServerAddress = findStunServer(host);
- if (stunServerAddress != null) {
- foundStunServer = true;
- appSettings.setStunServerAddress(stunServerAddress);
- }
- }
- }
- if (!foundStunServer) {
- appSettings.setStunServerAddress(AppConstants.PUBLIC_STUN_SERVER);
- /*
- DialogFactory.showErrorMessageDialog(language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "STUN_SERVER_NOT_FOUND"));
- setRuntimeStunActivated(false);
- if (possibleSipNat) {
- isSipCompatibleNatDetected = true;
- }
- */
- }
- }
- // Do STUN tests
- if (appSettings.getStunServerAddress() != null &&
- !appSettings.getStunServerAddress().trim().equals("") &&
- isRuntimeStunActivated()) {
- // First check if we might have a SIP compatible NAT here
- possibleSipNat = detectSipCompatibleNat();
- stunStack = new StunStack(getLocalIpAddress(),
- appSettings.getStunServerAddress());
- try {
- gui.setRegDetecting(language.getProperty("se.omnitor.tipcon1.AppController.DETECT"));
- stunStack.start();
- if (stunStack.getNatType().equals(StunStack.OPEN_INTERNET)) {
- if (stunMode == AppSettings.STUN_AUTO) {
- setRuntimeStunActivated(false);
- }
- isSipCompatibleNatDetected = false;
- } else {
- if (possibleSipNat) {
- isSipCompatibleNatDetected = true;
- if (stunMode == AppSettings.STUN_AUTO) {
- setRuntimeStunActivated(false);
- }
- } else if (stunStack.getNatType().equals(StunStack.
- UDP_BLOCKING_FIREWALL)) {
- if (stunMode == AppSettings.STUN_AUTO) {
- setRuntimeStunActivated(false);
- }
- DialogFactory.showErrorMessageDialog(language.
- getProperty(
- "se.omnitor.tipcon1.AppController." +
- "UDP_BLOCKING_FW_FOUND"));
- } else if (stunStack.getNatType().equals(StunStack.
- SYMMETRIC_NAT) ||
- stunStack.getNatType().equals(StunStack.
- SYMMETRIC_UDP_FIREWALL)) {
- if (stunMode == AppSettings.STUN_AUTO) {
- setRuntimeStunActivated(false);
- }
- DialogFactory.showErrorMessageDialog(language.
- getProperty(
- "se.omnitor.tipcon1.AppController." +
- "SYMMETRIC_FW_FOUND"));
- }
- }
- } catch (StunStackException sse) {
- if (stunMode == AppSettings.STUN_AUTO) {
- setRuntimeStunActivated(false);
- }
- if (possibleSipNat) {
- if (stunMode == AppSettings.STUN_AUTO) {
- isSipCompatibleNatDetected = true;
- }
- } else {
- DialogFactory.showErrorMessageDialog(language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "STUN_ERROR"));
- }
- }
- }
- gui.setRegDetecting("Initializing SIP");
- if (isRuntimeStunActivated()) {
- sc = new SipController(this, localIpAddress,
- appSettings.getOutboundProxy(),
- stunStack);
- } else {
- sc = new SipController(this, localIpAddress,
- appSettings.getOutboundProxy(), null);
- }
- try {
- sc.start();
- } catch (javax.sip.InvalidArgumentException iae) {
- logger.throwing(this.getClass().getName(), "startSip", iae);
- }
- sc.setPrimarySipAddress("unknown@" + localIpAddress);
- sc.setAuthInfo(convertToAuthInfo(appSettings.getSipRegistrarInfo()));
- sc.setFromAddressList(convertToFromAddress(appSettings.
- getSipRegistrarInfo()));
- gui.setRegNa();
- sipRegisterAll();
- sipSystemIsRunning = true;
- }
- }
- /**
- * Finds a STUN server by looking at STUN SRV records of a given host name.
- *
- * @param host The host name to search SRV records on
- * @return STUN server address. Null if no server was found.
- */
- private String findStunServer(String host) {
- if (findDns() == null) {
- return null;
- }
- boolean foundStunServer = false;
- String ssa = null;
- try {
- java.util.Hashtable env = new java.util.Hashtable();
- env.put("java.naming.factory.initial",
- "com.sun.jndi.dns.DnsContextFactory");
- env.put("java.naming.provider.url",
- "dns://" + findDns());
- javax.naming.directory.DirContext ctx = new javax.naming.directory.
- InitialDirContext(env);
- javax.naming.directory.Attributes attrs = ctx.getAttributes(
- "_stun._udp." + host, new String[] {"SRV"});
- for (javax.naming.NamingEnumeration ae = attrs.getAll();
- ae.hasMoreElements() &&
- !foundStunServer; ) {
- javax.naming.directory.Attribute attr = (javax.naming.directory.
- Attribute) ae.next();
- if (attr.getID().equals("SRV")) {
- for (java.util.Enumeration vals = attr.getAll();
- vals.hasMoreElements(); ) {
- String e = (String) vals.nextElement();
- String el[] = e.split(" ");
- if (el.length > 3) {
- if (el[3].endsWith(".")) {
- ssa = el[3].substring(0, el[3].length() - 1);
- } else {
- ssa = el[3];
- }
- foundStunServer = true;
- }
- }
- }
- }
- ctx.close();
- }
- catch (NameNotFoundException nnfe) {
- // DNS name not found, just continue
- }
- catch (NamingException ne) {
- // DNS problems just continue
- }
- /*catch (Exception e) {
- System.err.println("Problem querying DNS: " + e);
- e.printStackTrace();
- }*/
- return ssa;
- }
- /**
- * Returns the IP of a DNS server.
- *
- * @return IP of DNS server, null if no DNS server was found.
- */
- private String findDns() {
- int delayTime = -1000;
- for (int cnt=0; cnt<2; cnt++) {
- delayTime += 3000;
- // If this function has been run before, return the cached result to
- // speed up the application.
- if (dnsServer != null) {
- return dnsServer;
- }
- try {
- // Run nslookup and look at the printout to achieve system's DNS
- // server setting. There seems not to be any better solution! If
- // there is, please replace this.
- Process p = Runtime.getRuntime().exec("nslookup");
- // Sleep for 2 secs in order to wait for nslooup to start and
- // generate output.
- Thread.sleep(delayTime);
- p.destroy();
- // Read the output of nslookup
- BufferedReader in = new BufferedReader(new InputStreamReader(p.
- getInputStream()));
- String readerString = "";
- boolean foundDnsServer = false;
- while (((readerString = in.readLine()) != null)) {
- String spl[] = readerString.split("Address:");
- if (spl.length > 1) {
- return spl[1].trim();
- }
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- } catch (InterruptedException ie) {
- ie.printStackTrace();
- }
- }
- return null;
- }
- /**
- * Ends the program by shutting down the SIP client and then exiting.
- *
- */
- public void stop() {
- // Hide the frame
- gui.setTitle(gui.getTitle() + " - " +
- language.getProperty("se.omnitor.tipcon1.AppController." +
- "CLOSING"));
- gui.setVisible(false);
- // Stop the local video
- if (appSettings.getTipcon1Mode() && avPlayer != null) {
- avPlayer.close();
- avPlayer = null;
- }
- /*
- try {
- Thread.sleep(2000);
- } catch (Exception e) {
- // Ignore interruptions
- }*/
- // If detect is caused to program start, wait for it
- if (sipStarterThread != null && sipStarterThread.isAlive()) {
- for (int cnt=0; cnt<30&&sipStarterThread.isAlive(); cnt++) {
- try {
- Thread.sleep(1000);
- }
- catch (InterruptedException ie) {
- // Ignore
- }
- }
- if (sipStarterThread.isAlive()) {
- sipStarterThread.interrupt();
- }
- }
- // If detect is caused by SIP settings dialog, wait for it
- while (!sipSystemIsRunning || isQueuedSipSystemRestart()) {
- try {
- Thread.sleep(500);
- }
- catch (InterruptedException ie) {
- // Ignore
- }
- }
- stopSipSystem();
- // End the program
- System.exit(0);
- }
- /**
- * Stops the SIP controller, disconnects any call and unregisters.
- *
- */
- private void stopSipSystem() {
- synchronized (sipStartStopMutex) {
- gui.setRegDetecting("Stopping SIP");
- sipSystemIsRunning = false;
- // Disconnect
- if (callProcessor != null) {
- callProcessor.bye();
- callProcessor = null;
- }
- // Unregister
- sipUnregisterAll();
- // Allow 2 seconds for the unregister process
- try {
- Thread.sleep(2000);
- } catch (InterruptedException ie) {
- // Ignore this.
- }
- // Stop the SIP client
- if (sc != null) {
- sc.stop();
- sc = null;
- }
- // Stop the STUN stack
- if (stunStack != null) {
- stunStack.stop();
- }
- gui.setRegNa();
- }
- }
- /**
- * Handles incoming call.
- *
- */
- public void signalIncomingCall(IncomingCallDialog call) {
- if (call.getSdp().indexOf("eConf 3.5.1") > 0) {
- isEconf351 = true;
- }
- if (callProcessor != null) {
- call.busy();
- return;
- }
- callProcessor = call.getCallProcessor();
- remoteUserAddress = call.getRemoteUserAddress();
- // Show a popup dialog to the user
- gui.toFront();
- incomingCallDialog =
- DialogFactory.showAnswerDialog(remoteUserAddress);
- if (appSettings.isAlertingEnabled()) {
- System.out.println("Activating the Alert processn");
- Alert();
- }
- Thread ringThread = new Thread() {
- public void run() {
- try {
- while (true) {
- try {
- AudioInputStream ais =
- AudioSystem.getAudioInputStream
- (new File(appConstants.RING_SOUND_URL));
- javax.sound.sampled.AudioFormat format =
- ais.getFormat();
- Line.Info info =
- new Line.Info(Clip.class);
- Clip clip =
- (Clip) AudioSystem.getLine(info);
- clip.open(ais);
- clip.start();
- } catch (Exception e) {
- logger.throwing(this.getClass().getName(),
- "run", e);
- // If something fails,
- // just don't play the clip.
- }
- Thread.sleep(4000);
- }
- } catch (InterruptedException e) {
- // Jump out from the thread when interrupted.
- }
- }
- };
- ringThread.setName("Ring signal");
- ringThread.start();
- call.ringing();
- int result = incomingCallDialog.getResult();
- ringThread.interrupt();
- // Handle the result
- if (result == ThreadedDialog.YES) {
- gui.clearTextAreas();
- gui.changeInfoLabel(language.getProperty
- ("se.omnitor.tipcon1.AppController." +
- "MEDIA_SETUP"));
- negotiatedMedia = new Vector(0, 1);
- System.out.println("<<signalIncomingCall::" + call.getSdp() + ">>");
- if (call.getSdp().indexOf("eConf 3.5.1") > 0) {
- isEconf351 = true;
- }
- try {
- deploySdpSettings(true);
- String sdp =
- currentSdpManager.negotiate(call.getSdp(),
- negotiatedMedia);
- call.answer("application", "sdp", sdp);
- int a = negotiatedMedia.size();
- SdpMedia m;
- Vector v;
- for (int cnt = 0; cnt < a; cnt++) {
- m = (SdpMedia) negotiatedMedia.elementAt(cnt);
- v = m.getFormats();
- System.out.println("Media " + cnt + ": " + v);
- System.out.println("(PP = " + m.getPhysicalPort() + ")");
- }
- } catch (SdpException se) {
- logger.throwing(this.getClass().getName(),
- "signalIncomingCall",
- se);
- call.badRequest("SDP parse error");
- DialogFactory.showErrorMessageDialog
- (language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "SIP_SEND_PROBLEM"));
- callProcessor = null;
- gui.setTerminatedGui();
- }
- /* Error handling should be done here, see below for example.
- catch (Exception see) {
- try {
- sc.sipCancel();
- }
- catch (Exception e) {
- // Ignore exceptions here, there is anyway nothing
- // here to do if an error occurs.
- }
- DialogFactory.showErrorMessageDialog
- (language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "SIP_SEND_PROBLEM"));
- gui.setTerminatedGui();
- }
- */
- } else if (result == ThreadedDialog.NO ||
- result == ThreadedDialog.USER_CLOSED_WINDOW) {
- call.decline();
- callProcessor = null;
- }
- }
- public String getRemoteUserAddress() {
- return remoteUserAddress;
- }
- /**
- * Handles an established call.
- *
- */
- public void signalEstablishedCall(CallProcessor cp) {
- this.callProcessor = cp;
- System.out.println("<<signalEstablishedCall::" + cp.getRemoteSdp() +
- ">>");
- // n鋜 client ringer sipcon blir d nullpexception
- String cpString = cp.getRemoteSdp();
- if (cpString != null && cpString.indexOf("eConf 3.5.1") > 0) {
- isEconf351 = true;
- }
- System.out.println("<<signalEstablishedCall::isEconf351" + isEconf351 +
- ">>");
- gui.setPendingGui();
- // Inform the user
- if (outgoingCallDialog != null) {
- outgoingCallDialog.setInfoText
- (language.getProperty("se.omnitor.tipcon1.AppController." +
- "MEDIA_SETUP"));
- }
- // Store the remote address
- if (appSettings.isRealtimePreviewEnabled()) {
- // Get a nice name which can be presented in GUI
- String addr = cp.getNiceRemoteName();
- if (addr == null || addr.trim().equals("")) {
- addr = "You";
- }
- else {
- int ix1 = addr.indexOf("<");
- int ix2 = addr.indexOf(">");
- if (ix1 < ix2 && (ix2-ix1 > 1)) {
- addr = addr.substring(ix1+1, ix2-ix1);
- }
- if (addr.startsWith("sip:")) {
- addr = addr.substring(4);
- }
- addr = addr.split("@")[0];
- String[] addrSplit = addr.split("\.");
- if (addrSplit.length == 4) {
- addr = "You";
- }
- else {
- addr = addrSplit[0];
- }
- }
- t140Panel.setRemoteLogName(addr);
- }
- // An outgoing call has no negotiated media (as negotiation was taken
- // place at remote's side)
- if (negotiatedMedia == null) {
- try {
- negotiatedMedia = SdpManager.getFormats(cp.getRemoteSdp());
- if (negotiatedMedia == null) {
- // We want to get into the catch clause.
- throw new SdpException("Dummy exception");
- }
- // Now, move the psysical ports from local config to current
- // negotiated media.
- int len = negotiatedMedia.size();
- for (int cnt=0; cnt<len; cnt++) {
- SdpMedia m1 = (SdpMedia) negotiatedMedia.get(cnt);
- SdpMedia m2 = currentSdpManager.getMedia(m1.getType());
- if (m1 != null && m2 != null) {
- m1.setPhysicalPort(m2.getPhysicalPort());
- }
- }
- } catch (SdpException e) {
- logger.throwing(this.getClass().getName(),
- "signalEstablishedCall", e);
- // TODO:
- // Strange SDP from remote, disconnect call here!
- negotiatedMedia = null;
- outgoingCallDialog.dispose();
- DialogFactory.showErrorMessageDialog(language.getProperty("se.omnitor.tipcon1.AppController." +
- "SDP_PARSE_ERROR"));
- cp.bye();
- return;
- }
- }
- startMedia();
- if (outgoingCallDialog != null) {
- outgoingCallDialog.dispose();
- }
- // Change GUI
- gui.setEstablishedGui();
- gui.setRemoteUserInfo(cp.getNiceRemoteName());
- gui.changeInfoLabel(language.getProperty("se.omnitor.tipcon1." +
- "AppController." +
- "CONNECTED"));
- }
- /**
- * Handles incoming cancellation.
- *
- */
- public void signalCancelledIncomingCall(IncomingCallDialog dialog) {
- // Hide call popup
- if (incomingCallDialog != null) {
- incomingCallDialog.dispose();
- }
- // Inform the user
- gui.changeInfoLabel
- (language.getProperty("se.omnitor.tipcon1.AppController." +
- "MISSED_CALL_FROM") + " " +
- remoteUserAddress);
- callProcessor = null;
- }
- /**
- * Handles terminated call signal.
- *
- */
- public void signalTerminatedCall(CallProcessor cp) {
- // Change GUI
- gui.setTerminatedGui();
- gui.changeInfoLabel(language.getProperty("se.omnitor." +
- "tipcon1." +
- "AppController." +
- "TERMINATED"));
- isMuted = false;
- gui.setMute(false);
- gui.repaint();
- if (mediaManager != null) {
- mediaManager.stopAll();
- mediaManager = null;
- }
- negotiatedMedia = null;
- callProcessor = null;
- // Remove the remote address
- remoteUserAddress = null;
- if(appSettings.getTipcon1Mode()) {
- restartVideo();
- }
- //settingsDialog.actionPerformed
- // (new ActionEvent(new Button("OK"), 666,"OK"));
- //deploySdpSettings(true);
- }
- /**
- * Handles call progress signal.
- *
- */
- public void signalOutgoingCallProgress(CallProcessor cp, int statusCode) {
- System.out.println("<<signalOutgoingCallProgress::" + cp.getRemoteSdp() +
- ">>");
- switch (statusCode) {
- case 100:
- // Inform the user only if nothing has been informed yet (NIST
- // SIP tends to turn the order of 100 and 180, so that 100 comes
- // after 180).
- if (outgoingCallDialog != null && !outgoingCallProgressReported) {
- outgoingCallDialog.setInfoText
- (language.getProperty(
- "se.omnitor.tipcon1.AppController." +
- "HOST_CONTACTED"));
- }
- break;
- case 182:
- // Inform the user