Improves logging. Starts work on SDP utilities for use with SIP and WebRTC. Starts work on trickle ICE.

This commit is contained in:
emcho 2013-06-24 21:06:31 +00:00
parent e6f719c503
commit c4278af39c
21 changed files with 1019 additions and 743 deletions

View File

@ -136,7 +136,15 @@ public class TransportAddress
*/
public String toString()
{
return super.toString() + "/" + getTransport();
StringBuilder bldr = new StringBuilder(getHostAddress());
if(isIPv6())
bldr.insert(0, "[").append("]");
bldr.append(":").append(getPort());
bldr.append("/").append(getTransport());
return bldr.toString();
}
/**

View File

@ -1,6 +1,6 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
@ -218,11 +218,17 @@ public class Agent
*/
private int generation = 0;
/**
* Determines whether this agent should perform trickling.
*/
private boolean trickle = true;
/**
* Indicates that ICE will be shutdown.
*/
private boolean shutdown = false;
/**
* Creates an empty <tt>Agent</tt> with no streams, and no address.
*/
@ -283,7 +289,7 @@ public class Agent
*/
public IceMediaStream createMediaStream(String mediaStreamName)
{
logger.info("Create media stream for " + mediaStreamName);
logger.fine("Create media stream for " + mediaStreamName);
IceMediaStream mediaStream
= new IceMediaStream(Agent.this, mediaStreamName);
@ -302,7 +308,7 @@ public class Agent
/**
* Creates a new {@link Component} for the specified <tt>stream</tt> and
* allocates all local candidates that should belong to it.
* allocates potentially all local candidates that should belong to it.
*
* @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to.
@ -344,8 +350,6 @@ public class Agent
Component component = stream.createComponent(transport);
logger.info("Create component " + component.toShortString());
gatherCandidates(component, preferredPort, minPort, maxPort);
for(Candidate<?> candidate : component.getLocalCandidates())
@ -436,7 +440,7 @@ public class Agent
logger.info("Gather candidates for component " +
component.toShortString());
this.startHarvesting();
this.startHarvestTiming();
hostCandidateHarvester.harvest(
component,
@ -452,33 +456,42 @@ public class Agent
logger.fine("host candidate count: " +
component.getLocalCandidateCount());
//apply other harvesters here
harvesters.harvest(component);
//in case we are not trickling, apply other harvesters here
if(!isTrickling())
harvesters.harvest(component);
this.stopHarvesting();
this.stopHarvestTiming();
logger.info(
"End candidate harvest for all harvesters within "
+ this.getTotalHarvestingTime() + " ms"
+ ", component: " + component.getComponentID());
"Harvest for " + component.toShortString() + " completed in "
+ this.getTotalHarvestingTime() + " ms.");
logger.fine("host+harvested candidate count: " +
component.getLocalCandidateCount());
computeFoundations(component);
//make sure we compute priorities only after we have all candidates
component.prioritizeCandidates();
//Emil: because of trickle we now compute foundations or priorities
// directly when adding candidates. This shouldn't change anything but
// there's no need to do it here again.
//computeFoundations(component);
//component.prioritizeCandidates();
//eliminate redundant candidates
component.eliminateRedundantCandidates();
logger.fine("host+harvested candidate count (after elimination): " +
component.getLocalCandidateCount());
//select the candidate to put in the media line.
component.selectDefaultCandidate();
}
/**
* Starts an asynchronous harvest across all components and reports newly
* discovered candidates to <tt>trickleCallback</tt>.
*
* @param trickleCallback
*/
public void startCandidateTrickle(TrickleCallback trickleCallback)
{
}
/**
* Initializes all stream check lists and begins the checks.
*/
@ -886,6 +899,17 @@ public class Agent
return ret;
}
/**
* Returns the {@link FoundationsRegistry} this agent is using to assign
* candidate foundations. We use the <tt>FoundationsRegistry</tt> to keep
* track of the foundations we assign within a session (i.e. the entire life
* time of an <tt>Agent</tt>)
*/
public final FoundationsRegistry getFoundationsRegistry()
{
return foundationsRegistry;
}
/**
* Returns the <tt>IceMediaStream</tt> with the specified <tt>name</tt> or
* <tt>null</tt> if no such stream has been registered with this
@ -1280,8 +1304,7 @@ public class Agent
* {@link org.ice4j.message.Request} contained the USE-CANDIDATE ICE
* attribute.
*/
protected void incomingCheckReceived(
TransportAddress remoteAddress,
protected void incomingCheckReceived(TransportAddress remoteAddress,
TransportAddress localAddress,
long priority,
String remoteUFrag,
@ -2231,6 +2254,37 @@ public class Agent
return null;
}
/**
* Indicates whether this agent is currently set to trickle candidates
* rather than gathering them synchronously while components are being
* added. When trickling is turned on, the agent will only gather host
* addresses for newly added components. When trickling is off, all
* harvesting for a specific component will be executed when that component
* is being added.
*
* @return <tt>false</tt> if this agent is configured to perform all
* harvesting when components are being added and <tt>false</tt> otherwise.
*/
public boolean isTrickling()
{
return trickle;
}
/**
* Determines whether this agent will trickle candidates rather than
* gather them synchronously while components are being added. When
* trickling is turned on, the agent will only gather host addresses for
* newly added components. When trickling is off, all harvesting for a
* specific component will be executed when that component is being added.
*
* @param trickle <tt>false</tt> if this agent is configured to perform all
* harvesting when components are being added and <tt>false</tt> otherwise.
*/
public void setTrickling(boolean trickle)
{
this.trickle = trickle;
}
/**
* Returns the harvesting time (in ms) for the harvester given in parameter.
@ -2311,17 +2365,17 @@ public class Agent
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
public void startHarvesting()
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvesting();
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvesting()
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvesting();
this.harvestingTimeStat.stopHarvestTiming();
}
/**

View File

@ -28,6 +28,7 @@ import org.ice4j.*;
*/
public abstract class Candidate
<T extends Candidate<?>>
implements Comparable<T>
{
/**
* The transport address represented by this candidate.
@ -754,16 +755,16 @@ public abstract class Candidate
return 30;
if( getType() == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
return 20;
return 10;
if( getType() == CandidateType.HOST_CANDIDATE)
{
//prefer IPv4 as default since many servers would still freak out
//when seeing IPv6 address.
if(getTransportAddress().isIPv6())
return 10;
return 20;
else
return 15;
return 25;
}
//WTF?
@ -940,4 +941,21 @@ public abstract class Candidate
return this.relatedCandidate;
}
}
/**
* Compares this <tt>Candidate</tt> with the specified one based on their
* priority and returns a negative integer, zero, or a positive integer if
* this <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*
* @param candidate the second <tt>Candidate</tt> to compare.
*
* @return a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*/
public int compareTo(T candidate)
{
return CandidatePrioritizer.compareCandidates(this, candidate);
}
}

View File

@ -0,0 +1,91 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.ice;
import java.util.*;
/**
* Compares candidates based on their priority.
*
* @author Emil Ivov
*/
class CandidatePrioritizer
implements Comparator<Candidate<?>>
{
/**
* Compares the two <tt>Candidate</tt>s based on their priority and
* returns a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*
* @param c1 the first <tt>Candidate</tt> to compare.
* @param c2 the second <tt>Candidate</tt> to compare.
*
* @return a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal,
* or greater priority than the
* second.
*/
public static int compareCandidates(Candidate<?> c1, Candidate<?> c2)
{
if (c1.getPriority() < c2.getPriority())
return 1;
else if (c1.getPriority() == c2.getPriority())
return 0;
else //if(c1.getPriority() > c2.getPriority())
return -1;
}
/**
* Compares the two <tt>Candidate</tt>s based on their priority and
* returns a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*
* @param c1 the first <tt>Candidate</tt> to compare.
* @param c2 the second <tt>Candidate</tt> to compare.
*
* @return a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal,
* or greater priority than the
* second.
*/
public int compare(Candidate<?> c1, Candidate<?> c2)
{
return CandidatePrioritizer.compareCandidates(c1, c2);
}
/**
* Indicates whether some other object is &quot;equal to&quot; this
* Comparator. This method must obey the general contract of
* <tt>Object.equals(Object)</tt>. Additionally, this method can return
* <tt>true</tt> <i>only</i> if the specified Object is also a
* comparator and it imposes the same ordering as this comparator. Thus,
* <code>comp1.equals(comp2)</code> implies that
* <tt>sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2))</tt> for
* every object reference <tt>o1</tt> and <tt>o2</tt>.<p>
* <p/>
* Note that it is <i>always</i> safe <i>not</i> to override
* <tt>Object.equals(Object)</tt>. However, overriding this method may,
* in some cases, improve performance by allowing programs to determine
* that two distinct Comparators impose the same order.
*
* @param obj the reference object with which to compare.
*
* @return <code>true</code> only if the specified object is also
* a comparator and it imposes the same ordering as this
* comparator.
*
* @see Object#equals(Object)
* @see Object#hashCode()
*/
public boolean equals(Object obj)
{
return (obj instanceof CandidatePrioritizer);
}
}

View File

@ -142,9 +142,27 @@ public class Component
*/
public void addLocalCandidate(LocalCandidate candidate)
{
Agent agent = getParentStream().getParentAgent();
//assign foundation.
agent.getFoundationsRegistry().assignFoundation(candidate);
//compute priority
CompatibilityMode compatibilityMode = getParentStream().getParentAgent()
.getCompatibilityMode();
if(compatibilityMode == CompatibilityMode.GTALK)
{
candidate.computeGTalkPriority();
}
else
{
candidate.computePriority();
}
synchronized(localCandidates)
{
localCandidates.add(candidate);
Collections.sort(localCandidates);
}
}
@ -419,19 +437,6 @@ public class Component
}
}
/**
* Adds a list of local <tt>Candidate</tt>s to this media-stream component.
*
* @param candidates a <tt>List</tt> of candidates to be added
*/
public void addLocalCandidates(List<LocalCandidate> candidates)
{
synchronized(localCandidates)
{
localCandidates.addAll(candidates);
}
}
/**
* Adds a List of remote <tt>Candidate</tt>s as reported by a remote agent.
*
@ -566,7 +571,7 @@ public class Component
StringBuffer buff
= new StringBuffer(parentStream.getName());
buff.append(".");
buff.append(componentID);
buff.append(getName());
return buff.toString();
}
@ -574,15 +579,20 @@ public class Component
/**
* Computes the priorities of all <tt>Candidate</tt>s and then sorts them
* accordingly.
*
* @Deprecated candidates are now being prioritized upon addition and
* calling this method is no longer necessary.
*/
protected void prioritizeCandidates()
{
synchronized(localCandidates)
{
CompatibilityMode compat = getParentStream().getParentAgent().
getCompatibilityMode();
CompatibilityMode compat = getParentStream().getParentAgent()
.getCompatibilityMode();
LocalCandidate[] candidates
= new LocalCandidate[localCandidates.size()];
localCandidates.toArray(candidates);
//first compute the actual priorities
@ -608,63 +618,6 @@ public class Component
}
}
/**
* Compares candidates based on their priority.
*/
private static class CandidatePrioritizer
implements Comparator<Candidate<?>>
{
/**
* Compares the two <tt>Candidate</tt>s based on their priority and
* returns a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*
* @param c1 the first <tt>Candidate</tt> to compare.
* @param c2 the second <tt>Candidate</tt> to compare.
*
* @return a negative integer, zero, or a positive integer as the first
* <tt>Candidate</tt> has a lower, equal, or greater priority than the
* second.
*/
public int compare(Candidate<?> c1, Candidate<?> c2)
{
if(c1.getPriority() < c2.getPriority())
return 1;
else if(c1.getPriority() == c2.getPriority())
return 0;
else //if(c1.getPriority() > c2.getPriority())
return -1;
}
/**
* Indicates whether some other object is &quot;equal to&quot; this
* Comparator. This method must obey the general contract of
* <tt>Object.equals(Object)</tt>. Additionally, this method can return
* <tt>true</tt> <i>only</i> if the specified Object is also a
* comparator and it imposes the same ordering as this comparator. Thus,
* <code>comp1.equals(comp2)</code> implies that
* <tt>sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2))</tt> for
* every object reference <tt>o1</tt> and <tt>o2</tt>.<p>
*
* Note that it is <i>always</i> safe <i>not</i> to override
* <tt>Object.equals(Object)</tt>. However, overriding this method may,
* in some cases, improve performance by allowing programs to determine
* that two distinct Comparators impose the same order.
*
* @param obj the reference object with which to compare.
* @return <code>true</code> only if the specified object is also
* a comparator and it imposes the same ordering as this
* comparator.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.Object#hashCode()
*/
public boolean equals(Object obj)
{
return (obj instanceof CandidatePrioritizer);
}
}
/**
* Eliminates redundant candidates, removing them from the specified
* <tt>component</tt>. A candidate is redundant if its transport address

View File

@ -0,0 +1,12 @@
package org.ice4j.ice;
/**
* Created with IntelliJ IDEA.
* User: emcho
* Date: 24.06.13
* Time: 22:56
* To change this template use File | Settings | File Templates.
*/
public class TrickleCallback
{
}

