Completes a first version of offerer semantics for Trickle ICE. Organizes logging and stats a bit.

This commit is contained in:
emcho 2013-06-26 00:26:48 +00:00
parent c4278af39c
commit 207a963196
20 changed files with 1040 additions and 366 deletions

View File

@ -156,7 +156,7 @@
</java> </java>
</target> </target>
<!-- runs our sample distributed application --> <!-- runs our sample application -->
<target name="run-sample"> <target name="run-sample">
<java fork="true" <java fork="true"
classname="test.Ice" classname="test.Ice"
@ -208,6 +208,18 @@
</java> </java>
</target> </target>
<!-- runs our sample Trickle ICE application -->
<target name="run-trickle">
<java fork="true"
classname="test.TrickleIce"
classpathref="project.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample lite application --> <!-- runs our sample lite application -->
<target name="run-lite"> <target name="run-lite">
<java fork="true" <java fork="true"

View File

@ -51,6 +51,7 @@ java.util.logging.ConsoleHandler.formatter = org.ice4j.util.Ice4jLogFormatter
# Things coming from ice4j # Things coming from ice4j
org.ice4j.level = INFO org.ice4j.level = INFO
test.level = INFO
#org.ice4j.ice.checks.levell = FINEST #org.ice4j.ice.checks.levell = FINEST
#org.ice4j.ice.ConnectivityCheckClient.level = FINER #org.ice4j.ice.ConnectivityCheckClient.level = FINER

View File

