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 TODO javadoc me please
071     * @throws NoProcessorException if there is no media processor.
072     * @throws UnsupportedFormatException if the format is not supported.
073     * @throws IOException if an I/O error occurred.
074     * @throws GeneralSecurityException if there was a geneeral security exception.
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     * @param jingleSession the jingle session.
106     */
107    public AudioMediaSession(final PayloadType payloadType, final TransportCandidate remote,
108            final TransportCandidate local, String locator, JingleSession jingleSession) {
109        super(payloadType, remote, local, locator == null ? "dsound://" : locator, jingleSession);
110        initialize();
111    }
112
113    /**
114     * Initialize the Audio Channel to make it able to send and receive audio.
115     */
116    @Override
117    public void initialize() {
118
119        String ip;
120        String localIp;
121        int localPort;
122        int remotePort;
123
124        if (this.getLocal().getSymmetric() != null) {
125            ip = this.getLocal().getIp();
126            localIp = this.getLocal().getLocalIp();
127            localPort = getFreePort();
128            remotePort = this.getLocal().getSymmetric().getPort();
129
130            LOGGER.fine(this.getLocal().getConnection() + " " + ip + ": " + localPort + "->" + remotePort);
131
132        }
133        else {
134            ip = this.getRemote().getIp();
135            localIp = this.getLocal().getLocalIp();
136            localPort = this.getLocal().getPort();
137            remotePort = this.getRemote().getPort();
138        }
139
140        try {
141            mediaSession = createSession(localIp, localPort, ip, remotePort, this, 2, false, true);
142        }
143        catch (NoProcessorException e) {
144            LOGGER.log(Level.WARNING, "exception", e);
145        }
146        catch (UnsupportedFormatException e) {
147            LOGGER.log(Level.WARNING, "exception", e);
148        }
149        catch (IOException e) {
150            LOGGER.log(Level.WARNING, "exception", e);
151        }
152        catch (GeneralSecurityException e) {
153            LOGGER.log(Level.WARNING, "exception", e);
154        }
155    }
156
157    /**
158     * Starts transmission and for NAT Traversal reasons start receiving also.
159     *
160     * @deprecated use {@link #startTransmit()} instead.
161     */
162    @Deprecated
163    public void startTrasmit() {
164        startTransmit();
165    }
166
167    /**
168     * Starts transmission and for NAT Traversal reasons start receiving also.
169     */
170    @Override
171    public void startTransmit() {
172        try {
173            LOGGER.fine("start");
174            mediaSession.start(true);
175            this.mediaReceived("");
176        }
177        catch (IOException e) {
178            LOGGER.log(Level.WARNING, "exception", e);
179        }
180    }
181
182    /**
183     * Set transmit activity. If the active is true, the instance should transmit.
184     * If it is set to false, the instance should pause transmit.
185     *
186     * @param active active state
187     * @deprecated use {@link #setTransmit(boolean)} instead.
188     */
189    @Deprecated
190    public void setTrasmit(boolean active) {
191        setTransmit(active);
192    }
193
194    /**
195     * Set transmit activity. If the active is true, the instance should transmit.
196     * If it is set to false, the instance should pause transmit.
197     *
198     * @param active active state
199     */
200    @Override
201    public void setTransmit(boolean active) {
202        // Do nothing
203    }
204
205    /**
206     * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf
207     */
208    @Override
209    public void startReceive() {
210        // Do nothing
211    }
212
213    /**
214     * Stops transmission and for NAT Traversal reasons stop receiving also.
215     *
216     * @deprecated use {@link #stopTransmit()} instead.
217     */
218    @Deprecated
219    public void stopTrasmit() {
220        stopTransmit();
221    }
222
223    /**
224     * Stops transmission and for NAT Traversal reasons stop receiving also.
225     */
226    @Override
227    public void stopTransmit() {
228        if (mediaSession != null)
229            mediaSession.close();
230    }
231
232    /**
233     * For NAT Reasons this method does nothing. Use startTransmit() to start transmit and receive jmf
234     */
235    @Override
236    public void stopReceive() {
237        // Do nothing
238    }
239
240    @Override
241    public void newStreamIdentified(StreamPlayer streamPlayer) {
242    }
243
244    @Override
245    public void senderReportReceived(SenderReport report) {
246    }
247
248    @Override
249    public void streamClosed(StreamPlayer stream, boolean timeout) {
250    }
251
252    /**
253     * Obtain a free port we can use.
254     *
255     * @return A free port number.
256     */
257    protected int getFreePort() {
258        ServerSocket ss;
259        int freePort = 0;
260
261        for (int i = 0; i < 10; i++) {
262            freePort = (int) (10000 + Math.round(Math.random() * 10000));
263            freePort = freePort % 2 == 0 ? freePort : freePort + 1;
264            try {
265                ss = new ServerSocket(freePort);
266                freePort = ss.getLocalPort();
267                ss.close();
268                return freePort;
269            }
270            catch (IOException e) {
271                LOGGER.log(Level.WARNING, "exception", e);
272            }
273        }
274        try {
275            ss = new ServerSocket(0);
276            freePort = ss.getLocalPort();
277            ss.close();
278        }
279        catch (IOException e) {
280            LOGGER.log(Level.WARNING, "exception", e);
281        }
282        return freePort;
283    }
284}