View File

@ -40,8 +40,7 @@ public class UPNPCandidate
LocalCandidate base, Component parentComponent,
GatewayDevice device)
{
super(
transportAddress,
super( transportAddress,
parentComponent,
CandidateType.SERVER_REFLEXIVE_CANDIDATE,
CandidateExtendedType.UPNP_CANDIDATE,

View File

@ -47,17 +47,17 @@ public abstract class CandidateHarvester
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
public void startHarvesting()
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvesting();
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvesting()
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvesting();
this.harvestingTimeStat.stopHarvestTiming();
}
/**

View File

@ -91,6 +91,7 @@ public class CandidateHarvesterSet
}
}
/**
* Gathers candidate addresses for a specific <tt>Component</tt> using
* specific <tt>CandidateHarvester</tt>s.
@ -107,89 +108,29 @@ public class CandidateHarvesterSet
final Component component,
ExecutorService executorService)
{
/**
* Represents a task to be executed by the specified executorService and
* to call {@link CandidateHarvester#harvestComponent} on the specified
* harvesters.
*/
class CandidateHarvesterSetTask
implements Runnable
{
/**
* The <tt>CandidateHarvester</tt> on which
* {@link CandidateHarvester#harvest(Component)} is to be or is
* being called.
*/
private CandidateHarvesterSetElement harvester;
/**
* Initializes a new <tt>CandidateHarvesterSetTask</tt> which is to
* call {@link CandidateHarvester#harvest(Component)} on a specific
* harvester and then as many harvesters as possible.
*
* @param harvester the <tt>CandidateHarvester</tt> on which the
* new instance is to call
* <tt>CandidateHarvester#harvest(Component)</tt> first
*/
public CandidateHarvesterSetTask(
CandidateHarvesterSetElement harvester)
{
this.harvester = harvester;
}
/**
* Gets the <tt>CandidateHarvester</tt> on which
* {@link CandidateHarvester#harvest(Component)} is being called.
*
* @return the <tt>CandidateHarvester</tt> on which
* <tt>CandidateHarvester#harvest(Component)</tt> is being called
*/
public CandidateHarvesterSetElement getHarvester()
{
return harvester;
}
public void run()
{
while (true)
{
if (harvester.isEnabled())
{
try
{
harvester.harvest(component);
}
catch (Throwable t)
{
logger.info(
"disabling harvester due to exception: " +
t.getLocalizedMessage());
harvester.setEnabled(false);
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
/*
* CandidateHarvester#harvest(Component) has been called on
* the harvester and its success or failure has been noted.
* Now forget the harvester because any failure to continue
* execution is surely not its fault.
*/
harvester = null;
synchronized (harvesters)
{
if (harvesters.hasNext())
harvester = harvesters.next();
else
break;
}
}
}
}
harvest(harvesters,
Arrays.asList(new Component[]{component}),
executorService);
}
/**
* Gathers candidate addresses for a specific <tt>Component</tt> using
* specific <tt>CandidateHarvester</tt>s.
*
* @param harvesters the <tt>CandidateHarvester</tt>s to gather candidate
* addresses for the specified <tt>Component</tt>
* @param components the <tt>Component</tt>s to gather candidate addresses
* for.
* @param executorService the <tt>ExecutorService</tt> to schedule the
* execution of the gathering of candidate addresses performed by the
* specified <tt>harvesters</tt>
*/
private void harvest(
final Iterator<CandidateHarvesterSetElement> harvesters,
final List<Component> components,
ExecutorService executorService)
{
/*
* Start asynchronously executing the
* CandidateHarvester#harvest(Component) method of the harvesters.
@ -212,14 +153,25 @@ public class CandidateHarvesterSet
else
break;
}
if (!harvester.isEnabled())
continue;
// Asynchronously start gathering candidates using the harvester.
CandidateHarvesterSetTask task
= new CandidateHarvesterSetTask(harvester);
List<Component> componentsCopy;
tasks.put(task, executorService.submit(task));
synchronized (components)
{
componentsCopy = new ArrayList<Component>(components);
}
for(Component component : componentsCopy)
{
// Asynchronously start gathering candidates using the harvester.
CandidateHarvesterSetTask task = new CandidateHarvesterSetTask(
harvester, component, harvesters);
tasks.put(task, executorService.submit(task));
}
}
/*
@ -253,6 +205,9 @@ public class CandidateHarvesterSet
}
catch (ExecutionException ee)
{
CandidateHarvesterSetElement harvester
= task.getKey().getHarvester();
/*
* A problem appeared during the execution of the task.
* CandidateHarvesterSetTask clears its harvester property
@ -260,12 +215,10 @@ public class CandidateHarvesterSet
* appeared while working with a harvester.
*/
logger.info(
"disabling harvester due to ExecutionException: " +
"disabling harvester "+ harvester.getHarvester()
+ " due to ExecutionException: " +
ee.getLocalizedMessage());
CandidateHarvesterSetElement harvester
= task.getKey().getHarvester();
if (harvester != null)
harvester.setEnabled(false);
break;
@ -319,7 +272,7 @@ public class CandidateHarvesterSet
public CandidateHarvester next()
throws NoSuchElementException
{
return elementIter.next().harvester;
return elementIter.next().getHarvester();
}
/**
@ -362,114 +315,4 @@ public class CandidateHarvesterSet
return elements.size();
}
}
/**
* Represents a <tt>CandidateHarvester</tt> as an element in a
* <tt>CandidateHarvesterSet</tt>.
*/
private static class CandidateHarvesterSetElement
{
/**
* The indicator which determines whether
* {@link CandidateHarvester#harvest(Component)} is to be called on
* {@link #harvester}.
*/
private boolean enabled = true;
/**
* The <tt>CandidateHarvester</tt> which is an element in a
* <tt>CandidateHarvesterSet</tt>.
*/
private final CandidateHarvester harvester;
/**
* Initializes a new <tt>CandidateHarvesterSetElement</tt> instance
* which is to represent a specific <tt>CandidateHarvester</tt> as an
* element in a <tt>CandidateHarvesterSet</tt>.
*
* @param harvester the <tt>CandidateHarvester</tt> which is to be
* represented as an element in a <tt>CandidateHarvesterSet</tt> by the
* new instance
*/
public CandidateHarvesterSetElement(CandidateHarvester harvester)
{
this.harvester = harvester;
}
/**
* Calls {@link CandidateHarvester#harvest(Component)} on the associated
* <tt>CandidateHarvester</tt> if <tt>enabled</tt>.
*
* @param component the <tt>Component</tt> to gather candidates for
*/
public void harvest(Component component)
{
if (isEnabled())
{
harvester.startHarvesting();
Collection<LocalCandidate> candidates
= harvester.harvest(component);
harvester.stopHarvesting();
logger.info(
"End candidate harvest within "
+ harvester.getHarvestingTime()
+ " ms, for "
+ harvester.getClass().getName()
+ ", component: " + component.getComponentID());
/*
* If the CandidateHarvester has not gathered any candidates, it
* is considered failed and will not be used again in order to
* not risk it slowing down the overall harvesting.
*/
if ((candidates == null) || candidates.isEmpty())
setEnabled(false);
}
}
/**
* Determines whether the associated <tt>CandidateHarvester</tt> is
* considered to be the same as a specific <tt>CandidateHarvester</tt>.
*
* @param harvester the <tt>CandidateHarvester</tt> to be compared to
* the associated <tt>CandidateHarvester</tt>
* @return <tt>true</tt> if the associated <tt>CandidateHarvester</tt>
* is considered to be the same as the specified <tt>harvester</tt>;
* otherwise, <tt>false</tt>
*/
public boolean harvesterEquals(CandidateHarvester harvester)
{
return this.harvester.equals(harvester);
}
/**
* Gets the indicator which determines whether
* {@link CandidateHarvester#harvest(Component)} is to be called on the
* associated <tt>CandidateHarvester</tt>.
*
* @return <tt>true</tt> if
* <tt>CandidateHarvester#harvest(Component)</tt> is to be called on the
* associated <tt>CandidateHarvester</tt>; otherwise, <tt>false</tt>
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Sets the indicator which determines whether
* {@link CandidateHarvester#harvest(Component)} is to be called on the
* associated <tt>CandidateHarvester</tt>.
*
* @param enabled <tt>true</tt> if
* <tt>CandidateHarvester#harvest(Component)</tt> is to be called on the
* associated <tt>CandidateHarvester</tt>; otherwise, <tt>false</tt>
*/
public void setEnabled(boolean enabled)
{
logger.info("disabling harvester: " + harvester);
this.enabled = enabled;
}
}
}

View File

@ -0,0 +1,142 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.ice.harvest;
import org.ice4j.ice.*;
import java.util.*;
import java.util.logging.*;
/**
* Represents a <tt>CandidateHarvester</tt> as an element in a
* <tt>CandidateHarvesterSet</tt>.
*
* @author Lyubomir Marinov
* @author Emil Ivov
*/
class CandidateHarvesterSetElement
{
/**
* The <tt>Logger</tt> used by the <tt>CandidateHarvesterSetElement</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(CandidateHarvesterSetElement.class.getName());
/**
* The indicator which determines whether
* {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is to be
* called on {@link #harvester}.
*/
private boolean enabled = true;
/**
* The <tt>CandidateHarvester</tt> which is an element in a
* <tt>CandidateHarvesterSet</tt>.
*/
private final CandidateHarvester harvester;
/**
* Initializes a new <tt>CandidateHarvesterSetElement</tt> instance
* which is to represent a specific <tt>CandidateHarvester</tt> as an
* element in a <tt>CandidateHarvesterSet</tt>.
*
* @param harvester the <tt>CandidateHarvester</tt> which is to be
* represented as an element in a <tt>CandidateHarvesterSet</tt> by the
* new instance
*/
public CandidateHarvesterSetElement(CandidateHarvester harvester)
{
this.harvester = harvester;
}
/**
* Calls {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} on the
* associated <tt>CandidateHarvester</tt> if <tt>enabled</tt>.
*
* @param component the <tt>Component</tt> to gather candidates for
*/
public void harvest(Component component)
{
if (isEnabled())
{
harvester.startHarvestTiming();
Collection<LocalCandidate> candidates
= harvester.harvest(component);
harvester.stopHarvestTiming();
logger.info(
"Completed " + component.getParentStream().getName()
+ "." + component.getName()
+ " harvest with " + harvester.toString() + " in "
+ harvester.getHarvestingTime()
+ " ms. Candidates found: " + candidates.size());
/*
* If the CandidateHarvester has not gathered any candidates, it
* is considered failed and will not be used again in order to
* not risk it slowing down the overall harvesting.
*/
if ((candidates == null) || candidates.isEmpty())
setEnabled(false);
}
}
/**
* Determines whether the associated <tt>CandidateHarvester</tt> is
* considered to be the same as a specific <tt>CandidateHarvester</tt>.
*
* @param harvester the <tt>CandidateHarvester</tt> to be compared to
* the associated <tt>CandidateHarvester</tt>
* @return <tt>true</tt> if the associated <tt>CandidateHarvester</tt>
* is considered to be the same as the specified <tt>harvester</tt>;
* otherwise, <tt>false</tt>
*/
public boolean harvesterEquals(CandidateHarvester harvester)
{
return this.harvester.equals(harvester);
}
/**
* Gets the indicator which determines whether
* {@link CandidateHarvester#harvest(Component)} is to be called on the
* associated <tt>CandidateHarvester</tt>.
*
* @return <tt>true</tt> if
* <tt>CandidateHarvester#harvest(Component)</tt> is to be called on the
* associated <tt>CandidateHarvester</tt>; otherwise, <tt>false</tt>
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Sets the indicator which determines whether
* {@link CandidateHarvester#harvest(Component)} is to be called on the
* associated <tt>CandidateHarvester</tt>.
*
* @param enabled <tt>true</tt> if
* <tt>CandidateHarvester#harvest(Component)</tt> is to be called on the
* associated <tt>CandidateHarvester</tt>; otherwise, <tt>false</tt>
*/
public void setEnabled(boolean enabled)
{
logger.info("Disabling: " + harvester);
this.enabled = enabled;
}
/**
* Returns the <tt>CandidateHarvester</tt> encapsulated by this element.
*
* @return the <tt>CandidateHarvester</tt> encapsulated by this element.
*/
public CandidateHarvester getHarvester()
{
return harvester;
}
}

View File

@ -0,0 +1,109 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.ice.harvest;
import org.ice4j.ice.*;
import java.util.logging.*;
/**
* Represents a task to be executed by the specified executorService and
* to call {@link CandidateHarvester#harvest(Component)} on the specified
* harvesters.
*
* @author Lyubomir Marinov
* @author Emil Ivov
*/
class CandidateHarvesterSetTask
implements Runnable
{
/**
* The <tt>Logger</tt> used by the <tt>CandidateHarvesterSetTask</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(CandidateHarvesterSetTask.class.getName());
/**
* The <tt>CandidateHarvester</tt> on which
* {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is to be or
* is being called.
*/
private CandidateHarvesterSetElement harvester;
/**
* The {@link Component} whose addresses we will be harvesting in this task.
*/
private Component component;
/**
* Initializes a new <tt>CandidateHarvesterSetTask</tt> which is to
* call {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} on a
* specific harvester and then as many harvesters as possible.
*
* @param harvester the <tt>CandidateHarvester</tt> on which the
* new instance is to call
* <tt>CandidateHarvester#harvest(Component)</tt> first
*/
java.util.Iterator<CandidateHarvesterSetElement> harvesters;
public CandidateHarvesterSetTask(
CandidateHarvesterSetElement harvester,
Component component,
java.util.Iterator<CandidateHarvesterSetElement> harvesters)
{
this.harvester = harvester;
this.component = component;
this.harvesters = harvesters;
}
/**
* Gets the <tt>CandidateHarvester</tt> on which
* {@link CandidateHarvester#harvest(org.ice4j.ice.Component)} is being
* called.
*
* @return the <tt>CandidateHarvester</tt> on which
* <tt>CandidateHarvester#harvest(Component)</tt> is being called
*/
public CandidateHarvesterSetElement getHarvester()
{
return harvester;
}
/**
* Runs the actual harvesting for this component
*/
public void run()
{
if (harvester.isEnabled())
{
try
{
harvester.harvest(component);
}
catch (Throwable t)
{
logger.info(
"disabling harvester due to exception: " +
t.getLocalizedMessage());
harvester.setEnabled(false);
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
/*
* CandidateHarvester#harvest(Component) has been called on
* the harvester and its success or failure has been noted.
* Now forget the harvester because any failure to continue
* execution is surely not its fault.
*/
harvester = null;
}
}

View File

@ -34,7 +34,7 @@ public class HarvestingTimeStat
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
public void startHarvesting()
public void startHarvestTiming()
{
++nbHarvesting;
// Remember the start date of this harvester.
@ -44,7 +44,7 @@ public class HarvestingTimeStat
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvesting()
public void stopHarvestTiming()
{
// Remember the last harvesting time.
this.lastHarvestingTime = this.getHarvestingTime();

View File

@ -69,7 +69,7 @@ public class HostCandidateHarvester
throws IllegalArgumentException,
IOException
{
this.startHarvesting();
this.startHarvestTiming();
Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
@ -177,13 +177,11 @@ public class HostCandidateHarvester
+ " maxPort=" + maxPort);
}
this.stopHarvesting();
this.stopHarvestTiming();
logger.info(
"End candidate harvest within "
+ this.getHarvestingTime()
+ " ms, for "
+ this.getClass().getName()
+ ", component: " + component.getComponentID());
"Completed " + component.toShortString() + " harvest with "
+ getClass().getSimpleName() + " in " + getHarvestingTime()
+ " ms. Candidates found: " + component.getLocalCandidateCount());
}
/**
@ -334,7 +332,7 @@ public class HostCandidateHarvester
+ " address " + laddr
+ " and port " + port
+ " (" + se.getMessage() +")");
logger.log(Level.INFO, "", se);
logger.log(Level.FINEST, "", se);
}
port ++;
@ -410,17 +408,17 @@ public class HostCandidateHarvester
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
public void startHarvesting()
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvesting();
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvesting()
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvesting();
this.harvestingTimeStat.stopHarvestTiming();
}
/**

View File

@ -226,9 +226,8 @@ public class StunCandidateHarvester
*/
public Collection<LocalCandidate> harvest(Component component)
{
logger.fine("invoked harvest / stream.component: " + toString() + " / "
+ component.getParentStream().getName() + " / " +
component.getComponentID());
logger.fine("starting " + component.toShortString()
+ " harvest for: " + toString() );
stunStack = component.getParentStream().getParentAgent().getStunStack();
for (Candidate<?> cand : component.getLocalCandidates())
@ -257,29 +256,17 @@ public class StunCandidateHarvester
if (completedHarvestCandidates != null)
{
logger.fine("harvest / stream.component: " + toString() +
" / " + component.getParentStream().getName() + " / " +
component.getComponentID() +
": completedHarvestCandidates element count: " +
completedHarvests.size());
if(completedHarvestCandidates.length != 0)
{
candidates.addAll(
Arrays.asList(completedHarvestCandidates));
}
}
else
logger.fine("harvest / stream.component: " + toString() +
" / " + component.getParentStream().getName() + " / " +
component.getComponentID() +
": completedHarvestCandidates == null");
}
}
logger.info("harvest / stream.component: " + toString() + " / "
+ component.getParentStream().getName() + " / " +
component.getComponentID() +
"found " + candidates.size() + " candidates.");
logger.finest(
"Completed " + component.toShortString() + " harvest: " + toString()
+ ". Found " + candidates.size() + " candidates.");
return candidates;
}
@ -390,7 +377,7 @@ public class StunCandidateHarvester
String proto = (this instanceof TurnCandidateHarvester)
? "TURN"
: "STUN";
return proto + " harvester for srvr: " + this.stunServer;
return proto + " harvester(srvr: " + this.stunServer + ")";
}
/**

View File

@ -143,7 +143,7 @@ public class UPNPHarvester
port,
localAddress.getHostAddress(),
"UDP",
"Ice4J: " + port))
"ice4j.org: " + port))
{
List<LocalCandidate> cands = createUPNPCandidate(socket,
localAddress, externalIPAddress, externalPort,

View File

@ -0,0 +1,153 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.ice.sdp;
import gov.nist.core.*;
import gov.nist.javax.sdp.fields.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import javax.sdp.*;
public class CandidateAttribute extends AttributeField
{
/**
* The SDP name of candidate attributes.
*/
public static final String NAME = "candidate";
/**
* This class's serial version uid.
*/
private static final long serialVersionUID = 1L;
/**
* The Candidate that we will be encapsulating.
*/
private final Candidate candidate;
/**
* Creates an attribute instance
*
* @param candidate the Candidate
*/
public CandidateAttribute(Candidate candidate)
{
this.candidate = candidate;
}
/**
* Returns the name of this attribute
*
* @return a String identity.
*/
public String getName()
{
return NAME;
}
/**
* Does nothing .
*
* @param name ignored.
*/
public void setName(String name)
{
}
/**
* Always returns <tt>true</tt> as this attribute always has a value.
*
* @return true if the attribute has a value.
*/
public boolean hasValue()
{
return true;
}
;
/**
* Returns the value of this attribute.
*
* @return the value
*/
public String getValue()
{
StringBuffer buff = new StringBuffer();
buff.append(candidate.getFoundation());
buff.append(" ").append(
candidate.getParentComponent().getComponentID());
buff.append(" ").append(candidate.getTransport());
buff.append(" ").append(candidate.getPriority());
buff.append(" ").append(
candidate.getTransportAddress().getHostAddress());
buff.append(" ").append(
candidate.getTransportAddress().getPort());
buff.append(" typ ").append(
candidate.getType());
TransportAddress relAddr = candidate.getRelatedAddress();
if (relAddr != null)
{
buff.append(" raddr ").append(relAddr.getHostAddress());
buff.append(" rport ").append(relAddr.getPort());
}
return buff.toString();
}
/**
* Parses the value of this attribute.
*
* @param value the - attribute value
*
* @throws javax.sdp.SdpException if there's a problem with the <tt>value
* String</tt>.
*/
public void setValue(String value) throws
SdpException
{
}
/**
* Returns the type character for the field.
*
* @return the type character for the field.
*/
public char getTypeChar()
{
return 'a';
}
/**
* Returns a reference to this attribute.
*
* @return a reference to this attribute.
*/
public CandidateAttribute clone()
{
return null;
}
/**
* Returns the string encoded version of this object
*
* @return the string encoded version of this object
*/
public String encode()
{
StringBuffer sbuff = new StringBuffer(ATTRIBUTE_FIELD);
sbuff.append(getName()).append(Separators.COLON);
sbuff.append(getValue());
return sbuff.append(Separators.NEWLINE).toString();
}
}