@ -17,6 +17,7 @@ import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.harvest.*; import org.ice4j.ice.harvest.*;
import org.ice4j.ice.harvest.TrickleCallback;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -92,7 +93,7 @@ public class Agent
/** /**
* Manages statisics about harvesting time. * Manages statisics about harvesting time.
*/ */
private HarvestingTimeStat harvestingTimeStat = new HarvestingTimeStat(); private HarvestStatistics harvestStats = new HarvestStatistics();
/** /**
* We use the <tt>FoundationsRegistry</tt> to keep track of the foundations * We use the <tt>FoundationsRegistry</tt> to keep track of the foundations
@ -221,13 +222,20 @@ public class Agent
/** /**
* Determines whether this agent should perform trickling. * Determines whether this agent should perform trickling.
*/ */
private boolean trickle = true; private boolean trickle = false;
/** /**
* Indicates that ICE will be shutdown. * Indicates that ICE will be shutdown.
*/ */
private boolean shutdown = false; private boolean shutdown = false;
/**
* Indicates that harvesting has been started at least ones. Used to warn
* users who are trying to trickle, that they have already completed a
* harvest. We may use it to throw an exception at some point if it's ever
* a problem.
*/
private boolean harvestingStarted = false;
/** /**
* Creates an empty <tt>Agent</tt> with no streams, and no address. * Creates an empty <tt>Agent</tt> with no streams, and no address.
@ -440,8 +448,6 @@ public class Agent
logger.info("Gather candidates for component " + logger.info("Gather candidates for component " +
component.toShortString()); component.toShortString());
this.startHarvestTiming();
hostCandidateHarvester.harvest( hostCandidateHarvester.harvest(
component, component,
preferredPort, minPort, maxPort, Transport.UDP); preferredPort, minPort, maxPort, Transport.UDP);
@ -458,24 +464,20 @@ public class Agent
//in case we are not trickling, apply other harvesters here //in case we are not trickling, apply other harvesters here
if(!isTrickling()) if(!isTrickling())
{
harvestingStarted = true; //raise a flag to warn on a second call.
harvesters.harvest(component); harvesters.harvest(component);
}
this.stopHarvestTiming(); logger.fine("Candidate count in first harvest: " +
logger.info(
"Harvest for " + component.toShortString() + " completed in "
+ this.getTotalHarvestingTime() + " ms.");
logger.fine("host+harvested candidate count: " +
component.getLocalCandidateCount()); component.getLocalCandidateCount());
//Emil: because of trickle we now compute foundations or priorities //Emil: because of trickle we now assign foundations, compute priorities
// directly when adding candidates. This shouldn't change anything but //and eliminate redundancies while adding candidates on a component.
// there's no need to do it here again. // This means that we no longer need to do it here, where we did before.
//computeFoundations(component); //computeFoundations(component);
//component.prioritizeCandidates(); //component.prioritizeCandidates();
//component.eliminateRedundantCandidates();
//eliminate redundant candidates
component.eliminateRedundantCandidates();
//select the candidate to put in the media line. //select the candidate to put in the media line.
component.selectDefaultCandidate(); component.selectDefaultCandidate();
@ -485,11 +487,39 @@ public class Agent
* Starts an asynchronous harvest across all components and reports newly * Starts an asynchronous harvest across all components and reports newly
* discovered candidates to <tt>trickleCallback</tt>. * discovered candidates to <tt>trickleCallback</tt>.
* *
* @param trickleCallback * @param trickleCallback the callback that will be notified for all newly
* discovered candidates.
*
* @throws IllegalStateException if we try calling this method without being
* in a trickling state.
*/ */
public void startCandidateTrickle(TrickleCallback trickleCallback) public void startCandidateTrickle(TrickleCallback trickleCallback)
throws IllegalStateException
{ {
if(!isTrickling())
{
throw new IllegalStateException(
"Trying to start trickling without enabling it on the agent!");
}
if(harvestingStarted)
{
logger.warning(
"Hmmm ... why are you harvesting twice? You shouldn't be!");
}
//create a list of components and start harvesting
List<Component> components = new LinkedList<Component>();
for (IceMediaStream stream : getStreams())
{
components.addAll( stream.getComponents());
}
harvesters.harvest(components, trickleCallback);
//tell the tricklers that we are done (the WebRTC way, with null):
trickleCallback.onIceCandidates(null);
} }
/** /**
@ -540,7 +570,8 @@ public class Agent
/** /**
* <tt>Free()</tt>s and removes from this agent components or entire streams * <tt>Free()</tt>s and removes from this agent components or entire streams
* if they do not contain remote candidates. A possible reason for this * if they do not contain remote candidates. A possible reason for this
* could be the fact that the remote party canceled some of the streams. * could be the fact that the remote party canceled some of the streams or
* that it is using rtcp-mux or bundle.
*/ */
private void pruneNonMatchedStreams() private void pruneNonMatchedStreams()
{ {
@ -736,6 +767,16 @@ public class Agent
harvesters.add(harvester); harvesters.add(harvester);
} }
/**
* Returns the set of harvesters currently in use by this agent.
*
* @return the set of harvesters currently in use by this agent.
*/
public CandidateHarvesterSet getHarvesters()
{
return harvesters;
}
/** /**
* Returns that user name that should be advertised in session descriptions * Returns that user name that should be advertised in session descriptions
* containing ICE data from this agent. * containing ICE data from this agent.
@ -2292,26 +2333,17 @@ public class Agent
* @param harvesterName The class name if the harvester. * @param harvesterName The class name if the harvester.
* *
* @return The harvesting time (in ms) for the harvester given in parameter. * @return The harvesting time (in ms) for the harvester given in parameter.
* 0 if this harvester does not exists, or if the agent has not yet */
* harvested with this harvester.
*/
public long getHarvestingTime(String harvesterName) public long getHarvestingTime(String harvesterName)
{ {
if(this.hostCandidateHarvester.getClass().getName().endsWith(
harvesterName))
{
return this.hostCandidateHarvester.getHarvestingTime();
}
long harvestingTime = 0; long harvestingTime = 0;
CandidateHarvester tmpHarvester;
Iterator<CandidateHarvester> itHarvesters = this.harvesters.iterator(); for(CandidateHarvester harvester : harvesters)
while(itHarvesters.hasNext())
{ {
tmpHarvester = itHarvesters.next(); if(harvester.getClass().getName().endsWith(harvesterName))
if(tmpHarvester.getClass().getName().endsWith(harvesterName))
{ {
harvestingTime = tmpHarvester.getHarvestingTime(); harvestingTime = harvester.getHarvestStatistics()
.getHarvestDuration();
// There may be several harvester with the same class name. // There may be several harvester with the same class name.
// Thus, returns only an active one (if any). // Thus, returns only an active one (if any).
if(harvestingTime != 0) if(harvestingTime != 0)
@ -2333,28 +2365,21 @@ public class Agent
* @return The number of harvesting time for the harvester given in * @return The number of harvesting time for the harvester given in
* parameter. * parameter.
*/ */
public int getNbHarvesting(String harvesterName) public int getHarvestCount(String harvesterName)
{ {
if(this.hostCandidateHarvester.getClass().getName().endsWith( int harvestCount;
harvesterName))
{
return this.hostCandidateHarvester.getNbHarvesting();
}
int nbHarvesting = 0; for(CandidateHarvester harvester : harvesters)
CandidateHarvester tmpHarvester;
Iterator<CandidateHarvester> itHarvesters = this.harvesters.iterator();
while(itHarvesters.hasNext())
{ {
tmpHarvester = itHarvesters.next(); if(harvester.getClass().getName().endsWith(harvesterName))
if(tmpHarvester.getClass().getName().endsWith(harvesterName))
{ {
nbHarvesting = tmpHarvester.getNbHarvesting(); harvestCount
= harvester.getHarvestStatistics().getHarvestCount();
// There may be several harvester with the same class name. // There may be several harvester with the same class name.
// Thus, returns only an active one (if any). // Thus, returns only an active one (if any).
if(nbHarvesting != 0) if(harvestCount != 0)
{ {
return nbHarvesting; return harvestCount;
} }
} }
} }
@ -2363,42 +2388,41 @@ public class Agent
} }
/** /**
* Starts the harvesting timer. Called when the harvest begins. * Returns the combined harvesting time for all harvesters in this agent.
*/
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvestTiming();
}
/**
* Returns the current harvesting time in ms. If this agent is not currently
* harvesting, then returns the value of the last total harvesting time for
* all the harvesters. 0 if this agent has nerver harvested.
* *
* @return The current harvesting time in ms. If this agent is not currently * @return the total time this agent has spent harvesting.
* harvesting, then returns the value of the last total harvesting time for
* all the harvesters. 0 if this agent has nerver harvested.
*/ */
public long getTotalHarvestingTime() public long getTotalHarvestingTime()
{ {
return this.harvestingTimeStat.getHarvestingTime(); long harvestDuration = 0;
for(CandidateHarvester harvester : harvesters)
{
harvestDuration += harvester
.getHarvestStatistics().getHarvestDuration();
}
return harvestDuration;
} }
/** /**
* Returns the number of harvesting for this agent. * Returns the total number of harvests completed by this agent. Normally
* this number should be equal to NB_HARVESTERS*NB_COMPONENTS but could be
* less if some harvesters were disabled for inefficiency or more ... if
* there's a bug ;).
* *
* @return The number of harvesting for this agent. * @return the number of harvest this agent has completed.
*/ */
public int getNbHarvesting() public int getHarvestCount()
{ {
return this.harvestingTimeStat.getNbHarvesting(); int harvestCount = 0;
for(CandidateHarvester harvester : harvesters)
{
harvestCount += harvester
.getHarvestStatistics().getHarvestDuration();
}
return harvestCount;
} }
} }

View File

@ -139,8 +139,12 @@ public class Component
* registered with the agent. * registered with the agent.
* *
* @param candidate the candidate object to be added * @param candidate the candidate object to be added
*
* @return <tt>true</tt> if we actually added the new candidate or
* <tt>false</tt> in case we didn't because it was redundant to an existing
* candidate.
*/ */
public void addLocalCandidate(LocalCandidate candidate) public boolean addLocalCandidate(LocalCandidate candidate)
{ {
Agent agent = getParentStream().getParentAgent(); Agent agent = getParentStream().getParentAgent();
@ -161,8 +165,24 @@ public class Component
synchronized(localCandidates) synchronized(localCandidates)
{ {
//check if we already have such a candidate (redundant)
LocalCandidate redundantCandidate = findRedundant(candidate);
if (redundantCandidate != null)
{
//if we get here, then it's clear we won't be adding anything
//we will just update something at best. We purposefully don't
//care about priorities because allowing candidate replace is
//tricky to handle on the signalling layer with trickle
return false;
}
localCandidates.add(candidate); localCandidates.add(candidate);
//we are done adding ... now let's just order by priority.
Collections.sort(localCandidates); Collections.sort(localCandidates);
return true;
} }
} }
@ -240,11 +260,11 @@ public class Component
/** /**
* Update the media-stream <tt>Component</tt> with the specified * Update the media-stream <tt>Component</tt> with the specified
* <tt>Candidate</tt>. * <tt>Candidate</tt>s. This would happen when performing trickle ICE.
* *
* @param candidate new <tt>Candidate</tt> to add. * @param candidate new <tt>Candidate</tt> to add.
*/ */
public void addUpdateRemoteCandidate(RemoteCandidate candidate) public void addUpdateRemoteCandidates(RemoteCandidate candidate)
{ {
logger.info("Update remote candidate for " + toShortString() + ": " + logger.info("Update remote candidate for " + toShortString() + ": " +
candidate.getTransportAddress()); candidate.getTransportAddress());
@ -337,9 +357,9 @@ public class Component
} }
/** /**
* Update ICE processing with the new <tt>Candidate</tt>s. * Update ICE processing with new <tt>Candidate</tt>s.
*/ */
public void updateRemoteCandidate() public void updateRemoteCandidates()
{ {
List<CandidatePair> checkList = null; List<CandidatePair> checkList = null;
@ -580,14 +600,15 @@ public class Component
* Computes the priorities of all <tt>Candidate</tt>s and then sorts them * Computes the priorities of all <tt>Candidate</tt>s and then sorts them
* accordingly. * accordingly.
* *
* @Deprecated candidates are now being prioritized upon addition and * @deprecated candidates are now being prioritized upon addition and
* calling this method is no longer necessary. * calling this method is no longer necessary.
*/ */
@Deprecated
protected void prioritizeCandidates() protected void prioritizeCandidates()
{ {
synchronized(localCandidates) synchronized(localCandidates)
{ {
CompatibilityMode compat = getParentStream().getParentAgent() CompatibilityMode compatibility = getParentStream().getParentAgent()
.getCompatibilityMode(); .getCompatibilityMode();
LocalCandidate[] candidates LocalCandidate[] candidates
@ -598,7 +619,7 @@ public class Component
//first compute the actual priorities //first compute the actual priorities
for (Candidate<?> cand : candidates) for (Candidate<?> cand : candidates)
{ {
if(compat == CompatibilityMode.GTALK) if(compatibility == CompatibilityMode.GTALK)
{ {
cand.computeGTalkPriority(); cand.computeGTalkPriority();
} }
@ -628,7 +649,11 @@ public class Component
* redundant when the agent is not behind a NAT. The agent SHOULD eliminate * redundant when the agent is not behind a NAT. The agent SHOULD eliminate
* the redundant candidate with the lower priority which is why we have to * the redundant candidate with the lower priority which is why we have to
* run this method only after prioritizing candidates. * run this method only after prioritizing candidates.
*
* @deprecated redundancies are now being detected upon addition of
* candidates and calling this method is no longer necessary.
*/ */
@Deprecated
protected void eliminateRedundantCandidates() protected void eliminateRedundantCandidates()
{ {
/* /*
@ -668,6 +693,43 @@ public class Component
} }
} }
/**
* Finds and returns the first candidate that is redundant to <tt>cand</tt>.
* A candidate is redundant if its transport address equals another
* candidate, and its base equals the base of that other candidate. Note
* that two candidates can have the same transport address yet have
* different bases, and these would not be considered redundant. Frequently,
* a server reflexive candidate and a host candidate will be redundant when
* the agent is not behind a NAT. The agent SHOULD eliminate the redundant
* candidate with the lower priority which is why we have to run this method
* only after prioritizing candidates.
*
* @param cand the {@link LocalCandidate} that we'd like to check for
* redundancies.
*
* @return the first candidate that is redundant to <tt>cand</tt> or
* <tt>null</tt> if there is no such candidate.
*/
private LocalCandidate findRedundant(LocalCandidate cand)
{
synchronized (localCandidates)
{
for (LocalCandidate redundantCand : localCandidates)
{
if ((cand != redundantCand)
&& cand.getTransportAddress().equals(
redundantCand.getTransportAddress())
&& cand.getBase().equals(redundantCand.getBase()))
{
return redundantCand;
}
}
}
return null;
}
/** /**
* Returns the <tt>Candidate</tt> that has been selected as the default * Returns the <tt>Candidate</tt> that has been selected as the default
* for this <tt>Component</tt> or <tt>null</tt> if no such * for this <tt>Component</tt> or <tt>null</tt> if no such

View File

@ -1,12 +0,0 @@
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

@ -22,9 +22,9 @@ import org.ice4j.ice.*;
public abstract class CandidateHarvester public abstract class CandidateHarvester
{ {
/** /**
* Manages statisics about harvesting time. * Manages statistics about harvesting time.
*/ */
private HarvestingTimeStat harvestingTimeStat = new HarvestingTimeStat(); private HarvestStatistics harvestStatistics = new HarvestStatistics();
/** /**
* Gathers all candidate addresses of the type that this * Gathers all candidate addresses of the type that this
@ -45,42 +45,14 @@ public abstract class CandidateHarvester
public abstract Collection<LocalCandidate> harvest(Component component); public abstract Collection<LocalCandidate> harvest(Component component);
/** /**
* Starts the harvesting timer. Called when the harvest begins. * Returns the statistics describing how well the various harvests of this
*/ * harvester went.
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvestTiming();
}
/**
* Returns the current harvesting time in ms. If this harvester is not
* currently harvesting, then returns the value of the last harvesting time.
* 0 if this harvester has nerver harvested.
* *
* @return The current harvesting time in ms. If this harvester is not * @return The {@link HarvestStatistics} describing this harvester's
* currently harvesting, then returns the value of the last harvesting time. * harvests.
* 0 if this harvester has nerver harvested.
*/ */
public long getHarvestingTime() public HarvestStatistics getHarvestStatistics()
{ {
return this.harvestingTimeStat.getHarvestingTime(); return harvestStatistics;
}
/**
* Returns the number of harvesting for this harvester.
*
* @return The number of harvesting for this harvester.
*/
public int getNbHarvesting()
{
return this.harvestingTimeStat.getNbHarvesting();
} }
} }

View File

@ -85,33 +85,29 @@ public class CandidateHarvesterSet
*/ */
public void harvest(Component component) public void harvest(Component component)
{ {
synchronized (elements) harvest(Arrays.asList(new Component[]{component}), null);
{
harvest(elements.iterator(), component, threadPool);
}
} }
/** /**
* Gathers candidate addresses for a specific <tt>Component</tt> using * Gathers candidate addresses for a specific <tt>Component</tt>.
* specific <tt>CandidateHarvester</tt>s. * <tt>CandidateHarvesterSet</tt> delegates to the
* <tt>CandidateHarvester</tt>s which are its <tt>Set</tt> elements.
* *
* @param harvesters the <tt>CandidateHarvester</tt>s to gather candidate * @param components the <tt>Component</tt> to gather candidate addresses for
* addresses for the specified <tt>Component</tt> * @see CandidateHarvester#harvest(Component)
* @param component the <tt>Component</tt> to gather candidate addresses for * @param trickleCallback the {@link TrickleCallback} that we will be
* @param executorService the <tt>ExecutorService</tt> to schedule the * feeding candidates to, or <tt>null</tt> in case the application doesn't
* execution of the gathering of candidate addresses performed by the * want us trickling any candidates
* specified <tt>harvesters</tt>
*/ */
private void harvest( public void harvest(final List<Component> components,
final Iterator<CandidateHarvesterSetElement> harvesters, TrickleCallback trickleCallback)
final Component component,
ExecutorService executorService)
{ {
synchronized (elements)
harvest(harvesters, {
Arrays.asList(new Component[]{component}), harvest(
executorService); elements.iterator(), components, threadPool, trickleCallback);
}
} }
/** /**
@ -125,11 +121,15 @@ public class CandidateHarvesterSet
* @param executorService the <tt>ExecutorService</tt> to schedule the * @param executorService the <tt>ExecutorService</tt> to schedule the
* execution of the gathering of candidate addresses performed by the * execution of the gathering of candidate addresses performed by the
* specified <tt>harvesters</tt> * specified <tt>harvesters</tt>
* @param trickleCallback the {@link TrickleCallback} that we will be
* feeding candidates to, or <tt>null</tt> in case the application doesn't
* want us trickling any candidates
*/ */
private void harvest( private void harvest(
final Iterator<CandidateHarvesterSetElement> harvesters, final Iterator<CandidateHarvesterSetElement> harvesters,
final List<Component> components, final List<Component> components,
ExecutorService executorService) ExecutorService executorService,
final TrickleCallback trickleCallback)
{ {
/* /*
* Start asynchronously executing the * Start asynchronously executing the
@ -164,14 +164,11 @@ public class CandidateHarvesterSet
componentsCopy = new ArrayList<Component>(components); componentsCopy = new ArrayList<Component>(components);
} }
for(Component component : componentsCopy) // Asynchronously start gathering candidates using the harvester.
{ CandidateHarvesterSetTask task = new CandidateHarvesterSetTask(
// Asynchronously start gathering candidates using the harvester. harvester, componentsCopy, trickleCallback);
CandidateHarvesterSetTask task = new CandidateHarvesterSetTask(
harvester, component, harvesters);
tasks.put(task, executorService.submit(task)); tasks.put(task, executorService.submit(task));
}
} }
/* /*

View File

@ -17,7 +17,7 @@ import java.util.logging.*;
* <tt>CandidateHarvesterSet</tt>. * <tt>CandidateHarvesterSet</tt>.
* *
* @author Lyubomir Marinov * @author Lyubomir Marinov
* @author Emil Ivov * @author Emil Ivov
*/ */
class CandidateHarvesterSetElement class CandidateHarvesterSetElement
{ {
@ -53,6 +53,7 @@ class CandidateHarvesterSetElement
public CandidateHarvesterSetElement(CandidateHarvester harvester) public CandidateHarvesterSetElement(CandidateHarvester harvester)
{ {
this.harvester = harvester; this.harvester = harvester;
harvester.getHarvestStatistics().harvesterName = harvester.toString();
} }
/** /**
@ -60,30 +61,36 @@ class CandidateHarvesterSetElement
* associated <tt>CandidateHarvester</tt> if <tt>enabled</tt>. * associated <tt>CandidateHarvester</tt> if <tt>enabled</tt>.
* *
* @param component the <tt>Component</tt> to gather candidates for * @param component the <tt>Component</tt> to gather candidates for
* @param trickleCallback the {@link TrickleCallback} that we will be
* feeding candidates to, or <tt>null</tt> in case the application doesn't
* want us trickling any candidates
*/ */
public void harvest(Component component) public void harvest(Component component,
TrickleCallback trickleCallback)
{ {
if (isEnabled()) if (!isEnabled())
{ return;
harvester.startHarvestTiming();
Collection<LocalCandidate> candidates
= harvester.harvest(component);
harvester.stopHarvestTiming();
logger.info( startHarvestTiming();
"Completed " + component.getParentStream().getName()
+ "." + component.getName() Collection<LocalCandidate> candidates = harvester.harvest(component);
+ " harvest with " + harvester.toString() + " in "
+ harvester.getHarvestingTime() stopHarvestTiming(candidates);
+ " ms. Candidates found: " + candidates.size());
/* /*
* If the CandidateHarvester has not gathered any candidates, it * If the CandidateHarvester has not gathered any candidates, it
* is considered failed and will not be used again in order to * is considered failed and will not be used again in order to
* not risk it slowing down the overall harvesting. * not risk it slowing down the overall harvesting.
*/ */
if ((candidates == null) || candidates.isEmpty()) if ((candidates == null) || candidates.isEmpty())
setEnabled(false); {
setEnabled(false);
} }
else if(trickleCallback != null)
{
trickleCallback.onIceCandidates(candidates);
}
} }
/** /**
@ -139,4 +146,22 @@ class CandidateHarvesterSetElement
{ {
return harvester; return harvester;
} }
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
private void startHarvestTiming()
{
harvester.getHarvestStatistics().startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*
* @param harvest the harvest that we just concluded.
*/
private void stopHarvestTiming(Collection<LocalCandidate> harvest)
{
harvester.getHarvestStatistics().stopHarvestTiming(harvest);
}
} }

View File

@ -9,6 +9,7 @@ package org.ice4j.ice.harvest;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import java.util.*;
import java.util.logging.*; import java.util.logging.*;
/** /**
@ -37,9 +38,15 @@ class CandidateHarvesterSetTask
private CandidateHarvesterSetElement harvester; private CandidateHarvesterSetElement harvester;
/** /**
* The {@link Component} whose addresses we will be harvesting in this task. * The {@link Component}s whose addresses we will be harvesting in this
* task.
*/ */
private Component component; private Collection<Component> components;
/**
* The callback that we will be notifying every time a harvester completes.
*/
private final TrickleCallback trickleCallback;
/** /**
* Initializes a new <tt>CandidateHarvesterSetTask</tt> which is to * Initializes a new <tt>CandidateHarvesterSetTask</tt> which is to
@ -48,18 +55,18 @@ class CandidateHarvesterSetTask
* *
* @param harvester the <tt>CandidateHarvester</tt> on which the * @param harvester the <tt>CandidateHarvester</tt> on which the
* new instance is to call * new instance is to call
* @param components the <tt>Component</tt> whose candidates we are currently
* gathering.
* <tt>CandidateHarvester#harvest(Component)</tt> first * <tt>CandidateHarvester#harvest(Component)</tt> first
*/ */
java.util.Iterator<CandidateHarvesterSetElement> harvesters;
public CandidateHarvesterSetTask( public CandidateHarvesterSetTask(
CandidateHarvesterSetElement harvester, CandidateHarvesterSetElement harvester,
Component component, Collection<Component> components,
java.util.Iterator<CandidateHarvesterSetElement> harvesters) TrickleCallback trickleCallback)
{ {
this.harvester = harvester; this.harvester = harvester;
this.component = component; this.components = components;
this.harvesters = harvesters; this.trickleCallback = trickleCallback;
} }
/** /**
@ -80,11 +87,14 @@ class CandidateHarvesterSetTask
*/ */
public void run() public void run()
{ {
if (harvester.isEnabled()) if (harvester == null || !harvester.isEnabled())
return;
for (Component component : components)
{ {
try try
{ {
harvester.harvest(component); harvester.harvest(component, trickleCallback);
} }
catch (Throwable t) catch (Throwable t)
{ {

View File

@ -0,0 +1,172 @@
/*
* 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.*;
/**
* Manages statistics about harvesting time.
*
* @author Vincent Lucas
* @author Emil Ivov
*/
public class HarvestStatistics
{
/**
* The number of harvesting for this harvester.
*/
private int harvestCount = 0;
/**
* The last harvest start time for this harvester. -1 if this harvester is
* not currently harvesting.
*/
private long lastStartHarvestingTime = -1;
/**
* The last ended harvesting time for this harvester. -1 if this harvester
* has never harvested yet.
*/
private long lastHarvestingTime = 0;
/**
* The number of non-redundant candidates that this harvester has discovered
* during all its harvests.
*/
private int totalCandidateCount = 0;
/**
* The name of the harvester associated with these stats.
*/
protected String harvesterName;
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
protected void startHarvestTiming()
{
harvestCount++;
// Remember the start date of this harvester.
this.lastStartHarvestingTime = System.currentTimeMillis();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*
* @param harvest the harvest that we just concluded.
*/
protected void stopHarvestTiming(Collection<LocalCandidate> harvest)
{
//count total candidates
if(harvest != null)
stopHarvestTiming(harvest.size());
else
stopHarvestTiming(0);
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*
* @param candidateCount the number of candidates we harvested.
*/
protected void stopHarvestTiming(int candidateCount)
{
// Remember the last harvesting time.
this.lastHarvestingTime = this.getHarvestDuration();
// Stops the current timer (must be done after setting the
// lastHarvestingTime).
this.lastStartHarvestingTime = -1;
//count total candidates
this.totalCandidateCount += candidateCount;
}
/**
* Returns the current harvesting time in ms. If this harvester is not
* currently harvesting, then returns the value of the last harvesting time.
* 0 if this harvester has never harvested.
*
* @return The current harvesting time in ms.
*/
public long getHarvestDuration()
{
if(this.lastStartHarvestingTime != -1)
{
long currentHarvestingTime
= System.currentTimeMillis() - lastStartHarvestingTime;
// Retest here, while the harvesting may be end while computing the
// harvesting time.
if(this.lastStartHarvestingTime != -1)
{
return this.lastHarvestingTime + currentHarvestingTime;
}
}
// If we are ont currently harvesting, then returns the value of the
// last harvesting time.
return this.lastHarvestingTime;
}
/**
* Returns the number of candidates gathered by the associated harvester.
*
* @return the total number of candidates gatherer by this harvester.
*/
public int getTotalCandidateCount()
{
return totalCandidateCount;
}
/**
* Returns the number of harvests that the harvester associated with these
* statistics has completed so far.
*
* @return the number of harvests that the associated harvester has engaged
* in.
*/
public int getHarvestCount()
{
return this.harvestCount;
}
/**
* Specifies the name of the associated harvester.
*
* @param harvesterName the name of the associated harvester.
*/
protected void setName(String harvesterName)
{
this.harvesterName = harvesterName;
}
/**
* Returns the name of the associated harvester.
*
* @return the name of the associated harvester.
*/
public String getName()
{
return harvesterName;
}
/**
* Returns a string representation of these statistics in a concise format.
*
* @return a string representation of these stats.
*/
@Override
public String toString()
{
return harvesterName
+ ": time="+getHarvestDuration()
+ "ms harvests="+getHarvestCount()
+" candidates=" + getTotalCandidateCount() ;
}
}

View File

@ -1,92 +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 org.ice4j.ice.harvest;
/**
* Manages statisics about harvesting time.
*
* @author Vincent Lucas
*/
public class HarvestingTimeStat
{
/**
* The number of harvesting for this harvester.
*/
private int nbHarvesting = 0;
/**
* The last harvest start time for this harvester. -1 if this harvester is
* not currently harvesting.
*/
private long lastStartHarvestingTime = -1;
/**
* The last ended harvesting time for this harvester. -1 if this harvester
* has never harvested yet.
*/
private long lastHarvestingTime = 0;
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
public void startHarvestTiming()
{
++nbHarvesting;
// Remember the start date of this harvester.
this.lastStartHarvestingTime = System.currentTimeMillis();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvestTiming()
{
// Remember the last harvesting time.
this.lastHarvestingTime = this.getHarvestingTime();
// Stops the current timer (must be done after setting the
// lastHarvestingTime).
this.lastStartHarvestingTime = -1;
}
/**
* Returns the current harvesting time in ms. If this harvester is not
* currently harvesting, then returns the value of the last harvesting time.
* 0 if this harvester has nerver harvested.
*
* @return The current harvesting time in ms. If this harvester is not
* currently harvesting, then returns the value of the last harvesting time.
* 0 if this harvester has nerver harvested.
*/
public long getHarvestingTime()
{
if(this.lastStartHarvestingTime != -1)
{
long currentHarvestingTime
= System.currentTimeMillis() - lastStartHarvestingTime;
// Retest here, while the harvesting may be end while computing the
// harvsting time.
if(this.lastStartHarvestingTime != -1)
{
return this.lastHarvestingTime + currentHarvestingTime;
}
}
// If we are ont currently harvesting, then returns the value of the
// last harvesting time.
return this.lastHarvestingTime;
}
/**
* Returns the number of harvesting for this harvester.
*
* @return The number of harvesting for this harvester.
*/
public int getNbHarvesting()
{
return this.nbHarvesting;
}
}

View File

@ -36,7 +36,7 @@ public class HostCandidateHarvester
/** /**
* Manages statisics about harvesting time. * Manages statisics about harvesting time.
*/ */
private HarvestingTimeStat harvestingTimeStat = new HarvestingTimeStat(); private HarvestStatistics harvestStatistics = new HarvestStatistics();
/** /**
* Gathers all candidate addresses on the local machine, binds sockets on * Gathers all candidate addresses on the local machine, binds sockets on
@ -69,7 +69,7 @@ public class HostCandidateHarvester
throws IllegalArgumentException, throws IllegalArgumentException,
IOException IOException
{ {
this.startHarvestTiming(); harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces(); = NetworkInterface.getNetworkInterfaces();
@ -177,11 +177,8 @@ public class HostCandidateHarvester
+ " maxPort=" + maxPort); + " maxPort=" + maxPort);
} }
this.stopHarvestTiming(); this.harvestStatistics
logger.info( .stopHarvestTiming(component.getLocalCandidateCount());
"Completed " + component.toShortString() + " harvest with "
+ getClass().getSimpleName() + " in " + getHarvestingTime()
+ " ms. Candidates found: " + component.getLocalCandidateCount());
} }
/** /**
@ -406,42 +403,14 @@ public class HostCandidateHarvester
} }
/** /**
* Starts the harvesting timer. Called when the harvest begins. * Returns the statistics describing how well the various harvests of this
*/ * harvester went.
public void startHarvestTiming()
{
this.harvestingTimeStat.startHarvestTiming();
}
/**
* Stops the harvesting timer. Called when the harvest ends.
*/
public void stopHarvestTiming()
{
this.harvestingTimeStat.stopHarvestTiming();
}
/**
* Returns the current harvesting time in ms. If this harvester is not
* currently harvesting, then returns the value of the last harvesting time.
* 0 if this harvester has nerver harvested.
* *
* @return The current harvesting time in ms. If this harvester is not * @return The {@link HarvestStatistics} describing this harvester's
* currently harvesting, then returns the value of the last harvesting time. * harvests.
* 0 if this harvester has nerver harvested.
*/ */
public long getHarvestingTime() public HarvestStatistics getHarvestStatistics()
{ {
return this.harvestingTimeStat.getHarvestingTime(); return harvestStatistics;
}
/**
* Returns the number of harvesting for this harvester.
*
* @return The number of harvesting for this harvester.
*/
public int getNbHarvesting()
{
return this.harvestingTimeStat.getNbHarvesting();
} }
} }

View File

@ -160,8 +160,12 @@ public class StunCandidateHarvest
{ {
if (!candidates.contains(candidate)) if (!candidates.contains(candidate))
{ {
hostCandidate.getParentComponent().addLocalCandidate(candidate); //try to add the candidate to the component and then only add it to
candidates.add(candidate); //the harvest if it wasn't deemed redundant
if( hostCandidate.getParentComponent().addLocalCandidate(candidate))
{
candidates.add(candidate);
}
} }
} }

View File

@ -263,10 +263,15 @@ public class StunCandidateHarvester
} }
} }
} }
completedHarvests.clear();
} }
logger.finest( logger.finest(
"Completed " + component.toShortString() + " harvest: " + toString() "Completed " + component.toShortString() + " harvest: " + toString()
+ ". Found " + candidates.size() + " candidates."); + ". Found " + candidates.size() + " candidates.");
return candidates; return candidates;
} }

View File

@ -0,0 +1,49 @@
/*
* 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.harvest;
import org.ice4j.ice.*;
import java.util.*;
/**
* We use this callback to feed candidates to ice4j user applications that
* support trickle ICE. The interface provides two methods that allow passing
* candidates to applications either one-by-one or in batches. The former would
* typically be used for harvesters such as STUN, where candidates are learned
* one per message. Discovering batches of candidates is possible when querying
* a TURN server, which in many cases would return both server reflexive (STUN)
* and relayed (TURN) candidates.
*
* @author Emil Ivov
*/
public interface TrickleCallback
{
/**
* Notifies the callback that a new batch of <tt>LocalCandidate</tt>s has
* been discovered and should be advertised to the remove party.
*
* @param iceCandidates the newly discovered list of candidates or,
* similarly to WebRTC, <tt>null</tt> in case all candidate harvesting is
* now completed.
*/
public void onIceCandidates(Collection<LocalCandidate> iceCandidates);
/**
* Notifies the callback that harvesting has completed for a specific
* stream. This may allow for optimizations in cases where all checks for
* a specific stream have failed and no candidate has been found, so a
* failure is due and we wouldn't won't to waist any more time.
*
* @param stream the {@link IceMediaStream}, for which we have just
* completed harvesting.
*/
// we don't currently support this but we might do it one day.
//public void streamCompleted(IceMediaStream stream);
}

View File

@ -80,7 +80,7 @@ public class UPNPHarvester
Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>(); Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>();
int retries = 0; int retries = 0;
logger.info("Begin UPnP harvesting"); logger.fine("Begin UPnP harvesting");
try try
{ {
if(device == null) if(device == null)
@ -146,8 +146,7 @@ public class UPNPHarvester
"ice4j.org: " + port)) "ice4j.org: " + port))
{ {
List<LocalCandidate> cands = createUPNPCandidate(socket, List<LocalCandidate> cands = createUPNPCandidate(socket,
localAddress, externalIPAddress, externalPort, externalIPAddress, externalPort, component, device);
component, device);
logger.info("Add UPnP port mapping: " + logger.info("Add UPnP port mapping: " +
externalIPAddress + " " + externalPort); externalIPAddress + " " + externalPort);
@ -158,8 +157,12 @@ public class UPNPHarvester
// UPNPCandidate // UPNPCandidate
for(LocalCandidate cand : cands) for(LocalCandidate cand : cands)
{ {
component.addLocalCandidate(cand); //try to add the candidate to the component and then
candidates.add(cand); //only add it to the harvest not redundant
if(component.addLocalCandidate(cand))
{
candidates.add(cand);
}
} }
break; break;
@ -188,7 +191,6 @@ public class UPNPHarvester
* Create a UPnP candidate. * Create a UPnP candidate.
* *
* @param socket local socket * @param socket local socket
* @param localAddr local host address
* @param externalIP external IP address * @param externalIP external IP address
* @param port local port * @param port local port
* @param cmp parent component * @param cmp parent component
@ -198,8 +200,7 @@ public class UPNPHarvester
* @throws Exception if something goes wrong during candidate creation * @throws Exception if something goes wrong during candidate creation
*/ */
public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket, public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
InetAddress localAddr, String externalIP, int port, Component cmp, String externalIP, int port, Component cmp, GatewayDevice device)
GatewayDevice device)
throws Exception throws Exception
{ {
List<LocalCandidate> ret = new ArrayList<LocalCandidate>(); List<LocalCandidate> ret = new ArrayList<LocalCandidate>();
@ -292,4 +293,17 @@ public class UPNPHarvester
} }
} }
} }
/**
* Returns a <tt>String</tt> representation of this harvester containing its
* name.
*
* @return a <tt>String</tt> representation of this harvester containing its
* name.
*/
@Override
public String toString()
{
return getClass().getSimpleName();
}
} }

View File

@ -6,7 +6,6 @@
*/ */
package org.ice4j.ice.sdp; package org.ice4j.ice.sdp;
import gov.nist.javax.sdp.fields.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
@ -42,6 +41,22 @@ public class IceSdpUtils
*/ */
public static final String ICE_OPTION_TRICKLE = "trickle"; public static final String ICE_OPTION_TRICKLE = "trickle";
/**
* The name of the "mid" SDP attribute.
*/
public static final String MID = "mid";
/**
* The name of the SDP attribute that contains RTCP address and port.
*/
private static final String RTCP = "rtcp";
/**
* The name of the SDP attribute that indicates an end of candidate
* trickling: "end-of-candidates".
*/
private static final String END_OF_CANDIDATES = "end-of-candidates";
/** /**
* A reference to the currently valid SDP factory instance. * A reference to the currently valid SDP factory instance.
*/ */
@ -115,40 +130,67 @@ public class IceSdpUtils
public static void initMediaDescription(MediaDescription mediaDescription, public static void initMediaDescription(MediaDescription mediaDescription,
IceMediaStream iceMediaStream) IceMediaStream iceMediaStream)
{ {
for(Component component : iceMediaStream.getComponents()) try
{ {
//first add the candidates //set mid-s
for(Candidate<?> candidate : component.getLocalCandidates()) mediaDescription.setAttribute(MID, iceMediaStream.getName());
Component firstComponent = null;
//add candidates
for(Component component : iceMediaStream.getComponents())
{ {
mediaDescription.addAttribute( //if this is the first component, remember it so that we can
new CandidateAttribute(candidate)); //later use it for default candidates.
if(firstComponent == null)
firstComponent = component;
for(Candidate<?> candidate : component.getLocalCandidates())
{
mediaDescription.addAttribute(
new CandidateAttribute(candidate));
}
} }
//set the default candidate //set the default candidate
try TransportAddress defaultAddress = firstComponent
.getDefaultCandidate().getTransportAddress();
mediaDescription.getMedia().setMediaPort(
defaultAddress.getPort());
String addressFamily = defaultAddress.isIPv6()
? Connection.IP6
: Connection.IP4;
mediaDescription.setConnection(sdpFactory.createConnection(
"IN", defaultAddress.getHostAddress(), addressFamily));
//now check if the RTCP port for the default candidate is different
//than RTP.port +1, in which case we need to mention it.
Component rtcpComponent
= iceMediaStream.getComponent(Component.RTCP);
if( rtcpComponent != null )
{ {
TransportAddress defaultAddress TransportAddress defaultRtcpCandidate = rtcpComponent
= component.getDefaultCandidate().getTransportAddress(); .getDefaultCandidate().getTransportAddress();
mediaDescription.getMedia().setMediaPort( if(defaultRtcpCandidate.getPort() != defaultAddress.getPort()+1)
defaultAddress.getPort()); {
mediaDescription.setAttribute(
String addressFamily = defaultAddress.isIPv6() RTCP, Integer.toString(defaultRtcpCandidate.getPort()));
? 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);
} }
} }
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);
}
} }
/** /**
@ -159,10 +201,14 @@ public class IceSdpUtils
* the specified agent. * the specified agent.
* @param agent the {@link Agent} that we need to use when initializing * @param agent the {@link Agent} that we need to use when initializing
* the session description. * the session description.
*
* @throws IllegalArgumentException Obviously, if there's a problem with
* the arguments ... duh!
*/ */
@SuppressWarnings("unchecked") // jain-sdp legacy @SuppressWarnings("unchecked") // jain-sdp legacy
public static void initSessionDescription(SessionDescription sDes, public static void initSessionDescription(SessionDescription sDes,
Agent agent) Agent agent)
throws IllegalArgumentException
{ {
//now add ICE options //now add ICE options
StringBuilder allOptionsBuilder = new StringBuilder(); StringBuilder allOptionsBuilder = new StringBuilder();
@ -244,4 +290,47 @@ public class IceSdpUtils
setIceCredentials( setIceCredentials(
sDes, agent.getLocalUfrag(), agent.getLocalPassword()); sDes, agent.getLocalUfrag(), agent.getLocalPassword());
} }
/**
* Generates and returns a set of attributes that can be used for a trickle
* update, such as a SIP INFO, with the specified <tt>localCandidates</tt>.
*
* @param localCandidates the list of {@link LocalCandidate}s that we'd like
* to generate the update for.
*
* @return a collection of {@link CandidateAttribute}s and an MID attribute
* that we can use in a SIP INFO trickle update.
*/
public static Collection<Attribute> createTrickleUpdate(
Collection<LocalCandidate> localCandidates)
{
List<Attribute> trickleUpdate = null;
if(localCandidates == null || localCandidates.size() == 0)
{
trickleUpdate = new ArrayList<Attribute>(1);
trickleUpdate.add(
sdpFactory.createAttribute(END_OF_CANDIDATES, null));
return trickleUpdate;
}
trickleUpdate
= new ArrayList<Attribute>(localCandidates.size() + 1);
String streamName = null;
for(LocalCandidate candidate : localCandidates)
{
streamName = candidate.getParentComponent()
.getParentStream().getName();
trickleUpdate.add(new CandidateAttribute(candidate));
}
trickleUpdate.add(0, sdpFactory.createAttribute(MID, streamName));
return trickleUpdate;
}
} }

