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>
</target>
<!-- runs our sample distributed application -->
<!-- runs our sample application -->
<target name="run-sample">
<java fork="true"
classname="test.Ice"
@ -208,6 +208,18 @@
</java>
</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 -->
<target name="run-lite">
<java fork="true"

View File

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

View File

@ -17,6 +17,7 @@ import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.ice.harvest.TrickleCallback;
import org.ice4j.stack.*;
/**
@ -92,7 +93,7 @@ public class Agent
/**
* 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
@ -221,13 +222,20 @@ public class Agent
/**
* Determines whether this agent should perform trickling.
*/
private boolean trickle = true;
private boolean trickle = false;
/**
* Indicates that ICE will be shutdown.
*/
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.
@ -440,8 +448,6 @@ public class Agent
logger.info("Gather candidates for component " +
component.toShortString());
this.startHarvestTiming();
hostCandidateHarvester.harvest(
component,
preferredPort, minPort, maxPort, Transport.UDP);
@ -458,24 +464,20 @@ public class Agent
//in case we are not trickling, apply other harvesters here
if(!isTrickling())
{
harvestingStarted = true; //raise a flag to warn on a second call.
harvesters.harvest(component);
}
this.stopHarvestTiming();
logger.info(
"Harvest for " + component.toShortString() + " completed in "
+ this.getTotalHarvestingTime() + " ms.");
logger.fine("host+harvested candidate count: " +
logger.fine("Candidate count in first harvest: " +
component.getLocalCandidateCount());
//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.
//Emil: because of trickle we now assign foundations, compute priorities
//and eliminate redundancies while adding candidates on a component.
// This means that we no longer need to do it here, where we did before.
//computeFoundations(component);
//component.prioritizeCandidates();
//eliminate redundant candidates
component.eliminateRedundantCandidates();
//component.eliminateRedundantCandidates();
//select the candidate to put in the media line.
component.selectDefaultCandidate();
@ -485,11 +487,39 @@ public class Agent
* Starts an asynchronous harvest across all components and reports newly
* 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)
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
* 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()
{
@ -736,6 +767,16 @@ public class Agent
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
* containing ICE data from this agent.
@ -2292,26 +2333,17 @@ public class Agent
* @param harvesterName The class name if the harvester.
*
* @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)
{
if(this.hostCandidateHarvester.getClass().getName().endsWith(
harvesterName))
{
return this.hostCandidateHarvester.getHarvestingTime();
}
long harvestingTime = 0;
CandidateHarvester tmpHarvester;
Iterator<CandidateHarvester> itHarvesters = this.harvesters.iterator();
while(itHarvesters.hasNext())
for(CandidateHarvester harvester : harvesters)
{
tmpHarvester = itHarvesters.next();
if(tmpHarvester.getClass().getName().endsWith(harvesterName))
if(harvester.getClass().getName().endsWith(harvesterName))
{
harvestingTime = tmpHarvester.getHarvestingTime();
harvestingTime = harvester.getHarvestStatistics()
.getHarvestDuration();
// There may be several harvester with the same class name.
// Thus, returns only an active one (if any).
if(harvestingTime != 0)
@ -2333,28 +2365,21 @@ public class Agent
* @return The number of harvesting time for the harvester given in
* parameter.
*/
public int getNbHarvesting(String harvesterName)
public int getHarvestCount(String harvesterName)
{
if(this.hostCandidateHarvester.getClass().getName().endsWith(
harvesterName))
{
return this.hostCandidateHarvester.getNbHarvesting();
}
int harvestCount;
int nbHarvesting = 0;
CandidateHarvester tmpHarvester;
Iterator<CandidateHarvester> itHarvesters = this.harvesters.iterator();
while(itHarvesters.hasNext())
for(CandidateHarvester harvester : harvesters)
{
tmpHarvester = itHarvesters.next();
if(tmpHarvester.getClass().getName().endsWith(harvesterName))
if(harvester.getClass().getName().endsWith(harvesterName))
{
nbHarvesting = tmpHarvester.getNbHarvesting();
harvestCount
= harvester.getHarvestStatistics().getHarvestCount();
// There may be several harvester with the same class name.
// 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.
*/
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.
* Returns the combined harvesting time for all harvesters in this agent.
*
* @return 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 total time this agent has spent harvesting.
*/
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.
*
* @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();
@ -161,8 +165,24 @@ public class Component
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);
//we are done adding ... now let's just order by priority.
Collections.sort(localCandidates);
return true;
}
}
@ -240,11 +260,11 @@ public class Component
/**
* 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.
*/
public void addUpdateRemoteCandidate(RemoteCandidate candidate)
public void addUpdateRemoteCandidates(RemoteCandidate candidate)
{
logger.info("Update remote candidate for " + toShortString() + ": " +
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;
@ -580,14 +600,15 @@ 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
* @deprecated candidates are now being prioritized upon addition and
* calling this method is no longer necessary.
*/
@Deprecated
protected void prioritizeCandidates()
{
synchronized(localCandidates)
{
CompatibilityMode compat = getParentStream().getParentAgent()
CompatibilityMode compatibility = getParentStream().getParentAgent()
.getCompatibilityMode();
LocalCandidate[] candidates
@ -598,7 +619,7 @@ public class Component
//first compute the actual priorities
for (Candidate<?> cand : candidates)
{
if(compat == CompatibilityMode.GTALK)
if(compatibility == CompatibilityMode.GTALK)
{
cand.computeGTalkPriority();
}
@ -628,7 +649,11 @@ public class Component
* 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.
*
* @deprecated redundancies are now being detected upon addition of
* candidates and calling this method is no longer necessary.
*/
@Deprecated
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
* 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
{
/**
* 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
@ -45,42 +45,14 @@ public abstract class CandidateHarvester
public abstract Collection<LocalCandidate> harvest(Component component);
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
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.
* Returns the statistics describing how well the various harvests of this
* harvester went.
*
* @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.
* @return The {@link HarvestStatistics} describing this harvester's
* harvests.
*/
public long getHarvestingTime()
public HarvestStatistics getHarvestStatistics()
{
return this.harvestingTimeStat.getHarvestingTime();
}
/**
* Returns the number of harvesting for this harvester.
*
* @return The number of harvesting for this harvester.
*/
public int getNbHarvesting()
{
return this.harvestingTimeStat.getNbHarvesting();
return harvestStatistics;
}
}

View File

@ -85,33 +85,29 @@ public class CandidateHarvesterSet
*/
public void harvest(Component component)
{
synchronized (elements)
{
harvest(elements.iterator(), component, threadPool);
}
harvest(Arrays.asList(new Component[]{component}), null);
}
/**
* Gathers candidate addresses for a specific <tt>Component</tt> using
* specific <tt>CandidateHarvester</tt>s.
* Gathers candidate addresses for a specific <tt>Component</tt>.
* <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
* addresses for the specified <tt>Component</tt>
* @param component the <tt>Component</tt> 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>
* @param components the <tt>Component</tt> to gather candidate addresses for
* @see CandidateHarvester#harvest(Component)
* @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(
final Iterator<CandidateHarvesterSetElement> harvesters,
final Component component,
ExecutorService executorService)
public void harvest(final List<Component> components,
TrickleCallback trickleCallback)
{
harvest(harvesters,
Arrays.asList(new Component[]{component}),
executorService);
synchronized (elements)
{
harvest(
elements.iterator(), components, threadPool, trickleCallback);
}
}
/**
@ -125,11 +121,15 @@ public class CandidateHarvesterSet
* @param executorService the <tt>ExecutorService</tt> to schedule the
* execution of the gathering of candidate addresses performed by the
* 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(
final Iterator<CandidateHarvesterSetElement> harvesters,
final List<Component> components,
ExecutorService executorService)
final List<Component> components,
ExecutorService executorService,
final TrickleCallback trickleCallback)
{
/*
* Start asynchronously executing the
@ -164,14 +164,11 @@ public class CandidateHarvesterSet
componentsCopy = new ArrayList<Component>(components);
}
for(Component component : componentsCopy)
{
// Asynchronously start gathering candidates using the harvester.
CandidateHarvesterSetTask task = new CandidateHarvesterSetTask(
harvester, component, harvesters);
// Asynchronously start gathering candidates using the harvester.
CandidateHarvesterSetTask task = new CandidateHarvesterSetTask(
harvester, componentsCopy, trickleCallback);
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>.
*
* @author Lyubomir Marinov
* @author Emil Ivov
* @author Emil Ivov
*/
class CandidateHarvesterSetElement
{
@ -53,6 +53,7 @@ class CandidateHarvesterSetElement
public CandidateHarvesterSetElement(CandidateHarvester harvester)
{
this.harvester = harvester;
harvester.getHarvestStatistics().harvesterName = harvester.toString();
}
/**
@ -60,30 +61,36 @@ class CandidateHarvesterSetElement
* associated <tt>CandidateHarvester</tt> if <tt>enabled</tt>.
*
* @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())
{
harvester.startHarvestTiming();
Collection<LocalCandidate> candidates
= harvester.harvest(component);
harvester.stopHarvestTiming();
if (!isEnabled())
return;
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);
startHarvestTiming();
Collection<LocalCandidate> candidates = harvester.harvest(component);
stopHarvestTiming(candidates);
/*
* 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);
}
else if(trickleCallback != null)
{
trickleCallback.onIceCandidates(candidates);
}
}
/**
@ -139,4 +146,22 @@ class CandidateHarvesterSetElement
{
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 java.util.*;
import java.util.logging.*;
/**
@ -37,9 +38,15 @@ class CandidateHarvesterSetTask
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
@ -48,18 +55,18 @@ class CandidateHarvesterSetTask
*
* @param harvester the <tt>CandidateHarvester</tt> on which the
* new instance is to call
* @param components the <tt>Component</tt> whose candidates we are currently
* gathering.
* <tt>CandidateHarvester#harvest(Component)</tt> first
*/
java.util.Iterator<CandidateHarvesterSetElement> harvesters;
public CandidateHarvesterSetTask(
CandidateHarvesterSetElement harvester,
Component component,
java.util.Iterator<CandidateHarvesterSetElement> harvesters)
Collection<Component> components,
TrickleCallback trickleCallback)
{
this.harvester = harvester;
this.component = component;
this.harvesters = harvesters;
this.components = components;
this.trickleCallback = trickleCallback;
}
/**
@ -80,11 +87,14 @@ class CandidateHarvesterSetTask
*/
public void run()
{
if (harvester.isEnabled())
if (harvester == null || !harvester.isEnabled())
return;
for (Component component : components)
{
try
{
harvester.harvest(component);
harvester.harvest(component, trickleCallback);
}
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.
*/
private HarvestingTimeStat harvestingTimeStat = new HarvestingTimeStat();
private HarvestStatistics harvestStatistics = new HarvestStatistics();
/**
* Gathers all candidate addresses on the local machine, binds sockets on
@ -69,7 +69,7 @@ public class HostCandidateHarvester
throws IllegalArgumentException,
IOException
{
this.startHarvestTiming();
harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
@ -177,11 +177,8 @@ public class HostCandidateHarvester
+ " maxPort=" + maxPort);
}
this.stopHarvestTiming();
logger.info(
"Completed " + component.toShortString() + " harvest with "
+ getClass().getSimpleName() + " in " + getHarvestingTime()
+ " ms. Candidates found: " + component.getLocalCandidateCount());
this.harvestStatistics
.stopHarvestTiming(component.getLocalCandidateCount());
}
/**
@ -406,42 +403,14 @@ public class HostCandidateHarvester
}
/**
* Starts the harvesting timer. Called when the harvest begins.
*/
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.
* Returns the statistics describing how well the various harvests of this
* harvester went.
*
* @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.
* @return The {@link HarvestStatistics} describing this harvester's
* harvests.
*/
public long getHarvestingTime()
public HarvestStatistics getHarvestStatistics()
{
return this.harvestingTimeStat.getHarvestingTime();
}
/**
* Returns the number of harvesting for this harvester.
*
* @return The number of harvesting for this harvester.
*/
public int getNbHarvesting()
{
return this.harvestingTimeStat.getNbHarvesting();
return harvestStatistics;
}
}

View File

@ -160,8 +160,12 @@ public class StunCandidateHarvest
{
if (!candidates.contains(candidate))
{
hostCandidate.getParentComponent().addLocalCandidate(candidate);
candidates.add(candidate);
//try to add the candidate to the component and then only add it to
//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(
"Completed " + component.toShortString() + " harvest: " + toString()
+ ". Found " + candidates.size() + " 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>();
int retries = 0;
logger.info("Begin UPnP harvesting");
logger.fine("Begin UPnP harvesting");
try
{
if(device == null)
@ -146,8 +146,7 @@ public class UPNPHarvester
"ice4j.org: " + port))
{
List<LocalCandidate> cands = createUPNPCandidate(socket,
localAddress, externalIPAddress, externalPort,
component, device);
externalIPAddress, externalPort, component, device);
logger.info("Add UPnP port mapping: " +
externalIPAddress + " " + externalPort);
@ -158,8 +157,12 @@ public class UPNPHarvester
// UPNPCandidate
for(LocalCandidate cand : cands)
{
component.addLocalCandidate(cand);
candidates.add(cand);
//try to add the candidate to the component and then
//only add it to the harvest not redundant
if(component.addLocalCandidate(cand))
{
candidates.add(cand);
}
}
break;
@ -188,7 +191,6 @@ public class UPNPHarvester
* Create a UPnP candidate.
*
* @param socket local socket
* @param localAddr local host address
* @param externalIP external IP address
* @param port local port
* @param cmp parent component
@ -198,8 +200,7 @@ public class UPNPHarvester
* @throws Exception if something goes wrong during candidate creation
*/
public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
InetAddress localAddr, String externalIP, int port, Component cmp,
GatewayDevice device)
String externalIP, int port, Component cmp, GatewayDevice device)
throws Exception
{
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;
import gov.nist.javax.sdp.fields.*;
import org.ice4j.*;
import org.ice4j.ice.*;
@ -42,6 +41,22 @@ public class IceSdpUtils
*/
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.
*/
@ -115,40 +130,67 @@ public class IceSdpUtils
public static void initMediaDescription(MediaDescription mediaDescription,
IceMediaStream iceMediaStream)
{
for(Component component : iceMediaStream.getComponents())
try
{
//first add the candidates
for(Candidate<?> candidate : component.getLocalCandidates())
//set mid-s
mediaDescription.setAttribute(MID, iceMediaStream.getName());
Component firstComponent = null;
//add candidates
for(Component component : iceMediaStream.getComponents())
{
mediaDescription.addAttribute(
new CandidateAttribute(candidate));
//if this is the first component, remember it so that we can
//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
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
= component.getDefaultCandidate().getTransportAddress();
TransportAddress defaultRtcpCandidate = rtcpComponent
.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);
if(defaultRtcpCandidate.getPort() != defaultAddress.getPort()+1)
{
mediaDescription.setAttribute(
RTCP, Integer.toString(defaultRtcpCandidate.getPort()));
}
}
}
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.
* @param agent the {@link Agent} that we need to use when initializing
* the session description.
*
* @throws IllegalArgumentException Obviously, if there's a problem with
* the arguments ... duh!
*/
@SuppressWarnings("unchecked") // jain-sdp legacy
public static void initSessionDescription(SessionDescription sDes,
Agent agent)
throws IllegalArgumentException
{
//now add ICE options
StringBuilder allOptionsBuilder = new StringBuilder();
@ -244,4 +290,47 @@ public class IceSdpUtils
setIceCredentials(
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
* with RTP and RTCP components.
* Creates a vanilla ICE <tt>Agent</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)
@ -263,16 +263,36 @@ public class Ice
*/
protected static Agent createAgent(int rtpPort)
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();
Agent agent = new Agent();
agent.setTrickling(isTrickling);
// STUN
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("stun.jitsi.net", 3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("stun6.jitsi.net",
3478, Transport.UDP));
new TransportAddress("stun6.jitsi.net", 3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv);
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.
*
* @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());
}
}
}
}
}