View File

@ -0,0 +1,247 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.ice.sdp;
import gov.nist.javax.sdp.fields.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import javax.sdp.*;
import java.util.*;
import java.util.logging.*;
/**
* A number of utility methods that WebRTC or SIP applications may find useful
* in case they are also fine with using jain-sdp
*
* @author Emil Ivov
*/
public class IceSdpUtils
{
/**
* The name of the SDP attribute that contains an ICE user fragment.
*/
public static final String ICE_UFRAG = "ice-ufrag";
/**
* The name of the SDP attribute that contains an ICE password.
*/
public static final String ICE_PWD = "ice-pwd";
/**
* The name of the SDP attribute that contains an ICE options.
*/
public static final String ICE_OPTIONS = "ice-options";
/**
* The name of the ICE SDP option that indicates support for trickle.
*/
public static final String ICE_OPTION_TRICKLE = "trickle";
/**
* A reference to the currently valid SDP factory instance.
*/
private static final SdpFactory sdpFactory = SdpFactory.getInstance();
/**
* The <tt>Logger</tt> used by the <tt>IceSdpUtils</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(IceSdpUtils.class.getName());
/**
* Sets the specified ICE user fragment and password as attributes of the
* specified session description.
*
* @param sDes the session description where we'd like to set a user
* fragment and a password.
* @param uFrag the ICE user name fragment that we'd like to set on the
* session description
* @param pwd the ICE password that we'd like to set on the session
* description
*
* @throws NullPointerException if the either of the parameters is null
*/
@SuppressWarnings("unchecked") // SDP legacy
public static void setIceCredentials(SessionDescription sDes,
String uFrag,
String pwd)
throws NullPointerException
{
if (sDes == null || uFrag == null || pwd == null)
{
throw new NullPointerException(
"sDes, uFrag and pwd, cannot be null");
}
try
{
Vector<Attribute> sessionAttributes = sDes.getAttributes(true);
//ice u-frag and password
sessionAttributes.add(sdpFactory.createAttribute(ICE_UFRAG, uFrag));
sessionAttributes.add(sdpFactory.createAttribute(ICE_PWD, pwd));
sDes.setAttributes(sessionAttributes);
}
catch (Exception cause)
{
// this is very unlikely to happen but we should still log.
// Just in case.
logger.log(Level.INFO,
"Failed to set ICE credentials for some weird reason",
cause);
}
}
/**
* Reflects the candidates from the various components in
* <tt>iceMediaStream</tt> into the specified m-line. Also sets default
* candidates into m= lines and c= lines. This method uses media level
* c= lines. They override session level making them pointless. This
* shouldn't be causing problems, but for good taste, make sure you don't
* include session level ones and avoid duplication.
*
* @param mediaDescription the media descriptions that we'd like to add
* candidates to.
* @param iceMediaStream the media stream where we should extract candidates
* from.
*/
public static void initMediaDescription(MediaDescription mediaDescription,
IceMediaStream iceMediaStream)
{
for(Component component : iceMediaStream.getComponents())
{
//first add the candidates
for(Candidate<?> candidate : component.getLocalCandidates())
{
mediaDescription.addAttribute(
new CandidateAttribute(candidate));
}
//set the default candidate
try
{
TransportAddress defaultAddress
= component.getDefaultCandidate().getTransportAddress();
mediaDescription.getMedia().setMediaPort(
defaultAddress.getPort());
String addressFamily = defaultAddress.isIPv6()
? Connection.IP6
: Connection.IP4;
mediaDescription.setConnection(sdpFactory.createConnection(
"IN", defaultAddress.getHostAddress(), addressFamily));
}
catch (SdpException exc)
{
//this shouldn't happen but let's rethrow an SDP exception just
//in case.
throw new IllegalArgumentException(
"Something went wrong when setting default candidates",
exc);
}
}
}
/**
* Sets ice credentials, ICE options, media lines and candidates from agent,
* on the specified session description.
*
* @param sDes the {@link SessionDescription} that we'd like to setup as per
* the specified agent.
* @param agent the {@link Agent} that we need to use when initializing
* the session description.
*/
@SuppressWarnings("unchecked") // jain-sdp legacy
public static void initSessionDescription(SessionDescription sDes,
Agent agent)
{
//now add ICE options
StringBuilder allOptionsBuilder = new StringBuilder();
//if(agent.supportsTrickle())
allOptionsBuilder.append(ICE_OPTION_TRICKLE).append(" ");
String allOptions = allOptionsBuilder.toString().trim();
try
{
if (allOptions.length() > 0)
{
//get the attributes so that we could easily modify them
Vector<Attribute> sessionAttributes = sDes.getAttributes(true);
sessionAttributes.add(
sdpFactory.createAttribute(ICE_OPTIONS, allOptions));
}
//take care of the origin: first extract one of the default
// addresses so that we could set the origin.
TransportAddress defaultAddress = agent.getStreams().get(0)
.getComponent(Component.RTP).getDefaultCandidate()
.getTransportAddress();
String addressFamily = defaultAddress.isIPv6()
? Connection.IP6
: Connection.IP4;
//origin
Origin o = sDes.getOrigin();
if( o == null || "user".equals(o.getUsername()))
{
//looks like there wasn't any origin set: jain-sdp creates a
//default origin that has "user" as the user name so we use this
//to detect it. it's quite hacky but couldn't fine another way.
o = sdpFactory.createOrigin("ice4j.org", 0, 0, "IN",
addressFamily, defaultAddress.getHostAddress());
}
else
{
//if an origin existed, we just make sure it has the right
// address now and are care ful not to touch anything else.
o.setAddress(defaultAddress.getHostAddress());
o.setAddressType(addressFamily);
}
sDes.setOrigin(o);
//m lines
List<IceMediaStream> streams = agent.getStreams();
Vector<MediaDescription> mDescs = new Vector<MediaDescription>(
agent.getStreamCount());
for(IceMediaStream stream : streams)
{
MediaDescription mLine = sdpFactory.createMediaDescription(
stream.getName(), 0, //default port comes later
1, SdpConstants.RTP_AVP, new int[]{0});
IceSdpUtils.initMediaDescription(mLine, stream);
mDescs.add(mLine);
}
sDes.setMediaDescriptions(mDescs);
}
catch (SdpException exc)
{
//this shouldn't happen but let's rethrow an SDP exception just
//in case.
throw new IllegalArgumentException(
"Something went wrong when setting ICE options",
exc);
}
//first set credentials
setIceCredentials(
sDes, agent.getLocalUfrag(), agent.getLocalPassword());
}
}