View File

@ -251,8 +251,8 @@ public class Ice
} }
/** /**
* Creates an ICE <tt>Agent</tt> and adds to it an audio and a video stream * Creates a vanilla ICE <tt>Agent</tt> and adds to it an audio and a video
* with RTP and RTCP components. * stream with RTP and RTCP components.
* *
* @param rtpPort the port that we should try to bind the RTP component on * @param rtpPort the port that we should try to bind the RTP component on
* (the RTCP one would automatically go to rtpPort + 1) * (the RTCP one would automatically go to rtpPort + 1)
@ -263,16 +263,36 @@ public class Ice
*/ */
protected static Agent createAgent(int rtpPort) protected static Agent createAgent(int rtpPort)
throws Throwable throws Throwable
{
return createAgent(rtpPort, false);
}
/**
* Creates an ICE <tt>Agent</tt> (vanilla or trickle, depending on the
* value of <tt>isTrickling</tt>) and adds to it an audio and a video stream
* with RTP and RTCP components.
*
* @param rtpPort the port that we should try to bind the RTP component on
* (the RTCP one would automatically go to rtpPort + 1)
* @return an ICE <tt>Agent</tt> with an audio stream with RTP and RTCP
* components.
* @param isTrickling indicates whether the newly created agent should be
* performing trickle ICE.
*
* @throws Throwable if anything goes wrong.
*/
protected static Agent createAgent(int rtpPort, boolean isTrickling)
throws Throwable
{ {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
Agent agent = new Agent(); Agent agent = new Agent();
agent.setTrickling(isTrickling);
// STUN // STUN
StunCandidateHarvester stunHarv = new StunCandidateHarvester( StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("stun.jitsi.net", 3478, Transport.UDP)); new TransportAddress("stun.jitsi.net", 3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester( StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("stun6.jitsi.net", new TransportAddress("stun6.jitsi.net", 3478, Transport.UDP));
3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv); agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv); agent.addCandidateHarvester(stun6Harv);
@ -311,7 +331,7 @@ public class Ice
} }
/** /**
* Creates an <tt>IceMediaStrean</tt> and adds to it an RTP and and RTCP * Creates an <tt>IceMediaStream</tt> and adds to it an RTP and and RTCP
* component. * component.
* *
* @param rtpPort the port that we should try to bind the RTP component on * @param rtpPort the port that we should try to bind the RTP component on

207
test/test/SdpUtils.java Normal file
View File

@ -0,0 +1,207 @@
/*
* 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 test;
import java.util.*;
import java.util.StringTokenizer;
import javax.sdp.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.ice.Agent;
import org.ice4j.ice.sdp.*;
/**
* Utilities for manipulating SDP. Some of the utilities in 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. This method is unlikely to be of use
* to integrating applications as they would likely just want to feed a
* {@link MediaDescription} and have it populated with all the necessary
* attributes.
*
* @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();
IceSdpUtils.initSessionDescription(sdess, agent);
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;
}
}

146
test/test/TrickleIce.java Normal file
View File

@ -0,0 +1,146 @@
/*
* 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 org.ice4j.ice.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.ice.sdp.*;
import javax.sdp.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
/**
* An example of using trickle ICE.
* <p>
* @author Emil Ivov
*/
public class TrickleIce
extends Ice
{
/**
* The <tt>Logger</tt> used by the <tt>TrickleIce</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(TrickleIce.class.getName());
/**
* Runs a test application that allocates streams, generates an SDP, dumps
* it on stdout, waits for a remote peer SDP on stdin, then feeds that
* to our local agent and starts ICE processing.
*
* @param args none currently handled
* @throws Throwable every now and then.
*/
public static void main(String[] args) throws Throwable
{
Agent localAgent = createAgent(2020, true);
localAgent.setNominationStrategy(
NominationStrategy.NOMINATE_HIGHEST_PRIO);
localAgent.addStateChangeListener(new IceProcessingListener());
//let them fight ... fights forge character.
localAgent.setControlling(false);
String localSDP = SdpUtils.createSDPDescription(localAgent);
//wait a bit so that the logger can stop dumping stuff:
Thread.sleep(500);
System.err.println("=================== feed the following"
+" to the remote agent ===================");
System.err.println(localSDP);
System.err.println("======================================"
+ "========================================\n");
CandidatePrinter printer = new CandidatePrinter();
printer.agent = localAgent;
localAgent.startCandidateTrickle(printer);
List<Component> allComponents = new LinkedList<Component>();
int allCandidates = 0;
for (IceMediaStream stream : localAgent.getStreams())
{
for(Component component : stream.getComponents())
{
allComponents.add(component);
allCandidates += component.getLocalCandidateCount();
}
}
System.out.println("all candidates = " + allCandidates);
String sdp = IceDistributed.readSDP();
startTime = System.currentTimeMillis();
SdpUtils.parseSDP(localAgent, sdp);
localAgent.startConnectivityEstablishment();
//Give processing enough time to finish. We'll System.exit() anyway
//as soon as localAgent enters a final state.
Thread.sleep(60000);
}
static class CandidatePrinter implements TrickleCallback
{
/**
* Number of candidates that we have seen.
*/
static int candidateCounter = 0;
/**
* The ICE agent that's running the show.
*/
Agent agent;
/**
* Converts every trickled candidate to SDP and prints it on stdout.
*
* @param iceCandidates the newly discovered list of candidates or,
* similarly to WebRTC, <tt>null</tt> in case all candidate harvesting
* is now completed.
*/
public void onIceCandidates(Collection<LocalCandidate> iceCandidates)
{
if( iceCandidates != null)
candidateCounter++ ;
Collection<Attribute> update
= IceSdpUtils.createTrickleUpdate(iceCandidates);
for(Attribute attribute : update)
{
System.err.print(attribute);
}
if(iceCandidates == null)
{
try{Thread.sleep(1000);}catch(Exception e){};
System.err.println("ICE stats: time="
+ agent.getTotalHarvestingTime() + "ms");
//print statistics
for (CandidateHarvester harvester : agent.getHarvesters())
{
System.err.println(harvester.getHarvestStatistics());
}
}
}
}
}