001/**
002 *
003 * Copyright 2003-2006 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.jingleold.mediaimpl.jspeex;
018
019import java.io.IOException;
020import java.net.DatagramSocket;
021import java.net.InetAddress;
022import java.net.ServerSocket;
023import java.security.GeneralSecurityException;
024import java.util.logging.Level;
025import java.util.logging.Logger;
026
027import javax.media.NoProcessorException;
028import javax.media.format.UnsupportedFormatException;
029import javax.media.rtp.rtcp.SenderReport;
030import javax.media.rtp.rtcp.SourceDescription;
031
032import org.jivesoftware.smackx.jingleold.JingleSession;
033import org.jivesoftware.smackx.jingleold.media.JingleMediaSession;
034import org.jivesoftware.smackx.jingleold.media.PayloadType;
035import org.jivesoftware.smackx.jingleold.nat.TransportCandidate;
036
037import mil.jfcom.cie.media.session.MediaSession;
038import mil.jfcom.cie.media.session.MediaSessionListener;
039import mil.jfcom.cie.media.session.StreamPlayer;
040import mil.jfcom.cie.media.srtp.packetizer.SpeexFormat;
041
042/**
043 * This Class implements a complete JingleMediaSession.
044 * It should be used to transmit and receive audio captured from the Mic.
045 * This Class should be automatically controlled by JingleSession.
046 * But you could also use in any VOIP application.
047 * For better NAT Traversal support this implementation don't support only receive or only transmit.
048 * To receive you MUST transmit. So the only implemented and functionally methods are startTransmit() and stopTransmit()
049 *
050 * @author Thiago Camargo
051 */
052
053public class AudioMediaSession extends JingleMediaSession implements MediaSessionListener {
054
055    private static final Logger LOGGER = Logger.getLogger(AudioMediaSession.class.getName());
056
057    private MediaSession mediaSession;
058
059    /**
060     * Create a Session using Speex Codec.
061     *
062     * @param localhost    localHost
063     * @param localPort    localPort
064     * @param remoteHost   remoteHost
065     * @param remotePort   remotePort
066     * @param eventHandler eventHandler
067     * @param quality      quality
068     * @param secure       secure
069     * @param micOn        micOn
070     * @return MediaSession
071     * @throws NoProcessorException
072     * @throws UnsupportedFormatException
073     * @throws IOException
074     * @throws GeneralSecurityException
075     */
076    public static MediaSession createSession(String localhost, int localPort, String remoteHost, int remotePort, MediaSessionListener eventHandler, int quality, boolean secure, boolean micOn) throws NoProcessorException, UnsupportedFormatException, IOException, GeneralSecurityException {
077
078        SpeexFormat.setFramesPerPacket(1);
079        /**
080         * The master key. Hardcoded for now.
081         */
082        byte[] masterKey = new byte[] {(byte) 0xE1, (byte) 0xF9, 0x7A, 0x0D, 0x3E, 0x01, (byte) 0x8B, (byte) 0xE0, (byte) 0xD6, 0x4F, (byte) 0xA3, 0x2C, 0x06, (byte) 0xDE, 0x41, 0x39};
083
084        /**
085         * The master salt. Hardcoded for now.
086         */
087        byte[] masterSalt = new byte[] {0x0E, (byte) 0xC6, 0x75, (byte) 0xAD, 0x49, (byte) 0x8A, (byte) 0xFE, (byte) 0xEB, (byte) 0xB6, (byte) 0x96, 0x0B, 0x3A, (byte) 0xAB, (byte) 0xE6};
088
089        DatagramSocket[] localPorts = MediaSession.getLocalPorts(InetAddress.getByName(localhost), localPort);
090        MediaSession session = MediaSession.createInstance(remoteHost, remotePort, localPorts, quality, secure, masterKey, masterSalt);
091        session.setListener(eventHandler);
092
093        session.setSourceDescription(new SourceDescription[] {new SourceDescription(SourceDescription.SOURCE_DESC_NAME, "Superman", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_EMAIL, "cdcie.tester@je.jfcom.mil", 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_LOC, InetAddress.getByName(localhost) + " Port " + session.getLocalDataPort(), 1, false), new SourceDescription(SourceDescription.SOURCE_DESC_TOOL, "JFCOM CDCIE Audio Chat", 1, false)});
094        return session;
095    }
096
097
098    /**
099     * Creates a org.jivesoftware.jingleaudio.jspeex.AudioMediaSession with defined payload type, remote and local candidates.
100     *
101     * @param payloadType Payload of the jmf
102     * @param remote      the remote information. The candidate that the jmf will be sent to.
103     * @param local       the local information. The candidate that will receive the jmf
104     * @param locator     media locator
105     */
106    public AudioMediaSession(final PayloadType payloadType, final TransportCandidate remote,
107            final TransportCandidate local, String locator, JingleSession jingleSession) {
108        super(payloadType, remote, local, locator == null ? "dsound://" : locator, jingleSession);
109        initialize();
110    }
111
112    /**
113     * Initialize the Audio Channel to make it able to send and receive audio.
114     */
115    @Override
116    public void initialize() {
117
118        String ip;
119        String localIp;
120        int localPort;
121        int remotePort;
122
123        if (this.getLocal().getSymmetric() != null) {
124            ip = this.getLocal().getIp();
125            localIp = this.getLocal().getLocalIp();
126            localPort = getFreePort();
127            remotePort = this.getLocal().getSymmetric().getPort();
128
129            LOGGER.fine(this.getLocal().getConnection() + " " + ip + ": " + localPort + "->" + remotePort);
130
131        }
132        else {
133            ip = this.getRemote().getIp();
134            localIp = this.getLocal().getLocalIp();
135            localPort = this.getLocal().getPort();
136            remotePort = this.getRemote().getPort();
137        }
138
139        try {
140            mediaSession = createSession(localIp, localPort, ip, remotePort, this, 2, false, true);
141        }
142        catch (NoProcessorException e) {
143            LOGGER.log(Level.WARNING, "exception", e);
144        }
145        catch (UnsupportedFormatException e) {
146            LOGGER.log(Level.WARNING, "exception", e);
147        }
148        catch (IOException e) {
149            LOGGER.log(Level.WARNING, "exception", e);
150        }
151        catch (GeneralSecurityException e) {
152            LOGGER.log(Level.WARNING, "exception", e);
153        }
154    }
155
156    /**
157     * Starts transmission and for NAT Traversal reasons start receiving also.
158     *
159     * @deprecated use {@link #startTransmit()} instead.
160     */
161    @Deprecated
162    public void startTrasmit() {
163        startTransmit();
164    }
165
166    /**
167     * Starts transmission and for NAT Traversal reasons start receiving also.
168     */
169    @Override
170    public void startTransmit() {
171        try {
172            LOGGER.fine("start");
173            mediaSession.start(true);
174            this.mediaReceived("");
175        }
176        catch (IOException e) {
177            LOGGER.log(Level.WARNING, "exception", e);
178        }
179    }
180
181    /**
182     * Set transmit activity. If the active is true, the instance should transmit.
183     * If it is set to false, the instance should pause transmit.
184     *
185     * @param active active state
186     * @deprecated use {@link #setTransmit(boolean)} instead.
187     */
188    @Deprecated
189    public void setTrasmit(boolean active) {
190        setTransmit(active);
191    }
192
193    /**
194     * Set transmit activity. If the active is true, the instance should transmit.
195     * If it is set to false, the instance should pause transmit.
196     *
197     * @param active active state
198     */
199    @Override
200    public void setTransmit(boolean active) {
201        // Do nothing
202    }
203
204    /**
205     * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf
206     */
207    @Override
208    public void startReceive() {
209        // Do nothing
210    }
211
212    /**
213     * Stops transmission and for NAT Traversal reasons stop receiving also.
214     *
215     * @deprecated use {@link #stopTransmit()} instead.
216     */
217    @Deprecated
218    public void stopTrasmit() {
219        stopTransmit();
220    }
221
222    /**
223     * Stops transmission and for NAT Traversal reasons stop receiving also.
224     */
225    @Override
226    public void stopTransmit() {
227        if (mediaSession != null)
228            mediaSession.close();
229    }
230
231    /**
232     * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf
233     */
234    @Override
235    public void stopReceive() {
236        // Do nothing
237    }
238
239    @Override
240    public void newStreamIdentified(StreamPlayer streamPlayer) {
241    }
242
243    @Override
244    public void senderReportReceived(SenderReport report) {
245    }
246
247    @Override
248    public void streamClosed(StreamPlayer stream, boolean timeout) {
249    }
250
251    /**
252     * Obtain a free port we can use.
253     *
254     * @return A free port number.
255     */
256    protected int getFreePort() {
257        ServerSocket ss;
258        int freePort = 0;
259
260        for (int i = 0; i < 10; i++) {
261            freePort = (int) (10000 + Math.round(Math.random() * 10000));
262            freePort = freePort % 2 == 0 ? freePort : freePort + 1;
263            try {
264                ss = new ServerSocket(freePort);
265                freePort = ss.getLocalPort();
266                ss.close();
267                return freePort;
268            }
269            catch (IOException e) {
270                LOGGER.log(Level.WARNING, "exception", e);
271            }
272        }
273        try {
274            ss = new ServerSocket(0);
275            freePort = ss.getLocalPort();
276            ss.close();
277        }
278        catch (IOException e) {
279            LOGGER.log(Level.WARNING, "exception", e);
280        }
281        return freePort;
282    }
283}