View File

@ -0,0 +1,40 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.net.*;
/**
* Implements a <tt>DatagramPacketFilter</tt> which only accepts
* <tt>DatagramPacket</tt>s which represent RTCP messages according to the rules
* described in RFC5761.
* <p>
* This filter would only be able to demultiplex between RTP and RTCP packets.
* Other protocols such as STUN/TURN, DTLS or ZRTP are not taken into account
* and may produce false positives if left to this filter. They should hence
* be handled by lower layers/demuxers.
*
* @author Emil Ivov
*/
public class RtcpDemuxPacketFilter
implements DatagramPacketFilter
{
/**
* Determines whether a specific <tt>DatagramPacket</tt> is an RTCP.
* <tt>DatagramPacket</tt> in a selection based on this filter.
*
* @param p the <tt>DatagramPacket</tt> whose protocol we'd like to
* determine.
* @return <tt>true</tt> if <tt>p</tt> is an RTCP and this filter accepts it
* and <tt>false</tt> otherwise.
*/
public boolean accept(DatagramPacket p)
{
return false;
}
}

View File

@ -264,25 +264,25 @@ public class Ice
protected static Agent createAgent(int rtpPort)
throws Throwable
{
long startTime = System.currentTimeMillis();
Agent agent = new Agent();
// STUN
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("sip-communicator.net", 3478, Transport.UDP));
new TransportAddress("stun.jitsi.net", 3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("ipv6.sip-communicator.net",
new TransportAddress("stun6.jitsi.net",
3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv);
// TURN
String[] hostnames
= new String[]
{
"130.79.90.150",
"2001:660:4701:1001:230:5ff:fe1a:805f"
};
String[] hostnames = new String[]
{
"stun.jitsi.net",
"stun6.jitsi.net"
};
int port = 3478;
LongTermCredential longTermCredential
= new LongTermCredential("guest", "anonymouspower!!");
@ -293,10 +293,20 @@ public class Ice
new TransportAddress(hostname, port, Transport.UDP),
longTermCredential));
//UPnP: adding an UPnP harvester because they are generally slow
//which makes it more convenient to test things like trickle.
agent.addCandidateHarvester( new UPNPHarvester() );
//STREAMS
createStream(rtpPort, "audio", agent);
createStream(rtpPort + 2, "video", agent);
long endTime = System.currentTimeMillis();
long total = endTime - startTime;
System.out.println("Total harvesting time: " + total + "ms.");
return agent;
}

