diff --git a/build.xml b/build.xml index 9609cf6..c7bb8b7 100644 --- a/build.xml +++ b/build.xml @@ -156,7 +156,7 @@ - + + + + + + + + + + FoundationsRegistry 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 Agent 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 trickleCallback. * - * @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 components = new LinkedList(); + + 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 /** * Free()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 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 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; } } diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index 7749068..df95815 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -139,8 +139,12 @@ public class Component * registered with the agent. * * @param candidate the candidate object to be added + * + * @return true if we actually added the new candidate or + * false 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 Component with the specified - * Candidate. + * Candidates. This would happen when performing trickle ICE. * * @param candidate new Candidate 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 Candidates. + * Update ICE processing with new Candidates. */ - public void updateRemoteCandidate() + public void updateRemoteCandidates() { List checkList = null; @@ -580,14 +600,15 @@ public class Component * Computes the priorities of all Candidates 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 cand. + * 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 cand or + * null 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 Candidate that has been selected as the default * for this Component or null if no such diff --git a/src/org/ice4j/ice/TrickleCallback.java b/src/org/ice4j/ice/TrickleCallback.java deleted file mode 100644 index 3fd43c5..0000000 --- a/src/org/ice4j/ice/TrickleCallback.java +++ /dev/null @@ -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 -{ -} diff --git a/src/org/ice4j/ice/harvest/CandidateHarvester.java b/src/org/ice4j/ice/harvest/CandidateHarvester.java index 2bc0df6..3d03b43 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvester.java @@ -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 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; } } diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java index 8cc17ba..8dc8360 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSet.java @@ -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 Component using - * specific CandidateHarvesters. + * Gathers candidate addresses for a specific Component. + * CandidateHarvesterSet delegates to the + * CandidateHarvesters which are its Set elements. * - * @param harvesters the CandidateHarvesters to gather candidate - * addresses for the specified Component - * @param component the Component to gather candidate addresses for - * @param executorService the ExecutorService to schedule the - * execution of the gathering of candidate addresses performed by the - * specified harvesters + * @param components the Component to gather candidate addresses for + * @see CandidateHarvester#harvest(Component) + * @param trickleCallback the {@link TrickleCallback} that we will be + * feeding candidates to, or null in case the application doesn't + * want us trickling any candidates */ - private void harvest( - final Iterator harvesters, - final Component component, - ExecutorService executorService) + public void harvest(final List 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 ExecutorService to schedule the * execution of the gathering of candidate addresses performed by the * specified harvesters + * @param trickleCallback the {@link TrickleCallback} that we will be + * feeding candidates to, or null in case the application doesn't + * want us trickling any candidates */ private void harvest( final Iterator harvesters, - final List components, - ExecutorService executorService) + final List components, + ExecutorService executorService, + final TrickleCallback trickleCallback) { /* * Start asynchronously executing the @@ -164,14 +164,11 @@ public class CandidateHarvesterSet componentsCopy = new ArrayList(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)); } /* diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java index 559720d..782d471 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSetElement.java @@ -17,7 +17,7 @@ import java.util.logging.*; * CandidateHarvesterSet. * * @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 CandidateHarvester if enabled. * * @param component the Component to gather candidates for + * @param trickleCallback the {@link TrickleCallback} that we will be + * feeding candidates to, or null 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 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 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 harvest) + { + harvester.getHarvestStatistics().stopHarvestTiming(harvest); + } } \ No newline at end of file diff --git a/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java b/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java index 966ff40..32e82fd 100644 --- a/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java +++ b/src/org/ice4j/ice/harvest/CandidateHarvesterSetTask.java @@ -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 components; + + /** + * The callback that we will be notifying every time a harvester completes. + */ + private final TrickleCallback trickleCallback; /** * Initializes a new CandidateHarvesterSetTask which is to @@ -48,18 +55,18 @@ class CandidateHarvesterSetTask * * @param harvester the CandidateHarvester on which the * new instance is to call + * @param components the Component whose candidates we are currently + * gathering. * CandidateHarvester#harvest(Component) first */ - - java.util.Iterator harvesters; public CandidateHarvesterSetTask( CandidateHarvesterSetElement harvester, - Component component, - java.util.Iterator harvesters) + Collection 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) { diff --git a/src/org/ice4j/ice/harvest/HarvestStatistics.java b/src/org/ice4j/ice/harvest/HarvestStatistics.java new file mode 100644 index 0000000..36a3cc0 --- /dev/null +++ b/src/org/ice4j/ice/harvest/HarvestStatistics.java @@ -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 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() ; + } +} diff --git a/src/org/ice4j/ice/harvest/HarvestingTimeStat.java b/src/org/ice4j/ice/harvest/HarvestingTimeStat.java deleted file mode 100644 index 626ef25..0000000 --- a/src/org/ice4j/ice/harvest/HarvestingTimeStat.java +++ /dev/null @@ -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; - } -} diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index eb3e8f6..6cbef74 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -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 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; } } diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java index e8a7ede..fa5739e 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java @@ -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); + } } } diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java index 816db78..9488af4 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -263,10 +263,15 @@ public class StunCandidateHarvester } } } + + completedHarvests.clear(); } + logger.finest( "Completed " + component.toShortString() + " harvest: " + toString() + ". Found " + candidates.size() + " candidates."); + + return candidates; } diff --git a/src/org/ice4j/ice/harvest/TrickleCallback.java b/src/org/ice4j/ice/harvest/TrickleCallback.java new file mode 100644 index 0000000..dfbce68 --- /dev/null +++ b/src/org/ice4j/ice/harvest/TrickleCallback.java @@ -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 LocalCandidates has + * been discovered and should be advertised to the remove party. + * + * @param iceCandidates the newly discovered list of candidates or, + * similarly to WebRTC, null in case all candidate harvesting is + * now completed. + */ + public void onIceCandidates(Collection 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); +} diff --git a/src/org/ice4j/ice/harvest/UPNPHarvester.java b/src/org/ice4j/ice/harvest/UPNPHarvester.java index a0c5380..ddbe27a 100644 --- a/src/org/ice4j/ice/harvest/UPNPHarvester.java +++ b/src/org/ice4j/ice/harvest/UPNPHarvester.java @@ -80,7 +80,7 @@ public class UPNPHarvester Collection candidates = new HashSet(); 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 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 createUPNPCandidate(IceSocketWrapper socket, - InetAddress localAddr, String externalIP, int port, Component cmp, - GatewayDevice device) + String externalIP, int port, Component cmp, GatewayDevice device) throws Exception { List ret = new ArrayList(); @@ -292,4 +293,17 @@ public class UPNPHarvester } } } + + /** + * Returns a String representation of this harvester containing its + * name. + * + * @return a String representation of this harvester containing its + * name. + */ + @Override + public String toString() + { + return getClass().getSimpleName(); + } } diff --git a/src/org/ice4j/ice/sdp/IceSdpUtils.java b/src/org/ice4j/ice/sdp/IceSdpUtils.java index 66ed19c..6bc3927 100644 --- a/src/org/ice4j/ice/sdp/IceSdpUtils.java +++ b/src/org/ice4j/ice/sdp/IceSdpUtils.java @@ -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 localCandidates. + * + * @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 createTrickleUpdate( + Collection localCandidates) + { + List trickleUpdate = null; + + if(localCandidates == null || localCandidates.size() == 0) + { + trickleUpdate = new ArrayList(1); + trickleUpdate.add( + sdpFactory.createAttribute(END_OF_CANDIDATES, null)); + + return trickleUpdate; + } + + trickleUpdate + = new ArrayList(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; + } } diff --git a/test/test/Ice.java b/test/test/Ice.java index 4d45a7e..5c7953e 100644 --- a/test/test/Ice.java +++ b/test/test/Ice.java @@ -251,8 +251,8 @@ public class Ice } /** - * Creates an ICE Agent and adds to it an audio and a video stream - * with RTP and RTCP components. + * Creates a vanilla ICE Agent 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 Agent (vanilla or trickle, depending on the + * value of isTrickling) 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 Agent 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 IceMediaStrean and adds to it an RTP and and RTCP + * Creates an IceMediaStream and adds to it an RTP and and RTCP * component. * * @param rtpPort the port that we should try to bind the RTP component on diff --git a/test/test/SdpUtils.java b/test/test/SdpUtils.java new file mode 100644 index 0000000..4ae05da --- /dev/null +++ b/test/test/SdpUtils.java @@ -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 do + * not 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 + * agent 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 agent'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 localAgent the the remote peer streams, components, + * and candidates specified in sdp + * + * @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 mdescs = sdess.getMediaDescriptions(true); + + for (MediaDescription desc : mdescs) + { + String streamName = desc.getMedia().getMediaType(); + + IceMediaStream stream = localAgent.getStream(streamName); + + if(stream == null) + continue; + + Vector 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 attribute. + * + * @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 attribute or null 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; + } + + +} diff --git a/test/test/TrickleIce.java b/test/test/TrickleIce.java new file mode 100644 index 0000000..05c498a --- /dev/null +++ b/test/test/TrickleIce.java @@ -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. + *

+ * @author Emil Ivov + */ +public class TrickleIce + extends Ice +{ + /** + * The Logger used by the TrickleIce + * 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 allComponents = new LinkedList(); + 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, null in case all candidate harvesting + * is now completed. + */ + public void onIceCandidates(Collection iceCandidates) + { + if( iceCandidates != null) + candidateCounter++ ; + + Collection 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()); + } + + + + } + } + } + +}