View File

@ -44,9 +44,13 @@ public class IceDistributed
localAgent.setControlling(false);
String localSDP = SdpUtils.createSDPDescription(localAgent);
//wait a bit so that the logger can stop dumping stuff:
Thread.sleep(500);
System.out.println("=================== feed the following"
+" to the remote agent ===================");
System.out.println(localSDP);
System.out.println("======================================"

View File

@ -1,392 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package test;
import gov.nist.core.*;
import gov.nist.javax.sdp.fields.*;
import java.util.*;
import java.util.StringTokenizer;
import javax.sdp.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.ice.Agent;
/**
* Utilities for manipulating SDP. The utilities This method <b>do not</b> try
* to act smart and make a lot of assumptions (e.g. at least one media stream
* with at least one component) that may not always be true in real life and
* lead to exceptions. Therefore, make sure you reread the code if reusing it
* in an application. It should be fine for the purposes of our ice4j examples
* though.
*
* @author Emil Ivov
*/
public class SdpUtils
{
/**
* Creates a session description containing the streams from the specified
* <tt>agent</tt> using dummy codecs.
*
* @param agent the {@link Agent} we'd like to generate.
*
* @return a {@link SessionDescription} representing <tt>agent</tt>'s
* streams.
*
* @throws Throwable on rainy days
*/
public static String createSDPDescription(Agent agent) throws Throwable
{
SdpFactory factory = SdpFactory.getInstance();
SessionDescription sdess = factory.createSessionDescription();
Vector<Attribute> sessionAttributes = new Vector<Attribute>();
TransportAddress defaultAddress = agent.getStreams().get(0)
.getComponent(Component.RTP).getDefaultCandidate()
.getTransportAddress();
String addrType = defaultAddress.isIPv6()
? Connection.IP6
: Connection.IP4;
//origin (use ip from the first component of the first stream)
Origin o = factory.createOrigin("ice4j.org", 0, 0, "IN", addrType,
defaultAddress.getHostAddress());
sdess.setOrigin(o);
//connection (again use ip from first stream's component)
Connection c = factory.createConnection("IN", addrType,
defaultAddress.getHostAddress() );
sdess.setConnection(c);
//ice u-frag and password
sessionAttributes.add(factory.createAttribute("ice-pwd",
agent.getLocalPassword()));
sessionAttributes.add(factory.createAttribute("ice-ufrag",
agent.getLocalUfrag()));
//m lines
List<IceMediaStream> streams = agent.getStreams();
Vector<MediaDescription> mDescs = new Vector<MediaDescription>(
agent.getStreamCount());
for(IceMediaStream stream : streams)
{
TransportAddress streamDefaultAddr = stream.getComponent(
Component.RTP).getDefaultCandidate().getTransportAddress();
MediaDescription mdesc = factory.createMediaDescription(
stream.getName(), streamDefaultAddr.getPort(),
1, SdpConstants.RTP_AVP, new int[]{0});
Vector<Attribute> candidates = new Vector<Attribute>();
for(Component component : stream.getComponents())
{
for(Candidate cand : component.getLocalCandidates())
{
candidates.add(new CandidateAttribute(cand));
}
}
mdesc.setAttributes(candidates);
mDescs.add(mdesc);
}
sdess.setAttributes(sessionAttributes);
sdess.setMediaDescriptions(mDescs);
return sdess.toString();
}
/**
* Configures <tt>localAgent</tt> the the remote peer streams, components,
* and candidates specified in <tt>sdp</tt>
*
* @param localAgent the {@link Agent} that we'd like to configure.
*
* @param sdp the SDP string that the remote peer sent.
*
* @throws Exception for all sorts of reasons.
*/
@SuppressWarnings("unchecked") // jain-sdp legacy code.
public static void parseSDP(Agent localAgent, String sdp)
throws Exception
{
SdpFactory factory = SdpFactory.getInstance();
SessionDescription sdess = factory.createSessionDescription(sdp);
for(IceMediaStream stream : localAgent.getStreams())
{
stream.setRemotePassword(sdess.getAttribute("ice-pwd"));
stream.setRemoteUfrag(sdess.getAttribute("ice-ufrag"));
}
Connection globalConn = sdess.getConnection();
String globalConnAddr = null;
if(globalConn != null)
globalConnAddr = globalConn.getAddress();
Vector<MediaDescription> mdescs = sdess.getMediaDescriptions(true);
for (MediaDescription desc : mdescs)
{
String streamName = desc.getMedia().getMediaType();
IceMediaStream stream = localAgent.getStream(streamName);
if(stream == null)
continue;
Vector<Attribute> attributes = desc.getAttributes(true);
for( Attribute attribute : attributes)
{
if(!attribute.getName().equals(CandidateAttribute.NAME))
continue;
parseCandidate(attribute, stream);
}
//set default candidates
Connection streamConn = desc.getConnection();
String streamConnAddr = null;
if(streamConn != null)
streamConnAddr = streamConn.getAddress();
else
streamConnAddr = globalConnAddr;
int port = desc.getMedia().getMediaPort();
TransportAddress defaultRtpAddress =
new TransportAddress(streamConnAddr, port, Transport.UDP);
int rtcpPort = port + 1;
String rtcpAttributeValue = desc.getAttribute("rtcp");
if (rtcpAttributeValue != null)
rtcpPort = Integer.parseInt(rtcpAttributeValue);
TransportAddress defaultRtcpAddress =
new TransportAddress(streamConnAddr, rtcpPort, Transport.UDP);
Component rtpComponent = stream.getComponent(Component.RTP);
Component rtcpComponent = stream.getComponent(Component.RTCP);
Candidate defaultRtpCandidate
= rtpComponent.findRemoteCandidate(defaultRtpAddress);
rtpComponent.setDefaultRemoteCandidate(defaultRtpCandidate);
if(rtcpComponent != null)
{
Candidate defaultRtcpCandidate
= rtcpComponent.findRemoteCandidate(defaultRtcpAddress);
rtcpComponent.setDefaultRemoteCandidate(defaultRtcpCandidate);
}
}
}
/**
* Parses the <tt>attribute</tt>.
*
* @param attribute the attribute that we need to parse.
* @param stream the {@link IceMediaStream} that the candidate is supposed
* to belong to.
*
* @return a newly created {@link RemoteCandidate} matching the
* content of the specified <tt>attribute</tt> or <tt>null</tt> if the
* candidate belonged to a component we don't have.
*/
private static RemoteCandidate parseCandidate(Attribute attribute,
IceMediaStream stream)
{
String value = null;
try{
value = attribute.getValue();
}catch (Throwable t){}//can't happen
StringTokenizer tokenizer = new StringTokenizer(value);
//XXX add exception handling.
String foundation = tokenizer.nextToken();
int componentID = Integer.parseInt( tokenizer.nextToken() );
Transport transport = Transport.parse(tokenizer.nextToken());
long priority = Long.parseLong(tokenizer.nextToken());
String address = tokenizer.nextToken();
int port = Integer.parseInt(tokenizer.nextToken());
TransportAddress transAddr
= new TransportAddress(address, port, transport);
tokenizer.nextToken(); //skip the "typ" String
CandidateType type = CandidateType.parse(tokenizer.nextToken());
Component component = stream.getComponent(componentID);
if(component == null)
return null;
// check if there's a related address property
RemoteCandidate relatedCandidate = null;
if (tokenizer.countTokens() >= 4)
{
tokenizer.nextToken(); // skip the raddr element
String relatedAddr = tokenizer.nextToken();
tokenizer.nextToken(); // skip the rport element
int relatedPort = Integer.parseInt(tokenizer.nextToken());
TransportAddress raddr = new TransportAddress(
relatedAddr, relatedPort, Transport.UDP);
relatedCandidate = component.findRemoteCandidate(raddr);
}
RemoteCandidate cand = new RemoteCandidate(transAddr, component, type,
foundation, priority, relatedCandidate);
component.addRemoteCandidate(cand);
return cand;
}
/**
* An implementation of the <tt>candidate</tt> SDP attribute.
*/
private static class CandidateAttribute extends AttributeField
{
/**
* The SDP name of candidate attributes.
*/
public static final String NAME = "candidate";
/**
* This class's serial version uid.
*/
private static final long serialVersionUID = 1L;
/**
* The Candidate that we will be encapsulating.
*/
private final Candidate candidate;
/**
* Creates an attribute instance
*
* @param candidate the Candidate
*/
public CandidateAttribute(Candidate candidate)
{
this.candidate = candidate;
}
/**
* Returns the name of this attribute
*
* @return a String identity.
*/
public String getName()
{
return NAME;
}
/**
* Does nothing .
*
* @param name ignored.
*/
public void setName(String name){}
/**
* Always returns <tt>true</tt> as this attribute always has a value.
*
* @return true if the attribute has a value.
*/
public boolean hasValue()
{
return true;
};
/**
* Returns the value of this attribute.
*
* @return the value
*/
public String getValue()
{
StringBuffer buff= new StringBuffer();
buff.append(candidate.getFoundation());
buff.append(" ").append(
candidate.getParentComponent().getComponentID());
buff.append(" ").append(candidate.getTransport());
buff.append(" ").append(candidate.getPriority());
buff.append(" ").append(
candidate.getTransportAddress().getHostAddress());
buff.append(" ").append(
candidate.getTransportAddress().getPort());
buff.append(" typ ").append(
candidate.getType());
TransportAddress relAddr = candidate.getRelatedAddress();
if(relAddr != null)
{
buff.append(" raddr ").append(relAddr.getHostAddress());
buff.append(" rport ").append(relAddr.getPort());
}
return buff.toString();
}
/**
* Parses the value of this attribute.
*
* @param value the - attribute value
*
* @throws SdpException if there's a problem with the <tt>value
* String</tt>.
*/
public void setValue(String value) throws SdpException
{
}
/**
* Returns the type character for the field.
*
* @return the type character for the field.
*/
public char getTypeChar()
{
return 'a';
}
/**
* Returns a reference to this attribute.
*
* @return a reference to this attribute.
*/
public CandidateAttribute clone()
{
return this;
}
/**
* Returns the string encoded version of this object
*
* @return the string encoded version of this object
*/
public String encode()
{
StringBuffer sbuff = new StringBuffer(ATTRIBUTE_FIELD);
sbuff.append(getName()).append(Separators.COLON);
sbuff.append(getValue());
return sbuff.append(Separators.NEWLINE).toString();
}
}
}